MDL-55707 grades: Stop infinite loop when regrading.
[moodle.git] / lib / filelib.php
blobe2f19c94fe07304881b74b5c2cdaca6714d57b7a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for file handling.
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 /**
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
42 /**
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56 global $CFG;
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
65 if ($forcedownload) {
66 $return .= '?forcedownload=1';
68 } else {
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
71 if ($forcedownload) {
72 $return .= '&amp;forcedownload=1';
76 if ($https) {
77 $return = str_replace('http://', 'https://', $return);
80 return $return;
83 /**
84 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
92 * @return bool
94 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
95 global $DB;
97 if (!isset($itemid)) {
98 // Not initialised yet.
99 return false;
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
114 * displayed.
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
118 * @category files
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id != $context->id) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
161 $contextid = null;
162 $itemid = null;
163 if (!isset($data)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
176 } else {
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
183 } else {
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
195 } else {
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
199 return $data;
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
213 * @category files
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
241 if ($options['trusttext']) {
242 $data->{$field.'trust'} = trusttext_trusted($context);
243 } else {
244 $data->{$field.'trust'} = 0;
247 $editor = $data->{$field.'_editor'};
249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
250 $data->{$field} = $editor['text'];
251 } else {
252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
254 $data->{$field.'format'} = $editor['format'];
256 return $data;
260 * Saves text and files modified by Editor formslib element
262 * @category files
263 * @param stdClass $data $database entry field
264 * @param string $field name of data field
265 * @param array $options various options
266 * @param stdClass $context context - must already exist
267 * @param string $component
268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
270 * @return stdClass modified data obejct
272 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
277 if (is_null($itemid) or is_null($context)) {
278 $itemid = null;
279 $contextid = null;
280 } else {
281 $contextid = $context->id;
284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
286 $data->{$field.'_filemanager'} = $draftid_editor;
288 return $data;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
295 * @category files
296 * @param stdClass $data $database entry field
297 * @param string $field name of data field
298 * @param array $options various options
299 * @param stdClass $context context - must already exist
300 * @param string $component
301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
303 * @return stdClass modified data obejct
305 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
317 if (empty($data->{$field.'_filemanager'})) {
318 $data->$field = '';
320 } else {
321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
322 $fs = get_file_storage();
324 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
326 } else {
327 $data->$field = '';
331 return $data;
335 * Generate a draft itemid
337 * @category files
338 * @global moodle_database $DB
339 * @global stdClass $USER
340 * @return int a random but available draft itemid that can be used to create a new draft
341 * file area.
343 function file_get_unused_draft_itemid() {
344 global $DB, $USER;
346 if (isguestuser() or !isloggedin()) {
347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
348 print_error('noguest');
351 $contextid = context_user::instance($USER->id)->id;
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
356 $draftitemid = rand(1, 999999999);
359 return $draftitemid;
363 * Initialise a draft file area from a real one by copying the files. A draft
364 * area will be created if one does not already exist. Normally you should
365 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
367 * @category files
368 * @global stdClass $CFG
369 * @global stdClass $USER
370 * @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.
371 * @param int $contextid This parameter and the next two identify the file area to copy files from.
372 * @param string $component
373 * @param string $filearea helps indentify the file area.
374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
379 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
380 global $CFG, $USER, $CFG;
382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
386 if (!isset($options['forcehttps'])) {
387 $options['forcehttps'] = false;
390 $usercontext = context_user::instance($USER->id);
391 $fs = get_file_storage();
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
395 $draftitemid = file_get_unused_draft_itemid();
396 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
397 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
398 foreach ($files as $file) {
399 if ($file->is_directory() and $file->get_filepath() === '/') {
400 // we need a way to mark the age of each draft area,
401 // by not copying the root dir we force it to be created automatically with current timestamp
402 continue;
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
405 continue;
407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
408 // XXX: This is a hack for file manager (MDL-28666)
409 // File manager needs to know the original file information before copying
410 // to draft area, so we append these information in mdl_files.source field
411 // {@link file_storage::search_references()}
412 // {@link file_storage::search_references_count()}
413 $sourcefield = $file->get_source();
414 $newsourcefield = new stdClass;
415 $newsourcefield->source = $sourcefield;
416 $original = new stdClass;
417 $original->contextid = $contextid;
418 $original->component = $component;
419 $original->filearea = $filearea;
420 $original->itemid = $itemid;
421 $original->filename = $file->get_filename();
422 $original->filepath = $file->get_filepath();
423 $newsourcefield->original = file_storage::pack_reference($original);
424 $draftfile->set_source(serialize($newsourcefield));
425 // End of file manager hack
428 if (!is_null($text)) {
429 // at this point there should not be any draftfile links yet,
430 // because this is a new text from database that should still contain the @@pluginfile@@ links
431 // this happens when developers forget to post process the text
432 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
434 } else {
435 // nothing to do
438 if (is_null($text)) {
439 return null;
442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
448 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
449 * in the @@PLUGINFILE@@ form.
451 * @category files
452 * @global stdClass $CFG
453 * @param string $text The content that may contain ULRs in need of rewriting.
454 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
455 * @param int $contextid This parameter and the next two identify the file area to use.
456 * @param string $component
457 * @param string $filearea helps identify the file area.
458 * @param int $itemid helps identify the file area.
459 * @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function.
460 * @return string the processed text.
462 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
463 global $CFG;
465 $options = (array)$options;
466 if (!isset($options['forcehttps'])) {
467 $options['forcehttps'] = false;
470 if (!$CFG->slasharguments) {
471 $file = $file . '?file=';
474 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
476 if ($itemid !== null) {
477 $baseurl .= "$itemid/";
480 if ($options['forcehttps']) {
481 $baseurl = str_replace('http://', 'https://', $baseurl);
484 if (!empty($options['reverse'])) {
485 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
486 } else {
487 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
492 * Returns information about files in a draft area.
494 * @global stdClass $CFG
495 * @global stdClass $USER
496 * @param int $draftitemid the draft area item id.
497 * @param string $filepath path to the directory from which the information have to be retrieved.
498 * @return array with the following entries:
499 * 'filecount' => number of files in the draft area.
500 * 'filesize' => total size of the files in the draft area.
501 * 'foldercount' => number of folders in the draft area.
502 * 'filesize_without_references' => total size of the area excluding file references.
503 * (more information will be added as needed).
505 function file_get_draft_area_info($draftitemid, $filepath = '/') {
506 global $CFG, $USER;
508 $usercontext = context_user::instance($USER->id);
509 $fs = get_file_storage();
511 $results = array(
512 'filecount' => 0,
513 'foldercount' => 0,
514 'filesize' => 0,
515 'filesize_without_references' => 0
518 if ($filepath != '/') {
519 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
520 } else {
521 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
523 foreach ($draftfiles as $file) {
524 if ($file->is_directory()) {
525 $results['foldercount'] += 1;
526 } else {
527 $results['filecount'] += 1;
530 $filesize = $file->get_filesize();
531 $results['filesize'] += $filesize;
532 if (!$file->is_external_file()) {
533 $results['filesize_without_references'] += $filesize;
537 return $results;
541 * Returns whether a draft area has exceeded/will exceed its size limit.
543 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
545 * @param int $draftitemid the draft area item id.
546 * @param int $areamaxbytes the maximum size allowed in this draft area.
547 * @param int $newfilesize the size that would be added to the current area.
548 * @param bool $includereferences true to include the size of the references in the area size.
549 * @return bool true if the area will/has exceeded its limit.
550 * @since Moodle 2.4
552 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
553 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
554 $draftinfo = file_get_draft_area_info($draftitemid);
555 $areasize = $draftinfo['filesize_without_references'];
556 if ($includereferences) {
557 $areasize = $draftinfo['filesize'];
559 if ($areasize + $newfilesize > $areamaxbytes) {
560 return true;
563 return false;
567 * Get used space of files
568 * @global moodle_database $DB
569 * @global stdClass $USER
570 * @return int total bytes
572 function file_get_user_used_space() {
573 global $DB, $USER;
575 $usercontext = context_user::instance($USER->id);
576 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
577 JOIN (SELECT contenthash, filename, MAX(id) AS id
578 FROM {files}
579 WHERE contextid = ? AND component = ? AND filearea != ?
580 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
581 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
582 $record = $DB->get_record_sql($sql, $params);
583 return (int)$record->totalbytes;
587 * Convert any string to a valid filepath
588 * @todo review this function
589 * @param string $str
590 * @return string path
592 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
593 if ($str == '/' or empty($str)) {
594 return '/';
595 } else {
596 return '/'.trim($str, '/').'/';
601 * Generate a folder tree of draft area of current USER recursively
603 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
604 * @param int $draftitemid
605 * @param string $filepath
606 * @param mixed $data
608 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
609 global $USER, $OUTPUT, $CFG;
610 $data->children = array();
611 $context = context_user::instance($USER->id);
612 $fs = get_file_storage();
613 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
614 foreach ($files as $file) {
615 if ($file->is_directory()) {
616 $item = new stdClass();
617 $item->sortorder = $file->get_sortorder();
618 $item->filepath = $file->get_filepath();
620 $foldername = explode('/', trim($item->filepath, '/'));
621 $item->fullname = trim(array_pop($foldername), '/');
623 $item->id = uniqid();
624 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
625 $data->children[] = $item;
626 } else {
627 continue;
634 * Listing all files (including folders) in current path (draft area)
635 * used by file manager
636 * @param int $draftitemid
637 * @param string $filepath
638 * @return stdClass
640 function file_get_drafarea_files($draftitemid, $filepath = '/') {
641 global $USER, $OUTPUT, $CFG;
643 $context = context_user::instance($USER->id);
644 $fs = get_file_storage();
646 $data = new stdClass();
647 $data->path = array();
648 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
650 // will be used to build breadcrumb
651 $trail = '/';
652 if ($filepath !== '/') {
653 $filepath = file_correct_filepath($filepath);
654 $parts = explode('/', $filepath);
655 foreach ($parts as $part) {
656 if ($part != '' && $part != null) {
657 $trail .= ($part.'/');
658 $data->path[] = array('name'=>$part, 'path'=>$trail);
663 $list = array();
664 $maxlength = 12;
665 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
666 foreach ($files as $file) {
667 $item = new stdClass();
668 $item->filename = $file->get_filename();
669 $item->filepath = $file->get_filepath();
670 $item->fullname = trim($item->filename, '/');
671 $filesize = $file->get_filesize();
672 $item->size = $filesize ? $filesize : null;
673 $item->filesize = $filesize ? display_size($filesize) : '';
675 $item->sortorder = $file->get_sortorder();
676 $item->author = $file->get_author();
677 $item->license = $file->get_license();
678 $item->datemodified = $file->get_timemodified();
679 $item->datecreated = $file->get_timecreated();
680 $item->isref = $file->is_external_file();
681 if ($item->isref && $file->get_status() == 666) {
682 $item->originalmissing = true;
684 // find the file this draft file was created from and count all references in local
685 // system pointing to that file
686 $source = @unserialize($file->get_source());
687 if (isset($source->original)) {
688 $item->refcount = $fs->search_references_count($source->original);
691 if ($file->is_directory()) {
692 $item->filesize = 0;
693 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
694 $item->type = 'folder';
695 $foldername = explode('/', trim($item->filepath, '/'));
696 $item->fullname = trim(array_pop($foldername), '/');
697 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
698 } else {
699 // do NOT use file browser here!
700 $item->mimetype = get_mimetype_description($file);
701 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
702 $item->type = 'zip';
703 } else {
704 $item->type = 'file';
706 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
707 $item->url = $itemurl->out();
708 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
709 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
710 if ($imageinfo = $file->get_imageinfo()) {
711 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
712 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
713 $item->image_width = $imageinfo['width'];
714 $item->image_height = $imageinfo['height'];
717 $list[] = $item;
720 $data->itemid = $draftitemid;
721 $data->list = $list;
722 return $data;
726 * Returns draft area itemid for a given element.
728 * @category files
729 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
730 * @return int the itemid, or 0 if there is not one yet.
732 function file_get_submitted_draft_itemid($elname) {
733 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
734 if (!isset($_REQUEST[$elname])) {
735 return 0;
737 if (is_array($_REQUEST[$elname])) {
738 $param = optional_param_array($elname, 0, PARAM_INT);
739 if (!empty($param['itemid'])) {
740 $param = $param['itemid'];
741 } else {
742 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
743 return false;
746 } else {
747 $param = optional_param($elname, 0, PARAM_INT);
750 if ($param) {
751 require_sesskey();
754 return $param;
758 * Restore the original source field from draft files
760 * Do not use this function because it makes field files.source inconsistent
761 * for draft area files. This function will be deprecated in 2.6
763 * @param stored_file $storedfile This only works with draft files
764 * @return stored_file
766 function file_restore_source_field_from_draft_file($storedfile) {
767 $source = @unserialize($storedfile->get_source());
768 if (!empty($source)) {
769 if (is_object($source)) {
770 $restoredsource = $source->source;
771 $storedfile->set_source($restoredsource);
772 } else {
773 throw new moodle_exception('invalidsourcefield', 'error');
776 return $storedfile;
779 * Saves files from a draft file area to a real one (merging the list of files).
780 * Can rewrite URLs in some content at the same time if desired.
782 * @category files
783 * @global stdClass $USER
784 * @param int $draftitemid the id of the draft area to use. Normally obtained
785 * from file_get_submitted_draft_itemid('elementname') or similar.
786 * @param int $contextid This parameter and the next two identify the file area to save to.
787 * @param string $component
788 * @param string $filearea indentifies the file area.
789 * @param int $itemid helps identifies the file area.
790 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
791 * @param string $text some html content that needs to have embedded links rewritten
792 * to the @@PLUGINFILE@@ form for saving in the database.
793 * @param bool $forcehttps force https urls.
794 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
796 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
797 global $USER;
799 $usercontext = context_user::instance($USER->id);
800 $fs = get_file_storage();
802 $options = (array)$options;
803 if (!isset($options['subdirs'])) {
804 $options['subdirs'] = false;
806 if (!isset($options['maxfiles'])) {
807 $options['maxfiles'] = -1; // unlimited
809 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
810 $options['maxbytes'] = 0; // unlimited
812 if (!isset($options['areamaxbytes'])) {
813 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
815 $allowreferences = true;
816 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
817 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
818 // this is not exactly right. BUT there are many places in code where filemanager options
819 // are not passed to file_save_draft_area_files()
820 $allowreferences = false;
823 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
824 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
825 // anything at all in the next area.
826 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
827 return null;
830 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
831 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
833 // One file in filearea means it is empty (it has only top-level directory '.').
834 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
835 // we have to merge old and new files - we want to keep file ids for files that were not changed
836 // we change time modified for all new and changed files, we keep time created as is
838 $newhashes = array();
839 $filecount = 0;
840 foreach ($draftfiles as $file) {
841 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
842 continue;
844 if (!$allowreferences && $file->is_external_file()) {
845 continue;
847 if (!$file->is_directory()) {
848 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
849 // oversized file - should not get here at all
850 continue;
852 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
853 // more files - should not get here at all
854 continue;
856 $filecount++;
858 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
859 $newhashes[$newhash] = $file;
862 // Loop through oldfiles and decide which we need to delete and which to update.
863 // After this cycle the array $newhashes will only contain the files that need to be added.
864 foreach ($oldfiles as $oldfile) {
865 $oldhash = $oldfile->get_pathnamehash();
866 if (!isset($newhashes[$oldhash])) {
867 // delete files not needed any more - deleted by user
868 $oldfile->delete();
869 continue;
872 $newfile = $newhashes[$oldhash];
873 // Now we know that we have $oldfile and $newfile for the same path.
874 // Let's check if we can update this file or we need to delete and create.
875 if ($newfile->is_directory()) {
876 // Directories are always ok to just update.
877 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
878 // File has the 'original' - we need to update the file (it may even have not been changed at all).
879 $original = file_storage::unpack_reference($source->original);
880 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
881 // Very odd, original points to another file. Delete and create file.
882 $oldfile->delete();
883 continue;
885 } else {
886 // The same file name but absence of 'original' means that file was deteled and uploaded again.
887 // By deleting and creating new file we properly manage all existing references.
888 $oldfile->delete();
889 continue;
892 // status changed, we delete old file, and create a new one
893 if ($oldfile->get_status() != $newfile->get_status()) {
894 // file was changed, use updated with new timemodified data
895 $oldfile->delete();
896 // This file will be added later
897 continue;
900 // Updated author
901 if ($oldfile->get_author() != $newfile->get_author()) {
902 $oldfile->set_author($newfile->get_author());
904 // Updated license
905 if ($oldfile->get_license() != $newfile->get_license()) {
906 $oldfile->set_license($newfile->get_license());
909 // Updated file source
910 // Field files.source for draftarea files contains serialised object with source and original information.
911 // We only store the source part of it for non-draft file area.
912 $newsource = $newfile->get_source();
913 if ($source = @unserialize($newfile->get_source())) {
914 $newsource = $source->source;
916 if ($oldfile->get_source() !== $newsource) {
917 $oldfile->set_source($newsource);
920 // Updated sort order
921 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
922 $oldfile->set_sortorder($newfile->get_sortorder());
925 // Update file timemodified
926 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
927 $oldfile->set_timemodified($newfile->get_timemodified());
930 // Replaced file content
931 if (!$oldfile->is_directory() &&
932 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
933 $oldfile->get_filesize() != $newfile->get_filesize() ||
934 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
935 $oldfile->get_userid() != $newfile->get_userid())) {
936 $oldfile->replace_file_with($newfile);
939 // unchanged file or directory - we keep it as is
940 unset($newhashes[$oldhash]);
943 // Add fresh file or the file which has changed status
944 // the size and subdirectory tests are extra safety only, the UI should prevent it
945 foreach ($newhashes as $file) {
946 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
947 if ($source = @unserialize($file->get_source())) {
948 // Field files.source for draftarea files contains serialised object with source and original information.
949 // We only store the source part of it for non-draft file area.
950 $file_record['source'] = $source->source;
953 if ($file->is_external_file()) {
954 $repoid = $file->get_repository_id();
955 if (!empty($repoid)) {
956 $file_record['repositoryid'] = $repoid;
957 $file_record['reference'] = $file->get_reference();
961 $fs->create_file_from_storedfile($file_record, $file);
965 // note: do not purge the draft area - we clean up areas later in cron,
966 // the reason is that user might press submit twice and they would loose the files,
967 // also sometimes we might want to use hacks that save files into two different areas
969 if (is_null($text)) {
970 return null;
971 } else {
972 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
977 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
978 * ready to be saved in the database. Normally, this is done automatically by
979 * {@link file_save_draft_area_files()}.
981 * @category files
982 * @param string $text the content to process.
983 * @param int $draftitemid the draft file area the content was using.
984 * @param bool $forcehttps whether the content contains https URLs. Default false.
985 * @return string the processed content.
987 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
988 global $CFG, $USER;
990 $usercontext = context_user::instance($USER->id);
992 $wwwroot = $CFG->wwwroot;
993 if ($forcehttps) {
994 $wwwroot = str_replace('http://', 'https://', $wwwroot);
997 // relink embedded files if text submitted - no absolute links allowed in database!
998 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1000 if (strpos($text, 'draftfile.php?file=') !== false) {
1001 $matches = array();
1002 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1003 if ($matches) {
1004 foreach ($matches[0] as $match) {
1005 $replace = str_ireplace('%2F', '/', $match);
1006 $text = str_replace($match, $replace, $text);
1009 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1012 return $text;
1016 * Set file sort order
1018 * @global moodle_database $DB
1019 * @param int $contextid the context id
1020 * @param string $component file component
1021 * @param string $filearea file area.
1022 * @param int $itemid itemid.
1023 * @param string $filepath file path.
1024 * @param string $filename file name.
1025 * @param int $sortorder the sort order of file.
1026 * @return bool
1028 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1029 global $DB;
1030 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1031 if ($file_record = $DB->get_record('files', $conditions)) {
1032 $sortorder = (int)$sortorder;
1033 $file_record->sortorder = $sortorder;
1034 $DB->update_record('files', $file_record);
1035 return true;
1037 return false;
1041 * reset file sort order number to 0
1042 * @global moodle_database $DB
1043 * @param int $contextid the context id
1044 * @param string $component
1045 * @param string $filearea file area.
1046 * @param int|bool $itemid itemid.
1047 * @return bool
1049 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1050 global $DB;
1052 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1053 if ($itemid !== false) {
1054 $conditions['itemid'] = $itemid;
1057 $file_records = $DB->get_records('files', $conditions);
1058 foreach ($file_records as $file_record) {
1059 $file_record->sortorder = 0;
1060 $DB->update_record('files', $file_record);
1062 return true;
1066 * Returns description of upload error
1068 * @param int $errorcode found in $_FILES['filename.ext']['error']
1069 * @return string error description string, '' if ok
1071 function file_get_upload_error($errorcode) {
1073 switch ($errorcode) {
1074 case 0: // UPLOAD_ERR_OK - no error
1075 $errmessage = '';
1076 break;
1078 case 1: // UPLOAD_ERR_INI_SIZE
1079 $errmessage = get_string('uploadserverlimit');
1080 break;
1082 case 2: // UPLOAD_ERR_FORM_SIZE
1083 $errmessage = get_string('uploadformlimit');
1084 break;
1086 case 3: // UPLOAD_ERR_PARTIAL
1087 $errmessage = get_string('uploadpartialfile');
1088 break;
1090 case 4: // UPLOAD_ERR_NO_FILE
1091 $errmessage = get_string('uploadnofilefound');
1092 break;
1094 // Note: there is no error with a value of 5
1096 case 6: // UPLOAD_ERR_NO_TMP_DIR
1097 $errmessage = get_string('uploadnotempdir');
1098 break;
1100 case 7: // UPLOAD_ERR_CANT_WRITE
1101 $errmessage = get_string('uploadcantwrite');
1102 break;
1104 case 8: // UPLOAD_ERR_EXTENSION
1105 $errmessage = get_string('uploadextension');
1106 break;
1108 default:
1109 $errmessage = get_string('uploadproblem');
1112 return $errmessage;
1116 * Recursive function formating an array in POST parameter
1117 * @param array $arraydata - the array that we are going to format and add into &$data array
1118 * @param string $currentdata - a row of the final postdata array at instant T
1119 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1120 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1122 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1123 foreach ($arraydata as $k=>$v) {
1124 $newcurrentdata = $currentdata;
1125 if (is_array($v)) { //the value is an array, call the function recursively
1126 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1127 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1128 } else { //add the POST parameter to the $data array
1129 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1135 * Transform a PHP array into POST parameter
1136 * (see the recursive function format_array_postdata_for_curlcall)
1137 * @param array $postdata
1138 * @return array containing all POST parameters (1 row = 1 POST parameter)
1140 function format_postdata_for_curlcall($postdata) {
1141 $data = array();
1142 foreach ($postdata as $k=>$v) {
1143 if (is_array($v)) {
1144 $currentdata = urlencode($k);
1145 format_array_postdata_for_curlcall($v, $currentdata, $data);
1146 } else {
1147 $data[] = urlencode($k).'='.urlencode($v);
1150 $convertedpostdata = implode('&', $data);
1151 return $convertedpostdata;
1155 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1156 * Due to security concerns only downloads from http(s) sources are supported.
1158 * @category files
1159 * @param string $url file url starting with http(s)://
1160 * @param array $headers http headers, null if none. If set, should be an
1161 * associative array of header name => value pairs.
1162 * @param array $postdata array means use POST request with given parameters
1163 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1164 * (if false, just returns content)
1165 * @param int $timeout timeout for complete download process including all file transfer
1166 * (default 5 minutes)
1167 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1168 * usually happens if the remote server is completely down (default 20 seconds);
1169 * may not work when using proxy
1170 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1171 * Only use this when already in a trusted location.
1172 * @param string $tofile store the downloaded content to file instead of returning it.
1173 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1174 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1175 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1176 * if file downloaded into $tofile successfully or the file content as a string.
1178 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1179 global $CFG;
1181 // Only http and https links supported.
1182 if (!preg_match('|^https?://|i', $url)) {
1183 if ($fullresponse) {
1184 $response = new stdClass();
1185 $response->status = 0;
1186 $response->headers = array();
1187 $response->response_code = 'Invalid protocol specified in url';
1188 $response->results = '';
1189 $response->error = 'Invalid protocol specified in url';
1190 return $response;
1191 } else {
1192 return false;
1196 $options = array();
1198 $headers2 = array();
1199 if (is_array($headers)) {
1200 foreach ($headers as $key => $value) {
1201 if (is_numeric($key)) {
1202 $headers2[] = $value;
1203 } else {
1204 $headers2[] = "$key: $value";
1209 if ($skipcertverify) {
1210 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1211 } else {
1212 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1215 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1217 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1218 $options['CURLOPT_MAXREDIRS'] = 5;
1220 // Use POST if requested.
1221 if (is_array($postdata)) {
1222 $postdata = format_postdata_for_curlcall($postdata);
1223 } else if (empty($postdata)) {
1224 $postdata = null;
1227 // Optionally attempt to get more correct timeout by fetching the file size.
1228 if (!isset($CFG->curltimeoutkbitrate)) {
1229 // Use very slow rate of 56kbps as a timeout speed when not set.
1230 $bitrate = 56;
1231 } else {
1232 $bitrate = $CFG->curltimeoutkbitrate;
1234 if ($calctimeout and !isset($postdata)) {
1235 $curl = new curl();
1236 $curl->setHeader($headers2);
1238 $curl->head($url, $postdata, $options);
1240 $info = $curl->get_info();
1241 $error_no = $curl->get_errno();
1242 if (!$error_no && $info['download_content_length'] > 0) {
1243 // No curl errors - adjust for large files only - take max timeout.
1244 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1248 $curl = new curl();
1249 $curl->setHeader($headers2);
1251 $options['CURLOPT_RETURNTRANSFER'] = true;
1252 $options['CURLOPT_NOBODY'] = false;
1253 $options['CURLOPT_TIMEOUT'] = $timeout;
1255 if ($tofile) {
1256 $fh = fopen($tofile, 'w');
1257 if (!$fh) {
1258 if ($fullresponse) {
1259 $response = new stdClass();
1260 $response->status = 0;
1261 $response->headers = array();
1262 $response->response_code = 'Can not write to file';
1263 $response->results = false;
1264 $response->error = 'Can not write to file';
1265 return $response;
1266 } else {
1267 return false;
1270 $options['CURLOPT_FILE'] = $fh;
1273 if (isset($postdata)) {
1274 $content = $curl->post($url, $postdata, $options);
1275 } else {
1276 $content = $curl->get($url, null, $options);
1279 if ($tofile) {
1280 fclose($fh);
1281 @chmod($tofile, $CFG->filepermissions);
1285 // Try to detect encoding problems.
1286 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1287 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1288 $result = curl_exec($ch);
1292 $info = $curl->get_info();
1293 $error_no = $curl->get_errno();
1294 $rawheaders = $curl->get_raw_response();
1296 if ($error_no) {
1297 $error = $content;
1298 if (!$fullresponse) {
1299 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1300 return false;
1303 $response = new stdClass();
1304 if ($error_no == 28) {
1305 $response->status = '-100'; // Mimic snoopy.
1306 } else {
1307 $response->status = '0';
1309 $response->headers = array();
1310 $response->response_code = $error;
1311 $response->results = false;
1312 $response->error = $error;
1313 return $response;
1316 if ($tofile) {
1317 $content = true;
1320 if (empty($info['http_code'])) {
1321 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1322 $response = new stdClass();
1323 $response->status = '0';
1324 $response->headers = array();
1325 $response->response_code = 'Unknown cURL error';
1326 $response->results = false; // do NOT change this, we really want to ignore the result!
1327 $response->error = 'Unknown cURL error';
1329 } else {
1330 $response = new stdClass();
1331 $response->status = (string)$info['http_code'];
1332 $response->headers = $rawheaders;
1333 $response->results = $content;
1334 $response->error = '';
1336 // There might be multiple headers on redirect, find the status of the last one.
1337 $firstline = true;
1338 foreach ($rawheaders as $line) {
1339 if ($firstline) {
1340 $response->response_code = $line;
1341 $firstline = false;
1343 if (trim($line, "\r\n") === '') {
1344 $firstline = true;
1349 if ($fullresponse) {
1350 return $response;
1353 if ($info['http_code'] != 200) {
1354 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1355 return false;
1357 return $response->results;
1361 * Returns a list of information about file types based on extensions.
1363 * The following elements expected in value array for each extension:
1364 * 'type' - mimetype
1365 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1366 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1367 * also files with bigger sizes under names
1368 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1369 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1370 * commonly used in moodle the following groups:
1371 * - web_image - image that can be included as <img> in HTML
1372 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1373 * - video - file that can be imported as video in text editor
1374 * - audio - file that can be imported as audio in text editor
1375 * - archive - we can extract files from this archive
1376 * - spreadsheet - used for portfolio format
1377 * - document - used for portfolio format
1378 * - presentation - used for portfolio format
1379 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1380 * human-readable description for this filetype;
1381 * Function {@link get_mimetype_description()} first looks at the presence of string for
1382 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1383 * attribute, if not found returns the value of 'type';
1384 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1385 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1386 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1388 * @category files
1389 * @return array List of information about file types based on extensions.
1390 * Associative array of extension (lower-case) to associative array
1391 * from 'element name' to data. Current element names are 'type' and 'icon'.
1392 * Unknown types should use the 'xxx' entry which includes defaults.
1394 function &get_mimetypes_array() {
1395 // Get types from the core_filetypes function, which includes caching.
1396 return core_filetypes::get_types();
1400 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1402 * This function retrieves a file's MIME type for a file that will be sent to the user.
1403 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1404 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1405 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1407 * @param string $filename The file's filename.
1408 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1410 function get_mimetype_for_sending($filename = '') {
1411 // Guess the file's MIME type using mimeinfo.
1412 $mimetype = mimeinfo('type', $filename);
1414 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1415 if (!$mimetype || $mimetype === 'document/unknown') {
1416 $mimetype = 'application/octet-stream';
1419 return $mimetype;
1423 * Obtains information about a filetype based on its extension. Will
1424 * use a default if no information is present about that particular
1425 * extension.
1427 * @category files
1428 * @param string $element Desired information (usually 'icon'
1429 * for icon filename or 'type' for MIME type. Can also be
1430 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1431 * @param string $filename Filename we're looking up
1432 * @return string Requested piece of information from array
1434 function mimeinfo($element, $filename) {
1435 global $CFG;
1436 $mimeinfo = & get_mimetypes_array();
1437 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1439 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1440 if (empty($filetype)) {
1441 $filetype = 'xxx'; // file without extension
1443 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1444 $iconsize = max(array(16, (int)$iconsizematch[1]));
1445 $filenames = array($mimeinfo['xxx']['icon']);
1446 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1447 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1449 // find the file with the closest size, first search for specific icon then for default icon
1450 foreach ($filenames as $filename) {
1451 foreach ($iconpostfixes as $size => $postfix) {
1452 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1453 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1454 return $filename.$postfix;
1458 } else if (isset($mimeinfo[$filetype][$element])) {
1459 return $mimeinfo[$filetype][$element];
1460 } else if (isset($mimeinfo['xxx'][$element])) {
1461 return $mimeinfo['xxx'][$element]; // By default
1462 } else {
1463 return null;
1468 * Obtains information about a filetype based on the MIME type rather than
1469 * the other way around.
1471 * @category files
1472 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1473 * @param string $mimetype MIME type we're looking up
1474 * @return string Requested piece of information from array
1476 function mimeinfo_from_type($element, $mimetype) {
1477 /* array of cached mimetype->extension associations */
1478 static $cached = array();
1479 $mimeinfo = & get_mimetypes_array();
1481 if (!array_key_exists($mimetype, $cached)) {
1482 $cached[$mimetype] = null;
1483 foreach($mimeinfo as $filetype => $values) {
1484 if ($values['type'] == $mimetype) {
1485 if ($cached[$mimetype] === null) {
1486 $cached[$mimetype] = '.'.$filetype;
1488 if (!empty($values['defaulticon'])) {
1489 $cached[$mimetype] = '.'.$filetype;
1490 break;
1494 if (empty($cached[$mimetype])) {
1495 $cached[$mimetype] = '.xxx';
1498 if ($element === 'extension') {
1499 return $cached[$mimetype];
1500 } else {
1501 return mimeinfo($element, $cached[$mimetype]);
1506 * Return the relative icon path for a given file
1508 * Usage:
1509 * <code>
1510 * // $file - instance of stored_file or file_info
1511 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1512 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1513 * </code>
1514 * or
1515 * <code>
1516 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1517 * </code>
1519 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1520 * and $file->mimetype are expected)
1521 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1522 * @return string
1524 function file_file_icon($file, $size = null) {
1525 if (!is_object($file)) {
1526 $file = (object)$file;
1528 if (isset($file->filename)) {
1529 $filename = $file->filename;
1530 } else if (method_exists($file, 'get_filename')) {
1531 $filename = $file->get_filename();
1532 } else if (method_exists($file, 'get_visible_name')) {
1533 $filename = $file->get_visible_name();
1534 } else {
1535 $filename = '';
1537 if (isset($file->mimetype)) {
1538 $mimetype = $file->mimetype;
1539 } else if (method_exists($file, 'get_mimetype')) {
1540 $mimetype = $file->get_mimetype();
1541 } else {
1542 $mimetype = '';
1544 $mimetypes = &get_mimetypes_array();
1545 if ($filename) {
1546 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1547 if ($extension && !empty($mimetypes[$extension])) {
1548 // if file name has known extension, return icon for this extension
1549 return file_extension_icon($filename, $size);
1552 return file_mimetype_icon($mimetype, $size);
1556 * Return the relative icon path for a folder image
1558 * Usage:
1559 * <code>
1560 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1561 * echo html_writer::empty_tag('img', array('src' => $icon));
1562 * </code>
1563 * or
1564 * <code>
1565 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1566 * </code>
1568 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1569 * @return string
1571 function file_folder_icon($iconsize = null) {
1572 global $CFG;
1573 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1574 static $cached = array();
1575 $iconsize = max(array(16, (int)$iconsize));
1576 if (!array_key_exists($iconsize, $cached)) {
1577 foreach ($iconpostfixes as $size => $postfix) {
1578 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1579 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1580 $cached[$iconsize] = 'f/folder'.$postfix;
1581 break;
1585 return $cached[$iconsize];
1589 * Returns the relative icon path for a given mime type
1591 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1592 * a return the full path to an icon.
1594 * <code>
1595 * $mimetype = 'image/jpg';
1596 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1597 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1598 * </code>
1600 * @category files
1601 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1602 * to conform with that.
1603 * @param string $mimetype The mimetype to fetch an icon for
1604 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1605 * @return string The relative path to the icon
1607 function file_mimetype_icon($mimetype, $size = NULL) {
1608 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1612 * Returns the relative icon path for a given file name
1614 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1615 * a return the full path to an icon.
1617 * <code>
1618 * $filename = '.jpg';
1619 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1620 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1621 * </code>
1623 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1624 * to conform with that.
1625 * @todo MDL-31074 Implement $size
1626 * @category files
1627 * @param string $filename The filename to get the icon for
1628 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1629 * @return string
1631 function file_extension_icon($filename, $size = NULL) {
1632 return 'f/'.mimeinfo('icon'.$size, $filename);
1636 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1637 * mimetypes.php language file.
1639 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1640 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1641 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1642 * @param bool $capitalise If true, capitalises first character of result
1643 * @return string Text description
1645 function get_mimetype_description($obj, $capitalise=false) {
1646 $filename = $mimetype = '';
1647 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1648 // this is an instance of stored_file
1649 $mimetype = $obj->get_mimetype();
1650 $filename = $obj->get_filename();
1651 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1652 // this is an instance of file_info
1653 $mimetype = $obj->get_mimetype();
1654 $filename = $obj->get_visible_name();
1655 } else if (is_array($obj) || is_object ($obj)) {
1656 $obj = (array)$obj;
1657 if (!empty($obj['filename'])) {
1658 $filename = $obj['filename'];
1660 if (!empty($obj['mimetype'])) {
1661 $mimetype = $obj['mimetype'];
1663 } else {
1664 $mimetype = $obj;
1666 $mimetypefromext = mimeinfo('type', $filename);
1667 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1668 // if file has a known extension, overwrite the specified mimetype
1669 $mimetype = $mimetypefromext;
1671 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1672 if (empty($extension)) {
1673 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1674 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1675 } else {
1676 $mimetypestr = mimeinfo('string', $filename);
1678 $chunks = explode('/', $mimetype, 2);
1679 $chunks[] = '';
1680 $attr = array(
1681 'mimetype' => $mimetype,
1682 'ext' => $extension,
1683 'mimetype1' => $chunks[0],
1684 'mimetype2' => $chunks[1],
1686 $a = array();
1687 foreach ($attr as $key => $value) {
1688 $a[$key] = $value;
1689 $a[strtoupper($key)] = strtoupper($value);
1690 $a[ucfirst($key)] = ucfirst($value);
1693 // MIME types may include + symbol but this is not permitted in string ids.
1694 $safemimetype = str_replace('+', '_', $mimetype);
1695 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1696 $customdescription = mimeinfo('customdescription', $filename);
1697 if ($customdescription) {
1698 // Call format_string on the custom description so that multilang
1699 // filter can be used (if enabled on system context). We use system
1700 // context because it is possible that the page context might not have
1701 // been defined yet.
1702 $result = format_string($customdescription, true,
1703 array('context' => context_system::instance()));
1704 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1705 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1706 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1707 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1708 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1709 $result = get_string('default', 'mimetypes', (object)$a);
1710 } else {
1711 $result = $mimetype;
1713 if ($capitalise) {
1714 $result=ucfirst($result);
1716 return $result;
1720 * Returns array of elements of type $element in type group(s)
1722 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1723 * @param string|array $groups one group or array of groups/extensions/mimetypes
1724 * @return array
1726 function file_get_typegroup($element, $groups) {
1727 static $cached = array();
1728 if (!is_array($groups)) {
1729 $groups = array($groups);
1731 if (!array_key_exists($element, $cached)) {
1732 $cached[$element] = array();
1734 $result = array();
1735 foreach ($groups as $group) {
1736 if (!array_key_exists($group, $cached[$element])) {
1737 // retrieive and cache all elements of type $element for group $group
1738 $mimeinfo = & get_mimetypes_array();
1739 $cached[$element][$group] = array();
1740 foreach ($mimeinfo as $extension => $value) {
1741 $value['extension'] = '.'.$extension;
1742 if (empty($value[$element])) {
1743 continue;
1745 if (($group === '.'.$extension || $group === $value['type'] ||
1746 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1747 !in_array($value[$element], $cached[$element][$group])) {
1748 $cached[$element][$group][] = $value[$element];
1752 $result = array_merge($result, $cached[$element][$group]);
1754 return array_values(array_unique($result));
1758 * Checks if file with name $filename has one of the extensions in groups $groups
1760 * @see get_mimetypes_array()
1761 * @param string $filename name of the file to check
1762 * @param string|array $groups one group or array of groups to check
1763 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1764 * file mimetype is in mimetypes in groups $groups
1765 * @return bool
1767 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1768 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1769 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1770 return true;
1772 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1776 * Checks if mimetype $mimetype belongs to one of the groups $groups
1778 * @see get_mimetypes_array()
1779 * @param string $mimetype
1780 * @param string|array $groups one group or array of groups to check
1781 * @return bool
1783 function file_mimetype_in_typegroup($mimetype, $groups) {
1784 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1788 * Requested file is not found or not accessible, does not return, terminates script
1790 * @global stdClass $CFG
1791 * @global stdClass $COURSE
1793 function send_file_not_found() {
1794 global $CFG, $COURSE;
1796 // Allow cross-origin requests only for Web Services.
1797 // This allow to receive requests done by Web Workers or webapps in different domains.
1798 if (WS_SERVER) {
1799 header('Access-Control-Allow-Origin: *');
1802 send_header_404();
1803 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1806 * Helper function to send correct 404 for server.
1808 function send_header_404() {
1809 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1810 header("Status: 404 Not Found");
1811 } else {
1812 header('HTTP/1.0 404 not found');
1817 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1818 * platforms). This wrapper uses readfile for small files and custom code for
1819 * large ones.
1821 * @param string $path Path to file
1822 * @param int $filesize Size of file (if left out, will get it automatically)
1823 * @return int|bool Size read (will always be $filesize) or false if failed
1825 function readfile_allow_large($path, $filesize = -1) {
1826 // Automatically get size if not specified.
1827 if ($filesize === -1) {
1828 $filesize = filesize($path);
1830 if ($filesize <= 2147483647) {
1831 // If the file is up to 2^31 - 1, send it normally using readfile.
1832 return readfile($path);
1833 } else {
1834 // For large files, read and output in 64KB chunks.
1835 $handle = fopen($path, 'r');
1836 if ($handle === false) {
1837 return false;
1839 $left = $filesize;
1840 while ($left > 0) {
1841 $size = min($left, 65536);
1842 $buffer = fread($handle, $size);
1843 if ($buffer === false) {
1844 return false;
1846 echo $buffer;
1847 $left -= $size;
1849 return $filesize;
1854 * Enhanced readfile() with optional acceleration.
1855 * @param string|stored_file $file
1856 * @param string $mimetype
1857 * @param bool $accelerate
1858 * @return void
1860 function readfile_accel($file, $mimetype, $accelerate) {
1861 global $CFG;
1863 if ($mimetype === 'text/plain') {
1864 // there is no encoding specified in text files, we need something consistent
1865 header('Content-Type: text/plain; charset=utf-8');
1866 } else {
1867 header('Content-Type: '.$mimetype);
1870 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1871 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1873 if (is_object($file)) {
1874 header('Etag: "' . $file->get_contenthash() . '"');
1875 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1876 header('HTTP/1.1 304 Not Modified');
1877 return;
1881 // if etag present for stored file rely on it exclusively
1882 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1883 // get unixtime of request header; clip extra junk off first
1884 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1885 if ($since && $since >= $lastmodified) {
1886 header('HTTP/1.1 304 Not Modified');
1887 return;
1891 if ($accelerate and !empty($CFG->xsendfile)) {
1892 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1893 header('Accept-Ranges: bytes');
1894 } else {
1895 header('Accept-Ranges: none');
1898 if (is_object($file)) {
1899 $fs = get_file_storage();
1900 if ($fs->xsendfile($file->get_contenthash())) {
1901 return;
1904 } else {
1905 require_once("$CFG->libdir/xsendfilelib.php");
1906 if (xsendfile($file)) {
1907 return;
1912 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1914 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1916 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1917 header('Accept-Ranges: bytes');
1919 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1920 // byteserving stuff - for acrobat reader and download accelerators
1921 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1922 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1923 $ranges = false;
1924 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1925 foreach ($ranges as $key=>$value) {
1926 if ($ranges[$key][1] == '') {
1927 //suffix case
1928 $ranges[$key][1] = $filesize - $ranges[$key][2];
1929 $ranges[$key][2] = $filesize - 1;
1930 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1931 //fix range length
1932 $ranges[$key][2] = $filesize - 1;
1934 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1935 //invalid byte-range ==> ignore header
1936 $ranges = false;
1937 break;
1939 //prepare multipart header
1940 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1941 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1943 } else {
1944 $ranges = false;
1946 if ($ranges) {
1947 if (is_object($file)) {
1948 $handle = $file->get_content_file_handle();
1949 } else {
1950 $handle = fopen($file, 'rb');
1952 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1955 } else {
1956 // Do not byteserve
1957 header('Accept-Ranges: none');
1960 header('Content-Length: '.$filesize);
1962 if ($filesize > 10000000) {
1963 // for large files try to flush and close all buffers to conserve memory
1964 while(@ob_get_level()) {
1965 if (!@ob_end_flush()) {
1966 break;
1971 // send the whole file content
1972 if (is_object($file)) {
1973 $file->readfile();
1974 } else {
1975 readfile_allow_large($file, $filesize);
1980 * Similar to readfile_accel() but designed for strings.
1981 * @param string $string
1982 * @param string $mimetype
1983 * @param bool $accelerate
1984 * @return void
1986 function readstring_accel($string, $mimetype, $accelerate) {
1987 global $CFG;
1989 if ($mimetype === 'text/plain') {
1990 // there is no encoding specified in text files, we need something consistent
1991 header('Content-Type: text/plain; charset=utf-8');
1992 } else {
1993 header('Content-Type: '.$mimetype);
1995 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
1996 header('Accept-Ranges: none');
1998 if ($accelerate and !empty($CFG->xsendfile)) {
1999 $fs = get_file_storage();
2000 if ($fs->xsendfile(sha1($string))) {
2001 return;
2005 header('Content-Length: '.strlen($string));
2006 echo $string;
2010 * Handles the sending of temporary file to user, download is forced.
2011 * File is deleted after abort or successful sending, does not return, script terminated
2013 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2014 * @param string $filename proposed file name when saving file
2015 * @param bool $pathisstring If the path is string
2017 function send_temp_file($path, $filename, $pathisstring=false) {
2018 global $CFG;
2020 // Guess the file's MIME type.
2021 $mimetype = get_mimetype_for_sending($filename);
2023 // close session - not needed anymore
2024 \core\session\manager::write_close();
2026 if (!$pathisstring) {
2027 if (!file_exists($path)) {
2028 send_header_404();
2029 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2031 // executed after normal finish or abort
2032 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2035 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2036 if (core_useragent::is_ie()) {
2037 $filename = urlencode($filename);
2040 header('Content-Disposition: attachment; filename="'.$filename.'"');
2041 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2042 header('Cache-Control: private, max-age=10, no-transform');
2043 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2044 header('Pragma: ');
2045 } else { //normal http - prevent caching at all cost
2046 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2047 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2048 header('Pragma: no-cache');
2051 // send the contents - we can not accelerate this because the file will be deleted asap
2052 if ($pathisstring) {
2053 readstring_accel($path, $mimetype, false);
2054 } else {
2055 readfile_accel($path, $mimetype, false);
2056 @unlink($path);
2059 die; //no more chars to output
2063 * Internal callback function used by send_temp_file()
2065 * @param string $path
2067 function send_temp_file_finished($path) {
2068 if (file_exists($path)) {
2069 @unlink($path);
2074 * Serve content which is not meant to be cached.
2076 * This is only intended to be used for volatile public files, for instance
2077 * when development is enabled, or when caching is not required on a public resource.
2079 * @param string $content Raw content.
2080 * @param string $filename The file name.
2081 * @return void
2083 function send_content_uncached($content, $filename) {
2084 $mimetype = mimeinfo('type', $filename);
2085 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2087 header('Content-Disposition: inline; filename="' . $filename . '"');
2088 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2089 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2090 header('Pragma: ');
2091 header('Accept-Ranges: none');
2092 header('Content-Type: ' . $mimetype . $charset);
2093 header('Content-Length: ' . strlen($content));
2095 echo $content;
2096 die();
2100 * Safely save content to a certain path.
2102 * This function tries hard to be atomic by first copying the content
2103 * to a separate file, and then moving the file across. It also prevents
2104 * the user to abort a request to prevent half-safed files.
2106 * This function is intended to be used when saving some content to cache like
2107 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2109 * @param string $content The file content.
2110 * @param string $destination The absolute path of the final file.
2111 * @return void
2113 function file_safe_save_content($content, $destination) {
2114 global $CFG;
2116 clearstatcache();
2117 if (!file_exists(dirname($destination))) {
2118 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2121 // Prevent serving of incomplete file from concurrent request,
2122 // the rename() should be more atomic than fwrite().
2123 ignore_user_abort(true);
2124 if ($fp = fopen($destination . '.tmp', 'xb')) {
2125 fwrite($fp, $content);
2126 fclose($fp);
2127 rename($destination . '.tmp', $destination);
2128 @chmod($destination, $CFG->filepermissions);
2129 @unlink($destination . '.tmp'); // Just in case anything fails.
2131 ignore_user_abort(false);
2132 if (connection_aborted()) {
2133 die();
2138 * Handles the sending of file data to the user's browser, including support for
2139 * byteranges etc.
2141 * @category files
2142 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2143 * @param string $filename Filename to send
2144 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2145 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2146 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2147 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2148 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2149 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2150 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2151 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2152 * and should not be reopened.
2153 * @param array $options An array of options, currently accepts:
2154 * - (string) cacheability: public, or private.
2155 * @return null script execution stopped unless $dontdie is true
2157 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2158 $dontdie=false, array $options = array()) {
2159 global $CFG, $COURSE;
2161 if ($dontdie) {
2162 ignore_user_abort(true);
2165 if ($lifetime === 'default' or is_null($lifetime)) {
2166 $lifetime = $CFG->filelifetime;
2169 \core\session\manager::write_close(); // Unlock session during file serving.
2171 // Use given MIME type if specified, otherwise guess it.
2172 if (!$mimetype || $mimetype === 'document/unknown') {
2173 $mimetype = get_mimetype_for_sending($filename);
2176 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2177 if (core_useragent::is_ie()) {
2178 $filename = rawurlencode($filename);
2181 if ($forcedownload) {
2182 header('Content-Disposition: attachment; filename="'.$filename.'"');
2183 } else if ($mimetype !== 'application/x-shockwave-flash') {
2184 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2185 // as an upload and enforces security that may prevent the file from being loaded.
2187 header('Content-Disposition: inline; filename="'.$filename.'"');
2190 if ($lifetime > 0) {
2191 $cacheability = ' public,';
2192 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2193 // This file must be cache-able by both browsers and proxies.
2194 $cacheability = ' public,';
2195 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2196 // This file must be cache-able only by browsers.
2197 $cacheability = ' private,';
2198 } else if (isloggedin() and !isguestuser()) {
2199 // By default, under the conditions above, this file must be cache-able only by browsers.
2200 $cacheability = ' private,';
2202 $nobyteserving = false;
2203 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2204 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2205 header('Pragma: ');
2207 } else { // Do not cache files in proxies and browsers
2208 $nobyteserving = true;
2209 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2210 header('Cache-Control: private, max-age=10, no-transform');
2211 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2212 header('Pragma: ');
2213 } else { //normal http - prevent caching at all cost
2214 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2215 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2216 header('Pragma: no-cache');
2220 if (empty($filter)) {
2221 // send the contents
2222 if ($pathisstring) {
2223 readstring_accel($path, $mimetype, !$dontdie);
2224 } else {
2225 readfile_accel($path, $mimetype, !$dontdie);
2228 } else {
2229 // Try to put the file through filters
2230 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2231 $options = new stdClass();
2232 $options->noclean = true;
2233 $options->nocache = true; // temporary workaround for MDL-5136
2234 $text = $pathisstring ? $path : implode('', file($path));
2236 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2238 readstring_accel($output, $mimetype, false);
2240 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2241 // only filter text if filter all files is selected
2242 $options = new stdClass();
2243 $options->newlines = false;
2244 $options->noclean = true;
2245 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2246 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2248 readstring_accel($output, $mimetype, false);
2250 } else {
2251 // send the contents
2252 if ($pathisstring) {
2253 readstring_accel($path, $mimetype, !$dontdie);
2254 } else {
2255 readfile_accel($path, $mimetype, !$dontdie);
2259 if ($dontdie) {
2260 return;
2262 die; //no more chars to output!!!
2266 * Handles the sending of file data to the user's browser, including support for
2267 * byteranges etc.
2269 * The $options parameter supports the following keys:
2270 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2271 * (string|null) filename - overrides the implicit filename
2272 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2273 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2274 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2275 * and should not be reopened
2276 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2277 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2278 * defaults to "public".
2280 * @category files
2281 * @param stored_file $stored_file local file object
2282 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2283 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2284 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2285 * @param array $options additional options affecting the file serving
2286 * @return null script execution stopped unless $options['dontdie'] is true
2288 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2289 global $CFG, $COURSE;
2291 if (empty($options['filename'])) {
2292 $filename = null;
2293 } else {
2294 $filename = $options['filename'];
2297 if (empty($options['dontdie'])) {
2298 $dontdie = false;
2299 } else {
2300 $dontdie = true;
2303 if ($lifetime === 'default' or is_null($lifetime)) {
2304 $lifetime = $CFG->filelifetime;
2307 if (!empty($options['preview'])) {
2308 // replace the file with its preview
2309 $fs = get_file_storage();
2310 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2311 if (!$preview_file) {
2312 // unable to create a preview of the file, send its default mime icon instead
2313 if ($options['preview'] === 'tinyicon') {
2314 $size = 24;
2315 } else if ($options['preview'] === 'thumb') {
2316 $size = 90;
2317 } else {
2318 $size = 256;
2320 $fileicon = file_file_icon($stored_file, $size);
2321 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2322 } else {
2323 // preview images have fixed cache lifetime and they ignore forced download
2324 // (they are generated by GD and therefore they are considered reasonably safe).
2325 $stored_file = $preview_file;
2326 $lifetime = DAYSECS;
2327 $filter = 0;
2328 $forcedownload = false;
2332 // handle external resource
2333 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2334 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2335 die;
2338 if (!$stored_file or $stored_file->is_directory()) {
2339 // nothing to serve
2340 if ($dontdie) {
2341 return;
2343 die;
2346 if ($dontdie) {
2347 ignore_user_abort(true);
2350 \core\session\manager::write_close(); // Unlock session during file serving.
2352 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2354 // Use given MIME type if specified.
2355 $mimetype = $stored_file->get_mimetype();
2357 // Otherwise guess it.
2358 if (!$mimetype || $mimetype === 'document/unknown') {
2359 $mimetype = get_mimetype_for_sending($filename);
2362 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2363 if (core_useragent::is_ie()) {
2364 $filename = rawurlencode($filename);
2367 if ($forcedownload) {
2368 header('Content-Disposition: attachment; filename="'.$filename.'"');
2369 } else if ($mimetype !== 'application/x-shockwave-flash') {
2370 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2371 // as an upload and enforces security that may prevent the file from being loaded.
2373 header('Content-Disposition: inline; filename="'.$filename.'"');
2376 if ($lifetime > 0) {
2377 $cacheability = ' public,';
2378 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2379 // This file must be cache-able by both browsers and proxies.
2380 $cacheability = ' public,';
2381 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2382 // This file must be cache-able only by browsers.
2383 $cacheability = ' private,';
2384 } else if (isloggedin() and !isguestuser()) {
2385 $cacheability = ' private,';
2387 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2388 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2389 header('Pragma: ');
2391 } else { // Do not cache files in proxies and browsers
2392 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2393 header('Cache-Control: private, max-age=10, no-transform');
2394 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2395 header('Pragma: ');
2396 } else { //normal http - prevent caching at all cost
2397 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2398 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2399 header('Pragma: no-cache');
2403 // Allow cross-origin requests only for Web Services.
2404 // This allow to receive requests done by Web Workers or webapps in different domains.
2405 if (WS_SERVER) {
2406 header('Access-Control-Allow-Origin: *');
2409 if (empty($filter)) {
2410 // send the contents
2411 readfile_accel($stored_file, $mimetype, !$dontdie);
2413 } else { // Try to put the file through filters
2414 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2415 $options = new stdClass();
2416 $options->noclean = true;
2417 $options->nocache = true; // temporary workaround for MDL-5136
2418 $text = $stored_file->get_content();
2419 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2421 readstring_accel($output, $mimetype, false);
2423 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2424 // only filter text if filter all files is selected
2425 $options = new stdClass();
2426 $options->newlines = false;
2427 $options->noclean = true;
2428 $text = $stored_file->get_content();
2429 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2431 readstring_accel($output, $mimetype, false);
2433 } else { // Just send it out raw
2434 readfile_accel($stored_file, $mimetype, !$dontdie);
2437 if ($dontdie) {
2438 return;
2440 die; //no more chars to output!!!
2444 * Recursively delete the file or folder with path $location. That is,
2445 * if it is a file delete it. If it is a folder, delete all its content
2446 * then delete it. If $location does not exist to start, that is not
2447 * considered an error.
2449 * @param string $location the path to remove.
2450 * @return bool
2452 function fulldelete($location) {
2453 if (empty($location)) {
2454 // extra safety against wrong param
2455 return false;
2457 if (is_dir($location)) {
2458 if (!$currdir = opendir($location)) {
2459 return false;
2461 while (false !== ($file = readdir($currdir))) {
2462 if ($file <> ".." && $file <> ".") {
2463 $fullfile = $location."/".$file;
2464 if (is_dir($fullfile)) {
2465 if (!fulldelete($fullfile)) {
2466 return false;
2468 } else {
2469 if (!unlink($fullfile)) {
2470 return false;
2475 closedir($currdir);
2476 if (! rmdir($location)) {
2477 return false;
2480 } else if (file_exists($location)) {
2481 if (!unlink($location)) {
2482 return false;
2485 return true;
2489 * Send requested byterange of file.
2491 * @param resource $handle A file handle
2492 * @param string $mimetype The mimetype for the output
2493 * @param array $ranges An array of ranges to send
2494 * @param string $filesize The size of the content if only one range is used
2496 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2497 // better turn off any kind of compression and buffering
2498 ini_set('zlib.output_compression', 'Off');
2500 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2501 if ($handle === false) {
2502 die;
2504 if (count($ranges) == 1) { //only one range requested
2505 $length = $ranges[0][2] - $ranges[0][1] + 1;
2506 header('HTTP/1.1 206 Partial content');
2507 header('Content-Length: '.$length);
2508 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2509 header('Content-Type: '.$mimetype);
2511 while(@ob_get_level()) {
2512 if (!@ob_end_flush()) {
2513 break;
2517 fseek($handle, $ranges[0][1]);
2518 while (!feof($handle) && $length > 0) {
2519 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2520 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2521 echo $buffer;
2522 flush();
2523 $length -= strlen($buffer);
2525 fclose($handle);
2526 die;
2527 } else { // multiple ranges requested - not tested much
2528 $totallength = 0;
2529 foreach($ranges as $range) {
2530 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2532 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2533 header('HTTP/1.1 206 Partial content');
2534 header('Content-Length: '.$totallength);
2535 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2537 while(@ob_get_level()) {
2538 if (!@ob_end_flush()) {
2539 break;
2543 foreach($ranges as $range) {
2544 $length = $range[2] - $range[1] + 1;
2545 echo $range[0];
2546 fseek($handle, $range[1]);
2547 while (!feof($handle) && $length > 0) {
2548 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2549 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2550 echo $buffer;
2551 flush();
2552 $length -= strlen($buffer);
2555 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2556 fclose($handle);
2557 die;
2562 * Tells whether the filename is executable.
2564 * @link http://php.net/manual/en/function.is-executable.php
2565 * @link https://bugs.php.net/bug.php?id=41062
2566 * @param string $filename Path to the file.
2567 * @return bool True if the filename exists and is executable; otherwise, false.
2569 function file_is_executable($filename) {
2570 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2571 if (is_executable($filename)) {
2572 return true;
2573 } else {
2574 $fileext = strrchr($filename, '.');
2575 // If we have an extension we can check if it is listed as executable.
2576 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2577 $winpathext = strtolower(getenv('PATHEXT'));
2578 $winpathexts = explode(';', $winpathext);
2580 return in_array(strtolower($fileext), $winpathexts);
2583 return false;
2585 } else {
2586 return is_executable($filename);
2591 * Overwrite an existing file in a draft area.
2593 * @param stored_file $newfile the new file with the new content and meta-data
2594 * @param stored_file $existingfile the file that will be overwritten
2595 * @throws moodle_exception
2596 * @since Moodle 3.2
2598 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2599 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2600 throw new coding_exception('The file to overwrite is not in a draft area.');
2603 $fs = get_file_storage();
2604 // Remember original file source field.
2605 $source = @unserialize($existingfile->get_source());
2606 // Remember the original sortorder.
2607 $sortorder = $existingfile->get_sortorder();
2608 if ($newfile->is_external_file()) {
2609 // New file is a reference. Check that existing file does not have any other files referencing to it
2610 if (isset($source->original) && $fs->search_references_count($source->original)) {
2611 throw new moodle_exception('errordoublereference', 'repository');
2615 // Delete existing file to release filename.
2616 $newfilerecord = array(
2617 'contextid' => $existingfile->get_contextid(),
2618 'component' => 'user',
2619 'filearea' => 'draft',
2620 'itemid' => $existingfile->get_itemid(),
2621 'timemodified' => time()
2623 $existingfile->delete();
2625 // Create new file.
2626 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2627 // Preserve original file location (stored in source field) for handling references.
2628 if (isset($source->original)) {
2629 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2630 $newfilesource = new stdClass();
2632 $newfilesource->original = $source->original;
2633 $newfile->set_source(serialize($newfilesource));
2635 $newfile->set_sortorder($sortorder);
2639 * Add files from a draft area into a final area.
2641 * Most of the time you do not want to use this. It is intended to be used
2642 * by asynchronous services which cannot direcly manipulate a final
2643 * area through a draft area. Instead they add files to a new draft
2644 * area and merge that new draft into the final area when ready.
2646 * @param int $draftitemid the id of the draft area to use.
2647 * @param int $contextid this parameter and the next two identify the file area to save to.
2648 * @param string $component component name
2649 * @param string $filearea indentifies the file area
2650 * @param int $itemid identifies the item id or false for all items in the file area
2651 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2652 * @see file_save_draft_area_files
2653 * @since Moodle 3.2
2655 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2656 array $options = null) {
2657 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2658 $finaldraftid = 0;
2659 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2660 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2661 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2665 * Merge files from two draftarea areas.
2667 * This does not handle conflict resolution, files in the destination area which appear
2668 * to be more recent will be kept disregarding the intended ones.
2670 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2671 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2672 * @throws coding_exception
2673 * @since Moodle 3.2
2675 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2676 global $USER;
2678 $fs = get_file_storage();
2679 $contextid = context_user::instance($USER->id)->id;
2681 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2682 throw new coding_exception('Nothing to merge or area does not belong to current user');
2685 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2687 // Get hashes of the files to merge.
2688 $newhashes = array();
2689 foreach ($filestomerge as $filetomerge) {
2690 $filepath = $filetomerge->get_filepath();
2691 $filename = $filetomerge->get_filename();
2693 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2694 $newhashes[$newhash] = $filetomerge;
2697 // Calculate wich files must be added.
2698 foreach ($currentfiles as $file) {
2699 $filehash = $file->get_pathnamehash();
2700 // One file to be merged already exists.
2701 if (isset($newhashes[$filehash])) {
2702 $updatedfile = $newhashes[$filehash];
2704 // Avoid race conditions.
2705 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2706 // The existing file is more recent, do not copy the suposedly "new" one.
2707 unset($newhashes[$filehash]);
2708 continue;
2710 // Update existing file (not only content, meta-data too).
2711 file_overwrite_existing_draftfile($updatedfile, $file);
2712 unset($newhashes[$filehash]);
2716 foreach ($newhashes as $newfile) {
2717 $newfilerecord = array(
2718 'contextid' => $contextid,
2719 'component' => 'user',
2720 'filearea' => 'draft',
2721 'itemid' => $mergeintodraftid,
2722 'timemodified' => time()
2725 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2730 * RESTful cURL class
2732 * This is a wrapper class for curl, it is quite easy to use:
2733 * <code>
2734 * $c = new curl;
2735 * // enable cache
2736 * $c = new curl(array('cache'=>true));
2737 * // enable cookie
2738 * $c = new curl(array('cookie'=>true));
2739 * // enable proxy
2740 * $c = new curl(array('proxy'=>true));
2742 * // HTTP GET Method
2743 * $html = $c->get('http://example.com');
2744 * // HTTP POST Method
2745 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2746 * // HTTP PUT Method
2747 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2748 * </code>
2750 * @package core_files
2751 * @category files
2752 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2753 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2755 class curl {
2756 /** @var bool Caches http request contents */
2757 public $cache = false;
2758 /** @var bool Uses proxy, null means automatic based on URL */
2759 public $proxy = null;
2760 /** @var string library version */
2761 public $version = '0.4 dev';
2762 /** @var array http's response */
2763 public $response = array();
2764 /** @var array Raw response headers, needed for BC in download_file_content(). */
2765 public $rawresponse = array();
2766 /** @var array http header */
2767 public $header = array();
2768 /** @var string cURL information */
2769 public $info;
2770 /** @var string error */
2771 public $error;
2772 /** @var int error code */
2773 public $errno;
2774 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2775 public $emulateredirects = null;
2777 /** @var array cURL options */
2778 private $options;
2780 /** @var string Proxy host */
2781 private $proxy_host = '';
2782 /** @var string Proxy auth */
2783 private $proxy_auth = '';
2784 /** @var string Proxy type */
2785 private $proxy_type = '';
2786 /** @var bool Debug mode on */
2787 private $debug = false;
2788 /** @var bool|string Path to cookie file */
2789 private $cookie = false;
2790 /** @var bool tracks multiple headers in response - redirect detection */
2791 private $responsefinished = false;
2794 * Curl constructor.
2796 * Allowed settings are:
2797 * proxy: (bool) use proxy server, null means autodetect non-local from url
2798 * debug: (bool) use debug output
2799 * cookie: (string) path to cookie file, false if none
2800 * cache: (bool) use cache
2801 * module_cache: (string) type of cache
2803 * @param array $settings
2805 public function __construct($settings = array()) {
2806 global $CFG;
2807 if (!function_exists('curl_init')) {
2808 $this->error = 'cURL module must be enabled!';
2809 trigger_error($this->error, E_USER_ERROR);
2810 return false;
2813 // All settings of this class should be init here.
2814 $this->resetopt();
2815 if (!empty($settings['debug'])) {
2816 $this->debug = true;
2818 if (!empty($settings['cookie'])) {
2819 if($settings['cookie'] === true) {
2820 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2821 } else {
2822 $this->cookie = $settings['cookie'];
2825 if (!empty($settings['cache'])) {
2826 if (class_exists('curl_cache')) {
2827 if (!empty($settings['module_cache'])) {
2828 $this->cache = new curl_cache($settings['module_cache']);
2829 } else {
2830 $this->cache = new curl_cache('misc');
2834 if (!empty($CFG->proxyhost)) {
2835 if (empty($CFG->proxyport)) {
2836 $this->proxy_host = $CFG->proxyhost;
2837 } else {
2838 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2840 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2841 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2842 $this->setopt(array(
2843 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2844 'proxyuserpwd'=>$this->proxy_auth));
2846 if (!empty($CFG->proxytype)) {
2847 if ($CFG->proxytype == 'SOCKS5') {
2848 $this->proxy_type = CURLPROXY_SOCKS5;
2849 } else {
2850 $this->proxy_type = CURLPROXY_HTTP;
2851 $this->setopt(array('httpproxytunnel'=>false));
2853 $this->setopt(array('proxytype'=>$this->proxy_type));
2856 if (isset($settings['proxy'])) {
2857 $this->proxy = $settings['proxy'];
2859 } else {
2860 $this->proxy = false;
2863 if (!isset($this->emulateredirects)) {
2864 $this->emulateredirects = ini_get('open_basedir');
2869 * Resets the CURL options that have already been set
2871 public function resetopt() {
2872 $this->options = array();
2873 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2874 // True to include the header in the output
2875 $this->options['CURLOPT_HEADER'] = 0;
2876 // True to Exclude the body from the output
2877 $this->options['CURLOPT_NOBODY'] = 0;
2878 // Redirect ny default.
2879 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2880 $this->options['CURLOPT_MAXREDIRS'] = 10;
2881 $this->options['CURLOPT_ENCODING'] = '';
2882 // TRUE to return the transfer as a string of the return
2883 // value of curl_exec() instead of outputting it out directly.
2884 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2885 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2886 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2887 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2889 if ($cacert = self::get_cacert()) {
2890 $this->options['CURLOPT_CAINFO'] = $cacert;
2895 * Get the location of ca certificates.
2896 * @return string absolute file path or empty if default used
2898 public static function get_cacert() {
2899 global $CFG;
2901 // Bundle in dataroot always wins.
2902 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2903 return realpath("$CFG->dataroot/moodleorgca.crt");
2906 // Next comes the default from php.ini
2907 $cacert = ini_get('curl.cainfo');
2908 if (!empty($cacert) and is_readable($cacert)) {
2909 return realpath($cacert);
2912 // Windows PHP does not have any certs, we need to use something.
2913 if ($CFG->ostype === 'WINDOWS') {
2914 if (is_readable("$CFG->libdir/cacert.pem")) {
2915 return realpath("$CFG->libdir/cacert.pem");
2919 // Use default, this should work fine on all properly configured *nix systems.
2920 return null;
2924 * Reset Cookie
2926 public function resetcookie() {
2927 if (!empty($this->cookie)) {
2928 if (is_file($this->cookie)) {
2929 $fp = fopen($this->cookie, 'w');
2930 if (!empty($fp)) {
2931 fwrite($fp, '');
2932 fclose($fp);
2939 * Set curl options.
2941 * Do not use the curl constants to define the options, pass a string
2942 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2943 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2945 * @param array $options If array is null, this function will reset the options to default value.
2946 * @return void
2947 * @throws coding_exception If an option uses constant value instead of option name.
2949 public function setopt($options = array()) {
2950 if (is_array($options)) {
2951 foreach ($options as $name => $val) {
2952 if (!is_string($name)) {
2953 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2955 if (stripos($name, 'CURLOPT_') === false) {
2956 $name = strtoupper('CURLOPT_'.$name);
2957 } else {
2958 $name = strtoupper($name);
2960 $this->options[$name] = $val;
2966 * Reset http method
2968 public function cleanopt() {
2969 unset($this->options['CURLOPT_HTTPGET']);
2970 unset($this->options['CURLOPT_POST']);
2971 unset($this->options['CURLOPT_POSTFIELDS']);
2972 unset($this->options['CURLOPT_PUT']);
2973 unset($this->options['CURLOPT_INFILE']);
2974 unset($this->options['CURLOPT_INFILESIZE']);
2975 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2976 unset($this->options['CURLOPT_FILE']);
2980 * Resets the HTTP Request headers (to prepare for the new request)
2982 public function resetHeader() {
2983 $this->header = array();
2987 * Set HTTP Request Header
2989 * @param array $header
2991 public function setHeader($header) {
2992 if (is_array($header)) {
2993 foreach ($header as $v) {
2994 $this->setHeader($v);
2996 } else {
2997 // Remove newlines, they are not allowed in headers.
2998 $this->header[] = preg_replace('/[\r\n]/', '', $header);
3003 * Get HTTP Response Headers
3004 * @return array of arrays
3006 public function getResponse() {
3007 return $this->response;
3011 * Get raw HTTP Response Headers
3012 * @return array of strings
3014 public function get_raw_response() {
3015 return $this->rawresponse;
3019 * private callback function
3020 * Formatting HTTP Response Header
3022 * We only keep the last headers returned. For example during a redirect the
3023 * redirect headers will not appear in {@link self::getResponse()}, if you need
3024 * to use those headers, refer to {@link self::get_raw_response()}.
3026 * @param resource $ch Apparently not used
3027 * @param string $header
3028 * @return int The strlen of the header
3030 private function formatHeader($ch, $header) {
3031 $this->rawresponse[] = $header;
3033 if (trim($header, "\r\n") === '') {
3034 // This must be the last header.
3035 $this->responsefinished = true;
3038 if (strlen($header) > 2) {
3039 if ($this->responsefinished) {
3040 // We still have headers after the supposedly last header, we must be
3041 // in a redirect so let's empty the response to keep the last headers.
3042 $this->responsefinished = false;
3043 $this->response = array();
3045 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3046 $key = rtrim($key, ':');
3047 if (!empty($this->response[$key])) {
3048 if (is_array($this->response[$key])) {
3049 $this->response[$key][] = $value;
3050 } else {
3051 $tmp = $this->response[$key];
3052 $this->response[$key] = array();
3053 $this->response[$key][] = $tmp;
3054 $this->response[$key][] = $value;
3057 } else {
3058 $this->response[$key] = $value;
3061 return strlen($header);
3065 * Set options for individual curl instance
3067 * @param resource $curl A curl handle
3068 * @param array $options
3069 * @return resource The curl handle
3071 private function apply_opt($curl, $options) {
3072 // Clean up
3073 $this->cleanopt();
3074 // set cookie
3075 if (!empty($this->cookie) || !empty($options['cookie'])) {
3076 $this->setopt(array('cookiejar'=>$this->cookie,
3077 'cookiefile'=>$this->cookie
3081 // Bypass proxy if required.
3082 if ($this->proxy === null) {
3083 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3084 $proxy = false;
3085 } else {
3086 $proxy = true;
3088 } else {
3089 $proxy = (bool)$this->proxy;
3092 // Set proxy.
3093 if ($proxy) {
3094 $options['CURLOPT_PROXY'] = $this->proxy_host;
3095 } else {
3096 unset($this->options['CURLOPT_PROXY']);
3099 $this->setopt($options);
3101 // Reset before set options.
3102 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3104 // Setting the User-Agent based on options provided.
3105 $useragent = '';
3107 if (!empty($options['CURLOPT_USERAGENT'])) {
3108 $useragent = $options['CURLOPT_USERAGENT'];
3109 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3110 $useragent = $this->options['CURLOPT_USERAGENT'];
3111 } else {
3112 $useragent = 'MoodleBot/1.0';
3115 // Set headers.
3116 if (empty($this->header)) {
3117 $this->setHeader(array(
3118 'User-Agent: ' . $useragent,
3119 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3120 'Connection: keep-alive'
3122 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3123 // Remove old User-Agent if one existed.
3124 // We have to partial search since we don't know what the original User-Agent is.
3125 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3126 $key = array_keys($match)[0];
3127 unset($this->header[$key]);
3129 $this->setHeader(array('User-Agent: ' . $useragent));
3131 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3133 if ($this->debug) {
3134 echo '<h1>Options</h1>';
3135 var_dump($this->options);
3136 echo '<h1>Header</h1>';
3137 var_dump($this->header);
3140 // Do not allow infinite redirects.
3141 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3142 $this->options['CURLOPT_MAXREDIRS'] = 0;
3143 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3144 $this->options['CURLOPT_MAXREDIRS'] = 100;
3145 } else {
3146 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3149 // Make sure we always know if redirects expected.
3150 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3151 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3154 // Limit the protocols to HTTP and HTTPS.
3155 if (defined('CURLOPT_PROTOCOLS')) {
3156 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3157 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3160 // Set options.
3161 foreach($this->options as $name => $val) {
3162 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3163 // The redirects are emulated elsewhere.
3164 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3165 continue;
3167 $name = constant($name);
3168 curl_setopt($curl, $name, $val);
3171 return $curl;
3175 * Download multiple files in parallel
3177 * Calls {@link multi()} with specific download headers
3179 * <code>
3180 * $c = new curl();
3181 * $file1 = fopen('a', 'wb');
3182 * $file2 = fopen('b', 'wb');
3183 * $c->download(array(
3184 * array('url'=>'http://localhost/', 'file'=>$file1),
3185 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3186 * ));
3187 * fclose($file1);
3188 * fclose($file2);
3189 * </code>
3191 * or
3193 * <code>
3194 * $c = new curl();
3195 * $c->download(array(
3196 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3197 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3198 * ));
3199 * </code>
3201 * @param array $requests An array of files to request {
3202 * url => url to download the file [required]
3203 * file => file handler, or
3204 * filepath => file path
3206 * If 'file' and 'filepath' parameters are both specified in one request, the
3207 * open file handle in the 'file' parameter will take precedence and 'filepath'
3208 * will be ignored.
3210 * @param array $options An array of options to set
3211 * @return array An array of results
3213 public function download($requests, $options = array()) {
3214 $options['RETURNTRANSFER'] = false;
3215 return $this->multi($requests, $options);
3219 * Multi HTTP Requests
3220 * This function could run multi-requests in parallel.
3222 * @param array $requests An array of files to request
3223 * @param array $options An array of options to set
3224 * @return array An array of results
3226 protected function multi($requests, $options = array()) {
3227 $count = count($requests);
3228 $handles = array();
3229 $results = array();
3230 $main = curl_multi_init();
3231 for ($i = 0; $i < $count; $i++) {
3232 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3233 // open file
3234 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3235 $requests[$i]['auto-handle'] = true;
3237 foreach($requests[$i] as $n=>$v) {
3238 $options[$n] = $v;
3240 $handles[$i] = curl_init($requests[$i]['url']);
3241 $this->apply_opt($handles[$i], $options);
3242 curl_multi_add_handle($main, $handles[$i]);
3244 $running = 0;
3245 do {
3246 curl_multi_exec($main, $running);
3247 } while($running > 0);
3248 for ($i = 0; $i < $count; $i++) {
3249 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3250 $results[] = true;
3251 } else {
3252 $results[] = curl_multi_getcontent($handles[$i]);
3254 curl_multi_remove_handle($main, $handles[$i]);
3256 curl_multi_close($main);
3258 for ($i = 0; $i < $count; $i++) {
3259 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3260 // close file handler if file is opened in this function
3261 fclose($requests[$i]['file']);
3264 return $results;
3268 * Single HTTP Request
3270 * @param string $url The URL to request
3271 * @param array $options
3272 * @return bool
3274 protected function request($url, $options = array()) {
3275 // Set the URL as a curl option.
3276 $this->setopt(array('CURLOPT_URL' => $url));
3278 // Create curl instance.
3279 $curl = curl_init();
3281 // Reset here so that the data is valid when result returned from cache.
3282 $this->info = array();
3283 $this->error = '';
3284 $this->errno = 0;
3285 $this->response = array();
3286 $this->rawresponse = array();
3287 $this->responsefinished = false;
3289 $this->apply_opt($curl, $options);
3290 if ($this->cache && $ret = $this->cache->get($this->options)) {
3291 return $ret;
3294 $ret = curl_exec($curl);
3295 $this->info = curl_getinfo($curl);
3296 $this->error = curl_error($curl);
3297 $this->errno = curl_errno($curl);
3298 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3300 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3301 $redirects = 0;
3303 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3305 if ($this->info['http_code'] == 301) {
3306 // Moved Permanently - repeat the same request on new URL.
3308 } else if ($this->info['http_code'] == 302) {
3309 // Found - the standard redirect - repeat the same request on new URL.
3311 } else if ($this->info['http_code'] == 303) {
3312 // 303 See Other - repeat only if GET, do not bother with POSTs.
3313 if (empty($this->options['CURLOPT_HTTPGET'])) {
3314 break;
3317 } else if ($this->info['http_code'] == 307) {
3318 // Temporary Redirect - must repeat using the same request type.
3320 } else if ($this->info['http_code'] == 308) {
3321 // Permanent Redirect - must repeat using the same request type.
3323 } else {
3324 // Some other http code means do not retry!
3325 break;
3328 $redirects++;
3330 $redirecturl = null;
3331 if (isset($this->info['redirect_url'])) {
3332 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3333 $redirecturl = $this->info['redirect_url'];
3336 if (!$redirecturl) {
3337 foreach ($this->response as $k => $v) {
3338 if (strtolower($k) === 'location') {
3339 $redirecturl = $v;
3340 break;
3343 if (preg_match('|^https?://|i', $redirecturl)) {
3344 // Great, this is the correct location format!
3346 } else if ($redirecturl) {
3347 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3348 if (strpos($redirecturl, '/') === 0) {
3349 // Relative to server root - just guess.
3350 $pos = strpos('/', $current, 8);
3351 if ($pos === false) {
3352 $redirecturl = $current.$redirecturl;
3353 } else {
3354 $redirecturl = substr($current, 0, $pos).$redirecturl;
3356 } else {
3357 // Relative to current script.
3358 $redirecturl = dirname($current).'/'.$redirecturl;
3363 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3364 $ret = curl_exec($curl);
3366 $this->info = curl_getinfo($curl);
3367 $this->error = curl_error($curl);
3368 $this->errno = curl_errno($curl);
3370 $this->info['redirect_count'] = $redirects;
3372 if ($this->info['http_code'] === 200) {
3373 // Finally this is what we wanted.
3374 break;
3376 if ($this->errno != CURLE_OK) {
3377 // Something wrong is going on.
3378 break;
3381 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3382 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3383 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3387 if ($this->cache) {
3388 $this->cache->set($this->options, $ret);
3391 if ($this->debug) {
3392 echo '<h1>Return Data</h1>';
3393 var_dump($ret);
3394 echo '<h1>Info</h1>';
3395 var_dump($this->info);
3396 echo '<h1>Error</h1>';
3397 var_dump($this->error);
3400 curl_close($curl);
3402 if (empty($this->error)) {
3403 return $ret;
3404 } else {
3405 return $this->error;
3406 // exception is not ajax friendly
3407 //throw new moodle_exception($this->error, 'curl');
3412 * HTTP HEAD method
3414 * @see request()
3416 * @param string $url
3417 * @param array $options
3418 * @return bool
3420 public function head($url, $options = array()) {
3421 $options['CURLOPT_HTTPGET'] = 0;
3422 $options['CURLOPT_HEADER'] = 1;
3423 $options['CURLOPT_NOBODY'] = 1;
3424 return $this->request($url, $options);
3428 * HTTP POST method
3430 * @param string $url
3431 * @param array|string $params
3432 * @param array $options
3433 * @return bool
3435 public function post($url, $params = '', $options = array()) {
3436 $options['CURLOPT_POST'] = 1;
3437 if (is_array($params)) {
3438 $this->_tmp_file_post_params = array();
3439 foreach ($params as $key => $value) {
3440 if ($value instanceof stored_file) {
3441 $value->add_to_curl_request($this, $key);
3442 } else {
3443 $this->_tmp_file_post_params[$key] = $value;
3446 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3447 unset($this->_tmp_file_post_params);
3448 } else {
3449 // $params is the raw post data
3450 $options['CURLOPT_POSTFIELDS'] = $params;
3452 return $this->request($url, $options);
3456 * HTTP GET method
3458 * @param string $url
3459 * @param array $params
3460 * @param array $options
3461 * @return bool
3463 public function get($url, $params = array(), $options = array()) {
3464 $options['CURLOPT_HTTPGET'] = 1;
3466 if (!empty($params)) {
3467 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3468 $url .= http_build_query($params, '', '&');
3470 return $this->request($url, $options);
3474 * Downloads one file and writes it to the specified file handler
3476 * <code>
3477 * $c = new curl();
3478 * $file = fopen('savepath', 'w');
3479 * $result = $c->download_one('http://localhost/', null,
3480 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3481 * fclose($file);
3482 * $download_info = $c->get_info();
3483 * if ($result === true) {
3484 * // file downloaded successfully
3485 * } else {
3486 * $error_text = $result;
3487 * $error_code = $c->get_errno();
3489 * </code>
3491 * <code>
3492 * $c = new curl();
3493 * $result = $c->download_one('http://localhost/', null,
3494 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3495 * // ... see above, no need to close handle and remove file if unsuccessful
3496 * </code>
3498 * @param string $url
3499 * @param array|null $params key-value pairs to be added to $url as query string
3500 * @param array $options request options. Must include either 'file' or 'filepath'
3501 * @return bool|string true on success or error string on failure
3503 public function download_one($url, $params, $options = array()) {
3504 $options['CURLOPT_HTTPGET'] = 1;
3505 if (!empty($params)) {
3506 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3507 $url .= http_build_query($params, '', '&');
3509 if (!empty($options['filepath']) && empty($options['file'])) {
3510 // open file
3511 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3512 $this->errno = 100;
3513 return get_string('cannotwritefile', 'error', $options['filepath']);
3515 $filepath = $options['filepath'];
3517 unset($options['filepath']);
3518 $result = $this->request($url, $options);
3519 if (isset($filepath)) {
3520 fclose($options['file']);
3521 if ($result !== true) {
3522 unlink($filepath);
3525 return $result;
3529 * HTTP PUT method
3531 * @param string $url
3532 * @param array $params
3533 * @param array $options
3534 * @return bool
3536 public function put($url, $params = array(), $options = array()) {
3537 $file = $params['file'];
3538 if (!is_file($file)) {
3539 return null;
3541 $fp = fopen($file, 'r');
3542 $size = filesize($file);
3543 $options['CURLOPT_PUT'] = 1;
3544 $options['CURLOPT_INFILESIZE'] = $size;
3545 $options['CURLOPT_INFILE'] = $fp;
3546 if (!isset($this->options['CURLOPT_USERPWD'])) {
3547 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3549 $ret = $this->request($url, $options);
3550 fclose($fp);
3551 return $ret;
3555 * HTTP DELETE method
3557 * @param string $url
3558 * @param array $param
3559 * @param array $options
3560 * @return bool
3562 public function delete($url, $param = array(), $options = array()) {
3563 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3564 if (!isset($options['CURLOPT_USERPWD'])) {
3565 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3567 $ret = $this->request($url, $options);
3568 return $ret;
3572 * HTTP TRACE method
3574 * @param string $url
3575 * @param array $options
3576 * @return bool
3578 public function trace($url, $options = array()) {
3579 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3580 $ret = $this->request($url, $options);
3581 return $ret;
3585 * HTTP OPTIONS method
3587 * @param string $url
3588 * @param array $options
3589 * @return bool
3591 public function options($url, $options = array()) {
3592 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3593 $ret = $this->request($url, $options);
3594 return $ret;
3598 * Get curl information
3600 * @return string
3602 public function get_info() {
3603 return $this->info;
3607 * Get curl error code
3609 * @return int
3611 public function get_errno() {
3612 return $this->errno;
3616 * When using a proxy, an additional HTTP response code may appear at
3617 * the start of the header. For example, when using https over a proxy
3618 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3619 * also possible and some may come with their own headers.
3621 * If using the return value containing all headers, this function can be
3622 * called to remove unwanted doubles.
3624 * Note that it is not possible to distinguish this situation from valid
3625 * data unless you know the actual response part (below the headers)
3626 * will not be included in this string, or else will not 'look like' HTTP
3627 * headers. As a result it is not safe to call this function for general
3628 * data.
3630 * @param string $input Input HTTP response
3631 * @return string HTTP response with additional headers stripped if any
3633 public static function strip_double_headers($input) {
3634 // I have tried to make this regular expression as specific as possible
3635 // to avoid any case where it does weird stuff if you happen to put
3636 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3637 // also make it faster because it can abandon regex processing as soon
3638 // as it hits something that doesn't look like an http header. The
3639 // header definition is taken from RFC 822, except I didn't support
3640 // folding which is never used in practice.
3641 $crlf = "\r\n";
3642 return preg_replace(
3643 // HTTP version and status code (ignore value of code).
3644 '~^HTTP/1\..*' . $crlf .
3645 // Header name: character between 33 and 126 decimal, except colon.
3646 // Colon. Header value: any character except \r and \n. CRLF.
3647 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3648 // Headers are terminated by another CRLF (blank line).
3649 $crlf .
3650 // Second HTTP status code, this time must be 200.
3651 '(HTTP/1.[01] 200 )~', '$1', $input);
3656 * This class is used by cURL class, use case:
3658 * <code>
3659 * $CFG->repositorycacheexpire = 120;
3660 * $CFG->curlcache = 120;
3662 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3663 * $ret = $c->get('http://www.google.com');
3664 * </code>
3666 * @package core_files
3667 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3668 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3670 class curl_cache {
3671 /** @var string Path to cache directory */
3672 public $dir = '';
3675 * Constructor
3677 * @global stdClass $CFG
3678 * @param string $module which module is using curl_cache
3680 public function __construct($module = 'repository') {
3681 global $CFG;
3682 if (!empty($module)) {
3683 $this->dir = $CFG->cachedir.'/'.$module.'/';
3684 } else {
3685 $this->dir = $CFG->cachedir.'/misc/';
3687 if (!file_exists($this->dir)) {
3688 mkdir($this->dir, $CFG->directorypermissions, true);
3690 if ($module == 'repository') {
3691 if (empty($CFG->repositorycacheexpire)) {
3692 $CFG->repositorycacheexpire = 120;
3694 $this->ttl = $CFG->repositorycacheexpire;
3695 } else {
3696 if (empty($CFG->curlcache)) {
3697 $CFG->curlcache = 120;
3699 $this->ttl = $CFG->curlcache;
3704 * Get cached value
3706 * @global stdClass $CFG
3707 * @global stdClass $USER
3708 * @param mixed $param
3709 * @return bool|string
3711 public function get($param) {
3712 global $CFG, $USER;
3713 $this->cleanup($this->ttl);
3714 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3715 if(file_exists($this->dir.$filename)) {
3716 $lasttime = filemtime($this->dir.$filename);
3717 if (time()-$lasttime > $this->ttl) {
3718 return false;
3719 } else {
3720 $fp = fopen($this->dir.$filename, 'r');
3721 $size = filesize($this->dir.$filename);
3722 $content = fread($fp, $size);
3723 return unserialize($content);
3726 return false;
3730 * Set cache value
3732 * @global object $CFG
3733 * @global object $USER
3734 * @param mixed $param
3735 * @param mixed $val
3737 public function set($param, $val) {
3738 global $CFG, $USER;
3739 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3740 $fp = fopen($this->dir.$filename, 'w');
3741 fwrite($fp, serialize($val));
3742 fclose($fp);
3743 @chmod($this->dir.$filename, $CFG->filepermissions);
3747 * Remove cache files
3749 * @param int $expire The number of seconds before expiry
3751 public function cleanup($expire) {
3752 if ($dir = opendir($this->dir)) {
3753 while (false !== ($file = readdir($dir))) {
3754 if(!is_dir($file) && $file != '.' && $file != '..') {
3755 $lasttime = @filemtime($this->dir.$file);
3756 if (time() - $lasttime > $expire) {
3757 @unlink($this->dir.$file);
3761 closedir($dir);
3765 * delete current user's cache file
3767 * @global object $CFG
3768 * @global object $USER
3770 public function refresh() {
3771 global $CFG, $USER;
3772 if ($dir = opendir($this->dir)) {
3773 while (false !== ($file = readdir($dir))) {
3774 if (!is_dir($file) && $file != '.' && $file != '..') {
3775 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3776 @unlink($this->dir.$file);
3785 * This function delegates file serving to individual plugins
3787 * @param string $relativepath
3788 * @param bool $forcedownload
3789 * @param null|string $preview the preview mode, defaults to serving the original file
3790 * @todo MDL-31088 file serving improments
3792 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3793 global $DB, $CFG, $USER;
3794 // relative path must start with '/'
3795 if (!$relativepath) {
3796 print_error('invalidargorconf');
3797 } else if ($relativepath[0] != '/') {
3798 print_error('pathdoesnotstartslash');
3801 // extract relative path components
3802 $args = explode('/', ltrim($relativepath, '/'));
3804 if (count($args) < 3) { // always at least context, component and filearea
3805 print_error('invalidarguments');
3808 $contextid = (int)array_shift($args);
3809 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3810 $filearea = clean_param(array_shift($args), PARAM_AREA);
3812 list($context, $course, $cm) = get_context_info_array($contextid);
3814 $fs = get_file_storage();
3816 // ========================================================================================================================
3817 if ($component === 'blog') {
3818 // Blog file serving
3819 if ($context->contextlevel != CONTEXT_SYSTEM) {
3820 send_file_not_found();
3822 if ($filearea !== 'attachment' and $filearea !== 'post') {
3823 send_file_not_found();
3826 if (empty($CFG->enableblogs)) {
3827 print_error('siteblogdisable', 'blog');
3830 $entryid = (int)array_shift($args);
3831 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3832 send_file_not_found();
3834 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3835 require_login();
3836 if (isguestuser()) {
3837 print_error('noguest');
3839 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3840 if ($USER->id != $entry->userid) {
3841 send_file_not_found();
3846 if ($entry->publishstate === 'public') {
3847 if ($CFG->forcelogin) {
3848 require_login();
3851 } else if ($entry->publishstate === 'site') {
3852 require_login();
3853 //ok
3854 } else if ($entry->publishstate === 'draft') {
3855 require_login();
3856 if ($USER->id != $entry->userid) {
3857 send_file_not_found();
3861 $filename = array_pop($args);
3862 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3864 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3865 send_file_not_found();
3868 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3870 // ========================================================================================================================
3871 } else if ($component === 'grade') {
3872 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3873 // Global gradebook files
3874 if ($CFG->forcelogin) {
3875 require_login();
3878 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3880 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3881 send_file_not_found();
3884 \core\session\manager::write_close(); // Unlock session during file serving.
3885 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3887 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3888 //TODO: nobody implemented this yet in grade edit form!!
3889 send_file_not_found();
3891 if ($CFG->forcelogin || $course->id != SITEID) {
3892 require_login($course);
3895 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3897 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3898 send_file_not_found();
3901 \core\session\manager::write_close(); // Unlock session during file serving.
3902 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3903 } else {
3904 send_file_not_found();
3907 // ========================================================================================================================
3908 } else if ($component === 'tag') {
3909 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3911 // All tag descriptions are going to be public but we still need to respect forcelogin
3912 if ($CFG->forcelogin) {
3913 require_login();
3916 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3918 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3919 send_file_not_found();
3922 \core\session\manager::write_close(); // Unlock session during file serving.
3923 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3925 } else {
3926 send_file_not_found();
3928 // ========================================================================================================================
3929 } else if ($component === 'badges') {
3930 require_once($CFG->libdir . '/badgeslib.php');
3932 $badgeid = (int)array_shift($args);
3933 $badge = new badge($badgeid);
3934 $filename = array_pop($args);
3936 if ($filearea === 'badgeimage') {
3937 if ($filename !== 'f1' && $filename !== 'f2') {
3938 send_file_not_found();
3940 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
3941 send_file_not_found();
3944 \core\session\manager::write_close();
3945 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3946 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
3947 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
3948 send_file_not_found();
3951 \core\session\manager::write_close();
3952 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3954 // ========================================================================================================================
3955 } else if ($component === 'calendar') {
3956 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3958 // All events here are public the one requirement is that we respect forcelogin
3959 if ($CFG->forcelogin) {
3960 require_login();
3963 // Get the event if from the args array
3964 $eventid = array_shift($args);
3966 // Load the event from the database
3967 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3968 send_file_not_found();
3971 // Get the file and serve if successful
3972 $filename = array_pop($args);
3973 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3974 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3975 send_file_not_found();
3978 \core\session\manager::write_close(); // Unlock session during file serving.
3979 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3981 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3983 // Must be logged in, if they are not then they obviously can't be this user
3984 require_login();
3986 // Don't want guests here, potentially saves a DB call
3987 if (isguestuser()) {
3988 send_file_not_found();
3991 // Get the event if from the args array
3992 $eventid = array_shift($args);
3994 // Load the event from the database - user id must match
3995 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3996 send_file_not_found();
3999 // Get the file and serve if successful
4000 $filename = array_pop($args);
4001 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4002 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4003 send_file_not_found();
4006 \core\session\manager::write_close(); // Unlock session during file serving.
4007 send_stored_file($file, 0, 0, true, array('preview' => $preview));
4009 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4011 // Respect forcelogin and require login unless this is the site.... it probably
4012 // should NEVER be the site
4013 if ($CFG->forcelogin || $course->id != SITEID) {
4014 require_login($course);
4017 // Must be able to at least view the course. This does not apply to the front page.
4018 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4019 //TODO: hmm, do we really want to block guests here?
4020 send_file_not_found();
4023 // Get the event id
4024 $eventid = array_shift($args);
4026 // Load the event from the database we need to check whether it is
4027 // a) valid course event
4028 // b) a group event
4029 // Group events use the course context (there is no group context)
4030 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4031 send_file_not_found();
4034 // If its a group event require either membership of view all groups capability
4035 if ($event->eventtype === 'group') {
4036 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4037 send_file_not_found();
4039 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4040 // Ok. Please note that the event type 'site' still uses a course context.
4041 } else {
4042 // Some other type.
4043 send_file_not_found();
4046 // If we get this far we can serve the file
4047 $filename = array_pop($args);
4048 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4049 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4050 send_file_not_found();
4053 \core\session\manager::write_close(); // Unlock session during file serving.
4054 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4056 } else {
4057 send_file_not_found();
4060 // ========================================================================================================================
4061 } else if ($component === 'user') {
4062 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4063 if (count($args) == 1) {
4064 $themename = theme_config::DEFAULT_THEME;
4065 $filename = array_shift($args);
4066 } else {
4067 $themename = array_shift($args);
4068 $filename = array_shift($args);
4071 // fix file name automatically
4072 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4073 $filename = 'f1';
4076 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4077 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4078 // protect images if login required and not logged in;
4079 // also if login is required for profile images and is not logged in or guest
4080 // do not use require_login() because it is expensive and not suitable here anyway
4081 $theme = theme_config::load($themename);
4082 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
4085 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4086 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4087 if ($filename === 'f3') {
4088 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4089 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4090 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4095 if (!$file) {
4096 // bad reference - try to prevent future retries as hard as possible!
4097 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4098 if ($user->picture > 0) {
4099 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4102 // no redirect here because it is not cached
4103 $theme = theme_config::load($themename);
4104 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4105 send_file($imagefile, basename($imagefile), 60*60*24*14);
4108 $options = array('preview' => $preview);
4109 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4110 // Profile images should be cache-able by both browsers and proxies according
4111 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4112 $options['cacheability'] = 'public';
4114 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4116 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4117 require_login();
4119 if (isguestuser()) {
4120 send_file_not_found();
4123 if ($USER->id !== $context->instanceid) {
4124 send_file_not_found();
4127 $filename = array_pop($args);
4128 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4129 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4130 send_file_not_found();
4133 \core\session\manager::write_close(); // Unlock session during file serving.
4134 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4136 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4138 if ($CFG->forcelogin) {
4139 require_login();
4142 $userid = $context->instanceid;
4144 if ($USER->id == $userid) {
4145 // always can access own
4147 } else if (!empty($CFG->forceloginforprofiles)) {
4148 require_login();
4150 if (isguestuser()) {
4151 send_file_not_found();
4154 // we allow access to site profile of all course contacts (usually teachers)
4155 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4156 send_file_not_found();
4159 $canview = false;
4160 if (has_capability('moodle/user:viewdetails', $context)) {
4161 $canview = true;
4162 } else {
4163 $courses = enrol_get_my_courses();
4166 while (!$canview && count($courses) > 0) {
4167 $course = array_shift($courses);
4168 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4169 $canview = true;
4174 $filename = array_pop($args);
4175 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4176 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4177 send_file_not_found();
4180 \core\session\manager::write_close(); // Unlock session during file serving.
4181 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4183 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4184 $userid = (int)array_shift($args);
4185 $usercontext = context_user::instance($userid);
4187 if ($CFG->forcelogin) {
4188 require_login();
4191 if (!empty($CFG->forceloginforprofiles)) {
4192 require_login();
4193 if (isguestuser()) {
4194 print_error('noguest');
4197 //TODO: review this logic of user profile access prevention
4198 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4199 print_error('usernotavailable');
4201 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4202 print_error('cannotviewprofile');
4204 if (!is_enrolled($context, $userid)) {
4205 print_error('notenrolledprofile');
4207 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4208 print_error('groupnotamember');
4212 $filename = array_pop($args);
4213 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4214 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4215 send_file_not_found();
4218 \core\session\manager::write_close(); // Unlock session during file serving.
4219 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4221 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4222 require_login();
4224 if (isguestuser()) {
4225 send_file_not_found();
4227 $userid = $context->instanceid;
4229 if ($USER->id != $userid) {
4230 send_file_not_found();
4233 $filename = array_pop($args);
4234 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4235 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4236 send_file_not_found();
4239 \core\session\manager::write_close(); // Unlock session during file serving.
4240 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4242 } else {
4243 send_file_not_found();
4246 // ========================================================================================================================
4247 } else if ($component === 'coursecat') {
4248 if ($context->contextlevel != CONTEXT_COURSECAT) {
4249 send_file_not_found();
4252 if ($filearea === 'description') {
4253 if ($CFG->forcelogin) {
4254 // no login necessary - unless login forced everywhere
4255 require_login();
4258 // Check if user can view this category.
4259 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4260 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid));
4261 if (!$coursecatvisible) {
4262 send_file_not_found();
4266 $filename = array_pop($args);
4267 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4268 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4269 send_file_not_found();
4272 \core\session\manager::write_close(); // Unlock session during file serving.
4273 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4274 } else {
4275 send_file_not_found();
4278 // ========================================================================================================================
4279 } else if ($component === 'course') {
4280 if ($context->contextlevel != CONTEXT_COURSE) {
4281 send_file_not_found();
4284 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4285 if ($CFG->forcelogin) {
4286 require_login();
4289 $filename = array_pop($args);
4290 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4291 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4292 send_file_not_found();
4295 \core\session\manager::write_close(); // Unlock session during file serving.
4296 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4298 } else if ($filearea === 'section') {
4299 if ($CFG->forcelogin) {
4300 require_login($course);
4301 } else if ($course->id != SITEID) {
4302 require_login($course);
4305 $sectionid = (int)array_shift($args);
4307 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4308 send_file_not_found();
4311 $filename = array_pop($args);
4312 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4313 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4314 send_file_not_found();
4317 \core\session\manager::write_close(); // Unlock session during file serving.
4318 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4320 } else {
4321 send_file_not_found();
4324 } else if ($component === 'cohort') {
4326 $cohortid = (int)array_shift($args);
4327 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4328 $cohortcontext = context::instance_by_id($cohort->contextid);
4330 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4331 if ($context->id != $cohort->contextid &&
4332 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4333 send_file_not_found();
4336 // User is able to access cohort if they have view cap on cohort level or
4337 // the cohort is visible and they have view cap on course level.
4338 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4339 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4341 if ($filearea === 'description' && $canview) {
4342 $filename = array_pop($args);
4343 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4344 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4345 && !$file->is_directory()) {
4346 \core\session\manager::write_close(); // Unlock session during file serving.
4347 send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
4351 send_file_not_found();
4353 } else if ($component === 'group') {
4354 if ($context->contextlevel != CONTEXT_COURSE) {
4355 send_file_not_found();
4358 require_course_login($course, true, null, false);
4360 $groupid = (int)array_shift($args);
4362 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4363 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4364 // do not allow access to separate group info if not member or teacher
4365 send_file_not_found();
4368 if ($filearea === 'description') {
4370 require_login($course);
4372 $filename = array_pop($args);
4373 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4374 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4375 send_file_not_found();
4378 \core\session\manager::write_close(); // Unlock session during file serving.
4379 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4381 } else if ($filearea === 'icon') {
4382 $filename = array_pop($args);
4384 if ($filename !== 'f1' and $filename !== 'f2') {
4385 send_file_not_found();
4387 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4388 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4389 send_file_not_found();
4393 \core\session\manager::write_close(); // Unlock session during file serving.
4394 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4396 } else {
4397 send_file_not_found();
4400 } else if ($component === 'grouping') {
4401 if ($context->contextlevel != CONTEXT_COURSE) {
4402 send_file_not_found();
4405 require_login($course);
4407 $groupingid = (int)array_shift($args);
4409 // note: everybody has access to grouping desc images for now
4410 if ($filearea === 'description') {
4412 $filename = array_pop($args);
4413 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4414 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4415 send_file_not_found();
4418 \core\session\manager::write_close(); // Unlock session during file serving.
4419 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4421 } else {
4422 send_file_not_found();
4425 // ========================================================================================================================
4426 } else if ($component === 'backup') {
4427 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4428 require_login($course);
4429 require_capability('moodle/backup:downloadfile', $context);
4431 $filename = array_pop($args);
4432 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4433 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4434 send_file_not_found();
4437 \core\session\manager::write_close(); // Unlock session during file serving.
4438 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4440 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4441 require_login($course);
4442 require_capability('moodle/backup:downloadfile', $context);
4444 $sectionid = (int)array_shift($args);
4446 $filename = array_pop($args);
4447 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4448 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4449 send_file_not_found();
4452 \core\session\manager::write_close();
4453 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4455 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4456 require_login($course, false, $cm);
4457 require_capability('moodle/backup:downloadfile', $context);
4459 $filename = array_pop($args);
4460 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4461 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4462 send_file_not_found();
4465 \core\session\manager::write_close();
4466 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4468 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4469 // Backup files that were generated by the automated backup systems.
4471 require_login($course);
4472 require_capability('moodle/site:config', $context);
4474 $filename = array_pop($args);
4475 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4476 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4477 send_file_not_found();
4480 \core\session\manager::write_close(); // Unlock session during file serving.
4481 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4483 } else {
4484 send_file_not_found();
4487 // ========================================================================================================================
4488 } else if ($component === 'question') {
4489 require_once($CFG->libdir . '/questionlib.php');
4490 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4491 send_file_not_found();
4493 // ========================================================================================================================
4494 } else if ($component === 'grading') {
4495 if ($filearea === 'description') {
4496 // files embedded into the form definition description
4498 if ($context->contextlevel == CONTEXT_SYSTEM) {
4499 require_login();
4501 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4502 require_login($course, false, $cm);
4504 } else {
4505 send_file_not_found();
4508 $formid = (int)array_shift($args);
4510 $sql = "SELECT ga.id
4511 FROM {grading_areas} ga
4512 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4513 WHERE gd.id = ? AND ga.contextid = ?";
4514 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4516 if (!$areaid) {
4517 send_file_not_found();
4520 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4522 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4523 send_file_not_found();
4526 \core\session\manager::write_close(); // Unlock session during file serving.
4527 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4530 // ========================================================================================================================
4531 } else if (strpos($component, 'mod_') === 0) {
4532 $modname = substr($component, 4);
4533 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4534 send_file_not_found();
4536 require_once("$CFG->dirroot/mod/$modname/lib.php");
4538 if ($context->contextlevel == CONTEXT_MODULE) {
4539 if ($cm->modname !== $modname) {
4540 // somebody tries to gain illegal access, cm type must match the component!
4541 send_file_not_found();
4545 if ($filearea === 'intro') {
4546 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4547 send_file_not_found();
4549 require_course_login($course, true, $cm);
4551 // all users may access it
4552 $filename = array_pop($args);
4553 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4554 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4555 send_file_not_found();
4558 // finally send the file
4559 send_stored_file($file, null, 0, false, array('preview' => $preview));
4562 $filefunction = $component.'_pluginfile';
4563 $filefunctionold = $modname.'_pluginfile';
4564 if (function_exists($filefunction)) {
4565 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4566 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4567 } else if (function_exists($filefunctionold)) {
4568 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4569 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4572 send_file_not_found();
4574 // ========================================================================================================================
4575 } else if (strpos($component, 'block_') === 0) {
4576 $blockname = substr($component, 6);
4577 // note: no more class methods in blocks please, that is ....
4578 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4579 send_file_not_found();
4581 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4583 if ($context->contextlevel == CONTEXT_BLOCK) {
4584 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4585 if ($birecord->blockname !== $blockname) {
4586 // somebody tries to gain illegal access, cm type must match the component!
4587 send_file_not_found();
4590 if ($context->get_course_context(false)) {
4591 // If block is in course context, then check if user has capability to access course.
4592 require_course_login($course);
4593 } else if ($CFG->forcelogin) {
4594 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4595 require_login();
4598 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4599 // User can't access file, if block is hidden or doesn't have block:view capability
4600 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4601 send_file_not_found();
4603 } else {
4604 $birecord = null;
4607 $filefunction = $component.'_pluginfile';
4608 if (function_exists($filefunction)) {
4609 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4610 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4613 send_file_not_found();
4615 // ========================================================================================================================
4616 } else if (strpos($component, '_') === false) {
4617 // all core subsystems have to be specified above, no more guessing here!
4618 send_file_not_found();
4620 } else {
4621 // try to serve general plugin file in arbitrary context
4622 $dir = core_component::get_component_directory($component);
4623 if (!file_exists("$dir/lib.php")) {
4624 send_file_not_found();
4626 include_once("$dir/lib.php");
4628 $filefunction = $component.'_pluginfile';
4629 if (function_exists($filefunction)) {
4630 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4631 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4634 send_file_not_found();