Merge branch 'MDL-76905-master' of https://github.com/ferranrecio/moodle
[moodle.git] / lib / filelib.php
blob57f170f9d2fb3f3947adbd0a278715868e9c7dca
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');
33 /**
34 * Do not process file merging when working with draft area files.
36 define('IGNORE_FILE_MERGE', -1);
38 /**
39 * Unlimited area size constant
41 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
43 /**
44 * Capacity of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
46 define('DRAFT_AREA_BUCKET_CAPACITY', 50);
48 /**
49 * Leaking rate of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
51 define('DRAFT_AREA_BUCKET_LEAK', 0.2);
53 require_once("$CFG->libdir/filestorage/file_exceptions.php");
54 require_once("$CFG->libdir/filestorage/file_storage.php");
55 require_once("$CFG->libdir/filestorage/zip_packer.php");
56 require_once("$CFG->libdir/filebrowser/file_browser.php");
58 /**
59 * Encodes file serving url
61 * @deprecated use moodle_url factory methods instead
63 * @todo MDL-31071 deprecate this function
64 * @global stdClass $CFG
65 * @param string $urlbase
66 * @param string $path /filearea/itemid/dir/dir/file.exe
67 * @param bool $forcedownload
68 * @param bool $https https url required
69 * @return string encoded file url
71 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
72 global $CFG;
74 //TODO: deprecate this
76 if ($CFG->slasharguments) {
77 $parts = explode('/', $path);
78 $parts = array_map('rawurlencode', $parts);
79 $path = implode('/', $parts);
80 $return = $urlbase.$path;
81 if ($forcedownload) {
82 $return .= '?forcedownload=1';
84 } else {
85 $path = rawurlencode($path);
86 $return = $urlbase.'?file='.$path;
87 if ($forcedownload) {
88 $return .= '&amp;forcedownload=1';
92 if ($https) {
93 $return = str_replace('http://', 'https://', $return);
96 return $return;
99 /**
100 * Detects if area contains subdirs,
101 * this is intended for file areas that are attached to content
102 * migrated from 1.x where subdirs were allowed everywhere.
104 * @param context $context
105 * @param string $component
106 * @param string $filearea
107 * @param string $itemid
108 * @return bool
110 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
111 global $DB;
113 if (!isset($itemid)) {
114 // Not initialised yet.
115 return false;
118 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
119 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
120 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
121 return $DB->record_exists_select('files', $select, $params);
125 * Prepares 'editor' formslib element from data in database
127 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
128 * function then copies the embedded files into draft area (assigning itemids automatically),
129 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
130 * displayed.
131 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
132 * your mform's set_data() supplying the object returned by this function.
134 * @category files
135 * @param stdClass $data database field that holds the html text with embedded media
136 * @param string $field the name of the database field that holds the html text with embedded media
137 * @param array $options editor options (like maxifiles, maxbytes etc.)
138 * @param stdClass $context context of the editor
139 * @param string $component
140 * @param string $filearea file area name
141 * @param int $itemid item id, required if item exists
142 * @return stdClass modified data object
144 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
145 $options = (array)$options;
146 if (!isset($options['trusttext'])) {
147 $options['trusttext'] = false;
149 if (!isset($options['forcehttps'])) {
150 $options['forcehttps'] = false;
152 if (!isset($options['subdirs'])) {
153 $options['subdirs'] = false;
155 if (!isset($options['maxfiles'])) {
156 $options['maxfiles'] = 0; // no files by default
158 if (!isset($options['noclean'])) {
159 $options['noclean'] = false;
162 //sanity check for passed context. This function doesn't expect $option['context'] to be set
163 //But this function is called before creating editor hence, this is one of the best places to check
164 //if context is used properly. This check notify developer that they missed passing context to editor.
165 if (isset($context) && !isset($options['context'])) {
166 //if $context is not null then make sure $option['context'] is also set.
167 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
168 } else if (isset($options['context']) && isset($context)) {
169 //If both are passed then they should be equal.
170 if ($options['context']->id != $context->id) {
171 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
172 throw new coding_exception($exceptionmsg);
176 if (is_null($itemid) or is_null($context)) {
177 $contextid = null;
178 $itemid = null;
179 if (!isset($data)) {
180 $data = new stdClass();
182 if (!isset($data->{$field})) {
183 $data->{$field} = '';
185 if (!isset($data->{$field.'format'})) {
186 $data->{$field.'format'} = editors_get_preferred_format();
188 if (!$options['noclean']) {
189 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
192 } else {
193 if ($options['trusttext']) {
194 // noclean ignored if trusttext enabled
195 if (!isset($data->{$field.'trust'})) {
196 $data->{$field.'trust'} = 0;
198 $data = trusttext_pre_edit($data, $field, $context);
199 } else {
200 if (!$options['noclean']) {
201 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
204 $contextid = $context->id;
207 if ($options['maxfiles'] != 0) {
208 $draftid_editor = file_get_submitted_draft_itemid($field);
209 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
210 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
211 } else {
212 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
215 return $data;
219 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
221 * This function moves files from draft area to the destination area and
222 * encodes URLs to the draft files so they can be safely saved into DB. The
223 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
224 * is the name of the database field to hold the wysiwyg editor content. The
225 * editor data comes as an array with text, format and itemid properties. This
226 * function automatically adds $data properties foobar, foobarformat and
227 * foobartrust, where foobar has URL to embedded files encoded.
229 * @category files
230 * @param stdClass $data raw data submitted by the form
231 * @param string $field name of the database field containing the html with embedded media files
232 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
233 * @param stdClass $context context, required for existing data
234 * @param string $component file component
235 * @param string $filearea file area name
236 * @param int $itemid item id, required if item exists
237 * @return stdClass modified data object
239 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
240 $options = (array)$options;
241 if (!isset($options['trusttext'])) {
242 $options['trusttext'] = false;
244 if (!isset($options['forcehttps'])) {
245 $options['forcehttps'] = false;
247 if (!isset($options['subdirs'])) {
248 $options['subdirs'] = false;
250 if (!isset($options['maxfiles'])) {
251 $options['maxfiles'] = 0; // no files by default
253 if (!isset($options['maxbytes'])) {
254 $options['maxbytes'] = 0; // unlimited
256 if (!isset($options['removeorphaneddrafts'])) {
257 $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
260 if ($options['trusttext']) {
261 $data->{$field.'trust'} = trusttext_trusted($context);
262 } else {
263 $data->{$field.'trust'} = 0;
266 $editor = $data->{$field.'_editor'};
268 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
269 $data->{$field} = $editor['text'];
270 } else {
271 // Clean the user drafts area of any files not referenced in the editor text.
272 if ($options['removeorphaneddrafts']) {
273 file_remove_editor_orphaned_files($editor);
275 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
277 $data->{$field.'format'} = $editor['format'];
279 return $data;
283 * Saves text and files modified by Editor formslib element
285 * @category files
286 * @param stdClass $data $database entry field
287 * @param string $field name of data field
288 * @param array $options various options
289 * @param stdClass $context context - must already exist
290 * @param string $component
291 * @param string $filearea file area name
292 * @param int $itemid must already exist, usually means data is in db
293 * @return stdClass modified data obejct
295 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
296 $options = (array)$options;
297 if (!isset($options['subdirs'])) {
298 $options['subdirs'] = false;
300 if (is_null($itemid) or is_null($context)) {
301 $itemid = null;
302 $contextid = null;
303 } else {
304 $contextid = $context->id;
307 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
308 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
309 $data->{$field.'_filemanager'} = $draftid_editor;
311 return $data;
315 * Saves files modified by File manager formslib element
317 * @todo MDL-31073 review this function
318 * @category files
319 * @param stdClass $data $database entry field
320 * @param string $field name of data field
321 * @param array $options various options
322 * @param stdClass $context context - must already exist
323 * @param string $component
324 * @param string $filearea file area name
325 * @param int $itemid must already exist, usually means data is in db
326 * @return stdClass modified data obejct
328 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
329 $options = (array)$options;
330 if (!isset($options['subdirs'])) {
331 $options['subdirs'] = false;
333 if (!isset($options['maxfiles'])) {
334 $options['maxfiles'] = -1; // unlimited
336 if (!isset($options['maxbytes'])) {
337 $options['maxbytes'] = 0; // unlimited
340 if (empty($data->{$field.'_filemanager'})) {
341 $data->$field = '';
343 } else {
344 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
345 $fs = get_file_storage();
347 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
348 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
349 } else {
350 $data->$field = '';
354 return $data;
358 * Generate a draft itemid
360 * @category files
361 * @global moodle_database $DB
362 * @global stdClass $USER
363 * @return int a random but available draft itemid that can be used to create a new draft
364 * file area.
366 function file_get_unused_draft_itemid() {
367 global $DB, $USER;
369 if (isguestuser() or !isloggedin()) {
370 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
371 throw new \moodle_exception('noguest');
374 $contextid = context_user::instance($USER->id)->id;
376 $fs = get_file_storage();
377 $draftitemid = rand(1, 999999999);
378 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
379 $draftitemid = rand(1, 999999999);
382 return $draftitemid;
386 * Initialise a draft file area from a real one by copying the files. A draft
387 * area will be created if one does not already exist. Normally you should
388 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
390 * @category files
391 * @global stdClass $CFG
392 * @global stdClass $USER
393 * @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.
394 * @param int $contextid This parameter and the next two identify the file area to copy files from.
395 * @param string $component
396 * @param string $filearea helps indentify the file area.
397 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
398 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
399 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
400 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
402 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
403 global $CFG, $USER;
405 $options = (array)$options;
406 if (!isset($options['subdirs'])) {
407 $options['subdirs'] = false;
409 if (!isset($options['forcehttps'])) {
410 $options['forcehttps'] = false;
413 $usercontext = context_user::instance($USER->id);
414 $fs = get_file_storage();
416 if (empty($draftitemid)) {
417 // create a new area and copy existing files into
418 $draftitemid = file_get_unused_draft_itemid();
419 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
420 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
421 foreach ($files as $file) {
422 if ($file->is_directory() and $file->get_filepath() === '/') {
423 // we need a way to mark the age of each draft area,
424 // by not copying the root dir we force it to be created automatically with current timestamp
425 continue;
427 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
428 continue;
430 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
431 // XXX: This is a hack for file manager (MDL-28666)
432 // File manager needs to know the original file information before copying
433 // to draft area, so we append these information in mdl_files.source field
434 // {@link file_storage::search_references()}
435 // {@link file_storage::search_references_count()}
436 $sourcefield = $file->get_source();
437 $newsourcefield = new stdClass;
438 $newsourcefield->source = $sourcefield;
439 $original = new stdClass;
440 $original->contextid = $contextid;
441 $original->component = $component;
442 $original->filearea = $filearea;
443 $original->itemid = $itemid;
444 $original->filename = $file->get_filename();
445 $original->filepath = $file->get_filepath();
446 $newsourcefield->original = file_storage::pack_reference($original);
447 $draftfile->set_source(serialize($newsourcefield));
448 // End of file manager hack
451 if (!is_null($text)) {
452 // at this point there should not be any draftfile links yet,
453 // because this is a new text from database that should still contain the @@pluginfile@@ links
454 // this happens when developers forget to post process the text
455 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
457 } else {
458 // nothing to do
461 if (is_null($text)) {
462 return null;
465 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
466 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
470 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
471 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
472 * in the @@PLUGINFILE@@ form.
474 * @param string $text The content that may contain ULRs in need of rewriting.
475 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
476 * @param int $contextid This parameter and the next two identify the file area to use.
477 * @param string $component
478 * @param string $filearea helps identify the file area.
479 * @param int $itemid helps identify the file area.
480 * @param array $options
481 * bool $options.forcehttps Force the user of https
482 * bool $options.reverse Reverse the behaviour of the function
483 * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
484 * string The processed text.
486 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
487 global $CFG, $USER;
489 $options = (array)$options;
490 if (!isset($options['forcehttps'])) {
491 $options['forcehttps'] = false;
494 $baseurl = "{$CFG->wwwroot}/{$file}";
495 if (!empty($options['includetoken'])) {
496 $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
497 $token = get_user_key('core_files', $userid);
498 $finalfile = basename($file);
499 $tokenfile = "token{$finalfile}";
500 $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
501 $baseurl = "{$CFG->wwwroot}/{$file}";
503 if (!$CFG->slasharguments) {
504 $baseurl .= "?token={$token}&file=";
505 } else {
506 $baseurl .= "/{$token}";
510 $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
512 if ($itemid !== null) {
513 $baseurl .= "$itemid/";
516 if ($options['forcehttps']) {
517 $baseurl = str_replace('http://', 'https://', $baseurl);
520 if (!empty($options['reverse'])) {
521 return str_replace($baseurl, '@@PLUGINFILE@@/', $text ?? '');
522 } else {
523 return str_replace('@@PLUGINFILE@@/', $baseurl, $text ?? '');
528 * Returns information about files in a draft area.
530 * @global stdClass $CFG
531 * @global stdClass $USER
532 * @param int $draftitemid the draft area item id.
533 * @param string $filepath path to the directory from which the information have to be retrieved.
534 * @return array with the following entries:
535 * 'filecount' => number of files in the draft area.
536 * 'filesize' => total size of the files in the draft area.
537 * 'foldercount' => number of folders in the draft area.
538 * 'filesize_without_references' => total size of the area excluding file references.
539 * (more information will be added as needed).
541 function file_get_draft_area_info($draftitemid, $filepath = '/') {
542 global $USER;
544 $usercontext = context_user::instance($USER->id);
545 return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
549 * Returns information about files in an area.
551 * @param int $contextid context id
552 * @param string $component component
553 * @param string $filearea file area name
554 * @param int $itemid item id or all files if not specified
555 * @param string $filepath path to the directory from which the information have to be retrieved.
556 * @return array with the following entries:
557 * 'filecount' => number of files in the area.
558 * 'filesize' => total size of the files in the area.
559 * 'foldercount' => number of folders in the area.
560 * 'filesize_without_references' => total size of the area excluding file references.
561 * @since Moodle 3.4
563 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
565 $fs = get_file_storage();
567 $results = array(
568 'filecount' => 0,
569 'foldercount' => 0,
570 'filesize' => 0,
571 'filesize_without_references' => 0
574 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
576 foreach ($draftfiles as $file) {
577 if ($file->is_directory()) {
578 $results['foldercount'] += 1;
579 } else {
580 $results['filecount'] += 1;
583 $filesize = $file->get_filesize();
584 $results['filesize'] += $filesize;
585 if (!$file->is_external_file()) {
586 $results['filesize_without_references'] += $filesize;
590 return $results;
594 * Returns whether a draft area has exceeded/will exceed its size limit.
596 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
598 * @param int $draftitemid the draft area item id.
599 * @param int $areamaxbytes the maximum size allowed in this draft area.
600 * @param int $newfilesize the size that would be added to the current area.
601 * @param bool $includereferences true to include the size of the references in the area size.
602 * @return bool true if the area will/has exceeded its limit.
603 * @since Moodle 2.4
605 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
606 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
607 $draftinfo = file_get_draft_area_info($draftitemid);
608 $areasize = $draftinfo['filesize_without_references'];
609 if ($includereferences) {
610 $areasize = $draftinfo['filesize'];
612 if ($areasize + $newfilesize > $areamaxbytes) {
613 return true;
616 return false;
620 * Returns whether a user has reached their draft area upload rate.
622 * @param int $userid The user id
623 * @return bool
625 function file_is_draft_areas_limit_reached(int $userid): bool {
626 global $CFG;
628 $capacity = $CFG->draft_area_bucket_capacity ?? DRAFT_AREA_BUCKET_CAPACITY;
629 $leak = $CFG->draft_area_bucket_leak ?? DRAFT_AREA_BUCKET_LEAK;
631 $since = time() - floor($capacity / $leak); // The items that were in the bucket before this time are already leaked by now.
632 // We are going to be a bit generous to the user when using the leaky bucket
633 // algorithm below. We are going to assume that the bucket is empty at $since.
634 // We have to do an assumption here unless we really want to get ALL user's draft
635 // items without any limit and put all of them in the leaking bucket.
636 // I decided to favour performance over accuracy here.
638 $fs = get_file_storage();
639 $items = $fs->get_user_draft_items($userid, $since);
640 $items = array_reverse($items); // So that the items are sorted based on time in the ascending direction.
642 // We only need to store the time that each element in the bucket is going to leak. So $bucket is array of leaking times.
643 $bucket = [];
644 foreach ($items as $item) {
645 $now = $item->timemodified;
646 // First let's see if items can be dropped from the bucket as a result of leakage.
647 while (!empty($bucket) && ($now >= $bucket[0])) {
648 array_shift($bucket);
651 // Calculate the time that the new item we put into the bucket will be leaked from it, and store it into the bucket.
652 if ($bucket) {
653 $bucket[] = max($bucket[count($bucket) - 1], $now) + (1 / $leak);
654 } else {
655 $bucket[] = $now + (1 / $leak);
659 // Recalculate the bucket's content based on the leakage until now.
660 $now = time();
661 while (!empty($bucket) && ($now >= $bucket[0])) {
662 array_shift($bucket);
665 return count($bucket) >= $capacity;
669 * Get used space of files
670 * @global moodle_database $DB
671 * @global stdClass $USER
672 * @return int total bytes
674 function file_get_user_used_space() {
675 global $DB, $USER;
677 $usercontext = context_user::instance($USER->id);
678 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
679 JOIN (SELECT contenthash, filename, MAX(id) AS id
680 FROM {files}
681 WHERE contextid = ? AND component = ? AND filearea != ?
682 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
683 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
684 $record = $DB->get_record_sql($sql, $params);
685 return (int)$record->totalbytes;
689 * Convert any string to a valid filepath
690 * @todo review this function
691 * @param string $str
692 * @return string path
694 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
695 if ($str == '/' or empty($str)) {
696 return '/';
697 } else {
698 return '/'.trim($str, '/').'/';
703 * Generate a folder tree of draft area of current USER recursively
705 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
706 * @param int $draftitemid
707 * @param string $filepath
708 * @param mixed $data
710 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
711 global $USER, $OUTPUT, $CFG;
712 $data->children = array();
713 $context = context_user::instance($USER->id);
714 $fs = get_file_storage();
715 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
716 foreach ($files as $file) {
717 if ($file->is_directory()) {
718 $item = new stdClass();
719 $item->sortorder = $file->get_sortorder();
720 $item->filepath = $file->get_filepath();
722 $foldername = explode('/', trim($item->filepath, '/'));
723 $item->fullname = trim(array_pop($foldername), '/');
725 $item->id = uniqid();
726 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
727 $data->children[] = $item;
728 } else {
729 continue;
736 * Listing all files (including folders) in current path (draft area)
737 * used by file manager
738 * @param int $draftitemid
739 * @param string $filepath
740 * @return stdClass
742 function file_get_drafarea_files($draftitemid, $filepath = '/') {
743 global $USER, $OUTPUT, $CFG;
745 $context = context_user::instance($USER->id);
746 $fs = get_file_storage();
748 $data = new stdClass();
749 $data->path = array();
750 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
752 // will be used to build breadcrumb
753 $trail = '/';
754 if ($filepath !== '/') {
755 $filepath = file_correct_filepath($filepath);
756 $parts = explode('/', $filepath);
757 foreach ($parts as $part) {
758 if ($part != '' && $part != null) {
759 $trail .= ($part.'/');
760 $data->path[] = array('name'=>$part, 'path'=>$trail);
765 $list = array();
766 $maxlength = 12;
767 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
768 foreach ($files as $file) {
769 $item = new stdClass();
770 $item->filename = $file->get_filename();
771 $item->filepath = $file->get_filepath();
772 $item->fullname = trim($item->filename, '/');
773 $filesize = $file->get_filesize();
774 $item->size = $filesize ? $filesize : null;
775 $item->filesize = $filesize ? display_size($filesize) : '';
777 $item->sortorder = $file->get_sortorder();
778 $item->author = $file->get_author();
779 $item->license = $file->get_license();
780 $item->datemodified = $file->get_timemodified();
781 $item->datecreated = $file->get_timecreated();
782 $item->isref = $file->is_external_file();
783 if ($item->isref && $file->get_status() == 666) {
784 $item->originalmissing = true;
786 // find the file this draft file was created from and count all references in local
787 // system pointing to that file
788 $source = @unserialize($file->get_source() ?? '');
789 if (isset($source->original)) {
790 $item->refcount = $fs->search_references_count($source->original);
793 if ($file->is_directory()) {
794 $item->filesize = 0;
795 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
796 $item->type = 'folder';
797 $foldername = explode('/', trim($item->filepath, '/'));
798 $item->fullname = trim(array_pop($foldername), '/');
799 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
800 } else {
801 // do NOT use file browser here!
802 $item->mimetype = get_mimetype_description($file);
803 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
804 $item->type = 'zip';
805 } else {
806 $item->type = 'file';
808 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
809 $item->url = $itemurl->out();
810 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
811 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
813 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
814 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
815 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
816 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
817 // used by the widget to display a warning about the problem files.
818 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
819 $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
820 if ($item->status == 0) {
821 if ($imageinfo = $file->get_imageinfo()) {
822 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
823 'oid' => $file->get_timemodified()));
824 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
825 $item->image_width = $imageinfo['width'];
826 $item->image_height = $imageinfo['height'];
830 $list[] = $item;
833 $data->itemid = $draftitemid;
834 $data->list = $list;
835 return $data;
839 * Returns all of the files in the draftarea.
841 * @param int $draftitemid The draft item ID
842 * @param string $filepath path for the uploaded files.
843 * @return array An array of files associated with this draft item id.
845 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
846 $files = [];
847 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
848 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
850 if (!empty($draftfiles)) {
851 foreach ($draftfiles->list as $draftfile) {
852 if ($draftfile->type == 'file') {
853 $files[] = $draftfile;
857 if (isset($draftfiles->children)) {
858 foreach ($draftfiles->children as $draftfile) {
859 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
863 return $files;
867 * Returns draft area itemid for a given element.
869 * @category files
870 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
871 * @return int the itemid, or 0 if there is not one yet.
873 function file_get_submitted_draft_itemid($elname) {
874 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
875 if (!isset($_REQUEST[$elname])) {
876 return 0;
878 if (is_array($_REQUEST[$elname])) {
879 $param = optional_param_array($elname, 0, PARAM_INT);
880 if (!empty($param['itemid'])) {
881 $param = $param['itemid'];
882 } else {
883 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
884 return false;
887 } else {
888 $param = optional_param($elname, 0, PARAM_INT);
891 if ($param) {
892 require_sesskey();
895 return $param;
899 * Restore the original source field from draft files
901 * Do not use this function because it makes field files.source inconsistent
902 * for draft area files. This function will be deprecated in 2.6
904 * @param stored_file $storedfile This only works with draft files
905 * @return stored_file
907 function file_restore_source_field_from_draft_file($storedfile) {
908 $source = @unserialize($storedfile->get_source() ?? '');
909 if (!empty($source)) {
910 if (is_object($source)) {
911 $restoredsource = $source->source;
912 $storedfile->set_source($restoredsource);
913 } else {
914 throw new moodle_exception('invalidsourcefield', 'error');
917 return $storedfile;
921 * Removes those files from the user drafts filearea which are not referenced in the editor text.
923 * @param stdClass $editor The online text editor element from the submitted form data.
925 function file_remove_editor_orphaned_files($editor) {
926 global $CFG, $USER;
928 // Find those draft files included in the text, and generate their hashes.
929 $context = context_user::instance($USER->id);
930 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
931 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
932 preg_match_all($pattern, $editor['text'], $matches);
933 $usedfilehashes = [];
934 foreach ($matches[1] as $matchedfilename) {
935 $matchedfilename = urldecode($matchedfilename);
936 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
937 $matchedfilename);
940 // Now, compare the hashes of all draft files, and remove those which don't match used files.
941 $fs = get_file_storage();
942 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
943 foreach ($files as $file) {
944 $tmphash = $file->get_pathnamehash();
945 if (!in_array($tmphash, $usedfilehashes)) {
946 $file->delete();
952 * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
953 * content from another draft area it's possible for a single textarea to reference multiple draft areas.
955 * @category files
956 * @param int $draftitemid the id of the primary draft area.
957 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
958 * @param int $usercontextid the user's context id.
959 * @param string $text some html content that needs to have files copied to the correct draft area.
960 * @param bool $forcehttps force https urls.
962 * @return string $text html content modified with new draft links
964 function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
965 if (is_null($text)) {
966 return null;
969 // Do not merge files, leave it as it was.
970 if ($draftitemid === IGNORE_FILE_MERGE) {
971 return null;
974 $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
976 // No draft areas to rewrite.
977 if (empty($urls)) {
978 return $text;
981 foreach ($urls as $url) {
982 // Do not process the "home" draft area.
983 if ($url['itemid'] == $draftitemid) {
984 continue;
987 // Decode the filename.
988 $filename = urldecode($url['filename']);
990 // Copy the file.
991 file_copy_file_to_file_area($url, $filename, $draftitemid);
993 // Rewrite draft area.
994 $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
996 return $text;
1000 * Rewrites a file area in arbitrary text.
1002 * @param array $file General information about the file.
1003 * @param int $newid The new file area itemid.
1004 * @param string $text The text to rewrite.
1005 * @param bool $forcehttps force https urls.
1006 * @return string The rewritten text.
1008 function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
1009 global $CFG;
1011 $wwwroot = $CFG->wwwroot;
1012 if ($forcehttps) {
1013 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1016 $search = [
1017 $wwwroot,
1018 $file['urlbase'],
1019 $file['contextid'],
1020 $file['component'],
1021 $file['filearea'],
1022 $file['itemid'],
1023 $file['filename']
1025 $replace = [
1026 $wwwroot,
1027 $file['urlbase'],
1028 $file['contextid'],
1029 $file['component'],
1030 $file['filearea'],
1031 $newid,
1032 $file['filename']
1035 $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
1036 return $text;
1040 * Copies a file from one file area to another.
1042 * @param array $file Information about the file to be copied.
1043 * @param string $filename The filename.
1044 * @param int $itemid The new file area.
1046 function file_copy_file_to_file_area($file, $filename, $itemid) {
1047 $fs = get_file_storage();
1049 // Load the current file in the old draft area.
1050 $fileinfo = array(
1051 'component' => $file['component'],
1052 'filearea' => $file['filearea'],
1053 'itemid' => $file['itemid'],
1054 'contextid' => $file['contextid'],
1055 'filepath' => '/',
1056 'filename' => $filename
1058 $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
1059 $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
1060 $newfileinfo = array(
1061 'component' => $file['component'],
1062 'filearea' => $file['filearea'],
1063 'itemid' => $itemid,
1064 'contextid' => $file['contextid'],
1065 'filepath' => '/',
1066 'filename' => $filename
1069 $newcontextid = $newfileinfo['contextid'];
1070 $newcomponent = $newfileinfo['component'];
1071 $newfilearea = $newfileinfo['filearea'];
1072 $newitemid = $newfileinfo['itemid'];
1073 $newfilepath = $newfileinfo['filepath'];
1074 $newfilename = $newfileinfo['filename'];
1076 // Check if the file exists.
1077 if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1078 $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1083 * Saves files from a draft file area to a real one (merging the list of files).
1084 * Can rewrite URLs in some content at the same time if desired.
1086 * @category files
1087 * @global stdClass $USER
1088 * @param int $draftitemid the id of the draft area to use. Normally obtained
1089 * from file_get_submitted_draft_itemid('elementname') or similar.
1090 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
1091 * @param int $contextid This parameter and the next two identify the file area to save to.
1092 * @param string $component
1093 * @param string $filearea indentifies the file area.
1094 * @param int $itemid helps identifies the file area.
1095 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1096 * @param string $text some html content that needs to have embedded links rewritten
1097 * to the @@PLUGINFILE@@ form for saving in the database.
1098 * @param bool $forcehttps force https urls.
1099 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1101 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1102 global $USER;
1104 // Do not merge files, leave it as it was.
1105 if ($draftitemid === IGNORE_FILE_MERGE) {
1106 // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
1107 return $text;
1110 if ($itemid === false) {
1111 // Catch a potentially dangerous coding error.
1112 throw new coding_exception('file_save_draft_area_files was called with $itemid false. ' .
1113 "This suggests a bug, because it would wipe all ($contextid, $component, $filearea) files.");
1116 $usercontext = context_user::instance($USER->id);
1117 $fs = get_file_storage();
1119 $options = (array)$options;
1120 if (!isset($options['subdirs'])) {
1121 $options['subdirs'] = false;
1123 if (!isset($options['maxfiles'])) {
1124 $options['maxfiles'] = -1; // unlimited
1126 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
1127 $options['maxbytes'] = 0; // unlimited
1129 if (!isset($options['areamaxbytes'])) {
1130 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
1132 $allowreferences = true;
1133 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
1134 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1135 // this is not exactly right. BUT there are many places in code where filemanager options
1136 // are not passed to file_save_draft_area_files()
1137 $allowreferences = false;
1140 // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1141 // areas and need to be copied into the current draft area.
1142 $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
1144 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1145 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1146 // anything at all in the next area.
1147 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1148 return null;
1151 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
1152 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1154 // One file in filearea means it is empty (it has only top-level directory '.').
1155 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
1156 // we have to merge old and new files - we want to keep file ids for files that were not changed
1157 // we change time modified for all new and changed files, we keep time created as is
1159 $newhashes = array();
1160 $filecount = 0;
1161 $context = context::instance_by_id($contextid, MUST_EXIST);
1162 foreach ($draftfiles as $file) {
1163 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1164 continue;
1166 if (!$allowreferences && $file->is_external_file()) {
1167 continue;
1169 if (!$file->is_directory()) {
1170 // Check to see if this file was uploaded by someone who can ignore the file size limits.
1171 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1172 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1173 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1174 // Oversized file.
1175 continue;
1177 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1178 // more files - should not get here at all
1179 continue;
1181 $filecount++;
1183 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1184 $newhashes[$newhash] = $file;
1187 // Loop through oldfiles and decide which we need to delete and which to update.
1188 // After this cycle the array $newhashes will only contain the files that need to be added.
1189 foreach ($oldfiles as $oldfile) {
1190 $oldhash = $oldfile->get_pathnamehash();
1191 if (!isset($newhashes[$oldhash])) {
1192 // delete files not needed any more - deleted by user
1193 $oldfile->delete();
1194 continue;
1197 $newfile = $newhashes[$oldhash];
1198 // Now we know that we have $oldfile and $newfile for the same path.
1199 // Let's check if we can update this file or we need to delete and create.
1200 if ($newfile->is_directory()) {
1201 // Directories are always ok to just update.
1202 } else if (($source = @unserialize($newfile->get_source() ?? '')) && isset($source->original)) {
1203 // File has the 'original' - we need to update the file (it may even have not been changed at all).
1204 $original = file_storage::unpack_reference($source->original);
1205 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
1206 // Very odd, original points to another file. Delete and create file.
1207 $oldfile->delete();
1208 continue;
1210 } else {
1211 // The same file name but absence of 'original' means that file was deteled and uploaded again.
1212 // By deleting and creating new file we properly manage all existing references.
1213 $oldfile->delete();
1214 continue;
1217 // status changed, we delete old file, and create a new one
1218 if ($oldfile->get_status() != $newfile->get_status()) {
1219 // file was changed, use updated with new timemodified data
1220 $oldfile->delete();
1221 // This file will be added later
1222 continue;
1225 // Updated author
1226 if ($oldfile->get_author() != $newfile->get_author()) {
1227 $oldfile->set_author($newfile->get_author());
1229 // Updated license
1230 if ($oldfile->get_license() != $newfile->get_license()) {
1231 $oldfile->set_license($newfile->get_license());
1234 // Updated file source
1235 // Field files.source for draftarea files contains serialised object with source and original information.
1236 // We only store the source part of it for non-draft file area.
1237 $newsource = $newfile->get_source();
1238 if ($source = @unserialize($newfile->get_source() ?? '')) {
1239 $newsource = $source->source;
1241 if ($oldfile->get_source() !== $newsource) {
1242 $oldfile->set_source($newsource);
1245 // Updated sort order
1246 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1247 $oldfile->set_sortorder($newfile->get_sortorder());
1250 // Update file timemodified
1251 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1252 $oldfile->set_timemodified($newfile->get_timemodified());
1255 // Replaced file content
1256 if (!$oldfile->is_directory() &&
1257 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1258 $oldfile->get_filesize() != $newfile->get_filesize() ||
1259 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1260 $oldfile->get_userid() != $newfile->get_userid())) {
1261 $oldfile->replace_file_with($newfile);
1264 // unchanged file or directory - we keep it as is
1265 unset($newhashes[$oldhash]);
1268 // Add fresh file or the file which has changed status
1269 // the size and subdirectory tests are extra safety only, the UI should prevent it
1270 foreach ($newhashes as $file) {
1271 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1272 if ($source = @unserialize($file->get_source() ?? '')) {
1273 // Field files.source for draftarea files contains serialised object with source and original information.
1274 // We only store the source part of it for non-draft file area.
1275 $file_record['source'] = $source->source;
1278 if ($file->is_external_file()) {
1279 $repoid = $file->get_repository_id();
1280 if (!empty($repoid)) {
1281 $context = context::instance_by_id($contextid, MUST_EXIST);
1282 $repo = repository::get_repository_by_id($repoid, $context);
1283 if (!empty($options)) {
1284 $repo->options = $options;
1286 $file_record['repositoryid'] = $repoid;
1287 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1288 // to the file store. E.g. transfer ownership of the file to a system account etc.
1289 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1291 $file_record['reference'] = $reference;
1295 $fs->create_file_from_storedfile($file_record, $file);
1299 // note: do not purge the draft area - we clean up areas later in cron,
1300 // the reason is that user might press submit twice and they would loose the files,
1301 // also sometimes we might want to use hacks that save files into two different areas
1303 if (is_null($text)) {
1304 return null;
1305 } else {
1306 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1311 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1312 * ready to be saved in the database. Normally, this is done automatically by
1313 * {@link file_save_draft_area_files()}.
1315 * @category files
1316 * @param string $text the content to process.
1317 * @param int $draftitemid the draft file area the content was using.
1318 * @param bool $forcehttps whether the content contains https URLs. Default false.
1319 * @return string the processed content.
1321 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1322 global $CFG, $USER;
1324 $usercontext = context_user::instance($USER->id);
1326 $wwwroot = $CFG->wwwroot;
1327 if ($forcehttps) {
1328 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1331 // relink embedded files if text submitted - no absolute links allowed in database!
1332 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1334 if (strpos($text, 'draftfile.php?file=') !== false) {
1335 $matches = array();
1336 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1337 if ($matches) {
1338 foreach ($matches[0] as $match) {
1339 $replace = str_ireplace('%2F', '/', $match);
1340 $text = str_replace($match, $replace, $text);
1343 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1346 return $text;
1350 * Set file sort order
1352 * @global moodle_database $DB
1353 * @param int $contextid the context id
1354 * @param string $component file component
1355 * @param string $filearea file area.
1356 * @param int $itemid itemid.
1357 * @param string $filepath file path.
1358 * @param string $filename file name.
1359 * @param int $sortorder the sort order of file.
1360 * @return bool
1362 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1363 global $DB;
1364 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1365 if ($file_record = $DB->get_record('files', $conditions)) {
1366 $sortorder = (int)$sortorder;
1367 $file_record->sortorder = $sortorder;
1368 $DB->update_record('files', $file_record);
1369 return true;
1371 return false;
1375 * reset file sort order number to 0
1376 * @global moodle_database $DB
1377 * @param int $contextid the context id
1378 * @param string $component
1379 * @param string $filearea file area.
1380 * @param int|bool $itemid itemid.
1381 * @return bool
1383 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1384 global $DB;
1386 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1387 if ($itemid !== false) {
1388 $conditions['itemid'] = $itemid;
1391 $file_records = $DB->get_records('files', $conditions);
1392 foreach ($file_records as $file_record) {
1393 $file_record->sortorder = 0;
1394 $DB->update_record('files', $file_record);
1396 return true;
1400 * Returns description of upload error
1402 * @param int $errorcode found in $_FILES['filename.ext']['error']
1403 * @return string error description string, '' if ok
1405 function file_get_upload_error($errorcode) {
1407 switch ($errorcode) {
1408 case 0: // UPLOAD_ERR_OK - no error
1409 $errmessage = '';
1410 break;
1412 case 1: // UPLOAD_ERR_INI_SIZE
1413 $errmessage = get_string('uploadserverlimit');
1414 break;
1416 case 2: // UPLOAD_ERR_FORM_SIZE
1417 $errmessage = get_string('uploadformlimit');
1418 break;
1420 case 3: // UPLOAD_ERR_PARTIAL
1421 $errmessage = get_string('uploadpartialfile');
1422 break;
1424 case 4: // UPLOAD_ERR_NO_FILE
1425 $errmessage = get_string('uploadnofilefound');
1426 break;
1428 // Note: there is no error with a value of 5
1430 case 6: // UPLOAD_ERR_NO_TMP_DIR
1431 $errmessage = get_string('uploadnotempdir');
1432 break;
1434 case 7: // UPLOAD_ERR_CANT_WRITE
1435 $errmessage = get_string('uploadcantwrite');
1436 break;
1438 case 8: // UPLOAD_ERR_EXTENSION
1439 $errmessage = get_string('uploadextension');
1440 break;
1442 default:
1443 $errmessage = get_string('uploadproblem');
1446 return $errmessage;
1450 * Recursive function formating an array in POST parameter
1451 * @param array $arraydata - the array that we are going to format and add into &$data array
1452 * @param string $currentdata - a row of the final postdata array at instant T
1453 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1454 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1456 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1457 foreach ($arraydata as $k=>$v) {
1458 $newcurrentdata = $currentdata;
1459 if (is_array($v)) { //the value is an array, call the function recursively
1460 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1461 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1462 } else { //add the POST parameter to the $data array
1463 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1469 * Transform a PHP array into POST parameter
1470 * (see the recursive function format_array_postdata_for_curlcall)
1471 * @param array $postdata
1472 * @return array containing all POST parameters (1 row = 1 POST parameter)
1474 function format_postdata_for_curlcall($postdata) {
1475 $data = array();
1476 foreach ($postdata as $k=>$v) {
1477 if (is_array($v)) {
1478 $currentdata = urlencode($k);
1479 format_array_postdata_for_curlcall($v, $currentdata, $data);
1480 } else {
1481 $data[] = urlencode($k).'='.urlencode($v ?? '');
1484 $convertedpostdata = implode('&', $data);
1485 return $convertedpostdata;
1489 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1490 * Due to security concerns only downloads from http(s) sources are supported.
1492 * @category files
1493 * @param string $url file url starting with http(s)://
1494 * @param array $headers http headers, null if none. If set, should be an
1495 * associative array of header name => value pairs.
1496 * @param array $postdata array means use POST request with given parameters
1497 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1498 * (if false, just returns content)
1499 * @param int $timeout timeout for complete download process including all file transfer
1500 * (default 5 minutes)
1501 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1502 * usually happens if the remote server is completely down (default 20 seconds);
1503 * may not work when using proxy
1504 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1505 * Only use this when already in a trusted location.
1506 * @param string $tofile store the downloaded content to file instead of returning it.
1507 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1508 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1509 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1510 * if file downloaded into $tofile successfully or the file content as a string.
1512 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1513 global $CFG;
1515 // Only http and https links supported.
1516 if (!preg_match('|^https?://|i', $url)) {
1517 if ($fullresponse) {
1518 $response = new stdClass();
1519 $response->status = 0;
1520 $response->headers = array();
1521 $response->response_code = 'Invalid protocol specified in url';
1522 $response->results = '';
1523 $response->error = 'Invalid protocol specified in url';
1524 return $response;
1525 } else {
1526 return false;
1530 $options = array();
1532 $headers2 = array();
1533 if (is_array($headers)) {
1534 foreach ($headers as $key => $value) {
1535 if (is_numeric($key)) {
1536 $headers2[] = $value;
1537 } else {
1538 $headers2[] = "$key: $value";
1543 if ($skipcertverify) {
1544 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1545 } else {
1546 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1549 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1551 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1552 $options['CURLOPT_MAXREDIRS'] = 5;
1554 // Use POST if requested.
1555 if (is_array($postdata)) {
1556 $postdata = format_postdata_for_curlcall($postdata);
1557 } else if (empty($postdata)) {
1558 $postdata = null;
1561 // Optionally attempt to get more correct timeout by fetching the file size.
1562 if (!isset($CFG->curltimeoutkbitrate)) {
1563 // Use very slow rate of 56kbps as a timeout speed when not set.
1564 $bitrate = 56;
1565 } else {
1566 $bitrate = $CFG->curltimeoutkbitrate;
1568 if ($calctimeout and !isset($postdata)) {
1569 $curl = new curl();
1570 $curl->setHeader($headers2);
1572 $curl->head($url, $postdata, $options);
1574 $info = $curl->get_info();
1575 $error_no = $curl->get_errno();
1576 if (!$error_no && $info['download_content_length'] > 0) {
1577 // No curl errors - adjust for large files only - take max timeout.
1578 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1582 $curl = new curl();
1583 $curl->setHeader($headers2);
1585 $options['CURLOPT_RETURNTRANSFER'] = true;
1586 $options['CURLOPT_NOBODY'] = false;
1587 $options['CURLOPT_TIMEOUT'] = $timeout;
1589 if ($tofile) {
1590 $fh = fopen($tofile, 'w');
1591 if (!$fh) {
1592 if ($fullresponse) {
1593 $response = new stdClass();
1594 $response->status = 0;
1595 $response->headers = array();
1596 $response->response_code = 'Can not write to file';
1597 $response->results = false;
1598 $response->error = 'Can not write to file';
1599 return $response;
1600 } else {
1601 return false;
1604 $options['CURLOPT_FILE'] = $fh;
1607 if (isset($postdata)) {
1608 $content = $curl->post($url, $postdata, $options);
1609 } else {
1610 $content = $curl->get($url, null, $options);
1613 if ($tofile) {
1614 fclose($fh);
1615 @chmod($tofile, $CFG->filepermissions);
1619 // Try to detect encoding problems.
1620 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1621 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1622 $result = curl_exec($ch);
1626 $info = $curl->get_info();
1627 $error_no = $curl->get_errno();
1628 $rawheaders = $curl->get_raw_response();
1630 if ($error_no) {
1631 $error = $content;
1632 if (!$fullresponse) {
1633 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1634 return false;
1637 $response = new stdClass();
1638 if ($error_no == 28) {
1639 $response->status = '-100'; // Mimic snoopy.
1640 } else {
1641 $response->status = '0';
1643 $response->headers = array();
1644 $response->response_code = $error;
1645 $response->results = false;
1646 $response->error = $error;
1647 return $response;
1650 if ($tofile) {
1651 $content = true;
1654 if (empty($info['http_code'])) {
1655 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1656 $response = new stdClass();
1657 $response->status = '0';
1658 $response->headers = array();
1659 $response->response_code = 'Unknown cURL error';
1660 $response->results = false; // do NOT change this, we really want to ignore the result!
1661 $response->error = 'Unknown cURL error';
1663 } else {
1664 $response = new stdClass();
1665 $response->status = (string)$info['http_code'];
1666 $response->headers = $rawheaders;
1667 $response->results = $content;
1668 $response->error = '';
1670 // There might be multiple headers on redirect, find the status of the last one.
1671 $firstline = true;
1672 foreach ($rawheaders as $line) {
1673 if ($firstline) {
1674 $response->response_code = $line;
1675 $firstline = false;
1677 if (trim($line, "\r\n") === '') {
1678 $firstline = true;
1683 if ($fullresponse) {
1684 return $response;
1687 if ($info['http_code'] != 200) {
1688 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1689 return false;
1691 return $response->results;
1695 * Returns a list of information about file types based on extensions.
1697 * The following elements expected in value array for each extension:
1698 * 'type' - mimetype
1699 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1700 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1701 * also files with bigger sizes under names
1702 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1703 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1704 * commonly used in moodle the following groups:
1705 * - web_image - image that can be included as <img> in HTML
1706 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1707 * - optimised_image - image that will be processed and optimised
1708 * - video - file that can be imported as video in text editor
1709 * - audio - file that can be imported as audio in text editor
1710 * - archive - we can extract files from this archive
1711 * - spreadsheet - used for portfolio format
1712 * - document - used for portfolio format
1713 * - presentation - used for portfolio format
1714 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1715 * human-readable description for this filetype;
1716 * Function {@link get_mimetype_description()} first looks at the presence of string for
1717 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1718 * attribute, if not found returns the value of 'type';
1719 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1720 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1721 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1723 * @category files
1724 * @return array List of information about file types based on extensions.
1725 * Associative array of extension (lower-case) to associative array
1726 * from 'element name' to data. Current element names are 'type' and 'icon'.
1727 * Unknown types should use the 'xxx' entry which includes defaults.
1729 function &get_mimetypes_array() {
1730 // Get types from the core_filetypes function, which includes caching.
1731 return core_filetypes::get_types();
1735 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1737 * This function retrieves a file's MIME type for a file that will be sent to the user.
1738 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1739 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1740 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1742 * @param string $filename The file's filename.
1743 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1745 function get_mimetype_for_sending($filename = '') {
1746 // Guess the file's MIME type using mimeinfo.
1747 $mimetype = mimeinfo('type', $filename);
1749 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1750 if (!$mimetype || $mimetype === 'document/unknown') {
1751 $mimetype = 'application/octet-stream';
1754 return $mimetype;
1758 * Obtains information about a filetype based on its extension. Will
1759 * use a default if no information is present about that particular
1760 * extension.
1762 * @category files
1763 * @param string $element Desired information (usually 'icon'
1764 * for icon filename or 'type' for MIME type. Can also be
1765 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1766 * @param string $filename Filename we're looking up
1767 * @return string Requested piece of information from array
1769 function mimeinfo($element, $filename) {
1770 global $CFG;
1771 $mimeinfo = & get_mimetypes_array();
1772 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1774 $filetype = strtolower(pathinfo($filename ?? '', PATHINFO_EXTENSION));
1775 if (empty($filetype)) {
1776 $filetype = 'xxx'; // file without extension
1778 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1779 $iconsize = max(array(16, (int)$iconsizematch[1]));
1780 $filenames = array($mimeinfo['xxx']['icon']);
1781 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1782 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1784 // find the file with the closest size, first search for specific icon then for default icon
1785 foreach ($filenames as $filename) {
1786 foreach ($iconpostfixes as $size => $postfix) {
1787 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1788 if ($iconsize >= $size &&
1789 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1790 return $filename.$postfix;
1794 } else if (isset($mimeinfo[$filetype][$element])) {
1795 return $mimeinfo[$filetype][$element];
1796 } else if (isset($mimeinfo['xxx'][$element])) {
1797 return $mimeinfo['xxx'][$element]; // By default
1798 } else {
1799 return null;
1804 * Obtains information about a filetype based on the MIME type rather than
1805 * the other way around.
1807 * @category files
1808 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1809 * @param string $mimetype MIME type we're looking up
1810 * @return string Requested piece of information from array
1812 function mimeinfo_from_type($element, $mimetype) {
1813 /* array of cached mimetype->extension associations */
1814 static $cached = array();
1815 $mimeinfo = & get_mimetypes_array();
1817 if (!array_key_exists($mimetype, $cached)) {
1818 $cached[$mimetype] = null;
1819 foreach($mimeinfo as $filetype => $values) {
1820 if ($values['type'] == $mimetype) {
1821 if ($cached[$mimetype] === null) {
1822 $cached[$mimetype] = '.'.$filetype;
1824 if (!empty($values['defaulticon'])) {
1825 $cached[$mimetype] = '.'.$filetype;
1826 break;
1830 if (empty($cached[$mimetype])) {
1831 $cached[$mimetype] = '.xxx';
1834 if ($element === 'extension') {
1835 return $cached[$mimetype];
1836 } else {
1837 return mimeinfo($element, $cached[$mimetype]);
1842 * Return the relative icon path for a given file
1844 * Usage:
1845 * <code>
1846 * // $file - instance of stored_file or file_info
1847 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1848 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1849 * </code>
1850 * or
1851 * <code>
1852 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1853 * </code>
1855 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1856 * and $file->mimetype are expected)
1857 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1858 * @return string
1860 function file_file_icon($file, $size = null) {
1861 if (!is_object($file)) {
1862 $file = (object)$file;
1864 if (isset($file->filename)) {
1865 $filename = $file->filename;
1866 } else if (method_exists($file, 'get_filename')) {
1867 $filename = $file->get_filename();
1868 } else if (method_exists($file, 'get_visible_name')) {
1869 $filename = $file->get_visible_name();
1870 } else {
1871 $filename = '';
1873 if (isset($file->mimetype)) {
1874 $mimetype = $file->mimetype;
1875 } else if (method_exists($file, 'get_mimetype')) {
1876 $mimetype = $file->get_mimetype();
1877 } else {
1878 $mimetype = '';
1880 $mimetypes = &get_mimetypes_array();
1881 if ($filename) {
1882 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1883 if ($extension && !empty($mimetypes[$extension])) {
1884 // if file name has known extension, return icon for this extension
1885 return file_extension_icon($filename, $size);
1888 return file_mimetype_icon($mimetype, $size);
1892 * Return the relative icon path for a folder image
1894 * Usage:
1895 * <code>
1896 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1897 * echo html_writer::empty_tag('img', array('src' => $icon));
1898 * </code>
1899 * or
1900 * <code>
1901 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1902 * </code>
1904 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1905 * @return string
1907 function file_folder_icon($iconsize = null) {
1908 global $CFG;
1909 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1910 static $cached = array();
1911 $iconsize = max(array(16, (int)$iconsize));
1912 if (!array_key_exists($iconsize, $cached)) {
1913 foreach ($iconpostfixes as $size => $postfix) {
1914 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1915 if ($iconsize >= $size &&
1916 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1917 $cached[$iconsize] = 'f/folder'.$postfix;
1918 break;
1922 return $cached[$iconsize];
1926 * Returns the relative icon path for a given mime type
1928 * This function should be used in conjunction with $OUTPUT->image_url to produce
1929 * a return the full path to an icon.
1931 * <code>
1932 * $mimetype = 'image/jpg';
1933 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1934 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1935 * </code>
1937 * @category files
1938 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1939 * to conform with that.
1940 * @param string $mimetype The mimetype to fetch an icon for
1941 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1942 * @return string The relative path to the icon
1944 function file_mimetype_icon($mimetype, $size = NULL) {
1945 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1949 * Returns the relative icon path for a given file name
1951 * This function should be used in conjunction with $OUTPUT->image_url to produce
1952 * a return the full path to an icon.
1954 * <code>
1955 * $filename = '.jpg';
1956 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1957 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1958 * </code>
1960 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1961 * to conform with that.
1962 * @todo MDL-31074 Implement $size
1963 * @category files
1964 * @param string $filename The filename to get the icon for
1965 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1966 * @return string
1968 function file_extension_icon($filename, $size = NULL) {
1969 return 'f/'.mimeinfo('icon'.$size, $filename);
1973 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1974 * mimetypes.php language file.
1976 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1977 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1978 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1979 * @param bool $capitalise If true, capitalises first character of result
1980 * @return string Text description
1982 function get_mimetype_description($obj, $capitalise=false) {
1983 $filename = $mimetype = '';
1984 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1985 // this is an instance of stored_file
1986 $mimetype = $obj->get_mimetype();
1987 $filename = $obj->get_filename();
1988 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1989 // this is an instance of file_info
1990 $mimetype = $obj->get_mimetype();
1991 $filename = $obj->get_visible_name();
1992 } else if (is_array($obj) || is_object ($obj)) {
1993 $obj = (array)$obj;
1994 if (!empty($obj['filename'])) {
1995 $filename = $obj['filename'];
1997 if (!empty($obj['mimetype'])) {
1998 $mimetype = $obj['mimetype'];
2000 } else {
2001 $mimetype = $obj;
2003 $mimetypefromext = mimeinfo('type', $filename);
2004 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
2005 // if file has a known extension, overwrite the specified mimetype
2006 $mimetype = $mimetypefromext;
2008 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
2009 if (empty($extension)) {
2010 $mimetypestr = mimeinfo_from_type('string', $mimetype);
2011 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
2012 } else {
2013 $mimetypestr = mimeinfo('string', $filename);
2015 $chunks = explode('/', $mimetype, 2);
2016 $chunks[] = '';
2017 $attr = array(
2018 'mimetype' => $mimetype,
2019 'ext' => $extension,
2020 'mimetype1' => $chunks[0],
2021 'mimetype2' => $chunks[1],
2023 $a = array();
2024 foreach ($attr as $key => $value) {
2025 $a[$key] = $value;
2026 $a[strtoupper($key)] = strtoupper($value);
2027 $a[ucfirst($key)] = ucfirst($value);
2030 // MIME types may include + symbol but this is not permitted in string ids.
2031 $safemimetype = str_replace('+', '_', $mimetype ?? '');
2032 $safemimetypestr = str_replace('+', '_', $mimetypestr ?? '');
2033 $customdescription = mimeinfo('customdescription', $filename);
2034 if ($customdescription) {
2035 // Call format_string on the custom description so that multilang
2036 // filter can be used (if enabled on system context). We use system
2037 // context because it is possible that the page context might not have
2038 // been defined yet.
2039 $result = format_string($customdescription, true,
2040 array('context' => context_system::instance()));
2041 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
2042 $result = get_string($safemimetype, 'mimetypes', (object)$a);
2043 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
2044 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
2045 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
2046 $result = get_string('default', 'mimetypes', (object)$a);
2047 } else {
2048 $result = $mimetype;
2050 if ($capitalise) {
2051 $result=ucfirst($result);
2053 return $result;
2057 * Returns array of elements of type $element in type group(s)
2059 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
2060 * @param string|array $groups one group or array of groups/extensions/mimetypes
2061 * @return array
2063 function file_get_typegroup($element, $groups) {
2064 static $cached = array();
2065 if (!is_array($groups)) {
2066 $groups = array($groups);
2068 if (!array_key_exists($element, $cached)) {
2069 $cached[$element] = array();
2071 $result = array();
2072 foreach ($groups as $group) {
2073 if (!array_key_exists($group, $cached[$element])) {
2074 // retrieive and cache all elements of type $element for group $group
2075 $mimeinfo = & get_mimetypes_array();
2076 $cached[$element][$group] = array();
2077 foreach ($mimeinfo as $extension => $value) {
2078 $value['extension'] = '.'.$extension;
2079 if (empty($value[$element])) {
2080 continue;
2082 if (($group === '.'.$extension || $group === $value['type'] ||
2083 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
2084 !in_array($value[$element], $cached[$element][$group])) {
2085 $cached[$element][$group][] = $value[$element];
2089 $result = array_merge($result, $cached[$element][$group]);
2091 return array_values(array_unique($result));
2095 * Checks if file with name $filename has one of the extensions in groups $groups
2097 * @see get_mimetypes_array()
2098 * @param string $filename name of the file to check
2099 * @param string|array $groups one group or array of groups to check
2100 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2101 * file mimetype is in mimetypes in groups $groups
2102 * @return bool
2104 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2105 $extension = pathinfo($filename, PATHINFO_EXTENSION);
2106 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2107 return true;
2109 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2113 * Checks if mimetype $mimetype belongs to one of the groups $groups
2115 * @see get_mimetypes_array()
2116 * @param string $mimetype
2117 * @param string|array $groups one group or array of groups to check
2118 * @return bool
2120 function file_mimetype_in_typegroup($mimetype, $groups) {
2121 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2125 * Requested file is not found or not accessible, does not return, terminates script
2127 * @global stdClass $CFG
2128 * @global stdClass $COURSE
2130 function send_file_not_found() {
2131 global $CFG, $COURSE;
2133 // Allow cross-origin requests only for Web Services.
2134 // This allow to receive requests done by Web Workers or webapps in different domains.
2135 if (WS_SERVER) {
2136 header('Access-Control-Allow-Origin: *');
2139 send_header_404();
2140 throw new \moodle_exception('filenotfound', 'error',
2141 $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); // This is not displayed on IIS?
2144 * Helper function to send correct 404 for server.
2146 function send_header_404() {
2147 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2148 header("Status: 404 Not Found");
2149 } else {
2150 header('HTTP/1.0 404 not found');
2155 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2156 * platforms). This wrapper uses readfile for small files and custom code for
2157 * large ones.
2159 * @param string $path Path to file
2160 * @param int $filesize Size of file (if left out, will get it automatically)
2161 * @return int|bool Size read (will always be $filesize) or false if failed
2163 function readfile_allow_large($path, $filesize = -1) {
2164 // Automatically get size if not specified.
2165 if ($filesize === -1) {
2166 $filesize = filesize($path);
2168 if ($filesize <= 2147483647) {
2169 // If the file is up to 2^31 - 1, send it normally using readfile.
2170 return readfile($path);
2171 } else {
2172 // For large files, read and output in 64KB chunks.
2173 $handle = fopen($path, 'r');
2174 if ($handle === false) {
2175 return false;
2177 $left = $filesize;
2178 while ($left > 0) {
2179 $size = min($left, 65536);
2180 $buffer = fread($handle, $size);
2181 if ($buffer === false) {
2182 return false;
2184 echo $buffer;
2185 $left -= $size;
2187 return $filesize;
2192 * Enhanced readfile() with optional acceleration.
2193 * @param string|stored_file $file
2194 * @param string $mimetype
2195 * @param bool $accelerate
2196 * @return void
2198 function readfile_accel($file, $mimetype, $accelerate) {
2199 global $CFG;
2201 if ($mimetype === 'text/plain') {
2202 // there is no encoding specified in text files, we need something consistent
2203 header('Content-Type: text/plain; charset=utf-8');
2204 } else {
2205 header('Content-Type: '.$mimetype);
2208 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2209 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2211 if (is_object($file)) {
2212 header('Etag: "' . $file->get_contenthash() . '"');
2213 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2214 header('HTTP/1.1 304 Not Modified');
2215 return;
2219 // if etag present for stored file rely on it exclusively
2220 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2221 // get unixtime of request header; clip extra junk off first
2222 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2223 if ($since && $since >= $lastmodified) {
2224 header('HTTP/1.1 304 Not Modified');
2225 return;
2229 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2230 header('Accept-Ranges: bytes');
2231 } else {
2232 header('Accept-Ranges: none');
2235 if ($accelerate) {
2236 if (is_object($file)) {
2237 $fs = get_file_storage();
2238 if ($fs->supports_xsendfile()) {
2239 if ($fs->xsendfile_file($file)) {
2240 return;
2243 } else {
2244 if (!empty($CFG->xsendfile)) {
2245 require_once("$CFG->libdir/xsendfilelib.php");
2246 if (xsendfile($file)) {
2247 return;
2253 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2255 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2257 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2259 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2260 // byteserving stuff - for acrobat reader and download accelerators
2261 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2262 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2263 $ranges = false;
2264 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2265 foreach ($ranges as $key=>$value) {
2266 if ($ranges[$key][1] == '') {
2267 //suffix case
2268 $ranges[$key][1] = $filesize - $ranges[$key][2];
2269 $ranges[$key][2] = $filesize - 1;
2270 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2271 //fix range length
2272 $ranges[$key][2] = $filesize - 1;
2274 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2275 //invalid byte-range ==> ignore header
2276 $ranges = false;
2277 break;
2279 //prepare multipart header
2280 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2281 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2283 } else {
2284 $ranges = false;
2286 if ($ranges) {
2287 if (is_object($file)) {
2288 $handle = $file->get_content_file_handle();
2289 if ($handle === false) {
2290 throw new file_exception('storedfilecannotreadfile', $file->get_filename());
2292 } else {
2293 $handle = fopen($file, 'rb');
2294 if ($handle === false) {
2295 throw new file_exception('cannotopenfile', $file);
2298 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2303 header('Content-Length: ' . $filesize);
2305 if (!empty($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] === 'HEAD') {
2306 exit;
2309 while (ob_get_level()) {
2310 $handlerstack = ob_list_handlers();
2311 $activehandler = array_pop($handlerstack);
2312 if ($activehandler === 'default output handler') {
2313 // We do not expect any content in the buffer when we are serving files.
2314 $buffercontents = ob_get_clean();
2315 if ($buffercontents !== '') {
2316 error_log('Non-empty default output handler buffer detected while serving the file ' . $file);
2318 } else {
2319 // Some handlers such as zlib output compression may have file signature buffered - flush it.
2320 ob_end_flush();
2324 // send the whole file content
2325 if (is_object($file)) {
2326 $file->readfile();
2327 } else {
2328 if (readfile_allow_large($file, $filesize) === false) {
2329 throw new file_exception('cannotopenfile', $file);
2335 * Similar to readfile_accel() but designed for strings.
2336 * @param string $string
2337 * @param string $mimetype
2338 * @param bool $accelerate Ignored
2339 * @return void
2341 function readstring_accel($string, $mimetype, $accelerate = false) {
2342 global $CFG;
2344 if ($mimetype === 'text/plain') {
2345 // there is no encoding specified in text files, we need something consistent
2346 header('Content-Type: text/plain; charset=utf-8');
2347 } else {
2348 header('Content-Type: '.$mimetype);
2350 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2351 header('Accept-Ranges: none');
2352 header('Content-Length: '.strlen($string));
2353 echo $string;
2357 * Handles the sending of temporary file to user, download is forced.
2358 * File is deleted after abort or successful sending, does not return, script terminated
2360 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2361 * @param string $filename proposed file name when saving file
2362 * @param bool $pathisstring If the path is string
2364 function send_temp_file($path, $filename, $pathisstring=false) {
2365 global $CFG;
2367 // Guess the file's MIME type.
2368 $mimetype = get_mimetype_for_sending($filename);
2370 // close session - not needed anymore
2371 \core\session\manager::write_close();
2373 if (!$pathisstring) {
2374 if (!file_exists($path)) {
2375 send_header_404();
2376 throw new \moodle_exception('filenotfound', 'error', $CFG->wwwroot.'/');
2378 // executed after normal finish or abort
2379 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2382 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2383 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2384 $filename = urlencode($filename);
2387 // If this file was requested from a form, then mark download as complete.
2388 \core_form\util::form_download_complete();
2390 header('Content-Disposition: attachment; filename="'.$filename.'"');
2391 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2392 header('Cache-Control: private, max-age=10, no-transform');
2393 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2394 header('Pragma: ');
2395 } else { //normal http - prevent caching at all cost
2396 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2397 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2398 header('Pragma: no-cache');
2401 // send the contents - we can not accelerate this because the file will be deleted asap
2402 if ($pathisstring) {
2403 readstring_accel($path, $mimetype);
2404 } else {
2405 readfile_accel($path, $mimetype, false);
2406 @unlink($path);
2409 die; //no more chars to output
2413 * Internal callback function used by send_temp_file()
2415 * @param string $path
2417 function send_temp_file_finished($path) {
2418 if (file_exists($path)) {
2419 @unlink($path);
2424 * Serve content which is not meant to be cached.
2426 * This is only intended to be used for volatile public files, for instance
2427 * when development is enabled, or when caching is not required on a public resource.
2429 * @param string $content Raw content.
2430 * @param string $filename The file name.
2431 * @return void
2433 function send_content_uncached($content, $filename) {
2434 $mimetype = mimeinfo('type', $filename);
2435 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2437 header('Content-Disposition: inline; filename="' . $filename . '"');
2438 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2439 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2440 header('Pragma: ');
2441 header('Accept-Ranges: none');
2442 header('Content-Type: ' . $mimetype . $charset);
2443 header('Content-Length: ' . strlen($content));
2445 echo $content;
2446 die();
2450 * Safely save content to a certain path.
2452 * This function tries hard to be atomic by first copying the content
2453 * to a separate file, and then moving the file across. It also prevents
2454 * the user to abort a request to prevent half-safed files.
2456 * This function is intended to be used when saving some content to cache like
2457 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2459 * @param string $content The file content.
2460 * @param string $destination The absolute path of the final file.
2461 * @return void
2463 function file_safe_save_content($content, $destination) {
2464 global $CFG;
2466 clearstatcache();
2467 if (!file_exists(dirname($destination))) {
2468 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2471 // Prevent serving of incomplete file from concurrent request,
2472 // the rename() should be more atomic than fwrite().
2473 ignore_user_abort(true);
2474 if ($fp = fopen($destination . '.tmp', 'xb')) {
2475 fwrite($fp, $content);
2476 fclose($fp);
2477 rename($destination . '.tmp', $destination);
2478 @chmod($destination, $CFG->filepermissions);
2479 @unlink($destination . '.tmp'); // Just in case anything fails.
2481 ignore_user_abort(false);
2482 if (connection_aborted()) {
2483 die();
2488 * Handles the sending of file data to the user's browser, including support for
2489 * byteranges etc.
2491 * @category files
2492 * @param string|stored_file $path Path of file on disk (including real filename),
2493 * or actual content of file as string,
2494 * or stored_file object
2495 * @param string $filename Filename to send
2496 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2497 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2498 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2499 * Forced to false when $path is a stored_file object.
2500 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2501 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2502 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2503 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2504 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2505 * and should not be reopened.
2506 * @param array $options An array of options, currently accepts:
2507 * - (string) cacheability: public, or private.
2508 * - (string|null) immutable
2509 * - (bool) dontforcesvgdownload: true if force download should be disabled on SVGs.
2510 * Note: This overrides a security feature, so should only be applied to "trusted" content
2511 * (eg module content that is created using an XSS risk flagged capability, such as SCORM).
2512 * @return null script execution stopped unless $dontdie is true
2514 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2515 $dontdie=false, array $options = array()) {
2516 global $CFG, $COURSE;
2518 if ($dontdie) {
2519 ignore_user_abort(true);
2522 if ($lifetime === 'default' or is_null($lifetime)) {
2523 $lifetime = $CFG->filelifetime;
2526 if (is_object($path)) {
2527 $pathisstring = false;
2530 \core\session\manager::write_close(); // Unlock session during file serving.
2532 // Use given MIME type if specified, otherwise guess it.
2533 if (!$mimetype || $mimetype === 'document/unknown') {
2534 $mimetype = get_mimetype_for_sending($filename);
2537 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2538 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2539 $filename = rawurlencode($filename);
2542 // Make sure we force download of SVG files, unless the module explicitly allows them (eg within SCORM content).
2543 // This is for security reasons (https://digi.ninja/blog/svg_xss.php).
2544 if (file_is_svg_image_from_mimetype($mimetype) && empty($options['dontforcesvgdownload'])) {
2545 $forcedownload = true;
2548 if ($forcedownload) {
2549 header('Content-Disposition: attachment; filename="'.$filename.'"');
2551 // If this file was requested from a form, then mark download as complete.
2552 \core_form\util::form_download_complete();
2553 } else if ($mimetype !== 'application/x-shockwave-flash') {
2554 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2555 // as an upload and enforces security that may prevent the file from being loaded.
2557 header('Content-Disposition: inline; filename="'.$filename.'"');
2560 if ($lifetime > 0) {
2561 $immutable = '';
2562 if (!empty($options['immutable'])) {
2563 $immutable = ', immutable';
2564 // Overwrite lifetime accordingly:
2565 // 90 days only - based on Moodle point release cadence being every 3 months.
2566 $lifetimemin = 60 * 60 * 24 * 90;
2567 $lifetime = max($lifetime, $lifetimemin);
2569 $cacheability = ' public,';
2570 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2571 // This file must be cache-able by both browsers and proxies.
2572 $cacheability = ' public,';
2573 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2574 // This file must be cache-able only by browsers.
2575 $cacheability = ' private,';
2576 } else if (isloggedin() and !isguestuser()) {
2577 // By default, under the conditions above, this file must be cache-able only by browsers.
2578 $cacheability = ' private,';
2580 $nobyteserving = false;
2581 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2582 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2583 header('Pragma: ');
2585 } else { // Do not cache files in proxies and browsers
2586 $nobyteserving = true;
2587 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2588 header('Cache-Control: private, max-age=10, no-transform');
2589 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2590 header('Pragma: ');
2591 } else { //normal http - prevent caching at all cost
2592 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2593 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2594 header('Pragma: no-cache');
2598 if (empty($filter)) {
2599 // send the contents
2600 if ($pathisstring) {
2601 readstring_accel($path, $mimetype);
2602 } else {
2603 readfile_accel($path, $mimetype, !$dontdie);
2606 } else {
2607 // Try to put the file through filters
2608 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml' || file_is_svg_image_from_mimetype($mimetype)) {
2609 $options = new stdClass();
2610 $options->noclean = true;
2611 $options->nocache = true; // temporary workaround for MDL-5136
2612 if (is_object($path)) {
2613 $text = $path->get_content();
2614 } else if ($pathisstring) {
2615 $text = $path;
2616 } else {
2617 $text = implode('', file($path));
2619 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2621 readstring_accel($output, $mimetype);
2623 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2624 // only filter text if filter all files is selected
2625 $options = new stdClass();
2626 $options->newlines = false;
2627 $options->noclean = true;
2628 if (is_object($path)) {
2629 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2630 } else if ($pathisstring) {
2631 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2632 } else {
2633 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2635 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2637 readstring_accel($output, $mimetype);
2639 } else {
2640 // send the contents
2641 if ($pathisstring) {
2642 readstring_accel($path, $mimetype);
2643 } else {
2644 readfile_accel($path, $mimetype, !$dontdie);
2648 if ($dontdie) {
2649 return;
2651 die; //no more chars to output!!!
2655 * Handles the sending of file data to the user's browser, including support for
2656 * byteranges etc.
2658 * The $options parameter supports the following keys:
2659 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2660 * (string|null) filename - overrides the implicit filename
2661 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2662 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2663 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2664 * and should not be reopened
2665 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2666 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2667 * defaults to "public".
2668 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2669 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2671 * @category files
2672 * @param stored_file $stored_file local file object
2673 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2674 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2675 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2676 * @param array $options additional options affecting the file serving
2677 * @return null script execution stopped unless $options['dontdie'] is true
2679 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2680 global $CFG, $COURSE;
2682 static $recursion = 0;
2684 if (empty($options['filename'])) {
2685 $filename = null;
2686 } else {
2687 $filename = $options['filename'];
2690 if (empty($options['dontdie'])) {
2691 $dontdie = false;
2692 } else {
2693 $dontdie = true;
2696 if ($lifetime === 'default' or is_null($lifetime)) {
2697 $lifetime = $CFG->filelifetime;
2700 if (!empty($options['preview'])) {
2701 // replace the file with its preview
2702 $fs = get_file_storage();
2703 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2704 if (!$preview_file) {
2705 // unable to create a preview of the file, send its default mime icon instead
2706 if ($options['preview'] === 'tinyicon') {
2707 $size = 24;
2708 } else if ($options['preview'] === 'thumb') {
2709 $size = 90;
2710 } else {
2711 $size = 256;
2713 $fileicon = file_file_icon($stored_file, $size);
2714 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2715 } else {
2716 // preview images have fixed cache lifetime and they ignore forced download
2717 // (they are generated by GD and therefore they are considered reasonably safe).
2718 $stored_file = $preview_file;
2719 $lifetime = DAYSECS;
2720 $filter = 0;
2721 $forcedownload = false;
2725 // handle external resource
2726 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2728 // Have we been here before?
2729 $recursion++;
2730 if ($recursion > 10) {
2731 throw new coding_exception('Recursive file serving detected');
2734 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2735 die;
2738 if (!$stored_file or $stored_file->is_directory()) {
2739 // nothing to serve
2740 if ($dontdie) {
2741 return;
2743 die;
2746 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2748 // Use given MIME type if specified.
2749 $mimetype = $stored_file->get_mimetype();
2751 // Allow cross-origin requests only for Web Services.
2752 // This allow to receive requests done by Web Workers or webapps in different domains.
2753 if (WS_SERVER) {
2754 header('Access-Control-Allow-Origin: *');
2757 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2761 * Recursively delete the file or folder with path $location. That is,
2762 * if it is a file delete it. If it is a folder, delete all its content
2763 * then delete it. If $location does not exist to start, that is not
2764 * considered an error.
2766 * @param string $location the path to remove.
2767 * @return bool
2769 function fulldelete($location) {
2770 if (empty($location)) {
2771 // extra safety against wrong param
2772 return false;
2774 if (is_dir($location)) {
2775 if (!$currdir = opendir($location)) {
2776 return false;
2778 while (false !== ($file = readdir($currdir))) {
2779 if ($file <> ".." && $file <> ".") {
2780 $fullfile = $location."/".$file;
2781 if (is_dir($fullfile)) {
2782 if (!fulldelete($fullfile)) {
2783 return false;
2785 } else {
2786 if (!unlink($fullfile)) {
2787 return false;
2792 closedir($currdir);
2793 if (! rmdir($location)) {
2794 return false;
2797 } else if (file_exists($location)) {
2798 if (!unlink($location)) {
2799 return false;
2802 return true;
2806 * Send requested byterange of file.
2808 * @param resource $handle A file handle
2809 * @param string $mimetype The mimetype for the output
2810 * @param array $ranges An array of ranges to send
2811 * @param string $filesize The size of the content if only one range is used
2813 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2814 // better turn off any kind of compression and buffering
2815 ini_set('zlib.output_compression', 'Off');
2817 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2818 if ($handle === false) {
2819 die;
2821 if (count($ranges) == 1) { //only one range requested
2822 $length = $ranges[0][2] - $ranges[0][1] + 1;
2823 header('HTTP/1.1 206 Partial content');
2824 header('Content-Length: '.$length);
2825 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2826 header('Content-Type: '.$mimetype);
2828 while(@ob_get_level()) {
2829 if (!@ob_end_flush()) {
2830 break;
2834 fseek($handle, $ranges[0][1]);
2835 while (!feof($handle) && $length > 0) {
2836 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2837 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2838 echo $buffer;
2839 flush();
2840 $length -= strlen($buffer);
2842 fclose($handle);
2843 die;
2844 } else { // multiple ranges requested - not tested much
2845 $totallength = 0;
2846 foreach($ranges as $range) {
2847 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2849 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2850 header('HTTP/1.1 206 Partial content');
2851 header('Content-Length: '.$totallength);
2852 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2854 while(@ob_get_level()) {
2855 if (!@ob_end_flush()) {
2856 break;
2860 foreach($ranges as $range) {
2861 $length = $range[2] - $range[1] + 1;
2862 echo $range[0];
2863 fseek($handle, $range[1]);
2864 while (!feof($handle) && $length > 0) {
2865 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2866 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2867 echo $buffer;
2868 flush();
2869 $length -= strlen($buffer);
2872 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2873 fclose($handle);
2874 die;
2879 * Tells whether the filename is executable.
2881 * @link http://php.net/manual/en/function.is-executable.php
2882 * @link https://bugs.php.net/bug.php?id=41062
2883 * @param string $filename Path to the file.
2884 * @return bool True if the filename exists and is executable; otherwise, false.
2886 function file_is_executable($filename) {
2887 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2888 if (is_executable($filename)) {
2889 return true;
2890 } else {
2891 $fileext = strrchr($filename, '.');
2892 // If we have an extension we can check if it is listed as executable.
2893 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2894 $winpathext = strtolower(getenv('PATHEXT'));
2895 $winpathexts = explode(';', $winpathext);
2897 return in_array(strtolower($fileext), $winpathexts);
2900 return false;
2902 } else {
2903 return is_executable($filename);
2908 * Overwrite an existing file in a draft area.
2910 * @param stored_file $newfile the new file with the new content and meta-data
2911 * @param stored_file $existingfile the file that will be overwritten
2912 * @throws moodle_exception
2913 * @since Moodle 3.2
2915 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2916 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2917 throw new coding_exception('The file to overwrite is not in a draft area.');
2920 $fs = get_file_storage();
2921 // Remember original file source field.
2922 $source = @unserialize($existingfile->get_source() ?? '');
2923 // Remember the original sortorder.
2924 $sortorder = $existingfile->get_sortorder();
2925 if ($newfile->is_external_file()) {
2926 // New file is a reference. Check that existing file does not have any other files referencing to it
2927 if (isset($source->original) && $fs->search_references_count($source->original)) {
2928 throw new moodle_exception('errordoublereference', 'repository');
2932 // Delete existing file to release filename.
2933 $newfilerecord = array(
2934 'contextid' => $existingfile->get_contextid(),
2935 'component' => 'user',
2936 'filearea' => 'draft',
2937 'itemid' => $existingfile->get_itemid(),
2938 'timemodified' => time()
2940 $existingfile->delete();
2942 // Create new file.
2943 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2944 // Preserve original file location (stored in source field) for handling references.
2945 if (isset($source->original)) {
2946 if (!($newfilesource = @unserialize($newfile->get_source() ?? ''))) {
2947 $newfilesource = new stdClass();
2949 $newfilesource->original = $source->original;
2950 $newfile->set_source(serialize($newfilesource));
2952 $newfile->set_sortorder($sortorder);
2956 * Add files from a draft area into a final area.
2958 * Most of the time you do not want to use this. It is intended to be used
2959 * by asynchronous services which cannot direcly manipulate a final
2960 * area through a draft area. Instead they add files to a new draft
2961 * area and merge that new draft into the final area when ready.
2963 * @param int $draftitemid the id of the draft area to use.
2964 * @param int $contextid this parameter and the next two identify the file area to save to.
2965 * @param string $component component name
2966 * @param string $filearea indentifies the file area
2967 * @param int $itemid identifies the item id or false for all items in the file area
2968 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2969 * @see file_save_draft_area_files
2970 * @since Moodle 3.2
2972 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2973 array $options = null) {
2974 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2975 $finaldraftid = 0;
2976 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2977 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2978 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2982 * Merge files from two draftarea areas.
2984 * This does not handle conflict resolution, files in the destination area which appear
2985 * to be more recent will be kept disregarding the intended ones.
2987 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2988 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2989 * @throws coding_exception
2990 * @since Moodle 3.2
2992 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2993 global $USER;
2995 $fs = get_file_storage();
2996 $contextid = context_user::instance($USER->id)->id;
2998 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2999 throw new coding_exception('Nothing to merge or area does not belong to current user');
3002 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
3004 // Get hashes of the files to merge.
3005 $newhashes = array();
3006 foreach ($filestomerge as $filetomerge) {
3007 $filepath = $filetomerge->get_filepath();
3008 $filename = $filetomerge->get_filename();
3010 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
3011 $newhashes[$newhash] = $filetomerge;
3014 // Calculate wich files must be added.
3015 foreach ($currentfiles as $file) {
3016 $filehash = $file->get_pathnamehash();
3017 // One file to be merged already exists.
3018 if (isset($newhashes[$filehash])) {
3019 $updatedfile = $newhashes[$filehash];
3021 // Avoid race conditions.
3022 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
3023 // The existing file is more recent, do not copy the suposedly "new" one.
3024 unset($newhashes[$filehash]);
3025 continue;
3027 // Update existing file (not only content, meta-data too).
3028 file_overwrite_existing_draftfile($updatedfile, $file);
3029 unset($newhashes[$filehash]);
3033 foreach ($newhashes as $newfile) {
3034 $newfilerecord = array(
3035 'contextid' => $contextid,
3036 'component' => 'user',
3037 'filearea' => 'draft',
3038 'itemid' => $mergeintodraftid,
3039 'timemodified' => time()
3042 $fs->create_file_from_storedfile($newfilerecord, $newfile);
3047 * Attempt to determine whether the specified mime-type is an SVG image or not.
3049 * @param string $mimetype Mime-type
3050 * @return bool True if it is an SVG file
3052 function file_is_svg_image_from_mimetype(string $mimetype): bool {
3053 return preg_match('|^image/svg|', $mimetype);
3057 * Returns the moodle proxy configuration as a formatted url
3059 * @return string the string to use for proxy settings.
3061 function get_moodle_proxy_url() {
3062 global $CFG;
3063 $proxy = '';
3064 if (empty($CFG->proxytype)) {
3065 return $proxy;
3067 if (empty($CFG->proxyhost)) {
3068 return $proxy;
3070 if ($CFG->proxytype === 'SOCKS5') {
3071 // If it is a SOCKS proxy, append the protocol info.
3072 $protocol = 'socks5://';
3073 } else {
3074 $protocol = '';
3076 $proxy = $CFG->proxyhost;
3077 if (!empty($CFG->proxyport)) {
3078 $proxy .= ':'. $CFG->proxyport;
3080 if (!empty($CFG->proxyuser) && !empty($CFG->proxypassword)) {
3081 $proxy = $protocol . $CFG->proxyuser . ':' . $CFG->proxypassword . '@' . $proxy;
3083 return $proxy;
3089 * RESTful cURL class
3091 * This is a wrapper class for curl, it is quite easy to use:
3092 * <code>
3093 * $c = new curl;
3094 * // enable cache
3095 * $c = new curl(array('cache'=>true));
3096 * // enable cookie
3097 * $c = new curl(array('cookie'=>true));
3098 * // enable proxy
3099 * $c = new curl(array('proxy'=>true));
3101 * // HTTP GET Method
3102 * $html = $c->get('http://example.com');
3103 * // HTTP POST Method
3104 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
3105 * // HTTP PUT Method
3106 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
3107 * </code>
3109 * @package core_files
3110 * @category files
3111 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3112 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
3114 class curl {
3115 /** @var bool Caches http request contents */
3116 public $cache = false;
3117 /** @var bool Uses proxy, null means automatic based on URL */
3118 public $proxy = null;
3119 /** @var string library version */
3120 public $version = '0.4 dev';
3121 /** @var array http's response */
3122 public $response = array();
3123 /** @var array Raw response headers, needed for BC in download_file_content(). */
3124 public $rawresponse = array();
3125 /** @var array http header */
3126 public $header = array();
3127 /** @var string cURL information */
3128 public $info;
3129 /** @var string error */
3130 public $error;
3131 /** @var int error code */
3132 public $errno;
3133 /** @var bool Perform redirects at PHP level instead of relying on native cURL functionality. Always true now. */
3134 public $emulateredirects = null;
3136 /** @var array cURL options */
3137 private $options;
3139 /** @var string Proxy host */
3140 private $proxy_host = '';
3141 /** @var string Proxy auth */
3142 private $proxy_auth = '';
3143 /** @var string Proxy type */
3144 private $proxy_type = '';
3145 /** @var bool Debug mode on */
3146 private $debug = false;
3147 /** @var bool|string Path to cookie file */
3148 private $cookie = false;
3149 /** @var bool tracks multiple headers in response - redirect detection */
3150 private $responsefinished = false;
3151 /** @var security helper class, responsible for checking host/ports against allowed/blocked entries.*/
3152 private $securityhelper;
3153 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
3154 private $ignoresecurity;
3155 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
3156 private static $mockresponses = [];
3159 * Curl constructor.
3161 * Allowed settings are:
3162 * proxy: (bool) use proxy server, null means autodetect non-local from url
3163 * debug: (bool) use debug output
3164 * cookie: (string) path to cookie file, false if none
3165 * cache: (bool) use cache
3166 * module_cache: (string) type of cache
3167 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3168 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3170 * @param array $settings
3172 public function __construct($settings = array()) {
3173 global $CFG;
3174 if (!function_exists('curl_init')) {
3175 $this->error = 'cURL module must be enabled!';
3176 trigger_error($this->error, E_USER_ERROR);
3177 return false;
3180 // All settings of this class should be init here.
3181 $this->resetopt();
3182 if (!empty($settings['debug'])) {
3183 $this->debug = true;
3185 if (!empty($settings['cookie'])) {
3186 if($settings['cookie'] === true) {
3187 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3188 } else {
3189 $this->cookie = $settings['cookie'];
3192 if (!empty($settings['cache'])) {
3193 if (class_exists('curl_cache')) {
3194 if (!empty($settings['module_cache'])) {
3195 $this->cache = new curl_cache($settings['module_cache']);
3196 } else {
3197 $this->cache = new curl_cache('misc');
3201 if (!empty($CFG->proxyhost)) {
3202 if (empty($CFG->proxyport)) {
3203 $this->proxy_host = $CFG->proxyhost;
3204 } else {
3205 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3207 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3208 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3209 $this->setopt(array(
3210 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3211 'proxyuserpwd'=>$this->proxy_auth));
3213 if (!empty($CFG->proxytype)) {
3214 if ($CFG->proxytype == 'SOCKS5') {
3215 $this->proxy_type = CURLPROXY_SOCKS5;
3216 } else {
3217 $this->proxy_type = CURLPROXY_HTTP;
3218 $this->setopt([
3219 'httpproxytunnel' => false,
3221 if (defined('CURLOPT_SUPPRESS_CONNECT_HEADERS')) {
3222 $this->setopt([
3223 'suppress_connect_headers' => true,
3227 $this->setopt(array('proxytype'=>$this->proxy_type));
3230 if (isset($settings['proxy'])) {
3231 $this->proxy = $settings['proxy'];
3233 } else {
3234 $this->proxy = false;
3237 // All redirects are performed at PHP level now and each one is checked against blocked URLs rules. We do not
3238 // want to let cURL naively follow the redirect chain and visit every URL for security reasons. Even when the
3239 // caller explicitly wants to ignore the security checks, we would need to fall back to the original
3240 // implementation and use emulated redirects if open_basedir is in effect to avoid the PHP warning
3241 // "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir". So it is better to simply
3242 // ignore this property and always handle redirects at this PHP wrapper level and not inside the native cURL.
3243 $this->emulateredirects = true;
3245 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3246 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3247 $this->set_security($settings['securityhelper']);
3248 } else {
3249 $this->set_security(new \core\files\curl_security_helper());
3251 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3255 * Resets the CURL options that have already been set
3257 public function resetopt() {
3258 $this->options = array();
3259 $this->options['CURLOPT_USERAGENT'] = \core_useragent::get_moodlebot_useragent();
3260 // True to include the header in the output
3261 $this->options['CURLOPT_HEADER'] = 0;
3262 // True to Exclude the body from the output
3263 $this->options['CURLOPT_NOBODY'] = 0;
3264 // Redirect ny default.
3265 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
3266 $this->options['CURLOPT_MAXREDIRS'] = 10;
3267 $this->options['CURLOPT_ENCODING'] = '';
3268 // TRUE to return the transfer as a string of the return
3269 // value of curl_exec() instead of outputting it out directly.
3270 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
3271 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
3272 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
3273 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
3275 if ($cacert = self::get_cacert()) {
3276 $this->options['CURLOPT_CAINFO'] = $cacert;
3281 * Get the location of ca certificates.
3282 * @return string absolute file path or empty if default used
3284 public static function get_cacert() {
3285 global $CFG;
3287 // Bundle in dataroot always wins.
3288 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3289 return realpath("$CFG->dataroot/moodleorgca.crt");
3292 // Next comes the default from php.ini
3293 $cacert = ini_get('curl.cainfo');
3294 if (!empty($cacert) and is_readable($cacert)) {
3295 return realpath($cacert);
3298 // Windows PHP does not have any certs, we need to use something.
3299 if ($CFG->ostype === 'WINDOWS') {
3300 if (is_readable("$CFG->libdir/cacert.pem")) {
3301 return realpath("$CFG->libdir/cacert.pem");
3305 // Use default, this should work fine on all properly configured *nix systems.
3306 return null;
3310 * Reset Cookie
3312 public function resetcookie() {
3313 if (!empty($this->cookie)) {
3314 if (is_file($this->cookie)) {
3315 $fp = fopen($this->cookie, 'w');
3316 if (!empty($fp)) {
3317 fwrite($fp, '');
3318 fclose($fp);
3325 * Set curl options.
3327 * Do not use the curl constants to define the options, pass a string
3328 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3329 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3331 * @param array $options If array is null, this function will reset the options to default value.
3332 * @return void
3333 * @throws coding_exception If an option uses constant value instead of option name.
3335 public function setopt($options = array()) {
3336 if (is_array($options)) {
3337 foreach ($options as $name => $val) {
3338 if (!is_string($name)) {
3339 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3341 if (stripos($name, 'CURLOPT_') === false) {
3342 // Only prefix with CURLOPT_ if the option doesn't contain CURLINFO_,
3343 // which is a valid prefix for at least one option CURLINFO_HEADER_OUT.
3344 if (stripos($name, 'CURLINFO_') === false) {
3345 $name = strtoupper('CURLOPT_'.$name);
3347 } else {
3348 $name = strtoupper($name);
3350 $this->options[$name] = $val;
3356 * Reset http method
3358 public function cleanopt() {
3359 unset($this->options['CURLOPT_HTTPGET']);
3360 unset($this->options['CURLOPT_POST']);
3361 unset($this->options['CURLOPT_POSTFIELDS']);
3362 unset($this->options['CURLOPT_PUT']);
3363 unset($this->options['CURLOPT_INFILE']);
3364 unset($this->options['CURLOPT_INFILESIZE']);
3365 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3366 unset($this->options['CURLOPT_FILE']);
3370 * Resets the HTTP Request headers (to prepare for the new request)
3372 public function resetHeader() {
3373 $this->header = array();
3377 * Set HTTP Request Header
3379 * @param array $header
3381 public function setHeader($header) {
3382 if (is_array($header)) {
3383 foreach ($header as $v) {
3384 $this->setHeader($v);
3386 } else {
3387 // Remove newlines, they are not allowed in headers.
3388 $newvalue = preg_replace('/[\r\n]/', '', $header);
3389 if (!in_array($newvalue, $this->header)) {
3390 $this->header[] = $newvalue;
3396 * Get HTTP Response Headers
3397 * @return array of arrays
3399 public function getResponse() {
3400 return $this->response;
3404 * Get raw HTTP Response Headers
3405 * @return array of strings
3407 public function get_raw_response() {
3408 return $this->rawresponse;
3412 * private callback function
3413 * Formatting HTTP Response Header
3415 * We only keep the last headers returned. For example during a redirect the
3416 * redirect headers will not appear in {@link self::getResponse()}, if you need
3417 * to use those headers, refer to {@link self::get_raw_response()}.
3419 * @param resource $ch Apparently not used
3420 * @param string $header
3421 * @return int The strlen of the header
3423 private function formatHeader($ch, $header) {
3424 $this->rawresponse[] = $header;
3426 if (trim($header, "\r\n") === '') {
3427 // This must be the last header.
3428 $this->responsefinished = true;
3431 if (strlen($header) > 2) {
3432 if ($this->responsefinished) {
3433 // We still have headers after the supposedly last header, we must be
3434 // in a redirect so let's empty the response to keep the last headers.
3435 $this->responsefinished = false;
3436 $this->response = array();
3438 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3439 $key = rtrim($parts[0], ':');
3440 $value = isset($parts[1]) ? $parts[1] : null;
3441 if (!empty($this->response[$key])) {
3442 if (is_array($this->response[$key])) {
3443 $this->response[$key][] = $value;
3444 } else {
3445 $tmp = $this->response[$key];
3446 $this->response[$key] = array();
3447 $this->response[$key][] = $tmp;
3448 $this->response[$key][] = $value;
3451 } else {
3452 $this->response[$key] = $value;
3455 return strlen($header);
3459 * Set options for individual curl instance
3461 * @param resource $curl A curl handle
3462 * @param array $options
3463 * @return resource The curl handle
3465 private function apply_opt($curl, $options) {
3466 // Clean up
3467 $this->cleanopt();
3468 // set cookie
3469 if (!empty($this->cookie) || !empty($options['cookie'])) {
3470 $this->setopt(array('cookiejar'=>$this->cookie,
3471 'cookiefile'=>$this->cookie
3475 // Bypass proxy if required.
3476 if ($this->proxy === null) {
3477 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3478 $proxy = false;
3479 } else {
3480 $proxy = true;
3482 } else {
3483 $proxy = (bool)$this->proxy;
3486 // Set proxy.
3487 if ($proxy) {
3488 $options['CURLOPT_PROXY'] = $this->proxy_host;
3489 } else {
3490 unset($this->options['CURLOPT_PROXY']);
3493 $this->setopt($options);
3495 // Reset before set options.
3496 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3498 // Setting the User-Agent based on options provided.
3499 $useragent = '';
3501 if (!empty($options['CURLOPT_USERAGENT'])) {
3502 $useragent = $options['CURLOPT_USERAGENT'];
3503 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3504 $useragent = $this->options['CURLOPT_USERAGENT'];
3505 } else {
3506 $useragent = \core_useragent::get_moodlebot_useragent();
3509 // Set headers.
3510 if (empty($this->header)) {
3511 $this->setHeader(array(
3512 'User-Agent: ' . $useragent,
3513 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3514 'Connection: keep-alive'
3516 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3517 // Remove old User-Agent if one existed.
3518 // We have to partial search since we don't know what the original User-Agent is.
3519 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3520 $key = array_keys($match)[0];
3521 unset($this->header[$key]);
3523 $this->setHeader(array('User-Agent: ' . $useragent));
3525 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3527 if ($this->debug) {
3528 echo '<h1>Options</h1>';
3529 var_dump($this->options);
3530 echo '<h1>Header</h1>';
3531 var_dump($this->header);
3534 // Do not allow infinite redirects.
3535 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3536 $this->options['CURLOPT_MAXREDIRS'] = 0;
3537 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3538 $this->options['CURLOPT_MAXREDIRS'] = 100;
3539 } else {
3540 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3543 // Make sure we always know if redirects expected.
3544 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3545 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3548 // Limit the protocols to HTTP and HTTPS.
3549 if (defined('CURLOPT_PROTOCOLS')) {
3550 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3551 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3554 // Set options.
3555 foreach($this->options as $name => $val) {
3556 if ($name === 'CURLOPT_FOLLOWLOCATION') {
3557 // All the redirects are emulated at PHP level.
3558 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3559 continue;
3561 $name = constant($name);
3562 curl_setopt($curl, $name, $val);
3565 return $curl;
3569 * Download multiple files in parallel
3571 * Calls {@link multi()} with specific download headers
3573 * <code>
3574 * $c = new curl();
3575 * $file1 = fopen('a', 'wb');
3576 * $file2 = fopen('b', 'wb');
3577 * $c->download(array(
3578 * array('url'=>'http://localhost/', 'file'=>$file1),
3579 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3580 * ));
3581 * fclose($file1);
3582 * fclose($file2);
3583 * </code>
3585 * or
3587 * <code>
3588 * $c = new curl();
3589 * $c->download(array(
3590 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3591 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3592 * ));
3593 * </code>
3595 * @param array $requests An array of files to request {
3596 * url => url to download the file [required]
3597 * file => file handler, or
3598 * filepath => file path
3600 * If 'file' and 'filepath' parameters are both specified in one request, the
3601 * open file handle in the 'file' parameter will take precedence and 'filepath'
3602 * will be ignored.
3604 * @param array $options An array of options to set
3605 * @return array An array of results
3607 public function download($requests, $options = array()) {
3608 $options['RETURNTRANSFER'] = false;
3609 return $this->multi($requests, $options);
3613 * Returns the current curl security helper.
3615 * @return \core\files\curl_security_helper instance.
3617 public function get_security() {
3618 return $this->securityhelper;
3622 * Sets the curl security helper.
3624 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3625 * @return bool true if the security helper could be set, false otherwise.
3627 public function set_security($securityobject) {
3628 if ($securityobject instanceof \core\files\curl_security_helper) {
3629 $this->securityhelper = $securityobject;
3630 return true;
3632 return false;
3636 * Multi HTTP Requests
3637 * This function could run multi-requests in parallel.
3639 * @param array $requests An array of files to request
3640 * @param array $options An array of options to set
3641 * @return array An array of results
3643 protected function multi($requests, $options = array()) {
3644 $count = count($requests);
3645 $handles = array();
3646 $results = array();
3647 $main = curl_multi_init();
3648 for ($i = 0; $i < $count; $i++) {
3649 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3650 // open file
3651 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3652 $requests[$i]['auto-handle'] = true;
3654 foreach($requests[$i] as $n=>$v) {
3655 $options[$n] = $v;
3657 $handles[$i] = curl_init($requests[$i]['url']);
3658 $this->apply_opt($handles[$i], $options);
3659 curl_multi_add_handle($main, $handles[$i]);
3661 $running = 0;
3662 do {
3663 curl_multi_exec($main, $running);
3664 } while($running > 0);
3665 for ($i = 0; $i < $count; $i++) {
3666 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3667 $results[] = true;
3668 } else {
3669 $results[] = curl_multi_getcontent($handles[$i]);
3671 curl_multi_remove_handle($main, $handles[$i]);
3673 curl_multi_close($main);
3675 for ($i = 0; $i < $count; $i++) {
3676 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3677 // close file handler if file is opened in this function
3678 fclose($requests[$i]['file']);
3681 return $results;
3685 * Helper function to reset the request state vars.
3687 * @return void.
3689 protected function reset_request_state_vars() {
3690 $this->info = array();
3691 $this->error = '';
3692 $this->errno = 0;
3693 $this->response = array();
3694 $this->rawresponse = array();
3695 $this->responsefinished = false;
3699 * For use only in unit tests - we can pre-set the next curl response.
3700 * This is useful for unit testing APIs that call external systems.
3701 * @param string $response
3703 public static function mock_response($response) {
3704 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3705 array_push(self::$mockresponses, $response);
3706 } else {
3707 throw new coding_exception('mock_response function is only available for unit tests.');
3712 * check_securityhelper_blocklist.
3713 * Checks whether the given URL is blocked by checking both plugin's security helpers
3714 * and core curl security helper or any curl security helper that passed to curl class constructor.
3715 * If ignoresecurity is set to true, skip checking and consider the url is not blocked.
3716 * This augments all installed plugin's security helpers if there is any.
3718 * @param string $url the url to check.
3719 * @return string - an error message if URL is blocked or null if URL is not blocked.
3721 protected function check_securityhelper_blocklist(string $url): ?string {
3723 // If curl security is not enabled, do not proceed.
3724 if ($this->ignoresecurity) {
3725 return null;
3728 // Augment all installed plugin's security helpers if there is any.
3729 // The plugin's function has to be defined as plugintype_pluginname_curl_security_helper in pluginname/lib.php.
3730 $plugintypes = get_plugins_with_function('curl_security_helper');
3732 // If any of the security helper's function returns true, treat as URL is blocked.
3733 foreach ($plugintypes as $plugins) {
3734 foreach ($plugins as $pluginfunction) {
3735 // Get curl security helper object from plugin lib.php.
3736 $pluginsecurityhelper = $pluginfunction();
3737 if ($pluginsecurityhelper instanceof \core\files\curl_security_helper_base) {
3738 if ($pluginsecurityhelper->url_is_blocked($url)) {
3739 $this->error = $pluginsecurityhelper->get_blocked_url_string();
3740 return $this->error;
3746 // Check if the URL is blocked in core curl_security_helper or
3747 // curl security helper that passed to curl class constructor.
3748 if ($this->securityhelper->url_is_blocked($url)) {
3749 $this->error = $this->securityhelper->get_blocked_url_string();
3750 return $this->error;
3753 return null;
3757 * Single HTTP Request
3759 * @param string $url The URL to request
3760 * @param array $options
3761 * @return bool
3763 protected function request($url, $options = array()) {
3764 // Reset here so that the data is valid when result returned from cache, or if we return due to a blocked URL hit.
3765 $this->reset_request_state_vars();
3767 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3768 $mockresponse = array_pop(self::$mockresponses);
3769 if ($mockresponse !== null) {
3770 $this->info = [ 'http_code' => 200 ];
3771 return $mockresponse;
3775 if (empty($this->emulateredirects)) {
3776 // Just in case someone had tried to explicitly disable emulated redirects in legacy code.
3777 debugging('Attempting to disable emulated redirects has no effect any more!', DEBUG_DEVELOPER);
3780 $urlisblocked = $this->check_securityhelper_blocklist($url);
3781 if (!is_null($urlisblocked)) {
3782 return $urlisblocked;
3785 // Set the URL as a curl option.
3786 $this->setopt(array('CURLOPT_URL' => $url));
3788 // Create curl instance.
3789 $curl = curl_init();
3791 $this->apply_opt($curl, $options);
3792 if ($this->cache && $ret = $this->cache->get($this->options)) {
3793 return $ret;
3796 $ret = curl_exec($curl);
3797 $this->info = curl_getinfo($curl);
3798 $this->error = curl_error($curl);
3799 $this->errno = curl_errno($curl);
3800 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3802 if (intval($this->info['redirect_count']) > 0) {
3803 // For security reasons we do not allow the cURL handle to follow redirects on its own.
3804 // See setting CURLOPT_FOLLOWLOCATION in {@see self::apply_opt()} method.
3805 throw new coding_exception('Internal cURL handle should never follow redirects on its own!',
3806 'Reported number of redirects: ' . $this->info['redirect_count']);
3809 if ($this->options['CURLOPT_FOLLOWLOCATION'] && $this->info['http_code'] != 200) {
3810 $redirects = 0;
3812 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3814 if ($this->info['http_code'] == 301) {
3815 // Moved Permanently - repeat the same request on new URL.
3817 } else if ($this->info['http_code'] == 302) {
3818 // Found - the standard redirect - repeat the same request on new URL.
3820 } else if ($this->info['http_code'] == 303) {
3821 // 303 See Other - repeat only if GET, do not bother with POSTs.
3822 if (empty($this->options['CURLOPT_HTTPGET'])) {
3823 break;
3826 } else if ($this->info['http_code'] == 307) {
3827 // Temporary Redirect - must repeat using the same request type.
3829 } else if ($this->info['http_code'] == 308) {
3830 // Permanent Redirect - must repeat using the same request type.
3832 } else {
3833 // Some other http code means do not retry!
3834 break;
3837 $redirects++;
3839 $redirecturl = null;
3840 if (isset($this->info['redirect_url'])) {
3841 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3842 $redirecturl = $this->info['redirect_url'];
3843 } else {
3844 // Emulate CURLOPT_REDIR_PROTOCOLS behaviour which we have set to (CURLPROTO_HTTP | CURLPROTO_HTTPS) only.
3845 $this->errno = CURLE_UNSUPPORTED_PROTOCOL;
3846 $this->error = 'Redirect to a URL with unsuported protocol: ' . $this->info['redirect_url'];
3847 curl_close($curl);
3848 return $this->error;
3851 if (!$redirecturl) {
3852 foreach ($this->response as $k => $v) {
3853 if (strtolower($k) === 'location') {
3854 $redirecturl = $v;
3855 break;
3858 if (preg_match('|^https?://|i', $redirecturl)) {
3859 // Great, this is the correct location format!
3861 } else if ($redirecturl) {
3862 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3863 if (strpos($redirecturl, '/') === 0) {
3864 // Relative to server root - just guess.
3865 $pos = strpos('/', $current, 8);
3866 if ($pos === false) {
3867 $redirecturl = $current.$redirecturl;
3868 } else {
3869 $redirecturl = substr($current, 0, $pos).$redirecturl;
3871 } else {
3872 // Relative to current script.
3873 $redirecturl = dirname($current).'/'.$redirecturl;
3878 $urlisblocked = $this->check_securityhelper_blocklist($redirecturl);
3879 if (!is_null($urlisblocked)) {
3880 $this->reset_request_state_vars();
3881 curl_close($curl);
3882 return $urlisblocked;
3885 // If the response body is written to a seekable stream resource, reset the stream pointer to avoid
3886 // appending multiple response bodies to the same resource.
3887 if (!empty($this->options['CURLOPT_FILE'])) {
3888 $streammetadata = stream_get_meta_data($this->options['CURLOPT_FILE']);
3889 if ($streammetadata['seekable']) {
3890 ftruncate($this->options['CURLOPT_FILE'], 0);
3891 rewind($this->options['CURLOPT_FILE']);
3895 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3896 $ret = curl_exec($curl);
3898 $this->info = curl_getinfo($curl);
3899 $this->error = curl_error($curl);
3900 $this->errno = curl_errno($curl);
3902 $this->info['redirect_count'] = $redirects;
3904 if ($this->info['http_code'] === 200) {
3905 // Finally this is what we wanted.
3906 break;
3908 if ($this->errno != CURLE_OK) {
3909 // Something wrong is going on.
3910 break;
3913 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3914 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3915 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3919 if ($this->cache) {
3920 $this->cache->set($this->options, $ret);
3923 if ($this->debug) {
3924 echo '<h1>Return Data</h1>';
3925 var_dump($ret);
3926 echo '<h1>Info</h1>';
3927 var_dump($this->info);
3928 echo '<h1>Error</h1>';
3929 var_dump($this->error);
3932 curl_close($curl);
3934 if (empty($this->error)) {
3935 return $ret;
3936 } else {
3937 return $this->error;
3938 // exception is not ajax friendly
3939 //throw new moodle_exception($this->error, 'curl');
3944 * HTTP HEAD method
3946 * @see request()
3948 * @param string $url
3949 * @param array $options
3950 * @return bool
3952 public function head($url, $options = array()) {
3953 $options['CURLOPT_HTTPGET'] = 0;
3954 $options['CURLOPT_HEADER'] = 1;
3955 $options['CURLOPT_NOBODY'] = 1;
3956 return $this->request($url, $options);
3960 * HTTP PATCH method
3962 * @param string $url
3963 * @param array|string $params
3964 * @param array $options
3965 * @return bool
3967 public function patch($url, $params = '', $options = array()) {
3968 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3969 if (is_array($params)) {
3970 $this->_tmp_file_post_params = array();
3971 foreach ($params as $key => $value) {
3972 if ($value instanceof stored_file) {
3973 $value->add_to_curl_request($this, $key);
3974 } else {
3975 $this->_tmp_file_post_params[$key] = $value;
3978 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3979 unset($this->_tmp_file_post_params);
3980 } else {
3981 // The variable $params is the raw post data.
3982 $options['CURLOPT_POSTFIELDS'] = $params;
3984 return $this->request($url, $options);
3988 * HTTP POST method
3990 * @param string $url
3991 * @param array|string $params
3992 * @param array $options
3993 * @return bool
3995 public function post($url, $params = '', $options = array()) {
3996 $options['CURLOPT_POST'] = 1;
3997 if (is_array($params)) {
3998 $this->_tmp_file_post_params = array();
3999 foreach ($params as $key => $value) {
4000 if ($value instanceof stored_file) {
4001 $value->add_to_curl_request($this, $key);
4002 } else {
4003 $this->_tmp_file_post_params[$key] = $value;
4006 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
4007 unset($this->_tmp_file_post_params);
4008 } else {
4009 // $params is the raw post data
4010 $options['CURLOPT_POSTFIELDS'] = $params;
4012 return $this->request($url, $options);
4016 * HTTP GET method
4018 * @param string $url
4019 * @param array $params
4020 * @param array $options
4021 * @return bool
4023 public function get($url, $params = array(), $options = array()) {
4024 $options['CURLOPT_HTTPGET'] = 1;
4026 if (!empty($params)) {
4027 $url .= (stripos($url, '?') !== false) ? '&' : '?';
4028 $url .= http_build_query($params, '', '&');
4030 return $this->request($url, $options);
4034 * Downloads one file and writes it to the specified file handler
4036 * <code>
4037 * $c = new curl();
4038 * $file = fopen('savepath', 'w');
4039 * $result = $c->download_one('http://localhost/', null,
4040 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
4041 * fclose($file);
4042 * $download_info = $c->get_info();
4043 * if ($result === true) {
4044 * // file downloaded successfully
4045 * } else {
4046 * $error_text = $result;
4047 * $error_code = $c->get_errno();
4049 * </code>
4051 * <code>
4052 * $c = new curl();
4053 * $result = $c->download_one('http://localhost/', null,
4054 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
4055 * // ... see above, no need to close handle and remove file if unsuccessful
4056 * </code>
4058 * @param string $url
4059 * @param array|null $params key-value pairs to be added to $url as query string
4060 * @param array $options request options. Must include either 'file' or 'filepath'
4061 * @return bool|string true on success or error string on failure
4063 public function download_one($url, $params, $options = array()) {
4064 $options['CURLOPT_HTTPGET'] = 1;
4065 if (!empty($params)) {
4066 $url .= (stripos($url, '?') !== false) ? '&' : '?';
4067 $url .= http_build_query($params, '', '&');
4069 if (!empty($options['filepath']) && empty($options['file'])) {
4070 // open file
4071 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
4072 $this->errno = 100;
4073 return get_string('cannotwritefile', 'error', $options['filepath']);
4075 $filepath = $options['filepath'];
4077 unset($options['filepath']);
4078 $result = $this->request($url, $options);
4079 if (isset($filepath)) {
4080 fclose($options['file']);
4081 if ($result !== true) {
4082 unlink($filepath);
4085 return $result;
4089 * HTTP PUT method
4091 * @param string $url
4092 * @param array $params
4093 * @param array $options
4094 * @return bool
4096 public function put($url, $params = array(), $options = array()) {
4097 $file = '';
4098 $fp = false;
4099 if (isset($params['file'])) {
4100 $file = $params['file'];
4101 if (is_file($file)) {
4102 $fp = fopen($file, 'r');
4103 $size = filesize($file);
4104 $options['CURLOPT_PUT'] = 1;
4105 $options['CURLOPT_INFILESIZE'] = $size;
4106 $options['CURLOPT_INFILE'] = $fp;
4107 } else {
4108 return null;
4110 if (!isset($this->options['CURLOPT_USERPWD'])) {
4111 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
4113 } else {
4114 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
4115 $options['CURLOPT_POSTFIELDS'] = $params;
4118 $ret = $this->request($url, $options);
4119 if ($fp !== false) {
4120 fclose($fp);
4122 return $ret;
4126 * HTTP DELETE method
4128 * @param string $url
4129 * @param array $param
4130 * @param array $options
4131 * @return bool
4133 public function delete($url, $param = array(), $options = array()) {
4134 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
4135 if (!isset($options['CURLOPT_USERPWD'])) {
4136 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
4138 $ret = $this->request($url, $options);
4139 return $ret;
4143 * HTTP TRACE method
4145 * @param string $url
4146 * @param array $options
4147 * @return bool
4149 public function trace($url, $options = array()) {
4150 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
4151 $ret = $this->request($url, $options);
4152 return $ret;
4156 * HTTP OPTIONS method
4158 * @param string $url
4159 * @param array $options
4160 * @return bool
4162 public function options($url, $options = array()) {
4163 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
4164 $ret = $this->request($url, $options);
4165 return $ret;
4169 * Get curl information
4171 * @return string
4173 public function get_info() {
4174 return $this->info;
4178 * Get curl error code
4180 * @return int
4182 public function get_errno() {
4183 return $this->errno;
4187 * When using a proxy, an additional HTTP response code may appear at
4188 * the start of the header. For example, when using https over a proxy
4189 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
4190 * also possible and some may come with their own headers.
4192 * If using the return value containing all headers, this function can be
4193 * called to remove unwanted doubles.
4195 * Note that it is not possible to distinguish this situation from valid
4196 * data unless you know the actual response part (below the headers)
4197 * will not be included in this string, or else will not 'look like' HTTP
4198 * headers. As a result it is not safe to call this function for general
4199 * data.
4201 * @param string $input Input HTTP response
4202 * @return string HTTP response with additional headers stripped if any
4204 public static function strip_double_headers($input) {
4205 // I have tried to make this regular expression as specific as possible
4206 // to avoid any case where it does weird stuff if you happen to put
4207 // HTTP/1.1 200 at the start of any line in your RSS file. This should
4208 // also make it faster because it can abandon regex processing as soon
4209 // as it hits something that doesn't look like an http header. The
4210 // header definition is taken from RFC 822, except I didn't support
4211 // folding which is never used in practice.
4212 $crlf = "\r\n";
4213 return preg_replace(
4214 // HTTP version and status code (ignore value of code).
4215 '~^HTTP/[1-9](\.[0-9])?.*' . $crlf .
4216 // Header name: character between 33 and 126 decimal, except colon.
4217 // Colon. Header value: any character except \r and \n. CRLF.
4218 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
4219 // Headers are terminated by another CRLF (blank line).
4220 $crlf .
4221 // Second HTTP status code, this time must be 200.
4222 '(HTTP/[1-9](\.[0-9])? 200)~', '$2', $input);
4227 * This class is used by cURL class, use case:
4229 * <code>
4230 * $CFG->repositorycacheexpire = 120;
4231 * $CFG->curlcache = 120;
4233 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
4234 * $ret = $c->get('http://www.google.com');
4235 * </code>
4237 * @package core_files
4238 * @copyright Dongsheng Cai <dongsheng@moodle.com>
4239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4241 class curl_cache {
4242 /** @var string Path to cache directory */
4243 public $dir = '';
4246 * Constructor
4248 * @global stdClass $CFG
4249 * @param string $module which module is using curl_cache
4251 public function __construct($module = 'repository') {
4252 global $CFG;
4253 if (!empty($module)) {
4254 $this->dir = $CFG->cachedir.'/'.$module.'/';
4255 } else {
4256 $this->dir = $CFG->cachedir.'/misc/';
4258 if (!file_exists($this->dir)) {
4259 mkdir($this->dir, $CFG->directorypermissions, true);
4261 if ($module == 'repository') {
4262 if (empty($CFG->repositorycacheexpire)) {
4263 $CFG->repositorycacheexpire = 120;
4265 $this->ttl = $CFG->repositorycacheexpire;
4266 } else {
4267 if (empty($CFG->curlcache)) {
4268 $CFG->curlcache = 120;
4270 $this->ttl = $CFG->curlcache;
4275 * Get cached value
4277 * @global stdClass $CFG
4278 * @global stdClass $USER
4279 * @param mixed $param
4280 * @return bool|string
4282 public function get($param) {
4283 global $CFG, $USER;
4284 $this->cleanup($this->ttl);
4285 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4286 if(file_exists($this->dir.$filename)) {
4287 $lasttime = filemtime($this->dir.$filename);
4288 if (time()-$lasttime > $this->ttl) {
4289 return false;
4290 } else {
4291 $fp = fopen($this->dir.$filename, 'r');
4292 $size = filesize($this->dir.$filename);
4293 $content = fread($fp, $size);
4294 return unserialize($content);
4297 return false;
4301 * Set cache value
4303 * @global object $CFG
4304 * @global object $USER
4305 * @param mixed $param
4306 * @param mixed $val
4308 public function set($param, $val) {
4309 global $CFG, $USER;
4310 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4311 $fp = fopen($this->dir.$filename, 'w');
4312 fwrite($fp, serialize($val));
4313 fclose($fp);
4314 @chmod($this->dir.$filename, $CFG->filepermissions);
4318 * Remove cache files
4320 * @param int $expire The number of seconds before expiry
4322 public function cleanup($expire) {
4323 if ($dir = opendir($this->dir)) {
4324 while (false !== ($file = readdir($dir))) {
4325 if(!is_dir($file) && $file != '.' && $file != '..') {
4326 $lasttime = @filemtime($this->dir.$file);
4327 if (time() - $lasttime > $expire) {
4328 @unlink($this->dir.$file);
4332 closedir($dir);
4336 * delete current user's cache file
4338 * @global object $CFG
4339 * @global object $USER
4341 public function refresh() {
4342 global $CFG, $USER;
4343 if ($dir = opendir($this->dir)) {
4344 while (false !== ($file = readdir($dir))) {
4345 if (!is_dir($file) && $file != '.' && $file != '..') {
4346 if (strpos($file, 'u'.$USER->id.'_') !== false) {
4347 @unlink($this->dir.$file);
4356 * This function delegates file serving to individual plugins
4358 * @param string $relativepath
4359 * @param bool $forcedownload
4360 * @param null|string $preview the preview mode, defaults to serving the original file
4361 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4362 * offline (e.g. mobile app).
4363 * @param bool $embed Whether this file will be served embed into an iframe.
4364 * @todo MDL-31088 file serving improments
4366 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4367 global $DB, $CFG, $USER;
4368 // relative path must start with '/'
4369 if (!$relativepath) {
4370 throw new \moodle_exception('invalidargorconf');
4371 } else if ($relativepath[0] != '/') {
4372 throw new \moodle_exception('pathdoesnotstartslash');
4375 // extract relative path components
4376 $args = explode('/', ltrim($relativepath, '/'));
4378 if (count($args) < 3) { // always at least context, component and filearea
4379 throw new \moodle_exception('invalidarguments');
4382 $contextid = (int)array_shift($args);
4383 $component = clean_param(array_shift($args), PARAM_COMPONENT);
4384 $filearea = clean_param(array_shift($args), PARAM_AREA);
4386 list($context, $course, $cm) = get_context_info_array($contextid);
4388 $fs = get_file_storage();
4390 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4392 // ========================================================================================================================
4393 if ($component === 'blog') {
4394 // Blog file serving
4395 if ($context->contextlevel != CONTEXT_SYSTEM) {
4396 send_file_not_found();
4398 if ($filearea !== 'attachment' and $filearea !== 'post') {
4399 send_file_not_found();
4402 if (empty($CFG->enableblogs)) {
4403 throw new \moodle_exception('siteblogdisable', 'blog');
4406 $entryid = (int)array_shift($args);
4407 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4408 send_file_not_found();
4410 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4411 require_login();
4412 if (isguestuser()) {
4413 throw new \moodle_exception('noguest');
4415 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4416 if ($USER->id != $entry->userid) {
4417 send_file_not_found();
4422 if ($entry->publishstate === 'public') {
4423 if ($CFG->forcelogin) {
4424 require_login();
4427 } else if ($entry->publishstate === 'site') {
4428 require_login();
4429 //ok
4430 } else if ($entry->publishstate === 'draft') {
4431 require_login();
4432 if ($USER->id != $entry->userid) {
4433 send_file_not_found();
4437 $filename = array_pop($args);
4438 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4440 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4441 send_file_not_found();
4444 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4446 // ========================================================================================================================
4447 } else if ($component === 'grade') {
4449 require_once($CFG->libdir . '/grade/constants.php');
4451 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4452 // Global gradebook files
4453 if ($CFG->forcelogin) {
4454 require_login();
4457 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4459 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4460 send_file_not_found();
4463 \core\session\manager::write_close(); // Unlock session during file serving.
4464 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4466 } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4467 if ($context->contextlevel != CONTEXT_MODULE) {
4468 send_file_not_found();
4471 require_login($course, false);
4473 $gradeid = (int) array_shift($args);
4474 $filename = array_pop($args);
4475 if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4476 $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4477 } else {
4478 $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4481 if (!$grade) {
4482 send_file_not_found();
4485 $iscurrentuser = $USER->id == $grade->userid;
4487 if (!$iscurrentuser) {
4488 $coursecontext = context_course::instance($course->id);
4489 if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4490 send_file_not_found();
4494 $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4496 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4497 send_file_not_found();
4500 \core\session\manager::write_close(); // Unlock session during file serving.
4501 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4502 } else {
4503 send_file_not_found();
4506 // ========================================================================================================================
4507 } else if ($component === 'tag') {
4508 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4510 // All tag descriptions are going to be public but we still need to respect forcelogin
4511 if ($CFG->forcelogin) {
4512 require_login();
4515 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4517 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4518 send_file_not_found();
4521 \core\session\manager::write_close(); // Unlock session during file serving.
4522 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4524 } else {
4525 send_file_not_found();
4527 // ========================================================================================================================
4528 } else if ($component === 'badges') {
4529 require_once($CFG->libdir . '/badgeslib.php');
4531 $badgeid = (int)array_shift($args);
4532 $badge = new badge($badgeid);
4533 $filename = array_pop($args);
4535 if ($filearea === 'badgeimage') {
4536 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4537 send_file_not_found();
4539 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4540 send_file_not_found();
4543 \core\session\manager::write_close();
4544 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4545 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4546 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4547 send_file_not_found();
4550 \core\session\manager::write_close();
4551 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4553 // ========================================================================================================================
4554 } else if ($component === 'calendar') {
4555 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4557 // All events here are public the one requirement is that we respect forcelogin
4558 if ($CFG->forcelogin) {
4559 require_login();
4562 // Get the event if from the args array
4563 $eventid = array_shift($args);
4565 // Load the event from the database
4566 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4567 send_file_not_found();
4570 // Get the file and serve if successful
4571 $filename = array_pop($args);
4572 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4573 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4574 send_file_not_found();
4577 \core\session\manager::write_close(); // Unlock session during file serving.
4578 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4580 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4582 // Must be logged in, if they are not then they obviously can't be this user
4583 require_login();
4585 // Don't want guests here, potentially saves a DB call
4586 if (isguestuser()) {
4587 send_file_not_found();
4590 // Get the event if from the args array
4591 $eventid = array_shift($args);
4593 // Load the event from the database - user id must match
4594 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4595 send_file_not_found();
4598 // Get the file and serve if successful
4599 $filename = array_pop($args);
4600 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4601 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4602 send_file_not_found();
4605 \core\session\manager::write_close(); // Unlock session during file serving.
4606 send_stored_file($file, 0, 0, true, $sendfileoptions);
4608 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSECAT) {
4609 if ($CFG->forcelogin) {
4610 require_login();
4613 // Get category, this will also validate access.
4614 $category = core_course_category::get($context->instanceid);
4616 // Get the event ID from the args array, load event.
4617 $eventid = array_shift($args);
4618 $event = $DB->get_record('event', [
4619 'id' => (int) $eventid,
4620 'eventtype' => 'category',
4621 'categoryid' => $category->id,
4624 if (!$event) {
4625 send_file_not_found();
4628 // Retrieve file from storage, and serve.
4629 $filename = array_pop($args);
4630 $filepath = $args ? '/' . implode('/', $args) .'/' : '/';
4631 $file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename);
4632 if (!$file || $file->is_directory()) {
4633 send_file_not_found();
4636 // Unlock session during file serving.
4637 \core\session\manager::write_close();
4638 send_stored_file($file, HOURSECS, 0, $forcedownload, $sendfileoptions);
4639 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4641 // Respect forcelogin and require login unless this is the site.... it probably
4642 // should NEVER be the site
4643 if ($CFG->forcelogin || $course->id != SITEID) {
4644 require_login($course);
4647 // Must be able to at least view the course. This does not apply to the front page.
4648 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4649 //TODO: hmm, do we really want to block guests here?
4650 send_file_not_found();
4653 // Get the event id
4654 $eventid = array_shift($args);
4656 // Load the event from the database we need to check whether it is
4657 // a) valid course event
4658 // b) a group event
4659 // Group events use the course context (there is no group context)
4660 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4661 send_file_not_found();
4664 // If its a group event require either membership of view all groups capability
4665 if ($event->eventtype === 'group') {
4666 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4667 send_file_not_found();
4669 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4670 // Ok. Please note that the event type 'site' still uses a course context.
4671 } else {
4672 // Some other type.
4673 send_file_not_found();
4676 // If we get this far we can serve the file
4677 $filename = array_pop($args);
4678 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4679 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4680 send_file_not_found();
4683 \core\session\manager::write_close(); // Unlock session during file serving.
4684 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4686 } else {
4687 send_file_not_found();
4690 // ========================================================================================================================
4691 } else if ($component === 'user') {
4692 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4693 if (count($args) == 1) {
4694 $themename = theme_config::DEFAULT_THEME;
4695 $filename = array_shift($args);
4696 } else {
4697 $themename = array_shift($args);
4698 $filename = array_shift($args);
4701 // fix file name automatically
4702 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4703 $filename = 'f1';
4706 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4707 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4708 // protect images if login required and not logged in;
4709 // also if login is required for profile images and is not logged in or guest
4710 // do not use require_login() because it is expensive and not suitable here anyway
4711 $theme = theme_config::load($themename);
4712 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4715 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4716 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4717 if ($filename === 'f3') {
4718 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4719 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4720 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4725 if (!$file) {
4726 // bad reference - try to prevent future retries as hard as possible!
4727 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4728 if ($user->picture > 0) {
4729 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4732 // no redirect here because it is not cached
4733 $theme = theme_config::load($themename);
4734 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4735 send_file($imagefile, basename($imagefile), 60*60*24*14);
4738 $options = $sendfileoptions;
4739 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4740 // Profile images should be cache-able by both browsers and proxies according
4741 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4742 $options['cacheability'] = 'public';
4744 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4746 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4747 require_login();
4749 if (isguestuser()) {
4750 send_file_not_found();
4753 if ($USER->id !== $context->instanceid) {
4754 send_file_not_found();
4757 $filename = array_pop($args);
4758 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4759 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4760 send_file_not_found();
4763 \core\session\manager::write_close(); // Unlock session during file serving.
4764 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4766 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4768 if ($CFG->forcelogin) {
4769 require_login();
4772 $userid = $context->instanceid;
4774 if (!empty($CFG->forceloginforprofiles)) {
4775 require_once("{$CFG->dirroot}/user/lib.php");
4777 require_login();
4779 // Verify the current user is able to view the profile of the supplied user anywhere.
4780 $user = core_user::get_user($userid);
4781 if (!user_can_view_profile($user, null, $context)) {
4782 send_file_not_found();
4786 $filename = array_pop($args);
4787 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4788 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4789 send_file_not_found();
4792 \core\session\manager::write_close(); // Unlock session during file serving.
4793 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4795 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4796 $userid = (int)array_shift($args);
4797 $usercontext = context_user::instance($userid);
4799 if ($CFG->forcelogin) {
4800 require_login();
4803 if (!empty($CFG->forceloginforprofiles)) {
4804 require_once("{$CFG->dirroot}/user/lib.php");
4806 require_login();
4808 // Verify the current user is able to view the profile of the supplied user in current course.
4809 $user = core_user::get_user($userid);
4810 if (!user_can_view_profile($user, $course, $usercontext)) {
4811 send_file_not_found();
4815 $filename = array_pop($args);
4816 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4817 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4818 send_file_not_found();
4821 \core\session\manager::write_close(); // Unlock session during file serving.
4822 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4824 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4825 require_login();
4827 if (isguestuser()) {
4828 send_file_not_found();
4830 $userid = $context->instanceid;
4832 if ($USER->id != $userid) {
4833 send_file_not_found();
4836 $filename = array_pop($args);
4837 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4838 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4839 send_file_not_found();
4842 \core\session\manager::write_close(); // Unlock session during file serving.
4843 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4845 } else {
4846 send_file_not_found();
4849 // ========================================================================================================================
4850 } else if ($component === 'coursecat') {
4851 if ($context->contextlevel != CONTEXT_COURSECAT) {
4852 send_file_not_found();
4855 if ($filearea === 'description') {
4856 if ($CFG->forcelogin) {
4857 // no login necessary - unless login forced everywhere
4858 require_login();
4861 // Check if user can view this category.
4862 if (!core_course_category::get($context->instanceid, IGNORE_MISSING)) {
4863 send_file_not_found();
4866 $filename = array_pop($args);
4867 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4868 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4869 send_file_not_found();
4872 \core\session\manager::write_close(); // Unlock session during file serving.
4873 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4874 } else {
4875 send_file_not_found();
4878 // ========================================================================================================================
4879 } else if ($component === 'course') {
4880 if ($context->contextlevel != CONTEXT_COURSE) {
4881 send_file_not_found();
4884 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4885 if ($CFG->forcelogin) {
4886 require_login();
4889 $filename = array_pop($args);
4890 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4891 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4892 send_file_not_found();
4895 \core\session\manager::write_close(); // Unlock session during file serving.
4896 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4898 } else if ($filearea === 'section') {
4899 if ($CFG->forcelogin) {
4900 require_login($course);
4901 } else if ($course->id != SITEID) {
4902 require_login($course);
4905 $sectionid = (int)array_shift($args);
4907 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4908 send_file_not_found();
4911 $filename = array_pop($args);
4912 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4913 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4914 send_file_not_found();
4917 \core\session\manager::write_close(); // Unlock session during file serving.
4918 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4920 } else {
4921 send_file_not_found();
4924 } else if ($component === 'cohort') {
4926 $cohortid = (int)array_shift($args);
4927 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4928 $cohortcontext = context::instance_by_id($cohort->contextid);
4930 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4931 if ($context->id != $cohort->contextid &&
4932 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4933 send_file_not_found();
4936 // User is able to access cohort if they have view cap on cohort level or
4937 // the cohort is visible and they have view cap on course level.
4938 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4939 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4941 if ($filearea === 'description' && $canview) {
4942 $filename = array_pop($args);
4943 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4944 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4945 && !$file->is_directory()) {
4946 \core\session\manager::write_close(); // Unlock session during file serving.
4947 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4951 send_file_not_found();
4953 } else if ($component === 'group') {
4954 if ($context->contextlevel != CONTEXT_COURSE) {
4955 send_file_not_found();
4958 require_course_login($course, true, null, false);
4960 $groupid = (int)array_shift($args);
4962 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4963 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4964 // do not allow access to separate group info if not member or teacher
4965 send_file_not_found();
4968 if ($filearea === 'description') {
4970 require_login($course);
4972 $filename = array_pop($args);
4973 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4974 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4975 send_file_not_found();
4978 \core\session\manager::write_close(); // Unlock session during file serving.
4979 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4981 } else if ($filearea === 'icon') {
4982 $filename = array_pop($args);
4984 if ($filename !== 'f1' and $filename !== 'f2') {
4985 send_file_not_found();
4987 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4988 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4989 send_file_not_found();
4993 \core\session\manager::write_close(); // Unlock session during file serving.
4994 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4996 } else {
4997 send_file_not_found();
5000 } else if ($component === 'grouping') {
5001 if ($context->contextlevel != CONTEXT_COURSE) {
5002 send_file_not_found();
5005 require_login($course);
5007 $groupingid = (int)array_shift($args);
5009 // note: everybody has access to grouping desc images for now
5010 if ($filearea === 'description') {
5012 $filename = array_pop($args);
5013 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5014 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
5015 send_file_not_found();
5018 \core\session\manager::write_close(); // Unlock session during file serving.
5019 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
5021 } else {
5022 send_file_not_found();
5025 // ========================================================================================================================
5026 } else if ($component === 'backup') {
5027 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
5028 require_login($course);
5029 require_capability('moodle/backup:downloadfile', $context);
5031 $filename = array_pop($args);
5032 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5033 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
5034 send_file_not_found();
5037 \core\session\manager::write_close(); // Unlock session during file serving.
5038 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
5040 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
5041 require_login($course);
5042 require_capability('moodle/backup:downloadfile', $context);
5044 $sectionid = (int)array_shift($args);
5046 $filename = array_pop($args);
5047 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5048 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
5049 send_file_not_found();
5052 \core\session\manager::write_close();
5053 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
5055 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
5056 require_login($course, false, $cm);
5057 require_capability('moodle/backup:downloadfile', $context);
5059 $filename = array_pop($args);
5060 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5061 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
5062 send_file_not_found();
5065 \core\session\manager::write_close();
5066 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
5068 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
5069 // Backup files that were generated by the automated backup systems.
5071 require_login($course);
5072 require_capability('moodle/backup:downloadfile', $context);
5073 require_capability('moodle/restore:userinfo', $context);
5075 $filename = array_pop($args);
5076 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5077 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
5078 send_file_not_found();
5081 \core\session\manager::write_close(); // Unlock session during file serving.
5082 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
5084 } else {
5085 send_file_not_found();
5088 // ========================================================================================================================
5089 } else if ($component === 'question') {
5090 require_once($CFG->libdir . '/questionlib.php');
5091 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
5092 send_file_not_found();
5094 // ========================================================================================================================
5095 } else if ($component === 'grading') {
5096 if ($filearea === 'description') {
5097 // files embedded into the form definition description
5099 if ($context->contextlevel == CONTEXT_SYSTEM) {
5100 require_login();
5102 } else if ($context->contextlevel >= CONTEXT_COURSE) {
5103 require_login($course, false, $cm);
5105 } else {
5106 send_file_not_found();
5109 $formid = (int)array_shift($args);
5111 $sql = "SELECT ga.id
5112 FROM {grading_areas} ga
5113 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
5114 WHERE gd.id = ? AND ga.contextid = ?";
5115 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
5117 if (!$areaid) {
5118 send_file_not_found();
5121 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
5123 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
5124 send_file_not_found();
5127 \core\session\manager::write_close(); // Unlock session during file serving.
5128 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
5130 } else if ($component === 'contentbank') {
5131 if ($filearea != 'public' || isguestuser()) {
5132 send_file_not_found();
5135 if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
5136 require_login();
5137 } else if ($context->contextlevel == CONTEXT_COURSE) {
5138 require_login($course);
5139 } else {
5140 send_file_not_found();
5143 $componentargs = fullclone($args);
5144 $itemid = (int)array_shift($args);
5145 $filename = array_pop($args);
5146 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5148 \core\session\manager::write_close(); // Unlock session during file serving.
5150 $contenttype = $DB->get_field('contentbank_content', 'contenttype', ['id' => $itemid]);
5151 if (component_class_callback("\\{$contenttype}\\contenttype", 'pluginfile',
5152 [$course, null, $context, $filearea, $componentargs, $forcedownload, $sendfileoptions], false) === false) {
5154 if (!$file = $fs->get_file($context->id, $component, $filearea, $itemid, $filepath, $filename) or
5156 $file->is_directory()) {
5157 send_file_not_found();
5159 } else {
5160 send_stored_file($file, 0, 0, true, $sendfileoptions); // Must force download - security!
5163 } else if (strpos($component, 'mod_') === 0) {
5164 $modname = substr($component, 4);
5165 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
5166 send_file_not_found();
5168 require_once("$CFG->dirroot/mod/$modname/lib.php");
5170 if ($context->contextlevel == CONTEXT_MODULE) {
5171 if ($cm->modname !== $modname) {
5172 // somebody tries to gain illegal access, cm type must match the component!
5173 send_file_not_found();
5177 if ($filearea === 'intro') {
5178 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
5179 send_file_not_found();
5182 // Require login to the course first (without login to the module).
5183 require_course_login($course, true);
5185 // Now check if module is available OR it is restricted but the intro is shown on the course page.
5186 $cminfo = cm_info::create($cm);
5187 if (!$cminfo->uservisible) {
5188 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
5189 // Module intro is not visible on the course page and module is not available, show access error.
5190 require_course_login($course, true, $cminfo);
5194 // all users may access it
5195 $filename = array_pop($args);
5196 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5197 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
5198 send_file_not_found();
5201 // finally send the file
5202 send_stored_file($file, null, 0, false, $sendfileoptions);
5205 $filefunction = $component.'_pluginfile';
5206 $filefunctionold = $modname.'_pluginfile';
5207 if (function_exists($filefunction)) {
5208 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5209 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5210 } else if (function_exists($filefunctionold)) {
5211 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5212 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5215 send_file_not_found();
5217 // ========================================================================================================================
5218 } else if (strpos($component, 'block_') === 0) {
5219 $blockname = substr($component, 6);
5220 // note: no more class methods in blocks please, that is ....
5221 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
5222 send_file_not_found();
5224 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
5226 if ($context->contextlevel == CONTEXT_BLOCK) {
5227 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
5228 if ($birecord->blockname !== $blockname) {
5229 // somebody tries to gain illegal access, cm type must match the component!
5230 send_file_not_found();
5233 if ($context->get_course_context(false)) {
5234 // If block is in course context, then check if user has capability to access course.
5235 require_course_login($course);
5236 } else if ($CFG->forcelogin) {
5237 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
5238 require_login();
5241 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
5242 // User can't access file, if block is hidden or doesn't have block:view capability
5243 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
5244 send_file_not_found();
5246 } else {
5247 $birecord = null;
5250 $filefunction = $component.'_pluginfile';
5251 if (function_exists($filefunction)) {
5252 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5253 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5256 send_file_not_found();
5258 // ========================================================================================================================
5259 } else if (strpos($component, '_') === false) {
5260 // all core subsystems have to be specified above, no more guessing here!
5261 send_file_not_found();
5263 } else {
5264 // try to serve general plugin file in arbitrary context
5265 $dir = core_component::get_component_directory($component);
5266 if (!file_exists("$dir/lib.php")) {
5267 send_file_not_found();
5269 include_once("$dir/lib.php");
5271 $filefunction = $component.'_pluginfile';
5272 if (function_exists($filefunction)) {
5273 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5274 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5277 send_file_not_found();