MDL-27639 restore of attempt data from 2.0 - first attempt.
[moodle.git] / lib / filelib.php
blob0f879fc234eefa49493d0f4c5dfd70a474dbecb6
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions for file handling.
21 * @package core
22 * @subpackage file
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** @var string unique string constant. */
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @global object
43 * @param string $urlbase
44 * @param string $path /filearea/itemid/dir/dir/file.exe
45 * @param bool $forcedownload
46 * @param bool $https https url required
47 * @return string encoded file url
49 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
50 global $CFG;
52 //TODO: deprecate this
54 if ($CFG->slasharguments) {
55 $parts = explode('/', $path);
56 $parts = array_map('rawurlencode', $parts);
57 $path = implode('/', $parts);
58 $return = $urlbase.$path;
59 if ($forcedownload) {
60 $return .= '?forcedownload=1';
62 } else {
63 $path = rawurlencode($path);
64 $return = $urlbase.'?file='.$path;
65 if ($forcedownload) {
66 $return .= '&amp;forcedownload=1';
70 if ($https) {
71 $return = str_replace('http://', 'https://', $return);
74 return $return;
77 /**
78 * Prepares 'editor' formslib element from data in database
80 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
81 * function then copies the embedded files into draft area (assigning itemids automatically),
82 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
83 * displayed.
84 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
85 * your mform's set_data() supplying the object returned by this function.
87 * @param object $data database field that holds the html text with embedded media
88 * @param string $field the name of the database field that holds the html text with embedded media
89 * @param array $options editor options (like maxifiles, maxbytes etc.)
90 * @param object $context context of the editor
91 * @param string $component
92 * @param string $filearea file area name
93 * @param int $itemid item id, required if item exists
94 * @return object modified data object
96 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
97 $options = (array)$options;
98 if (!isset($options['trusttext'])) {
99 $options['trusttext'] = false;
101 if (!isset($options['forcehttps'])) {
102 $options['forcehttps'] = false;
104 if (!isset($options['subdirs'])) {
105 $options['subdirs'] = false;
107 if (!isset($options['maxfiles'])) {
108 $options['maxfiles'] = 0; // no files by default
110 if (!isset($options['noclean'])) {
111 $options['noclean'] = false;
114 if (is_null($itemid) or is_null($context)) {
115 $contextid = null;
116 $itemid = null;
117 if (!isset($data->{$field})) {
118 $data->{$field} = '';
120 if (!isset($data->{$field.'format'})) {
121 $data->{$field.'format'} = editors_get_preferred_format();
123 if (!$options['noclean']) {
124 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
127 } else {
128 if ($options['trusttext']) {
129 // noclean ignored if trusttext enabled
130 if (!isset($data->{$field.'trust'})) {
131 $data->{$field.'trust'} = 0;
133 $data = trusttext_pre_edit($data, $field, $context);
134 } else {
135 if (!$options['noclean']) {
136 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
139 $contextid = $context->id;
142 if ($options['maxfiles'] != 0) {
143 $draftid_editor = file_get_submitted_draft_itemid($field);
144 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
145 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
146 } else {
147 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
150 return $data;
154 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
156 * This function moves files from draft area to the destination area and
157 * encodes URLs to the draft files so they can be safely saved into DB. The
158 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
159 * is the name of the database field to hold the wysiwyg editor content. The
160 * editor data comes as an array with text, format and itemid properties. This
161 * function automatically adds $data properties foobar, foobarformat and
162 * foobartrust, where foobar has URL to embedded files encoded.
164 * @param object $data raw data submitted by the form
165 * @param string $field name of the database field containing the html with embedded media files
166 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
167 * @param object $context context, required for existing data
168 * @param string component
169 * @param string $filearea file area name
170 * @param int $itemid item id, required if item exists
171 * @return object modified data object
173 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
174 $options = (array)$options;
175 if (!isset($options['trusttext'])) {
176 $options['trusttext'] = false;
178 if (!isset($options['forcehttps'])) {
179 $options['forcehttps'] = false;
181 if (!isset($options['subdirs'])) {
182 $options['subdirs'] = false;
184 if (!isset($options['maxfiles'])) {
185 $options['maxfiles'] = 0; // no files by default
187 if (!isset($options['maxbytes'])) {
188 $options['maxbytes'] = 0; // unlimited
191 if ($options['trusttext']) {
192 $data->{$field.'trust'} = trusttext_trusted($context);
193 } else {
194 $data->{$field.'trust'} = 0;
197 $editor = $data->{$field.'_editor'};
199 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
200 $data->{$field} = $editor['text'];
201 } else {
202 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
204 $data->{$field.'format'} = $editor['format'];
206 return $data;
210 * Saves text and files modified by Editor formslib element
212 * @param object $data $database entry field
213 * @param string $field name of data field
214 * @param array $options various options
215 * @param object $context context - must already exist
216 * @param string $component
217 * @param string $filearea file area name
218 * @param int $itemid must already exist, usually means data is in db
219 * @return object modified data obejct
221 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
222 $options = (array)$options;
223 if (!isset($options['subdirs'])) {
224 $options['subdirs'] = false;
226 if (is_null($itemid) or is_null($context)) {
227 $itemid = null;
228 $contextid = null;
229 } else {
230 $contextid = $context->id;
233 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
234 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
235 $data->{$field.'_filemanager'} = $draftid_editor;
237 return $data;
241 * Saves files modified by File manager formslib element
243 * @param object $data $database entry field
244 * @param string $field name of data field
245 * @param array $options various options
246 * @param object $context context - must already exist
247 * @param string $component
248 * @param string $filearea file area name
249 * @param int $itemid must already exist, usually means data is in db
250 * @return object modified data obejct
252 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
253 $options = (array)$options;
254 if (!isset($options['subdirs'])) {
255 $options['subdirs'] = false;
257 if (!isset($options['maxfiles'])) {
258 $options['maxfiles'] = -1; // unlimited
260 if (!isset($options['maxbytes'])) {
261 $options['maxbytes'] = 0; // unlimited
264 if (empty($data->{$field.'_filemanager'})) {
265 $data->$field = '';
267 } else {
268 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
269 $fs = get_file_storage();
271 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
272 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
273 } else {
274 $data->$field = '';
278 return $data;
283 * @global object
284 * @global object
285 * @return int a random but available draft itemid that can be used to create a new draft
286 * file area.
288 function file_get_unused_draft_itemid() {
289 global $DB, $USER;
291 if (isguestuser() or !isloggedin()) {
292 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
293 print_error('noguest');
296 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
298 $fs = get_file_storage();
299 $draftitemid = rand(1, 999999999);
300 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
301 $draftitemid = rand(1, 999999999);
304 return $draftitemid;
308 * Initialise a draft file area from a real one by copying the files. A draft
309 * area will be created if one does not already exist. Normally you should
310 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
312 * @global object
313 * @global object
314 * @param int &$draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
315 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
316 * @param string $component
317 * @param string $filearea helps indentify the file area.
318 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
319 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
320 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
321 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
323 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
324 global $CFG, $USER, $CFG;
326 $options = (array)$options;
327 if (!isset($options['subdirs'])) {
328 $options['subdirs'] = false;
330 if (!isset($options['forcehttps'])) {
331 $options['forcehttps'] = false;
334 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
335 $fs = get_file_storage();
337 if (empty($draftitemid)) {
338 // create a new area and copy existing files into
339 $draftitemid = file_get_unused_draft_itemid();
340 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
341 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
342 foreach ($files as $file) {
343 if ($file->is_directory() and $file->get_filepath() === '/') {
344 // we need a way to mark the age of each draft area,
345 // by not copying the root dir we force it to be created automatically with current timestamp
346 continue;
348 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
349 continue;
351 $fs->create_file_from_storedfile($file_record, $file);
354 if (!is_null($text)) {
355 // at this point there should not be any draftfile links yet,
356 // because this is a new text from database that should still contain the @@pluginfile@@ links
357 // this happens when developers forget to post process the text
358 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
360 } else {
361 // nothing to do
364 if (is_null($text)) {
365 return null;
368 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
369 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
373 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
375 * @global object
376 * @param string $text The content that may contain ULRs in need of rewriting.
377 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
378 * @param integer $contextid This parameter and the next two identify the file area to use.
379 * @param string $component
380 * @param string $filearea helps identify the file area.
381 * @param integer $itemid helps identify the file area.
382 * @param array $options text and file options ('forcehttps'=>false)
383 * @return string the processed text.
385 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
386 global $CFG;
388 $options = (array)$options;
389 if (!isset($options['forcehttps'])) {
390 $options['forcehttps'] = false;
393 if (!$CFG->slasharguments) {
394 $file = $file . '?file=';
397 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
399 if ($itemid !== null) {
400 $baseurl .= "$itemid/";
403 if ($options['forcehttps']) {
404 $baseurl = str_replace('http://', 'https://', $baseurl);
407 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
411 * Returns information about files in a draft area.
413 * @global object
414 * @global object
415 * @param integer $draftitemid the draft area item id.
416 * @return array with the following entries:
417 * 'filecount' => number of files in the draft area.
418 * (more information will be added as needed).
420 function file_get_draft_area_info($draftitemid) {
421 global $CFG, $USER;
423 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
424 $fs = get_file_storage();
426 $results = array();
428 // The number of files
429 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
430 $results['filecount'] = count($draftfiles);
431 $results['filesize'] = 0;
432 foreach ($draftfiles as $file) {
433 $results['filesize'] += $file->get_filesize();
436 return $results;
440 * Get used space of files
441 * @return int total bytes
443 function file_get_user_used_space() {
444 global $DB, $USER;
446 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
447 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
448 JOIN (SELECT contenthash, filename, MAX(id) AS id
449 FROM {files}
450 WHERE contextid = ? AND component = ? AND filearea != ?
451 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
452 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
453 $record = $DB->get_record_sql($sql, $params);
454 return (int)$record->totalbytes;
458 * Convert any string to a valid filepath
459 * @param string $str
460 * @return string path
462 function file_correct_filepath($str) { //TODO: what is this? (skodak)
463 if ($str == '/' or empty($str)) {
464 return '/';
465 } else {
466 return '/'.trim($str, './@#$ ').'/';
471 * Generate a folder tree of draft area of current USER recursively
472 * @param int $itemid
473 * @param string $filepath
474 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
476 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
477 global $USER, $OUTPUT, $CFG;
478 $data->children = array();
479 $context = get_context_instance(CONTEXT_USER, $USER->id);
480 $fs = get_file_storage();
481 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
482 foreach ($files as $file) {
483 if ($file->is_directory()) {
484 $item = new stdClass();
485 $item->sortorder = $file->get_sortorder();
486 $item->filepath = $file->get_filepath();
488 $foldername = explode('/', trim($item->filepath, '/'));
489 $item->fullname = trim(array_pop($foldername), '/');
491 $item->id = uniqid();
492 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
493 $data->children[] = $item;
494 } else {
495 continue;
502 * Listing all files (including folders) in current path (draft area)
503 * used by file manager
504 * @param int $draftitemid
505 * @param string $filepath
506 * @return mixed
508 function file_get_drafarea_files($draftitemid, $filepath = '/') {
509 global $USER, $OUTPUT, $CFG;
511 $context = get_context_instance(CONTEXT_USER, $USER->id);
512 $fs = get_file_storage();
514 $data = new stdClass();
515 $data->path = array();
516 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
518 // will be used to build breadcrumb
519 $trail = '';
520 if ($filepath !== '/') {
521 $filepath = file_correct_filepath($filepath);
522 $parts = explode('/', $filepath);
523 foreach ($parts as $part) {
524 if ($part != '' && $part != null) {
525 $trail .= ('/'.$part.'/');
526 $data->path[] = array('name'=>$part, 'path'=>$trail);
531 $list = array();
532 $maxlength = 12;
533 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
534 foreach ($files as $file) {
535 $item = new stdClass();
536 $item->filename = $file->get_filename();
537 $item->filepath = $file->get_filepath();
538 $item->fullname = trim($item->filename, '/');
539 $filesize = $file->get_filesize();
540 $item->filesize = $filesize ? display_size($filesize) : '';
542 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
543 $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
544 $item->sortorder = $file->get_sortorder();
546 if ($icon == 'zip') {
547 $item->type = 'zip';
548 } else {
549 $item->type = 'file';
552 if ($file->is_directory()) {
553 $item->filesize = 0;
554 $item->icon = $OUTPUT->pix_url('f/folder')->out();
555 $item->type = 'folder';
556 $foldername = explode('/', trim($item->filepath, '/'));
557 $item->fullname = trim(array_pop($foldername), '/');
558 } else {
559 // do NOT use file browser here!
560 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
562 $list[] = $item;
565 $data->itemid = $draftitemid;
566 $data->list = $list;
567 return $data;
571 * Returns draft area itemid for a given element.
573 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
574 * @return integer the itemid, or 0 if there is not one yet.
576 function file_get_submitted_draft_itemid($elname) {
577 $param = optional_param($elname, 0, PARAM_INT);
578 if ($param) {
579 require_sesskey();
581 if (is_array($param)) {
582 if (!empty($param['itemid'])) {
583 $param = $param['itemid'];
584 } else {
585 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
586 return false;
589 return $param;
593 * Saves files from a draft file area to a real one (merging the list of files).
594 * Can rewrite URLs in some content at the same time if desired.
596 * @global object
597 * @global object
598 * @param integer $draftitemid the id of the draft area to use. Normally obtained
599 * from file_get_submitted_draft_itemid('elementname') or similar.
600 * @param integer $contextid This parameter and the next two identify the file area to save to.
601 * @param string $component
602 * @param string $filearea indentifies the file area.
603 * @param integer $itemid helps identifies the file area.
604 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
605 * @param string $text some html content that needs to have embedded links rewritten
606 * to the @@PLUGINFILE@@ form for saving in the database.
607 * @param boolean $forcehttps force https urls.
608 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
610 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
611 global $USER;
613 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
614 $fs = get_file_storage();
616 $options = (array)$options;
617 if (!isset($options['subdirs'])) {
618 $options['subdirs'] = false;
620 if (!isset($options['maxfiles'])) {
621 $options['maxfiles'] = -1; // unlimited
623 if (!isset($options['maxbytes'])) {
624 $options['maxbytes'] = 0; // unlimited
627 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
628 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
630 if (count($draftfiles) < 2) {
631 // means there are no files - one file means root dir only ;-)
632 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
634 } else if (count($oldfiles) < 2) {
635 $filecount = 0;
636 // there were no files before - one file means root dir only ;-)
637 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
638 foreach ($draftfiles as $file) {
639 if (!$options['subdirs']) {
640 if ($file->get_filepath() !== '/' or $file->is_directory()) {
641 continue;
644 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
645 // oversized file - should not get here at all
646 continue;
648 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
649 // more files - should not get here at all
650 break;
652 if (!$file->is_directory()) {
653 $filecount++;
655 $fs->create_file_from_storedfile($file_record, $file);
658 } else {
659 // we have to merge old and new files - we want to keep file ids for files that were not changed
660 // we change time modified for all new and changed files, we keep time created as is
661 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
663 $newhashes = array();
664 foreach ($draftfiles as $file) {
665 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
666 $newhashes[$newhash] = $file;
668 $filecount = 0;
669 foreach ($oldfiles as $oldfile) {
670 $oldhash = $oldfile->get_pathnamehash();
671 if (!isset($newhashes[$oldhash])) {
672 // delete files not needed any more - deleted by user
673 $oldfile->delete();
674 continue;
676 $newfile = $newhashes[$oldhash];
677 if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
678 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
679 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
680 // file was changed, use updated with new timemodified data
681 $oldfile->delete();
682 continue;
684 // unchanged file or directory - we keep it as is
685 unset($newhashes[$oldhash]);
686 if (!$oldfile->is_directory()) {
687 $filecount++;
691 // now add new/changed files
692 // the size and subdirectory tests are extra safety only, the UI should prevent it
693 foreach ($newhashes as $file) {
694 if (!$options['subdirs']) {
695 if ($file->get_filepath() !== '/' or $file->is_directory()) {
696 continue;
699 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
700 // oversized file - should not get here at all
701 continue;
703 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
704 // more files - should not get here at all
705 break;
707 if (!$file->is_directory()) {
708 $filecount++;
710 $fs->create_file_from_storedfile($file_record, $file);
714 // note: do not purge the draft area - we clean up areas later in cron,
715 // the reason is that user might press submit twice and they would loose the files,
716 // also sometimes we might want to use hacks that save files into two different areas
718 if (is_null($text)) {
719 return null;
720 } else {
721 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
726 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
727 * ready to be saved in the database. Normally, this is done automatically by
728 * {@link file_save_draft_area_files()}.
729 * @param string $text the content to process.
730 * @param int $draftitemid the draft file area the content was using.
731 * @param bool $forcehttps whether the content contains https URLs. Default false.
732 * @return string the processed content.
734 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
735 global $CFG, $USER;
737 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
739 $wwwroot = $CFG->wwwroot;
740 if ($forcehttps) {
741 $wwwroot = str_replace('http://', 'https://', $wwwroot);
744 // relink embedded files if text submitted - no absolute links allowed in database!
745 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
747 if (strpos($text, 'draftfile.php?file=') !== false) {
748 $matches = array();
749 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
750 if ($matches) {
751 foreach ($matches[0] as $match) {
752 $replace = str_ireplace('%2F', '/', $match);
753 $text = str_replace($match, $replace, $text);
756 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
759 return $text;
763 * Set file sort order
764 * @global object $DB
765 * @param integer $contextid the context id
766 * @param string $component
767 * @param string $filearea file area.
768 * @param integer $itemid itemid.
769 * @param string $filepath file path.
770 * @param string $filename file name.
771 * @param integer $sortorer the sort order of file.
772 * @return boolean
774 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
775 global $DB;
776 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
777 if ($file_record = $DB->get_record('files', $conditions)) {
778 $sortorder = (int)$sortorder;
779 $file_record->sortorder = $sortorder;
780 $DB->update_record('files', $file_record);
781 return true;
783 return false;
787 * reset file sort order number to 0
788 * @global object $DB
789 * @param integer $contextid the context id
790 * @param string $component
791 * @param string $filearea file area.
792 * @param integer $itemid itemid.
793 * @return boolean
795 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
796 global $DB;
798 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
799 if ($itemid !== false) {
800 $conditions['itemid'] = $itemid;
803 $file_records = $DB->get_records('files', $conditions);
804 foreach ($file_records as $file_record) {
805 $file_record->sortorder = 0;
806 $DB->update_record('files', $file_record);
808 return true;
812 * Returns description of upload error
814 * @param int $errorcode found in $_FILES['filename.ext']['error']
815 * @return string error description string, '' if ok
817 function file_get_upload_error($errorcode) {
819 switch ($errorcode) {
820 case 0: // UPLOAD_ERR_OK - no error
821 $errmessage = '';
822 break;
824 case 1: // UPLOAD_ERR_INI_SIZE
825 $errmessage = get_string('uploadserverlimit');
826 break;
828 case 2: // UPLOAD_ERR_FORM_SIZE
829 $errmessage = get_string('uploadformlimit');
830 break;
832 case 3: // UPLOAD_ERR_PARTIAL
833 $errmessage = get_string('uploadpartialfile');
834 break;
836 case 4: // UPLOAD_ERR_NO_FILE
837 $errmessage = get_string('uploadnofilefound');
838 break;
840 // Note: there is no error with a value of 5
842 case 6: // UPLOAD_ERR_NO_TMP_DIR
843 $errmessage = get_string('uploadnotempdir');
844 break;
846 case 7: // UPLOAD_ERR_CANT_WRITE
847 $errmessage = get_string('uploadcantwrite');
848 break;
850 case 8: // UPLOAD_ERR_EXTENSION
851 $errmessage = get_string('uploadextension');
852 break;
854 default:
855 $errmessage = get_string('uploadproblem');
858 return $errmessage;
862 * Recursive function formating an array in POST parameter
863 * @param array $arraydata - the array that we are going to format and add into &$data array
864 * @param string $currentdata - a row of the final postdata array at instant T
865 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
866 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
868 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
869 foreach ($arraydata as $k=>$v) {
870 $newcurrentdata = $currentdata;
871 if (is_array($v)) { //the value is an array, call the function recursively
872 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
873 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
874 } else { //add the POST parameter to the $data array
875 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
881 * Transform a PHP array into POST parameter
882 * (see the recursive function format_array_postdata_for_curlcall)
883 * @param array $postdata
884 * @return array containing all POST parameters (1 row = 1 POST parameter)
886 function format_postdata_for_curlcall($postdata) {
887 $data = array();
888 foreach ($postdata as $k=>$v) {
889 if (is_array($v)) {
890 $currentdata = urlencode($k);
891 format_array_postdata_for_curlcall($v, $currentdata, $data);
892 } else {
893 $data[] = urlencode($k).'='.urlencode($v);
896 $convertedpostdata = implode('&', $data);
897 return $convertedpostdata;
904 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
905 * Due to security concerns only downloads from http(s) sources are supported.
907 * @param string $url file url starting with http(s)://
908 * @param array $headers http headers, null if none. If set, should be an
909 * associative array of header name => value pairs.
910 * @param array $postdata array means use POST request with given parameters
911 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
912 * (if false, just returns content)
913 * @param int $timeout timeout for complete download process including all file transfer
914 * (default 5 minutes)
915 * @param int $connecttimeout timeout for connection to server; this is the timeout that
916 * usually happens if the remote server is completely down (default 20 seconds);
917 * may not work when using proxy
918 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
919 * Only use this when already in a trusted location.
920 * @param string $tofile store the downloaded content to file instead of returning it.
921 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
922 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
923 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
925 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
926 global $CFG;
928 // some extra security
929 $newlines = array("\r", "\n");
930 if (is_array($headers) ) {
931 foreach ($headers as $key => $value) {
932 $headers[$key] = str_replace($newlines, '', $value);
935 $url = str_replace($newlines, '', $url);
936 if (!preg_match('|^https?://|i', $url)) {
937 if ($fullresponse) {
938 $response = new stdClass();
939 $response->status = 0;
940 $response->headers = array();
941 $response->response_code = 'Invalid protocol specified in url';
942 $response->results = '';
943 $response->error = 'Invalid protocol specified in url';
944 return $response;
945 } else {
946 return false;
950 // check if proxy (if used) should be bypassed for this url
951 $proxybypass = is_proxybypass($url);
953 if (!$ch = curl_init($url)) {
954 debugging('Can not init curl.');
955 return false;
958 // set extra headers
959 if (is_array($headers) ) {
960 $headers2 = array();
961 foreach ($headers as $key => $value) {
962 $headers2[] = "$key: $value";
964 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
967 if ($skipcertverify) {
968 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
971 // use POST if requested
972 if (is_array($postdata)) {
973 $postdata = format_postdata_for_curlcall($postdata);
974 curl_setopt($ch, CURLOPT_POST, true);
975 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
978 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
979 curl_setopt($ch, CURLOPT_HEADER, false);
980 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
982 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
983 // TODO: add version test for '7.10.5'
984 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
985 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
988 if (!empty($CFG->proxyhost) and !$proxybypass) {
989 // SOCKS supported in PHP5 only
990 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
991 if (defined('CURLPROXY_SOCKS5')) {
992 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
993 } else {
994 curl_close($ch);
995 if ($fullresponse) {
996 $response = new stdClass();
997 $response->status = '0';
998 $response->headers = array();
999 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1000 $response->results = '';
1001 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1002 return $response;
1003 } else {
1004 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1005 return false;
1010 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1012 if (empty($CFG->proxyport)) {
1013 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1014 } else {
1015 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1018 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1019 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1020 if (defined('CURLOPT_PROXYAUTH')) {
1021 // any proxy authentication if PHP 5.1
1022 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1027 // set up header and content handlers
1028 $received = new stdClass();
1029 $received->headers = array(); // received headers array
1030 $received->tofile = $tofile;
1031 $received->fh = null;
1032 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1033 if ($tofile) {
1034 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1037 if (!isset($CFG->curltimeoutkbitrate)) {
1038 //use very slow rate of 56kbps as a timeout speed when not set
1039 $bitrate = 56;
1040 } else {
1041 $bitrate = $CFG->curltimeoutkbitrate;
1044 // try to calculate the proper amount for timeout from remote file size.
1045 // if disabled or zero, we won't do any checks nor head requests.
1046 if ($calctimeout && $bitrate > 0) {
1047 //setup header request only options
1048 curl_setopt_array ($ch, array(
1049 CURLOPT_RETURNTRANSFER => false,
1050 CURLOPT_NOBODY => true)
1053 curl_exec($ch);
1054 $info = curl_getinfo($ch);
1055 $err = curl_error($ch);
1057 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1058 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1060 //reinstate affected curl options
1061 curl_setopt_array ($ch, array(
1062 CURLOPT_RETURNTRANSFER => true,
1063 CURLOPT_NOBODY => false)
1067 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1068 $result = curl_exec($ch);
1070 // try to detect encoding problems
1071 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1072 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1073 $result = curl_exec($ch);
1076 if ($received->fh) {
1077 fclose($received->fh);
1080 if (curl_errno($ch)) {
1081 $error = curl_error($ch);
1082 $error_no = curl_errno($ch);
1083 curl_close($ch);
1085 if ($fullresponse) {
1086 $response = new stdClass();
1087 if ($error_no == 28) {
1088 $response->status = '-100'; // mimic snoopy
1089 } else {
1090 $response->status = '0';
1092 $response->headers = array();
1093 $response->response_code = $error;
1094 $response->results = false;
1095 $response->error = $error;
1096 return $response;
1097 } else {
1098 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1099 return false;
1102 } else {
1103 $info = curl_getinfo($ch);
1104 curl_close($ch);
1106 if (empty($info['http_code'])) {
1107 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1108 $response = new stdClass();
1109 $response->status = '0';
1110 $response->headers = array();
1111 $response->response_code = 'Unknown cURL error';
1112 $response->results = false; // do NOT change this, we really want to ignore the result!
1113 $response->error = 'Unknown cURL error';
1115 } else {
1116 $response = new stdClass();;
1117 $response->status = (string)$info['http_code'];
1118 $response->headers = $received->headers;
1119 $response->response_code = $received->headers[0];
1120 $response->results = $result;
1121 $response->error = '';
1124 if ($fullresponse) {
1125 return $response;
1126 } else if ($info['http_code'] != 200) {
1127 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1128 return false;
1129 } else {
1130 return $response->results;
1136 * internal implementation
1138 function download_file_content_header_handler($received, $ch, $header) {
1139 $received->headers[] = $header;
1140 return strlen($header);
1144 * internal implementation
1146 function download_file_content_write_handler($received, $ch, $data) {
1147 if (!$received->fh) {
1148 $received->fh = fopen($received->tofile, 'w');
1149 if ($received->fh === false) {
1150 // bad luck, file creation or overriding failed
1151 return 0;
1154 if (fwrite($received->fh, $data) === false) {
1155 // bad luck, write failed, let's abort completely
1156 return 0;
1158 return strlen($data);
1162 * @return array List of information about file types based on extensions.
1163 * Associative array of extension (lower-case) to associative array
1164 * from 'element name' to data. Current element names are 'type' and 'icon'.
1165 * Unknown types should use the 'xxx' entry which includes defaults.
1167 function get_mimetypes_array() {
1168 static $mimearray = array (
1169 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1170 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1171 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
1172 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1173 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1174 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1175 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1176 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1177 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1178 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1179 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1180 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1181 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1182 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1183 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1184 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1185 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1186 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1187 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1188 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1189 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1191 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1192 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1193 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1194 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1195 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1197 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1198 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1199 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1200 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1201 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1202 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1203 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1204 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1205 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1206 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1207 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1208 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1209 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1210 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1211 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1212 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1213 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1214 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1215 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1216 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1217 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1218 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1219 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1220 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1221 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1222 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1223 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1224 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1225 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1226 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1227 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1228 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1229 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1230 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1231 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1232 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1233 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1234 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1235 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1236 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1237 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1238 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1239 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1240 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1241 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1242 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1243 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1244 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1246 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1247 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1248 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1249 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1250 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1251 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1252 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1253 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1254 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1255 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1256 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1257 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1258 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1259 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1260 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1261 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1262 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
1264 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1265 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1266 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1267 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1268 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1269 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1271 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1272 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1273 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1274 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1275 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1276 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1277 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1278 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1279 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1281 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1282 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1283 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1284 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1285 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1286 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1287 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
1288 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1289 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1290 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
1291 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1292 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1293 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1294 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1295 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1296 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1297 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1298 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1299 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1300 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1302 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1303 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1304 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1305 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1306 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1307 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1308 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1309 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1310 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1311 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1313 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1314 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1315 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1316 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1317 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1318 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1319 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1320 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1321 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1322 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
1323 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1324 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1325 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1326 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1327 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1329 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1330 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1331 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1332 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1333 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1334 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1335 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1337 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1338 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1339 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1341 return $mimearray;
1345 * Obtains information about a filetype based on its extension. Will
1346 * use a default if no information is present about that particular
1347 * extension.
1349 * @param string $element Desired information (usually 'icon'
1350 * for icon filename or 'type' for MIME type)
1351 * @param string $filename Filename we're looking up
1352 * @return string Requested piece of information from array
1354 function mimeinfo($element, $filename) {
1355 global $CFG;
1356 $mimeinfo = get_mimetypes_array();
1358 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1359 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1360 return $mimeinfo[strtolower($match[1])][$element];
1361 } else {
1362 if ($element == 'icon32') {
1363 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1364 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1365 } else {
1366 $filename = 'unknown';
1368 $filename .= '-32';
1369 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1370 return $filename;
1371 } else {
1372 return 'unknown-32';
1374 } else {
1375 return $mimeinfo['xxx'][$element]; // By default
1378 } else {
1379 if ($element == 'icon32') {
1380 return 'unknown-32';
1382 return $mimeinfo['xxx'][$element]; // By default
1387 * Obtains information about a filetype based on the MIME type rather than
1388 * the other way around.
1390 * @param string $element Desired information (usually 'icon')
1391 * @param string $mimetype MIME type we're looking up
1392 * @return string Requested piece of information from array
1394 function mimeinfo_from_type($element, $mimetype) {
1395 $mimeinfo = get_mimetypes_array();
1397 foreach($mimeinfo as $values) {
1398 if ($values['type']==$mimetype) {
1399 if (isset($values[$element])) {
1400 return $values[$element];
1402 break;
1405 return $mimeinfo['xxx'][$element]; // Default
1409 * Get information about a filetype based on the icon file.
1411 * @param string $element Desired information (usually 'icon')
1412 * @param string $icon Icon file name without extension
1413 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1414 * @return string Requested piece of information from array
1416 function mimeinfo_from_icon($element, $icon, $all=false) {
1417 $mimeinfo = get_mimetypes_array();
1419 if (preg_match("/\/(.*)/", $icon, $matches)) {
1420 $icon = $matches[1];
1422 // Try to get the extension
1423 $extension = '';
1424 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1425 $extension = substr($icon, $cutat + 1);
1427 $info = array($mimeinfo['xxx'][$element]); // Default
1428 foreach($mimeinfo as $key => $values) {
1429 if ($values['icon']==$icon) {
1430 if (isset($values[$element])) {
1431 $info[$key] = $values[$element];
1433 //No break, for example for 'excel' we don't want 'csv'!
1436 if ($all) {
1437 if (count($info) > 1) {
1438 array_shift($info); // take off document/unknown if we have better options
1440 return array_values($info); // Keep keys out when requesting all
1443 // Requested only one, try to get the best by extension coincidence, else return the last
1444 if ($extension && isset($info[$extension])) {
1445 return $info[$extension];
1448 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1452 * Returns the relative icon path for a given mime type
1454 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1455 * a return the full path to an icon.
1457 * <code>
1458 * $mimetype = 'image/jpg';
1459 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1460 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1461 * </code>
1463 * @todo When an $OUTPUT->icon method is available this function should be altered
1464 * to conform with that.
1466 * @param string $mimetype The mimetype to fetch an icon for
1467 * @param int $size The size of the icon. Not yet implemented
1468 * @return string The relative path to the icon
1470 function file_mimetype_icon($mimetype, $size = NULL) {
1471 global $CFG;
1473 $icon = mimeinfo_from_type('icon', $mimetype);
1474 if ($size) {
1475 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1476 $icon = "$icon-$size";
1479 return 'f/'.$icon;
1483 * Returns the relative icon path for a given file name
1485 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1486 * a return the full path to an icon.
1488 * <code>
1489 * $filename = 'jpg';
1490 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1491 * echo '<img src="'.$icon.'" alt="blah" />';
1492 * </code>
1494 * @todo When an $OUTPUT->icon method is available this function should be altered
1495 * to conform with that.
1496 * @todo Implement $size
1498 * @param string filename The filename to get the icon for
1499 * @param int $size The size of the icon. Defaults to null can also be 32
1500 * @return string
1502 function file_extension_icon($filename, $size = NULL) {
1503 global $CFG;
1505 $icon = mimeinfo('icon', $filename);
1506 if ($size) {
1507 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1508 $icon = "$icon-$size";
1511 return 'f/'.$icon;
1515 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1516 * mimetypes.php language file.
1518 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1519 * @param bool $capitalise If true, capitalises first character of result
1520 * @return string Text description
1522 function get_mimetype_description($mimetype, $capitalise=false) {
1523 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1524 $result = get_string($mimetype, 'mimetypes');
1525 } else {
1526 $result = get_string('document/unknown','mimetypes');
1528 if ($capitalise) {
1529 $result=ucfirst($result);
1531 return $result;
1535 * Requested file is not found or not accessible
1537 * @return does not return, terminates script
1539 function send_file_not_found() {
1540 global $CFG, $COURSE;
1541 header('HTTP/1.0 404 not found');
1542 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1546 * Check output buffering settings before sending file.
1547 * Please note you should not send any other headers after calling this function.
1549 * @private to be called only from lib/filelib.php !
1550 * @return void
1552 function prepare_file_content_sending() {
1553 // We needed to be able to send headers up until now
1554 if (headers_sent()) {
1555 throw new file_serving_exception('Headers already sent, can not serve file.');
1558 $olddebug = error_reporting(0);
1560 // IE compatibility HACK - it does not like zlib compression much
1561 // there is also a problem with the length header in older PHP versions
1562 if (ini_get_bool('zlib.output_compression')) {
1563 ini_set('zlib.output_compression', 'Off');
1566 // flush and close all buffers if possible
1567 while(ob_get_level()) {
1568 if (!ob_end_flush()) {
1569 // prevent infinite loop when buffer can not be closed
1570 break;
1574 error_reporting($olddebug);
1576 //NOTE: we can not reliable test headers_sent() here because
1577 // the headers might be sent which trying to close the buffers,
1578 // this happens especially if browser does not support gzip or deflate
1582 * Handles the sending of temporary file to user, download is forced.
1583 * File is deleted after abort or successful sending.
1585 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1586 * @param string $filename proposed file name when saving file
1587 * @param bool $path is content of file
1588 * @return does not return, script terminated
1590 function send_temp_file($path, $filename, $pathisstring=false) {
1591 global $CFG;
1593 // close session - not needed anymore
1594 @session_get_instance()->write_close();
1596 if (!$pathisstring) {
1597 if (!file_exists($path)) {
1598 header('HTTP/1.0 404 not found');
1599 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1601 // executed after normal finish or abort
1602 @register_shutdown_function('send_temp_file_finished', $path);
1605 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1606 if (check_browser_version('MSIE')) {
1607 $filename = urlencode($filename);
1610 $filesize = $pathisstring ? strlen($path) : filesize($path);
1612 header('Content-Disposition: attachment; filename='.$filename);
1613 header('Content-Length: '.$filesize);
1614 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1615 header('Cache-Control: max-age=10');
1616 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1617 header('Pragma: ');
1618 } else { //normal http - prevent caching at all cost
1619 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1620 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1621 header('Pragma: no-cache');
1623 header('Accept-Ranges: none'); // Do not allow byteserving
1625 //flush the buffers - save memory and disable sid rewrite
1626 // this also disables zlib compression
1627 prepare_file_content_sending();
1629 // send the contents
1630 if ($pathisstring) {
1631 echo $path;
1632 } else {
1633 @readfile($path);
1636 die; //no more chars to output
1640 * Internal callback function used by send_temp_file()
1642 function send_temp_file_finished($path) {
1643 if (file_exists($path)) {
1644 @unlink($path);
1649 * Handles the sending of file data to the user's browser, including support for
1650 * byteranges etc.
1652 * @global object
1653 * @global object
1654 * @global object
1655 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1656 * @param string $filename Filename to send
1657 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1658 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1659 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1660 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1661 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1662 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1663 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1664 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1665 * and should not be reopened.
1666 * @return no return or void, script execution stopped unless $dontdie is true
1668 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1669 global $CFG, $COURSE, $SESSION;
1671 if ($dontdie) {
1672 ignore_user_abort(true);
1675 // MDL-11789, apply $CFG->filelifetime here
1676 if ($lifetime === 'default') {
1677 if (!empty($CFG->filelifetime)) {
1678 $lifetime = $CFG->filelifetime;
1679 } else {
1680 $lifetime = 86400;
1684 session_get_instance()->write_close(); // unlock session during fileserving
1686 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1687 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1688 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1689 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1690 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1691 ($mimetype ? $mimetype : mimeinfo('type', $filename));
1693 $lastmodified = $pathisstring ? time() : filemtime($path);
1694 $filesize = $pathisstring ? strlen($path) : filesize($path);
1696 /* - MDL-13949
1697 //Adobe Acrobat Reader XSS prevention
1698 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1699 //please note that it prevents opening of pdfs in browser when http referer disabled
1700 //or file linked from another site; browser caching of pdfs is now disabled too
1701 if (!empty($_SERVER['HTTP_RANGE'])) {
1702 //already byteserving
1703 $lifetime = 1; // >0 needed for byteserving
1704 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1705 $mimetype = 'application/x-forcedownload';
1706 $forcedownload = true;
1707 $lifetime = 0;
1708 } else {
1709 $lifetime = 1; // >0 needed for byteserving
1714 //try to disable automatic sid rewrite in cookieless mode
1715 @ini_set("session.use_trans_sid", "false");
1717 //do not put '@' before the next header to detect incorrect moodle configurations,
1718 //error should be better than "weird" empty lines for admins/users
1719 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1721 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1722 if (check_browser_version('MSIE')) {
1723 $filename = rawurlencode($filename);
1726 if ($forcedownload) {
1727 header('Content-Disposition: attachment; filename="'.$filename.'"');
1728 } else {
1729 header('Content-Disposition: inline; filename="'.$filename.'"');
1732 if ($lifetime > 0) {
1733 header('Cache-Control: max-age='.$lifetime);
1734 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1735 header('Pragma: ');
1737 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1739 header('Accept-Ranges: bytes');
1741 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1742 // byteserving stuff - for acrobat reader and download accelerators
1743 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1744 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1745 $ranges = false;
1746 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1747 foreach ($ranges as $key=>$value) {
1748 if ($ranges[$key][1] == '') {
1749 //suffix case
1750 $ranges[$key][1] = $filesize - $ranges[$key][2];
1751 $ranges[$key][2] = $filesize - 1;
1752 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1753 //fix range length
1754 $ranges[$key][2] = $filesize - 1;
1756 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1757 //invalid byte-range ==> ignore header
1758 $ranges = false;
1759 break;
1761 //prepare multipart header
1762 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1763 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1765 } else {
1766 $ranges = false;
1768 if ($ranges) {
1769 $handle = fopen($path, 'rb');
1770 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1773 } else {
1774 /// Do not byteserve (disabled, strings, text and html files).
1775 header('Accept-Ranges: none');
1777 } else { // Do not cache files in proxies and browsers
1778 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1779 header('Cache-Control: max-age=10');
1780 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1781 header('Pragma: ');
1782 } else { //normal http - prevent caching at all cost
1783 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1784 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1785 header('Pragma: no-cache');
1787 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1790 if (empty($filter)) {
1791 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
1792 //cookieless mode - rewrite links
1793 header('Content-Type: text/html');
1794 $path = $pathisstring ? $path : implode('', file($path));
1795 $path = sid_ob_rewrite($path);
1796 $filesize = strlen($path);
1797 $pathisstring = true;
1798 } else if ($mimetype == 'text/plain') {
1799 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1800 } else {
1801 header('Content-Type: '.$mimetype);
1803 header('Content-Length: '.$filesize);
1805 //flush the buffers - save memory and disable sid rewrite
1806 //this also disables zlib compression
1807 prepare_file_content_sending();
1809 // send the contents
1810 if ($pathisstring) {
1811 echo $path;
1812 } else {
1813 @readfile($path);
1816 } else { // Try to put the file through filters
1817 if ($mimetype == 'text/html') {
1818 $options = new stdClass();
1819 $options->noclean = true;
1820 $options->nocache = true; // temporary workaround for MDL-5136
1821 $text = $pathisstring ? $path : implode('', file($path));
1823 $text = file_modify_html_header($text);
1824 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1825 if (!empty($CFG->usesid)) {
1826 //cookieless mode - rewrite links
1827 $output = sid_ob_rewrite($output);
1830 header('Content-Length: '.strlen($output));
1831 header('Content-Type: text/html');
1833 //flush the buffers - save memory and disable sid rewrite
1834 //this also disables zlib compression
1835 prepare_file_content_sending();
1837 // send the contents
1838 echo $output;
1839 // only filter text if filter all files is selected
1840 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1841 $options = new stdClass();
1842 $options->newlines = false;
1843 $options->noclean = true;
1844 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1845 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1846 if (!empty($CFG->usesid)) {
1847 //cookieless mode - rewrite links
1848 $output = sid_ob_rewrite($output);
1851 header('Content-Length: '.strlen($output));
1852 header('Content-Type: text/html; charset=utf-8'); //add encoding
1854 //flush the buffers - save memory and disable sid rewrite
1855 //this also disables zlib compression
1856 prepare_file_content_sending();
1858 // send the contents
1859 echo $output;
1861 } else { // Just send it out raw
1862 header('Content-Length: '.$filesize);
1863 header('Content-Type: '.$mimetype);
1865 //flush the buffers - save memory and disable sid rewrite
1866 //this also disables zlib compression
1867 prepare_file_content_sending();
1869 // send the contents
1870 if ($pathisstring) {
1871 echo $path;
1872 }else {
1873 @readfile($path);
1877 if ($dontdie) {
1878 return;
1880 die; //no more chars to output!!!
1884 * Handles the sending of file data to the user's browser, including support for
1885 * byteranges etc.
1887 * @global object
1888 * @global object
1889 * @global object
1890 * @param object $stored_file local file object
1891 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1892 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1893 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1894 * @param string $filename Override filename
1895 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1896 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1897 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1898 * and should not be reopened.
1899 * @return void no return or void, script execution stopped unless $dontdie is true
1901 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1902 global $CFG, $COURSE, $SESSION;
1904 if (!$stored_file or $stored_file->is_directory()) {
1905 // nothing to serve
1906 if ($dontdie) {
1907 return;
1909 die;
1912 if ($dontdie) {
1913 ignore_user_abort(true);
1916 session_get_instance()->write_close(); // unlock session during fileserving
1918 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1919 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1920 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1921 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1922 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1923 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1924 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1926 $lastmodified = $stored_file->get_timemodified();
1927 $filesize = $stored_file->get_filesize();
1929 //try to disable automatic sid rewrite in cookieless mode
1930 @ini_set("session.use_trans_sid", "false");
1932 //do not put '@' before the next header to detect incorrect moodle configurations,
1933 //error should be better than "weird" empty lines for admins/users
1934 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1935 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1937 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1938 if (check_browser_version('MSIE')) {
1939 $filename = rawurlencode($filename);
1942 if ($forcedownload) {
1943 header('Content-Disposition: attachment; filename="'.$filename.'"');
1944 } else {
1945 header('Content-Disposition: inline; filename="'.$filename.'"');
1948 if ($lifetime > 0) {
1949 header('Cache-Control: max-age='.$lifetime);
1950 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1951 header('Pragma: ');
1953 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1955 header('Accept-Ranges: bytes');
1957 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1958 // byteserving stuff - for acrobat reader and download accelerators
1959 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1960 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1961 $ranges = false;
1962 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1963 foreach ($ranges as $key=>$value) {
1964 if ($ranges[$key][1] == '') {
1965 //suffix case
1966 $ranges[$key][1] = $filesize - $ranges[$key][2];
1967 $ranges[$key][2] = $filesize - 1;
1968 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1969 //fix range length
1970 $ranges[$key][2] = $filesize - 1;
1972 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1973 //invalid byte-range ==> ignore header
1974 $ranges = false;
1975 break;
1977 //prepare multipart header
1978 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1979 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1981 } else {
1982 $ranges = false;
1984 if ($ranges) {
1985 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1988 } else {
1989 /// Do not byteserve (disabled, strings, text and html files).
1990 header('Accept-Ranges: none');
1992 } else { // Do not cache files in proxies and browsers
1993 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1994 header('Cache-Control: max-age=10');
1995 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1996 header('Pragma: ');
1997 } else { //normal http - prevent caching at all cost
1998 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1999 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2000 header('Pragma: no-cache');
2002 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
2005 if (empty($filter)) {
2006 $filtered = false;
2007 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
2008 //cookieless mode - rewrite links
2009 header('Content-Type: text/html');
2010 $text = $stored_file->get_content();
2011 $text = sid_ob_rewrite($text);
2012 $filesize = strlen($text);
2013 $filtered = true;
2014 } else if ($mimetype == 'text/plain') {
2015 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
2016 } else {
2017 header('Content-Type: '.$mimetype);
2019 header('Content-Length: '.$filesize);
2021 //flush the buffers - save memory and disable sid rewrite
2022 //this also disables zlib compression
2023 prepare_file_content_sending();
2025 // send the contents
2026 if ($filtered) {
2027 echo $text;
2028 } else {
2029 $stored_file->readfile();
2032 } else { // Try to put the file through filters
2033 if ($mimetype == 'text/html') {
2034 $options = new stdClass();
2035 $options->noclean = true;
2036 $options->nocache = true; // temporary workaround for MDL-5136
2037 $text = $stored_file->get_content();
2038 $text = file_modify_html_header($text);
2039 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2040 if (!empty($CFG->usesid)) {
2041 //cookieless mode - rewrite links
2042 $output = sid_ob_rewrite($output);
2045 header('Content-Length: '.strlen($output));
2046 header('Content-Type: text/html');
2048 //flush the buffers - save memory and disable sid rewrite
2049 //this also disables zlib compression
2050 prepare_file_content_sending();
2052 // send the contents
2053 echo $output;
2055 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2056 // only filter text if filter all files is selected
2057 $options = new stdClass();
2058 $options->newlines = false;
2059 $options->noclean = true;
2060 $text = $stored_file->get_content();
2061 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2062 if (!empty($CFG->usesid)) {
2063 //cookieless mode - rewrite links
2064 $output = sid_ob_rewrite($output);
2067 header('Content-Length: '.strlen($output));
2068 header('Content-Type: text/html; charset=utf-8'); //add encoding
2070 //flush the buffers - save memory and disable sid rewrite
2071 //this also disables zlib compression
2072 prepare_file_content_sending();
2074 // send the contents
2075 echo $output;
2077 } else { // Just send it out raw
2078 header('Content-Length: '.$filesize);
2079 header('Content-Type: '.$mimetype);
2081 //flush the buffers - save memory and disable sid rewrite
2082 //this also disables zlib compression
2083 prepare_file_content_sending();
2085 // send the contents
2086 $stored_file->readfile();
2089 if ($dontdie) {
2090 return;
2092 die; //no more chars to output!!!
2096 * Retrieves an array of records from a CSV file and places
2097 * them into a given table structure
2099 * @global object
2100 * @global object
2101 * @param string $file The path to a CSV file
2102 * @param string $table The table to retrieve columns from
2103 * @return bool|array Returns an array of CSV records or false
2105 function get_records_csv($file, $table) {
2106 global $CFG, $DB;
2108 if (!$metacolumns = $DB->get_columns($table)) {
2109 return false;
2112 if(!($handle = @fopen($file, 'r'))) {
2113 print_error('get_records_csv failed to open '.$file);
2116 $fieldnames = fgetcsv($handle, 4096);
2117 if(empty($fieldnames)) {
2118 fclose($handle);
2119 return false;
2122 $columns = array();
2124 foreach($metacolumns as $metacolumn) {
2125 $ord = array_search($metacolumn->name, $fieldnames);
2126 if(is_int($ord)) {
2127 $columns[$metacolumn->name] = $ord;
2131 $rows = array();
2133 while (($data = fgetcsv($handle, 4096)) !== false) {
2134 $item = new stdClass;
2135 foreach($columns as $name => $ord) {
2136 $item->$name = $data[$ord];
2138 $rows[] = $item;
2141 fclose($handle);
2142 return $rows;
2147 * @global object
2148 * @global object
2149 * @param string $file The file to put the CSV content into
2150 * @param array $records An array of records to write to a CSV file
2151 * @param string $table The table to get columns from
2152 * @return bool success
2154 function put_records_csv($file, $records, $table = NULL) {
2155 global $CFG, $DB;
2157 if (empty($records)) {
2158 return true;
2161 $metacolumns = NULL;
2162 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2163 return false;
2166 echo "x";
2168 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
2169 print_error('put_records_csv failed to open '.$file);
2172 $proto = reset($records);
2173 if(is_object($proto)) {
2174 $fields_records = array_keys(get_object_vars($proto));
2176 else if(is_array($proto)) {
2177 $fields_records = array_keys($proto);
2179 else {
2180 return false;
2182 echo "x";
2184 if(!empty($metacolumns)) {
2185 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2186 $fields = array_intersect($fields_records, $fields_table);
2188 else {
2189 $fields = $fields_records;
2192 fwrite($fp, implode(',', $fields));
2193 fwrite($fp, "\r\n");
2195 foreach($records as $record) {
2196 $array = (array)$record;
2197 $values = array();
2198 foreach($fields as $field) {
2199 if(strpos($array[$field], ',')) {
2200 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2202 else {
2203 $values[] = $array[$field];
2206 fwrite($fp, implode(',', $values)."\r\n");
2209 fclose($fp);
2210 return true;
2215 * Recursively delete the file or folder with path $location. That is,
2216 * if it is a file delete it. If it is a folder, delete all its content
2217 * then delete it. If $location does not exist to start, that is not
2218 * considered an error.
2220 * @param string $location the path to remove.
2221 * @return bool
2223 function fulldelete($location) {
2224 if (empty($location)) {
2225 // extra safety against wrong param
2226 return false;
2228 if (is_dir($location)) {
2229 $currdir = opendir($location);
2230 while (false !== ($file = readdir($currdir))) {
2231 if ($file <> ".." && $file <> ".") {
2232 $fullfile = $location."/".$file;
2233 if (is_dir($fullfile)) {
2234 if (!fulldelete($fullfile)) {
2235 return false;
2237 } else {
2238 if (!unlink($fullfile)) {
2239 return false;
2244 closedir($currdir);
2245 if (! rmdir($location)) {
2246 return false;
2249 } else if (file_exists($location)) {
2250 if (!unlink($location)) {
2251 return false;
2254 return true;
2258 * Send requested byterange of file.
2260 * @param object $handle A file handle
2261 * @param string $mimetype The mimetype for the output
2262 * @param array $ranges An array of ranges to send
2263 * @param string $filesize The size of the content if only one range is used
2265 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2266 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2267 if ($handle === false) {
2268 die;
2270 if (count($ranges) == 1) { //only one range requested
2271 $length = $ranges[0][2] - $ranges[0][1] + 1;
2272 header('HTTP/1.1 206 Partial content');
2273 header('Content-Length: '.$length);
2274 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2275 header('Content-Type: '.$mimetype);
2277 //flush the buffers - save memory and disable sid rewrite
2278 //this also disables zlib compression
2279 prepare_file_content_sending();
2281 $buffer = '';
2282 fseek($handle, $ranges[0][1]);
2283 while (!feof($handle) && $length > 0) {
2284 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2285 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2286 echo $buffer;
2287 flush();
2288 $length -= strlen($buffer);
2290 fclose($handle);
2291 die;
2292 } else { // multiple ranges requested - not tested much
2293 $totallength = 0;
2294 foreach($ranges as $range) {
2295 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2297 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2298 header('HTTP/1.1 206 Partial content');
2299 header('Content-Length: '.$totallength);
2300 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2301 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2303 //flush the buffers - save memory and disable sid rewrite
2304 //this also disables zlib compression
2305 prepare_file_content_sending();
2307 foreach($ranges as $range) {
2308 $length = $range[2] - $range[1] + 1;
2309 echo $range[0];
2310 $buffer = '';
2311 fseek($handle, $range[1]);
2312 while (!feof($handle) && $length > 0) {
2313 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2314 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2315 echo $buffer;
2316 flush();
2317 $length -= strlen($buffer);
2320 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2321 fclose($handle);
2322 die;
2327 * add includes (js and css) into uploaded files
2328 * before returning them, useful for themes and utf.js includes
2330 * @global object
2331 * @param string $text text to search and replace
2332 * @return string text with added head includes
2334 function file_modify_html_header($text) {
2335 // first look for <head> tag
2336 global $CFG;
2338 $stylesheetshtml = '';
2339 /* foreach ($CFG->stylesheets as $stylesheet) {
2340 //TODO: MDL-21120
2341 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2344 $ufo = '';
2345 if (filter_is_enabled('filter/mediaplugin')) {
2346 // this script is needed by most media filter plugins.
2347 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2348 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2351 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2352 if ($matches) {
2353 $replacement = '<head>'.$ufo.$stylesheetshtml;
2354 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2355 return $text;
2358 // if not, look for <html> tag, and stick <head> right after
2359 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2360 if ($matches) {
2361 // replace <html> tag with <html><head>includes</head>
2362 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2363 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2364 return $text;
2367 // if not, look for <body> tag, and stick <head> before body
2368 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2369 if ($matches) {
2370 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2371 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2372 return $text;
2375 // if not, just stick a <head> tag at the beginning
2376 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2377 return $text;
2381 * RESTful cURL class
2383 * This is a wrapper class for curl, it is quite easy to use:
2384 * <code>
2385 * $c = new curl;
2386 * // enable cache
2387 * $c = new curl(array('cache'=>true));
2388 * // enable cookie
2389 * $c = new curl(array('cookie'=>true));
2390 * // enable proxy
2391 * $c = new curl(array('proxy'=>true));
2393 * // HTTP GET Method
2394 * $html = $c->get('http://example.com');
2395 * // HTTP POST Method
2396 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2397 * // HTTP PUT Method
2398 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2399 * </code>
2401 * @package core
2402 * @subpackage file
2403 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2404 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2407 class curl {
2408 /** @var bool */
2409 public $cache = false;
2410 public $proxy = false;
2411 /** @var string */
2412 public $version = '0.4 dev';
2413 /** @var array */
2414 public $response = array();
2415 public $header = array();
2416 /** @var string */
2417 public $info;
2418 public $error;
2420 /** @var array */
2421 private $options;
2422 /** @var string */
2423 private $proxy_host = '';
2424 private $proxy_auth = '';
2425 private $proxy_type = '';
2426 /** @var bool */
2427 private $debug = false;
2428 private $cookie = false;
2431 * @global object
2432 * @param array $options
2434 public function __construct($options = array()){
2435 global $CFG;
2436 if (!function_exists('curl_init')) {
2437 $this->error = 'cURL module must be enabled!';
2438 trigger_error($this->error, E_USER_ERROR);
2439 return false;
2441 // the options of curl should be init here.
2442 $this->resetopt();
2443 if (!empty($options['debug'])) {
2444 $this->debug = true;
2446 if(!empty($options['cookie'])) {
2447 if($options['cookie'] === true) {
2448 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2449 } else {
2450 $this->cookie = $options['cookie'];
2453 if (!empty($options['cache'])) {
2454 if (class_exists('curl_cache')) {
2455 if (!empty($options['module_cache'])) {
2456 $this->cache = new curl_cache($options['module_cache']);
2457 } else {
2458 $this->cache = new curl_cache('misc');
2462 if (!empty($CFG->proxyhost)) {
2463 if (empty($CFG->proxyport)) {
2464 $this->proxy_host = $CFG->proxyhost;
2465 } else {
2466 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2468 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2469 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2470 $this->setopt(array(
2471 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2472 'proxyuserpwd'=>$this->proxy_auth));
2474 if (!empty($CFG->proxytype)) {
2475 if ($CFG->proxytype == 'SOCKS5') {
2476 $this->proxy_type = CURLPROXY_SOCKS5;
2477 } else {
2478 $this->proxy_type = CURLPROXY_HTTP;
2479 $this->setopt(array('httpproxytunnel'=>false));
2481 $this->setopt(array('proxytype'=>$this->proxy_type));
2484 if (!empty($this->proxy_host)) {
2485 $this->proxy = array('proxy'=>$this->proxy_host);
2489 * Resets the CURL options that have already been set
2491 public function resetopt(){
2492 $this->options = array();
2493 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2494 // True to include the header in the output
2495 $this->options['CURLOPT_HEADER'] = 0;
2496 // True to Exclude the body from the output
2497 $this->options['CURLOPT_NOBODY'] = 0;
2498 // TRUE to follow any "Location: " header that the server
2499 // sends as part of the HTTP header (note this is recursive,
2500 // PHP will follow as many "Location: " headers that it is sent,
2501 // unless CURLOPT_MAXREDIRS is set).
2502 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2503 $this->options['CURLOPT_MAXREDIRS'] = 10;
2504 $this->options['CURLOPT_ENCODING'] = '';
2505 // TRUE to return the transfer as a string of the return
2506 // value of curl_exec() instead of outputting it out directly.
2507 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2508 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2509 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2510 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2511 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2515 * Reset Cookie
2517 public function resetcookie() {
2518 if (!empty($this->cookie)) {
2519 if (is_file($this->cookie)) {
2520 $fp = fopen($this->cookie, 'w');
2521 if (!empty($fp)) {
2522 fwrite($fp, '');
2523 fclose($fp);
2530 * Set curl options
2532 * @param array $options If array is null, this function will
2533 * reset the options to default value.
2536 public function setopt($options = array()) {
2537 if (is_array($options)) {
2538 foreach($options as $name => $val){
2539 if (stripos($name, 'CURLOPT_') === false) {
2540 $name = strtoupper('CURLOPT_'.$name);
2542 $this->options[$name] = $val;
2547 * Reset http method
2550 public function cleanopt(){
2551 unset($this->options['CURLOPT_HTTPGET']);
2552 unset($this->options['CURLOPT_POST']);
2553 unset($this->options['CURLOPT_POSTFIELDS']);
2554 unset($this->options['CURLOPT_PUT']);
2555 unset($this->options['CURLOPT_INFILE']);
2556 unset($this->options['CURLOPT_INFILESIZE']);
2557 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2561 * Set HTTP Request Header
2563 * @param array $headers
2566 public function setHeader($header) {
2567 if (is_array($header)){
2568 foreach ($header as $v) {
2569 $this->setHeader($v);
2571 } else {
2572 $this->header[] = $header;
2576 * Set HTTP Response Header
2579 public function getResponse(){
2580 return $this->response;
2583 * private callback function
2584 * Formatting HTTP Response Header
2586 * @param mixed $ch Apparently not used
2587 * @param string $header
2588 * @return int The strlen of the header
2590 private function formatHeader($ch, $header)
2592 $this->count++;
2593 if (strlen($header) > 2) {
2594 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2595 $key = rtrim($key, ':');
2596 if (!empty($this->response[$key])) {
2597 if (is_array($this->response[$key])){
2598 $this->response[$key][] = $value;
2599 } else {
2600 $tmp = $this->response[$key];
2601 $this->response[$key] = array();
2602 $this->response[$key][] = $tmp;
2603 $this->response[$key][] = $value;
2606 } else {
2607 $this->response[$key] = $value;
2610 return strlen($header);
2614 * Set options for individual curl instance
2616 * @param object $curl A curl handle
2617 * @param array $options
2618 * @return object The curl handle
2620 private function apply_opt($curl, $options) {
2621 // Clean up
2622 $this->cleanopt();
2623 // set cookie
2624 if (!empty($this->cookie) || !empty($options['cookie'])) {
2625 $this->setopt(array('cookiejar'=>$this->cookie,
2626 'cookiefile'=>$this->cookie
2630 // set proxy
2631 if (!empty($this->proxy) || !empty($options['proxy'])) {
2632 $this->setopt($this->proxy);
2634 $this->setopt($options);
2635 // reset before set options
2636 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2637 // set headers
2638 if (empty($this->header)){
2639 $this->setHeader(array(
2640 'User-Agent: MoodleBot/1.0',
2641 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2642 'Connection: keep-alive'
2645 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2647 if ($this->debug){
2648 echo '<h1>Options</h1>';
2649 var_dump($this->options);
2650 echo '<h1>Header</h1>';
2651 var_dump($this->header);
2654 // set options
2655 foreach($this->options as $name => $val) {
2656 if (is_string($name)) {
2657 $name = constant(strtoupper($name));
2659 curl_setopt($curl, $name, $val);
2661 return $curl;
2664 * Download multiple files in parallel
2666 * Calls {@link multi()} with specific download headers
2668 * <code>
2669 * $c = new curl;
2670 * $c->download(array(
2671 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2672 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2673 * ));
2674 * </code>
2676 * @param array $requests An array of files to request
2677 * @param array $options An array of options to set
2678 * @return array An array of results
2680 public function download($requests, $options = array()) {
2681 $options['CURLOPT_BINARYTRANSFER'] = 1;
2682 $options['RETURNTRANSFER'] = false;
2683 return $this->multi($requests, $options);
2686 * Mulit HTTP Requests
2687 * This function could run multi-requests in parallel.
2689 * @param array $requests An array of files to request
2690 * @param array $options An array of options to set
2691 * @return array An array of results
2693 protected function multi($requests, $options = array()) {
2694 $count = count($requests);
2695 $handles = array();
2696 $results = array();
2697 $main = curl_multi_init();
2698 for ($i = 0; $i < $count; $i++) {
2699 $url = $requests[$i];
2700 foreach($url as $n=>$v){
2701 $options[$n] = $url[$n];
2703 $handles[$i] = curl_init($url['url']);
2704 $this->apply_opt($handles[$i], $options);
2705 curl_multi_add_handle($main, $handles[$i]);
2707 $running = 0;
2708 do {
2709 curl_multi_exec($main, $running);
2710 } while($running > 0);
2711 for ($i = 0; $i < $count; $i++) {
2712 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
2713 $results[] = true;
2714 } else {
2715 $results[] = curl_multi_getcontent($handles[$i]);
2717 curl_multi_remove_handle($main, $handles[$i]);
2719 curl_multi_close($main);
2720 return $results;
2723 * Single HTTP Request
2725 * @param string $url The URL to request
2726 * @param array $options
2727 * @return bool
2729 protected function request($url, $options = array()){
2730 // create curl instance
2731 $curl = curl_init($url);
2732 $options['url'] = $url;
2733 $this->apply_opt($curl, $options);
2734 if ($this->cache && $ret = $this->cache->get($this->options)) {
2735 return $ret;
2736 } else {
2737 $ret = curl_exec($curl);
2738 if ($this->cache) {
2739 $this->cache->set($this->options, $ret);
2743 $this->info = curl_getinfo($curl);
2744 $this->error = curl_error($curl);
2746 if ($this->debug){
2747 echo '<h1>Return Data</h1>';
2748 var_dump($ret);
2749 echo '<h1>Info</h1>';
2750 var_dump($this->info);
2751 echo '<h1>Error</h1>';
2752 var_dump($this->error);
2755 curl_close($curl);
2757 if (empty($this->error)){
2758 return $ret;
2759 } else {
2760 return $this->error;
2761 // exception is not ajax friendly
2762 //throw new moodle_exception($this->error, 'curl');
2767 * HTTP HEAD method
2769 * @see request()
2771 * @param string $url
2772 * @param array $options
2773 * @return bool
2775 public function head($url, $options = array()){
2776 $options['CURLOPT_HTTPGET'] = 0;
2777 $options['CURLOPT_HEADER'] = 1;
2778 $options['CURLOPT_NOBODY'] = 1;
2779 return $this->request($url, $options);
2783 * HTTP POST method
2785 * @param string $url
2786 * @param array|string $params
2787 * @param array $options
2788 * @return bool
2790 public function post($url, $params = '', $options = array()){
2791 $options['CURLOPT_POST'] = 1;
2792 if (is_array($params)) {
2793 $this->_tmp_file_post_params = array();
2794 foreach ($params as $key => $value) {
2795 if ($value instanceof stored_file) {
2796 $value->add_to_curl_request($this, $key);
2797 } else {
2798 $this->_tmp_file_post_params[$key] = $value;
2801 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2802 unset($this->_tmp_file_post_params);
2803 } else {
2804 // $params is the raw post data
2805 $options['CURLOPT_POSTFIELDS'] = $params;
2807 return $this->request($url, $options);
2811 * HTTP GET method
2813 * @param string $url
2814 * @param array $params
2815 * @param array $options
2816 * @return bool
2818 public function get($url, $params = array(), $options = array()){
2819 $options['CURLOPT_HTTPGET'] = 1;
2821 if (!empty($params)){
2822 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2823 $url .= http_build_query($params, '', '&');
2825 return $this->request($url, $options);
2829 * HTTP PUT method
2831 * @param string $url
2832 * @param array $params
2833 * @param array $options
2834 * @return bool
2836 public function put($url, $params = array(), $options = array()){
2837 $file = $params['file'];
2838 if (!is_file($file)){
2839 return null;
2841 $fp = fopen($file, 'r');
2842 $size = filesize($file);
2843 $options['CURLOPT_PUT'] = 1;
2844 $options['CURLOPT_INFILESIZE'] = $size;
2845 $options['CURLOPT_INFILE'] = $fp;
2846 if (!isset($this->options['CURLOPT_USERPWD'])){
2847 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2849 $ret = $this->request($url, $options);
2850 fclose($fp);
2851 return $ret;
2855 * HTTP DELETE method
2857 * @param string $url
2858 * @param array $params
2859 * @param array $options
2860 * @return bool
2862 public function delete($url, $param = array(), $options = array()){
2863 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2864 if (!isset($options['CURLOPT_USERPWD'])) {
2865 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2867 $ret = $this->request($url, $options);
2868 return $ret;
2871 * HTTP TRACE method
2873 * @param string $url
2874 * @param array $options
2875 * @return bool
2877 public function trace($url, $options = array()){
2878 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2879 $ret = $this->request($url, $options);
2880 return $ret;
2883 * HTTP OPTIONS method
2885 * @param string $url
2886 * @param array $options
2887 * @return bool
2889 public function options($url, $options = array()){
2890 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2891 $ret = $this->request($url, $options);
2892 return $ret;
2894 public function get_info() {
2895 return $this->info;
2900 * This class is used by cURL class, use case:
2902 * <code>
2903 * $CFG->repositorycacheexpire = 120;
2904 * $CFG->curlcache = 120;
2906 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2907 * $ret = $c->get('http://www.google.com');
2908 * </code>
2910 * @package core
2911 * @subpackage file
2912 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2915 class curl_cache {
2916 /** @var string */
2917 public $dir = '';
2920 * @global object
2921 * @param string @module which module is using curl_cache
2924 function __construct($module = 'repository'){
2925 global $CFG;
2926 if (!empty($module)) {
2927 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2928 } else {
2929 $this->dir = $CFG->dataroot.'/cache/misc/';
2931 if (!file_exists($this->dir)) {
2932 mkdir($this->dir, $CFG->directorypermissions, true);
2934 if ($module == 'repository') {
2935 if (empty($CFG->repositorycacheexpire)) {
2936 $CFG->repositorycacheexpire = 120;
2938 $this->ttl = $CFG->repositorycacheexpire;
2939 } else {
2940 if (empty($CFG->curlcache)) {
2941 $CFG->curlcache = 120;
2943 $this->ttl = $CFG->curlcache;
2948 * Get cached value
2950 * @global object
2951 * @global object
2952 * @param mixed $param
2953 * @return bool|string
2955 public function get($param){
2956 global $CFG, $USER;
2957 $this->cleanup($this->ttl);
2958 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2959 if(file_exists($this->dir.$filename)) {
2960 $lasttime = filemtime($this->dir.$filename);
2961 if(time()-$lasttime > $this->ttl)
2963 return false;
2964 } else {
2965 $fp = fopen($this->dir.$filename, 'r');
2966 $size = filesize($this->dir.$filename);
2967 $content = fread($fp, $size);
2968 return unserialize($content);
2971 return false;
2975 * Set cache value
2977 * @global object $CFG
2978 * @global object $USER
2979 * @param mixed $param
2980 * @param mixed $val
2982 public function set($param, $val){
2983 global $CFG, $USER;
2984 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2985 $fp = fopen($this->dir.$filename, 'w');
2986 fwrite($fp, serialize($val));
2987 fclose($fp);
2991 * Remove cache files
2993 * @param int $expire The number os seconds before expiry
2995 public function cleanup($expire){
2996 if($dir = opendir($this->dir)){
2997 while (false !== ($file = readdir($dir))) {
2998 if(!is_dir($file) && $file != '.' && $file != '..') {
2999 $lasttime = @filemtime($this->dir.$file);
3000 if(time() - $lasttime > $expire){
3001 @unlink($this->dir.$file);
3008 * delete current user's cache file
3010 * @global object $CFG
3011 * @global object $USER
3013 public function refresh(){
3014 global $CFG, $USER;
3015 if($dir = opendir($this->dir)){
3016 while (false !== ($file = readdir($dir))) {
3017 if(!is_dir($file) && $file != '.' && $file != '..') {
3018 if(strpos($file, 'u'.$USER->id.'_')!==false){
3019 @unlink($this->dir.$file);
3028 * This class is used to parse lib/file/file_types.mm which help get file
3029 * extensions by file types.
3030 * The file_types.mm file can be edited by freemind in graphic environment.
3032 * @package core
3033 * @subpackage file
3034 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
3035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3037 class filetype_parser {
3039 * Check file_types.mm file, setup variables
3041 * @global object $CFG
3042 * @param string $file
3044 public function __construct($file = '') {
3045 global $CFG;
3046 if (empty($file)) {
3047 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
3048 } else {
3049 $this->file = $file;
3051 $this->tree = array();
3052 $this->result = array();
3056 * A private function to browse xml nodes
3058 * @param array $parent
3059 * @param array $types
3061 private function _browse_nodes($parent, $types) {
3062 $key = (string)$parent['TEXT'];
3063 if(isset($parent->node)) {
3064 $this->tree[$key] = array();
3065 if (in_array((string)$parent['TEXT'], $types)) {
3066 $this->_select_nodes($parent, $this->result);
3067 } else {
3068 foreach($parent->node as $v){
3069 $this->_browse_nodes($v, $types);
3072 } else {
3073 $this->tree[] = $key;
3078 * A private function to select text nodes
3080 * @param array $parent
3082 private function _select_nodes($parent){
3083 if(isset($parent->node)) {
3084 foreach($parent->node as $v){
3085 $this->_select_nodes($v, $this->result);
3087 } else {
3088 $this->result[] = (string)$parent['TEXT'];
3094 * Get file extensions by file types names.
3096 * @param array $types
3097 * @return mixed
3099 public function get_extensions($types) {
3100 if (!is_array($types)) {
3101 $types = array($types);
3103 $this->result = array();
3104 if ((is_array($types) && in_array('*', $types)) ||
3105 $types == '*' || empty($types)) {
3106 return array('*');
3108 foreach ($types as $key=>$value){
3109 if (strpos($value, '.') !== false) {
3110 $this->result[] = $value;
3111 unset($types[$key]);
3114 if (file_exists($this->file)) {
3115 $xml = simplexml_load_file($this->file);
3116 foreach($xml->node->node as $v){
3117 if (in_array((string)$v['TEXT'], $types)) {
3118 $this->_select_nodes($v);
3119 } else {
3120 $this->_browse_nodes($v, $types);
3123 } else {
3124 exit('Failed to open file lib/filestorage/file_types.mm');
3126 return $this->result;