Merge branch 'MDL-70099-311' of git://github.com/paulholden/moodle into MOODLE_311_STABLE
[moodle.git] / lib / filelib.php
blob3b174550f8f32fc4766b8c61eafde8c741666ee0
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 require_once("$CFG->libdir/filestorage/file_exceptions.php");
44 require_once("$CFG->libdir/filestorage/file_storage.php");
45 require_once("$CFG->libdir/filestorage/zip_packer.php");
46 require_once("$CFG->libdir/filebrowser/file_browser.php");
48 /**
49 * Encodes file serving url
51 * @deprecated use moodle_url factory methods instead
53 * @todo MDL-31071 deprecate this function
54 * @global stdClass $CFG
55 * @param string $urlbase
56 * @param string $path /filearea/itemid/dir/dir/file.exe
57 * @param bool $forcedownload
58 * @param bool $https https url required
59 * @return string encoded file url
61 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
62 global $CFG;
64 //TODO: deprecate this
66 if ($CFG->slasharguments) {
67 $parts = explode('/', $path);
68 $parts = array_map('rawurlencode', $parts);
69 $path = implode('/', $parts);
70 $return = $urlbase.$path;
71 if ($forcedownload) {
72 $return .= '?forcedownload=1';
74 } else {
75 $path = rawurlencode($path);
76 $return = $urlbase.'?file='.$path;
77 if ($forcedownload) {
78 $return .= '&amp;forcedownload=1';
82 if ($https) {
83 $return = str_replace('http://', 'https://', $return);
86 return $return;
89 /**
90 * Detects if area contains subdirs,
91 * this is intended for file areas that are attached to content
92 * migrated from 1.x where subdirs were allowed everywhere.
94 * @param context $context
95 * @param string $component
96 * @param string $filearea
97 * @param string $itemid
98 * @return bool
100 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
101 global $DB;
103 if (!isset($itemid)) {
104 // Not initialised yet.
105 return false;
108 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
109 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
110 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
111 return $DB->record_exists_select('files', $select, $params);
115 * Prepares 'editor' formslib element from data in database
117 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
118 * function then copies the embedded files into draft area (assigning itemids automatically),
119 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
120 * displayed.
121 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
122 * your mform's set_data() supplying the object returned by this function.
124 * @category files
125 * @param stdClass $data database field that holds the html text with embedded media
126 * @param string $field the name of the database field that holds the html text with embedded media
127 * @param array $options editor options (like maxifiles, maxbytes etc.)
128 * @param stdClass $context context of the editor
129 * @param string $component
130 * @param string $filearea file area name
131 * @param int $itemid item id, required if item exists
132 * @return stdClass modified data object
134 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
135 $options = (array)$options;
136 if (!isset($options['trusttext'])) {
137 $options['trusttext'] = false;
139 if (!isset($options['forcehttps'])) {
140 $options['forcehttps'] = false;
142 if (!isset($options['subdirs'])) {
143 $options['subdirs'] = false;
145 if (!isset($options['maxfiles'])) {
146 $options['maxfiles'] = 0; // no files by default
148 if (!isset($options['noclean'])) {
149 $options['noclean'] = false;
152 //sanity check for passed context. This function doesn't expect $option['context'] to be set
153 //But this function is called before creating editor hence, this is one of the best places to check
154 //if context is used properly. This check notify developer that they missed passing context to editor.
155 if (isset($context) && !isset($options['context'])) {
156 //if $context is not null then make sure $option['context'] is also set.
157 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
158 } else if (isset($options['context']) && isset($context)) {
159 //If both are passed then they should be equal.
160 if ($options['context']->id != $context->id) {
161 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
162 throw new coding_exception($exceptionmsg);
166 if (is_null($itemid) or is_null($context)) {
167 $contextid = null;
168 $itemid = null;
169 if (!isset($data)) {
170 $data = new stdClass();
172 if (!isset($data->{$field})) {
173 $data->{$field} = '';
175 if (!isset($data->{$field.'format'})) {
176 $data->{$field.'format'} = editors_get_preferred_format();
178 if (!$options['noclean']) {
179 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
182 } else {
183 if ($options['trusttext']) {
184 // noclean ignored if trusttext enabled
185 if (!isset($data->{$field.'trust'})) {
186 $data->{$field.'trust'} = 0;
188 $data = trusttext_pre_edit($data, $field, $context);
189 } else {
190 if (!$options['noclean']) {
191 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
194 $contextid = $context->id;
197 if ($options['maxfiles'] != 0) {
198 $draftid_editor = file_get_submitted_draft_itemid($field);
199 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
200 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
201 } else {
202 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
205 return $data;
209 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
211 * This function moves files from draft area to the destination area and
212 * encodes URLs to the draft files so they can be safely saved into DB. The
213 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
214 * is the name of the database field to hold the wysiwyg editor content. The
215 * editor data comes as an array with text, format and itemid properties. This
216 * function automatically adds $data properties foobar, foobarformat and
217 * foobartrust, where foobar has URL to embedded files encoded.
219 * @category files
220 * @param stdClass $data raw data submitted by the form
221 * @param string $field name of the database field containing the html with embedded media files
222 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
223 * @param stdClass $context context, required for existing data
224 * @param string $component file component
225 * @param string $filearea file area name
226 * @param int $itemid item id, required if item exists
227 * @return stdClass modified data object
229 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
230 $options = (array)$options;
231 if (!isset($options['trusttext'])) {
232 $options['trusttext'] = false;
234 if (!isset($options['forcehttps'])) {
235 $options['forcehttps'] = false;
237 if (!isset($options['subdirs'])) {
238 $options['subdirs'] = false;
240 if (!isset($options['maxfiles'])) {
241 $options['maxfiles'] = 0; // no files by default
243 if (!isset($options['maxbytes'])) {
244 $options['maxbytes'] = 0; // unlimited
246 if (!isset($options['removeorphaneddrafts'])) {
247 $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
250 if ($options['trusttext']) {
251 $data->{$field.'trust'} = trusttext_trusted($context);
252 } else {
253 $data->{$field.'trust'} = 0;
256 $editor = $data->{$field.'_editor'};
258 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
259 $data->{$field} = $editor['text'];
260 } else {
261 // Clean the user drafts area of any files not referenced in the editor text.
262 if ($options['removeorphaneddrafts']) {
263 file_remove_editor_orphaned_files($editor);
265 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
267 $data->{$field.'format'} = $editor['format'];
269 return $data;
273 * Saves text and files modified by Editor formslib element
275 * @category files
276 * @param stdClass $data $database entry field
277 * @param string $field name of data field
278 * @param array $options various options
279 * @param stdClass $context context - must already exist
280 * @param string $component
281 * @param string $filearea file area name
282 * @param int $itemid must already exist, usually means data is in db
283 * @return stdClass modified data obejct
285 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
286 $options = (array)$options;
287 if (!isset($options['subdirs'])) {
288 $options['subdirs'] = false;
290 if (is_null($itemid) or is_null($context)) {
291 $itemid = null;
292 $contextid = null;
293 } else {
294 $contextid = $context->id;
297 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
298 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
299 $data->{$field.'_filemanager'} = $draftid_editor;
301 return $data;
305 * Saves files modified by File manager formslib element
307 * @todo MDL-31073 review this function
308 * @category files
309 * @param stdClass $data $database entry field
310 * @param string $field name of data field
311 * @param array $options various options
312 * @param stdClass $context context - must already exist
313 * @param string $component
314 * @param string $filearea file area name
315 * @param int $itemid must already exist, usually means data is in db
316 * @return stdClass modified data obejct
318 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
319 $options = (array)$options;
320 if (!isset($options['subdirs'])) {
321 $options['subdirs'] = false;
323 if (!isset($options['maxfiles'])) {
324 $options['maxfiles'] = -1; // unlimited
326 if (!isset($options['maxbytes'])) {
327 $options['maxbytes'] = 0; // unlimited
330 if (empty($data->{$field.'_filemanager'})) {
331 $data->$field = '';
333 } else {
334 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
335 $fs = get_file_storage();
337 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
338 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
339 } else {
340 $data->$field = '';
344 return $data;
348 * Generate a draft itemid
350 * @category files
351 * @global moodle_database $DB
352 * @global stdClass $USER
353 * @return int a random but available draft itemid that can be used to create a new draft
354 * file area.
356 function file_get_unused_draft_itemid() {
357 global $DB, $USER;
359 if (isguestuser() or !isloggedin()) {
360 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
361 print_error('noguest');
364 $contextid = context_user::instance($USER->id)->id;
366 $fs = get_file_storage();
367 $draftitemid = rand(1, 999999999);
368 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
369 $draftitemid = rand(1, 999999999);
372 return $draftitemid;
376 * Initialise a draft file area from a real one by copying the files. A draft
377 * area will be created if one does not already exist. Normally you should
378 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
380 * @category files
381 * @global stdClass $CFG
382 * @global stdClass $USER
383 * @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.
384 * @param int $contextid This parameter and the next two identify the file area to copy files from.
385 * @param string $component
386 * @param string $filearea helps indentify the file area.
387 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
388 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
389 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
390 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
392 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
393 global $CFG, $USER, $CFG;
395 $options = (array)$options;
396 if (!isset($options['subdirs'])) {
397 $options['subdirs'] = false;
399 if (!isset($options['forcehttps'])) {
400 $options['forcehttps'] = false;
403 $usercontext = context_user::instance($USER->id);
404 $fs = get_file_storage();
406 if (empty($draftitemid)) {
407 // create a new area and copy existing files into
408 $draftitemid = file_get_unused_draft_itemid();
409 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
410 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
411 foreach ($files as $file) {
412 if ($file->is_directory() and $file->get_filepath() === '/') {
413 // we need a way to mark the age of each draft area,
414 // by not copying the root dir we force it to be created automatically with current timestamp
415 continue;
417 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
418 continue;
420 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
421 // XXX: This is a hack for file manager (MDL-28666)
422 // File manager needs to know the original file information before copying
423 // to draft area, so we append these information in mdl_files.source field
424 // {@link file_storage::search_references()}
425 // {@link file_storage::search_references_count()}
426 $sourcefield = $file->get_source();
427 $newsourcefield = new stdClass;
428 $newsourcefield->source = $sourcefield;
429 $original = new stdClass;
430 $original->contextid = $contextid;
431 $original->component = $component;
432 $original->filearea = $filearea;
433 $original->itemid = $itemid;
434 $original->filename = $file->get_filename();
435 $original->filepath = $file->get_filepath();
436 $newsourcefield->original = file_storage::pack_reference($original);
437 $draftfile->set_source(serialize($newsourcefield));
438 // End of file manager hack
441 if (!is_null($text)) {
442 // at this point there should not be any draftfile links yet,
443 // because this is a new text from database that should still contain the @@pluginfile@@ links
444 // this happens when developers forget to post process the text
445 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
447 } else {
448 // nothing to do
451 if (is_null($text)) {
452 return null;
455 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
456 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
460 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
461 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
462 * in the @@PLUGINFILE@@ form.
464 * @param string $text The content that may contain ULRs in need of rewriting.
465 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
466 * @param int $contextid This parameter and the next two identify the file area to use.
467 * @param string $component
468 * @param string $filearea helps identify the file area.
469 * @param int $itemid helps identify the file area.
470 * @param array $options
471 * bool $options.forcehttps Force the user of https
472 * bool $options.reverse Reverse the behaviour of the function
473 * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
474 * string The processed text.
476 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
477 global $CFG, $USER;
479 $options = (array)$options;
480 if (!isset($options['forcehttps'])) {
481 $options['forcehttps'] = false;
484 $baseurl = "{$CFG->wwwroot}/{$file}";
485 if (!empty($options['includetoken'])) {
486 $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
487 $token = get_user_key('core_files', $userid);
488 $finalfile = basename($file);
489 $tokenfile = "token{$finalfile}";
490 $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
491 $baseurl = "{$CFG->wwwroot}/{$file}";
493 if (!$CFG->slasharguments) {
494 $baseurl .= "?token={$token}&file=";
495 } else {
496 $baseurl .= "/{$token}";
500 $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
502 if ($itemid !== null) {
503 $baseurl .= "$itemid/";
506 if ($options['forcehttps']) {
507 $baseurl = str_replace('http://', 'https://', $baseurl);
510 if (!empty($options['reverse'])) {
511 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
512 } else {
513 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
518 * Returns information about files in a draft area.
520 * @global stdClass $CFG
521 * @global stdClass $USER
522 * @param int $draftitemid the draft area item id.
523 * @param string $filepath path to the directory from which the information have to be retrieved.
524 * @return array with the following entries:
525 * 'filecount' => number of files in the draft area.
526 * 'filesize' => total size of the files in the draft area.
527 * 'foldercount' => number of folders in the draft area.
528 * 'filesize_without_references' => total size of the area excluding file references.
529 * (more information will be added as needed).
531 function file_get_draft_area_info($draftitemid, $filepath = '/') {
532 global $USER;
534 $usercontext = context_user::instance($USER->id);
535 return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
539 * Returns information about files in an area.
541 * @param int $contextid context id
542 * @param string $component component
543 * @param string $filearea file area name
544 * @param int $itemid item id or all files if not specified
545 * @param string $filepath path to the directory from which the information have to be retrieved.
546 * @return array with the following entries:
547 * 'filecount' => number of files in the area.
548 * 'filesize' => total size of the files in the area.
549 * 'foldercount' => number of folders in the area.
550 * 'filesize_without_references' => total size of the area excluding file references.
551 * @since Moodle 3.4
553 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
555 $fs = get_file_storage();
557 $results = array(
558 'filecount' => 0,
559 'foldercount' => 0,
560 'filesize' => 0,
561 'filesize_without_references' => 0
564 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
566 foreach ($draftfiles as $file) {
567 if ($file->is_directory()) {
568 $results['foldercount'] += 1;
569 } else {
570 $results['filecount'] += 1;
573 $filesize = $file->get_filesize();
574 $results['filesize'] += $filesize;
575 if (!$file->is_external_file()) {
576 $results['filesize_without_references'] += $filesize;
580 return $results;
584 * Returns whether a draft area has exceeded/will exceed its size limit.
586 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
588 * @param int $draftitemid the draft area item id.
589 * @param int $areamaxbytes the maximum size allowed in this draft area.
590 * @param int $newfilesize the size that would be added to the current area.
591 * @param bool $includereferences true to include the size of the references in the area size.
592 * @return bool true if the area will/has exceeded its limit.
593 * @since Moodle 2.4
595 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
596 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
597 $draftinfo = file_get_draft_area_info($draftitemid);
598 $areasize = $draftinfo['filesize_without_references'];
599 if ($includereferences) {
600 $areasize = $draftinfo['filesize'];
602 if ($areasize + $newfilesize > $areamaxbytes) {
603 return true;
606 return false;
610 * Get used space of files
611 * @global moodle_database $DB
612 * @global stdClass $USER
613 * @return int total bytes
615 function file_get_user_used_space() {
616 global $DB, $USER;
618 $usercontext = context_user::instance($USER->id);
619 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
620 JOIN (SELECT contenthash, filename, MAX(id) AS id
621 FROM {files}
622 WHERE contextid = ? AND component = ? AND filearea != ?
623 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
624 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
625 $record = $DB->get_record_sql($sql, $params);
626 return (int)$record->totalbytes;
630 * Convert any string to a valid filepath
631 * @todo review this function
632 * @param string $str
633 * @return string path
635 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
636 if ($str == '/' or empty($str)) {
637 return '/';
638 } else {
639 return '/'.trim($str, '/').'/';
644 * Generate a folder tree of draft area of current USER recursively
646 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
647 * @param int $draftitemid
648 * @param string $filepath
649 * @param mixed $data
651 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
652 global $USER, $OUTPUT, $CFG;
653 $data->children = array();
654 $context = context_user::instance($USER->id);
655 $fs = get_file_storage();
656 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
657 foreach ($files as $file) {
658 if ($file->is_directory()) {
659 $item = new stdClass();
660 $item->sortorder = $file->get_sortorder();
661 $item->filepath = $file->get_filepath();
663 $foldername = explode('/', trim($item->filepath, '/'));
664 $item->fullname = trim(array_pop($foldername), '/');
666 $item->id = uniqid();
667 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
668 $data->children[] = $item;
669 } else {
670 continue;
677 * Listing all files (including folders) in current path (draft area)
678 * used by file manager
679 * @param int $draftitemid
680 * @param string $filepath
681 * @return stdClass
683 function file_get_drafarea_files($draftitemid, $filepath = '/') {
684 global $USER, $OUTPUT, $CFG;
686 $context = context_user::instance($USER->id);
687 $fs = get_file_storage();
689 $data = new stdClass();
690 $data->path = array();
691 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
693 // will be used to build breadcrumb
694 $trail = '/';
695 if ($filepath !== '/') {
696 $filepath = file_correct_filepath($filepath);
697 $parts = explode('/', $filepath);
698 foreach ($parts as $part) {
699 if ($part != '' && $part != null) {
700 $trail .= ($part.'/');
701 $data->path[] = array('name'=>$part, 'path'=>$trail);
706 $list = array();
707 $maxlength = 12;
708 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
709 foreach ($files as $file) {
710 $item = new stdClass();
711 $item->filename = $file->get_filename();
712 $item->filepath = $file->get_filepath();
713 $item->fullname = trim($item->filename, '/');
714 $filesize = $file->get_filesize();
715 $item->size = $filesize ? $filesize : null;
716 $item->filesize = $filesize ? display_size($filesize) : '';
718 $item->sortorder = $file->get_sortorder();
719 $item->author = $file->get_author();
720 $item->license = $file->get_license();
721 $item->datemodified = $file->get_timemodified();
722 $item->datecreated = $file->get_timecreated();
723 $item->isref = $file->is_external_file();
724 if ($item->isref && $file->get_status() == 666) {
725 $item->originalmissing = true;
727 // find the file this draft file was created from and count all references in local
728 // system pointing to that file
729 $source = @unserialize($file->get_source());
730 if (isset($source->original)) {
731 $item->refcount = $fs->search_references_count($source->original);
734 if ($file->is_directory()) {
735 $item->filesize = 0;
736 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
737 $item->type = 'folder';
738 $foldername = explode('/', trim($item->filepath, '/'));
739 $item->fullname = trim(array_pop($foldername), '/');
740 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
741 } else {
742 // do NOT use file browser here!
743 $item->mimetype = get_mimetype_description($file);
744 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
745 $item->type = 'zip';
746 } else {
747 $item->type = 'file';
749 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
750 $item->url = $itemurl->out();
751 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
752 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
754 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
755 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
756 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
757 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
758 // used by the widget to display a warning about the problem files.
759 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
760 $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
761 if ($item->status == 0) {
762 if ($imageinfo = $file->get_imageinfo()) {
763 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
764 'oid' => $file->get_timemodified()));
765 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
766 $item->image_width = $imageinfo['width'];
767 $item->image_height = $imageinfo['height'];
771 $list[] = $item;
774 $data->itemid = $draftitemid;
775 $data->list = $list;
776 return $data;
780 * Returns all of the files in the draftarea.
782 * @param int $draftitemid The draft item ID
783 * @param string $filepath path for the uploaded files.
784 * @return array An array of files associated with this draft item id.
786 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
787 $files = [];
788 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
789 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
791 if (!empty($draftfiles)) {
792 foreach ($draftfiles->list as $draftfile) {
793 if ($draftfile->type == 'file') {
794 $files[] = $draftfile;
798 if (isset($draftfiles->children)) {
799 foreach ($draftfiles->children as $draftfile) {
800 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
804 return $files;
808 * Returns draft area itemid for a given element.
810 * @category files
811 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
812 * @return int the itemid, or 0 if there is not one yet.
814 function file_get_submitted_draft_itemid($elname) {
815 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
816 if (!isset($_REQUEST[$elname])) {
817 return 0;
819 if (is_array($_REQUEST[$elname])) {
820 $param = optional_param_array($elname, 0, PARAM_INT);
821 if (!empty($param['itemid'])) {
822 $param = $param['itemid'];
823 } else {
824 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
825 return false;
828 } else {
829 $param = optional_param($elname, 0, PARAM_INT);
832 if ($param) {
833 require_sesskey();
836 return $param;
840 * Restore the original source field from draft files
842 * Do not use this function because it makes field files.source inconsistent
843 * for draft area files. This function will be deprecated in 2.6
845 * @param stored_file $storedfile This only works with draft files
846 * @return stored_file
848 function file_restore_source_field_from_draft_file($storedfile) {
849 $source = @unserialize($storedfile->get_source());
850 if (!empty($source)) {
851 if (is_object($source)) {
852 $restoredsource = $source->source;
853 $storedfile->set_source($restoredsource);
854 } else {
855 throw new moodle_exception('invalidsourcefield', 'error');
858 return $storedfile;
862 * Removes those files from the user drafts filearea which are not referenced in the editor text.
864 * @param stdClass $editor The online text editor element from the submitted form data.
866 function file_remove_editor_orphaned_files($editor) {
867 global $CFG, $USER;
869 // Find those draft files included in the text, and generate their hashes.
870 $context = context_user::instance($USER->id);
871 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
872 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
873 preg_match_all($pattern, $editor['text'], $matches);
874 $usedfilehashes = [];
875 foreach ($matches[1] as $matchedfilename) {
876 $matchedfilename = urldecode($matchedfilename);
877 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
878 $matchedfilename);
881 // Now, compare the hashes of all draft files, and remove those which don't match used files.
882 $fs = get_file_storage();
883 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
884 foreach ($files as $file) {
885 $tmphash = $file->get_pathnamehash();
886 if (!in_array($tmphash, $usedfilehashes)) {
887 $file->delete();
893 * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
894 * content from another draft area it's possible for a single textarea to reference multiple draft areas.
896 * @category files
897 * @param int $draftitemid the id of the primary draft area.
898 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
899 * @param int $usercontextid the user's context id.
900 * @param string $text some html content that needs to have files copied to the correct draft area.
901 * @param bool $forcehttps force https urls.
903 * @return string $text html content modified with new draft links
905 function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
906 if (is_null($text)) {
907 return null;
910 // Do not merge files, leave it as it was.
911 if ($draftitemid === IGNORE_FILE_MERGE) {
912 return null;
915 $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
917 // No draft areas to rewrite.
918 if (empty($urls)) {
919 return $text;
922 foreach ($urls as $url) {
923 // Do not process the "home" draft area.
924 if ($url['itemid'] == $draftitemid) {
925 continue;
928 // Decode the filename.
929 $filename = urldecode($url['filename']);
931 // Copy the file.
932 file_copy_file_to_file_area($url, $filename, $draftitemid);
934 // Rewrite draft area.
935 $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
937 return $text;
941 * Rewrites a file area in arbitrary text.
943 * @param array $file General information about the file.
944 * @param int $newid The new file area itemid.
945 * @param string $text The text to rewrite.
946 * @param bool $forcehttps force https urls.
947 * @return string The rewritten text.
949 function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
950 global $CFG;
952 $wwwroot = $CFG->wwwroot;
953 if ($forcehttps) {
954 $wwwroot = str_replace('http://', 'https://', $wwwroot);
957 $search = [
958 $wwwroot,
959 $file['urlbase'],
960 $file['contextid'],
961 $file['component'],
962 $file['filearea'],
963 $file['itemid'],
964 $file['filename']
966 $replace = [
967 $wwwroot,
968 $file['urlbase'],
969 $file['contextid'],
970 $file['component'],
971 $file['filearea'],
972 $newid,
973 $file['filename']
976 $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
977 return $text;
981 * Copies a file from one file area to another.
983 * @param array $file Information about the file to be copied.
984 * @param string $filename The filename.
985 * @param int $itemid The new file area.
987 function file_copy_file_to_file_area($file, $filename, $itemid) {
988 $fs = get_file_storage();
990 // Load the current file in the old draft area.
991 $fileinfo = array(
992 'component' => $file['component'],
993 'filearea' => $file['filearea'],
994 'itemid' => $file['itemid'],
995 'contextid' => $file['contextid'],
996 'filepath' => '/',
997 'filename' => $filename
999 $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
1000 $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
1001 $newfileinfo = array(
1002 'component' => $file['component'],
1003 'filearea' => $file['filearea'],
1004 'itemid' => $itemid,
1005 'contextid' => $file['contextid'],
1006 'filepath' => '/',
1007 'filename' => $filename
1010 $newcontextid = $newfileinfo['contextid'];
1011 $newcomponent = $newfileinfo['component'];
1012 $newfilearea = $newfileinfo['filearea'];
1013 $newitemid = $newfileinfo['itemid'];
1014 $newfilepath = $newfileinfo['filepath'];
1015 $newfilename = $newfileinfo['filename'];
1017 // Check if the file exists.
1018 if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1019 $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1024 * Saves files from a draft file area to a real one (merging the list of files).
1025 * Can rewrite URLs in some content at the same time if desired.
1027 * @category files
1028 * @global stdClass $USER
1029 * @param int $draftitemid the id of the draft area to use. Normally obtained
1030 * from file_get_submitted_draft_itemid('elementname') or similar.
1031 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
1032 * @param int $contextid This parameter and the next two identify the file area to save to.
1033 * @param string $component
1034 * @param string $filearea indentifies the file area.
1035 * @param int $itemid helps identifies the file area.
1036 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1037 * @param string $text some html content that needs to have embedded links rewritten
1038 * to the @@PLUGINFILE@@ form for saving in the database.
1039 * @param bool $forcehttps force https urls.
1040 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1042 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1043 global $USER;
1045 // Do not merge files, leave it as it was.
1046 if ($draftitemid === IGNORE_FILE_MERGE) {
1047 // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
1048 return $text;
1051 $usercontext = context_user::instance($USER->id);
1052 $fs = get_file_storage();
1054 $options = (array)$options;
1055 if (!isset($options['subdirs'])) {
1056 $options['subdirs'] = false;
1058 if (!isset($options['maxfiles'])) {
1059 $options['maxfiles'] = -1; // unlimited
1061 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
1062 $options['maxbytes'] = 0; // unlimited
1064 if (!isset($options['areamaxbytes'])) {
1065 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
1067 $allowreferences = true;
1068 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
1069 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1070 // this is not exactly right. BUT there are many places in code where filemanager options
1071 // are not passed to file_save_draft_area_files()
1072 $allowreferences = false;
1075 // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1076 // areas and need to be copied into the current draft area.
1077 $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
1079 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1080 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1081 // anything at all in the next area.
1082 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1083 return null;
1086 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
1087 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1089 // One file in filearea means it is empty (it has only top-level directory '.').
1090 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
1091 // we have to merge old and new files - we want to keep file ids for files that were not changed
1092 // we change time modified for all new and changed files, we keep time created as is
1094 $newhashes = array();
1095 $filecount = 0;
1096 $context = context::instance_by_id($contextid, MUST_EXIST);
1097 foreach ($draftfiles as $file) {
1098 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1099 continue;
1101 if (!$allowreferences && $file->is_external_file()) {
1102 continue;
1104 if (!$file->is_directory()) {
1105 // Check to see if this file was uploaded by someone who can ignore the file size limits.
1106 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1107 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1108 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1109 // Oversized file.
1110 continue;
1112 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1113 // more files - should not get here at all
1114 continue;
1116 $filecount++;
1118 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1119 $newhashes[$newhash] = $file;
1122 // Loop through oldfiles and decide which we need to delete and which to update.
1123 // After this cycle the array $newhashes will only contain the files that need to be added.
1124 foreach ($oldfiles as $oldfile) {
1125 $oldhash = $oldfile->get_pathnamehash();
1126 if (!isset($newhashes[$oldhash])) {
1127 // delete files not needed any more - deleted by user
1128 $oldfile->delete();
1129 continue;
1132 $newfile = $newhashes[$oldhash];
1133 // Now we know that we have $oldfile and $newfile for the same path.
1134 // Let's check if we can update this file or we need to delete and create.
1135 if ($newfile->is_directory()) {
1136 // Directories are always ok to just update.
1137 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
1138 // File has the 'original' - we need to update the file (it may even have not been changed at all).
1139 $original = file_storage::unpack_reference($source->original);
1140 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
1141 // Very odd, original points to another file. Delete and create file.
1142 $oldfile->delete();
1143 continue;
1145 } else {
1146 // The same file name but absence of 'original' means that file was deteled and uploaded again.
1147 // By deleting and creating new file we properly manage all existing references.
1148 $oldfile->delete();
1149 continue;
1152 // status changed, we delete old file, and create a new one
1153 if ($oldfile->get_status() != $newfile->get_status()) {
1154 // file was changed, use updated with new timemodified data
1155 $oldfile->delete();
1156 // This file will be added later
1157 continue;
1160 // Updated author
1161 if ($oldfile->get_author() != $newfile->get_author()) {
1162 $oldfile->set_author($newfile->get_author());
1164 // Updated license
1165 if ($oldfile->get_license() != $newfile->get_license()) {
1166 $oldfile->set_license($newfile->get_license());
1169 // Updated file source
1170 // Field files.source for draftarea files contains serialised object with source and original information.
1171 // We only store the source part of it for non-draft file area.
1172 $newsource = $newfile->get_source();
1173 if ($source = @unserialize($newfile->get_source())) {
1174 $newsource = $source->source;
1176 if ($oldfile->get_source() !== $newsource) {
1177 $oldfile->set_source($newsource);
1180 // Updated sort order
1181 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1182 $oldfile->set_sortorder($newfile->get_sortorder());
1185 // Update file timemodified
1186 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1187 $oldfile->set_timemodified($newfile->get_timemodified());
1190 // Replaced file content
1191 if (!$oldfile->is_directory() &&
1192 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1193 $oldfile->get_filesize() != $newfile->get_filesize() ||
1194 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1195 $oldfile->get_userid() != $newfile->get_userid())) {
1196 $oldfile->replace_file_with($newfile);
1199 // unchanged file or directory - we keep it as is
1200 unset($newhashes[$oldhash]);
1203 // Add fresh file or the file which has changed status
1204 // the size and subdirectory tests are extra safety only, the UI should prevent it
1205 foreach ($newhashes as $file) {
1206 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1207 if ($source = @unserialize($file->get_source())) {
1208 // Field files.source for draftarea files contains serialised object with source and original information.
1209 // We only store the source part of it for non-draft file area.
1210 $file_record['source'] = $source->source;
1213 if ($file->is_external_file()) {
1214 $repoid = $file->get_repository_id();
1215 if (!empty($repoid)) {
1216 $context = context::instance_by_id($contextid, MUST_EXIST);
1217 $repo = repository::get_repository_by_id($repoid, $context);
1218 if (!empty($options)) {
1219 $repo->options = $options;
1221 $file_record['repositoryid'] = $repoid;
1222 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1223 // to the file store. E.g. transfer ownership of the file to a system account etc.
1224 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1226 $file_record['reference'] = $reference;
1230 $fs->create_file_from_storedfile($file_record, $file);
1234 // note: do not purge the draft area - we clean up areas later in cron,
1235 // the reason is that user might press submit twice and they would loose the files,
1236 // also sometimes we might want to use hacks that save files into two different areas
1238 if (is_null($text)) {
1239 return null;
1240 } else {
1241 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1246 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1247 * ready to be saved in the database. Normally, this is done automatically by
1248 * {@link file_save_draft_area_files()}.
1250 * @category files
1251 * @param string $text the content to process.
1252 * @param int $draftitemid the draft file area the content was using.
1253 * @param bool $forcehttps whether the content contains https URLs. Default false.
1254 * @return string the processed content.
1256 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1257 global $CFG, $USER;
1259 $usercontext = context_user::instance($USER->id);
1261 $wwwroot = $CFG->wwwroot;
1262 if ($forcehttps) {
1263 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1266 // relink embedded files if text submitted - no absolute links allowed in database!
1267 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1269 if (strpos($text, 'draftfile.php?file=') !== false) {
1270 $matches = array();
1271 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1272 if ($matches) {
1273 foreach ($matches[0] as $match) {
1274 $replace = str_ireplace('%2F', '/', $match);
1275 $text = str_replace($match, $replace, $text);
1278 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1281 return $text;
1285 * Set file sort order
1287 * @global moodle_database $DB
1288 * @param int $contextid the context id
1289 * @param string $component file component
1290 * @param string $filearea file area.
1291 * @param int $itemid itemid.
1292 * @param string $filepath file path.
1293 * @param string $filename file name.
1294 * @param int $sortorder the sort order of file.
1295 * @return bool
1297 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1298 global $DB;
1299 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1300 if ($file_record = $DB->get_record('files', $conditions)) {
1301 $sortorder = (int)$sortorder;
1302 $file_record->sortorder = $sortorder;
1303 $DB->update_record('files', $file_record);
1304 return true;
1306 return false;
1310 * reset file sort order number to 0
1311 * @global moodle_database $DB
1312 * @param int $contextid the context id
1313 * @param string $component
1314 * @param string $filearea file area.
1315 * @param int|bool $itemid itemid.
1316 * @return bool
1318 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1319 global $DB;
1321 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1322 if ($itemid !== false) {
1323 $conditions['itemid'] = $itemid;
1326 $file_records = $DB->get_records('files', $conditions);
1327 foreach ($file_records as $file_record) {
1328 $file_record->sortorder = 0;
1329 $DB->update_record('files', $file_record);
1331 return true;
1335 * Returns description of upload error
1337 * @param int $errorcode found in $_FILES['filename.ext']['error']
1338 * @return string error description string, '' if ok
1340 function file_get_upload_error($errorcode) {
1342 switch ($errorcode) {
1343 case 0: // UPLOAD_ERR_OK - no error
1344 $errmessage = '';
1345 break;
1347 case 1: // UPLOAD_ERR_INI_SIZE
1348 $errmessage = get_string('uploadserverlimit');
1349 break;
1351 case 2: // UPLOAD_ERR_FORM_SIZE
1352 $errmessage = get_string('uploadformlimit');
1353 break;
1355 case 3: // UPLOAD_ERR_PARTIAL
1356 $errmessage = get_string('uploadpartialfile');
1357 break;
1359 case 4: // UPLOAD_ERR_NO_FILE
1360 $errmessage = get_string('uploadnofilefound');
1361 break;
1363 // Note: there is no error with a value of 5
1365 case 6: // UPLOAD_ERR_NO_TMP_DIR
1366 $errmessage = get_string('uploadnotempdir');
1367 break;
1369 case 7: // UPLOAD_ERR_CANT_WRITE
1370 $errmessage = get_string('uploadcantwrite');
1371 break;
1373 case 8: // UPLOAD_ERR_EXTENSION
1374 $errmessage = get_string('uploadextension');
1375 break;
1377 default:
1378 $errmessage = get_string('uploadproblem');
1381 return $errmessage;
1385 * Recursive function formating an array in POST parameter
1386 * @param array $arraydata - the array that we are going to format and add into &$data array
1387 * @param string $currentdata - a row of the final postdata array at instant T
1388 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1389 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1391 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1392 foreach ($arraydata as $k=>$v) {
1393 $newcurrentdata = $currentdata;
1394 if (is_array($v)) { //the value is an array, call the function recursively
1395 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1396 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1397 } else { //add the POST parameter to the $data array
1398 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1404 * Transform a PHP array into POST parameter
1405 * (see the recursive function format_array_postdata_for_curlcall)
1406 * @param array $postdata
1407 * @return array containing all POST parameters (1 row = 1 POST parameter)
1409 function format_postdata_for_curlcall($postdata) {
1410 $data = array();
1411 foreach ($postdata as $k=>$v) {
1412 if (is_array($v)) {
1413 $currentdata = urlencode($k);
1414 format_array_postdata_for_curlcall($v, $currentdata, $data);
1415 } else {
1416 $data[] = urlencode($k).'='.urlencode($v);
1419 $convertedpostdata = implode('&', $data);
1420 return $convertedpostdata;
1424 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1425 * Due to security concerns only downloads from http(s) sources are supported.
1427 * @category files
1428 * @param string $url file url starting with http(s)://
1429 * @param array $headers http headers, null if none. If set, should be an
1430 * associative array of header name => value pairs.
1431 * @param array $postdata array means use POST request with given parameters
1432 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1433 * (if false, just returns content)
1434 * @param int $timeout timeout for complete download process including all file transfer
1435 * (default 5 minutes)
1436 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1437 * usually happens if the remote server is completely down (default 20 seconds);
1438 * may not work when using proxy
1439 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1440 * Only use this when already in a trusted location.
1441 * @param string $tofile store the downloaded content to file instead of returning it.
1442 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1443 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1444 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1445 * if file downloaded into $tofile successfully or the file content as a string.
1447 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1448 global $CFG;
1450 // Only http and https links supported.
1451 if (!preg_match('|^https?://|i', $url)) {
1452 if ($fullresponse) {
1453 $response = new stdClass();
1454 $response->status = 0;
1455 $response->headers = array();
1456 $response->response_code = 'Invalid protocol specified in url';
1457 $response->results = '';
1458 $response->error = 'Invalid protocol specified in url';
1459 return $response;
1460 } else {
1461 return false;
1465 $options = array();
1467 $headers2 = array();
1468 if (is_array($headers)) {
1469 foreach ($headers as $key => $value) {
1470 if (is_numeric($key)) {
1471 $headers2[] = $value;
1472 } else {
1473 $headers2[] = "$key: $value";
1478 if ($skipcertverify) {
1479 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1480 } else {
1481 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1484 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1486 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1487 $options['CURLOPT_MAXREDIRS'] = 5;
1489 // Use POST if requested.
1490 if (is_array($postdata)) {
1491 $postdata = format_postdata_for_curlcall($postdata);
1492 } else if (empty($postdata)) {
1493 $postdata = null;
1496 // Optionally attempt to get more correct timeout by fetching the file size.
1497 if (!isset($CFG->curltimeoutkbitrate)) {
1498 // Use very slow rate of 56kbps as a timeout speed when not set.
1499 $bitrate = 56;
1500 } else {
1501 $bitrate = $CFG->curltimeoutkbitrate;
1503 if ($calctimeout and !isset($postdata)) {
1504 $curl = new curl();
1505 $curl->setHeader($headers2);
1507 $curl->head($url, $postdata, $options);
1509 $info = $curl->get_info();
1510 $error_no = $curl->get_errno();
1511 if (!$error_no && $info['download_content_length'] > 0) {
1512 // No curl errors - adjust for large files only - take max timeout.
1513 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1517 $curl = new curl();
1518 $curl->setHeader($headers2);
1520 $options['CURLOPT_RETURNTRANSFER'] = true;
1521 $options['CURLOPT_NOBODY'] = false;
1522 $options['CURLOPT_TIMEOUT'] = $timeout;
1524 if ($tofile) {
1525 $fh = fopen($tofile, 'w');
1526 if (!$fh) {
1527 if ($fullresponse) {
1528 $response = new stdClass();
1529 $response->status = 0;
1530 $response->headers = array();
1531 $response->response_code = 'Can not write to file';
1532 $response->results = false;
1533 $response->error = 'Can not write to file';
1534 return $response;
1535 } else {
1536 return false;
1539 $options['CURLOPT_FILE'] = $fh;
1542 if (isset($postdata)) {
1543 $content = $curl->post($url, $postdata, $options);
1544 } else {
1545 $content = $curl->get($url, null, $options);
1548 if ($tofile) {
1549 fclose($fh);
1550 @chmod($tofile, $CFG->filepermissions);
1554 // Try to detect encoding problems.
1555 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1556 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1557 $result = curl_exec($ch);
1561 $info = $curl->get_info();
1562 $error_no = $curl->get_errno();
1563 $rawheaders = $curl->get_raw_response();
1565 if ($error_no) {
1566 $error = $content;
1567 if (!$fullresponse) {
1568 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1569 return false;
1572 $response = new stdClass();
1573 if ($error_no == 28) {
1574 $response->status = '-100'; // Mimic snoopy.
1575 } else {
1576 $response->status = '0';
1578 $response->headers = array();
1579 $response->response_code = $error;
1580 $response->results = false;
1581 $response->error = $error;
1582 return $response;
1585 if ($tofile) {
1586 $content = true;
1589 if (empty($info['http_code'])) {
1590 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1591 $response = new stdClass();
1592 $response->status = '0';
1593 $response->headers = array();
1594 $response->response_code = 'Unknown cURL error';
1595 $response->results = false; // do NOT change this, we really want to ignore the result!
1596 $response->error = 'Unknown cURL error';
1598 } else {
1599 $response = new stdClass();
1600 $response->status = (string)$info['http_code'];
1601 $response->headers = $rawheaders;
1602 $response->results = $content;
1603 $response->error = '';
1605 // There might be multiple headers on redirect, find the status of the last one.
1606 $firstline = true;
1607 foreach ($rawheaders as $line) {
1608 if ($firstline) {
1609 $response->response_code = $line;
1610 $firstline = false;
1612 if (trim($line, "\r\n") === '') {
1613 $firstline = true;
1618 if ($fullresponse) {
1619 return $response;
1622 if ($info['http_code'] != 200) {
1623 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1624 return false;
1626 return $response->results;
1630 * Returns a list of information about file types based on extensions.
1632 * The following elements expected in value array for each extension:
1633 * 'type' - mimetype
1634 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1635 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1636 * also files with bigger sizes under names
1637 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1638 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1639 * commonly used in moodle the following groups:
1640 * - web_image - image that can be included as <img> in HTML
1641 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1642 * - optimised_image - image that will be processed and optimised
1643 * - video - file that can be imported as video in text editor
1644 * - audio - file that can be imported as audio in text editor
1645 * - archive - we can extract files from this archive
1646 * - spreadsheet - used for portfolio format
1647 * - document - used for portfolio format
1648 * - presentation - used for portfolio format
1649 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1650 * human-readable description for this filetype;
1651 * Function {@link get_mimetype_description()} first looks at the presence of string for
1652 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1653 * attribute, if not found returns the value of 'type';
1654 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1655 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1656 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1658 * @category files
1659 * @return array List of information about file types based on extensions.
1660 * Associative array of extension (lower-case) to associative array
1661 * from 'element name' to data. Current element names are 'type' and 'icon'.
1662 * Unknown types should use the 'xxx' entry which includes defaults.
1664 function &get_mimetypes_array() {
1665 // Get types from the core_filetypes function, which includes caching.
1666 return core_filetypes::get_types();
1670 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1672 * This function retrieves a file's MIME type for a file that will be sent to the user.
1673 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1674 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1675 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1677 * @param string $filename The file's filename.
1678 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1680 function get_mimetype_for_sending($filename = '') {
1681 // Guess the file's MIME type using mimeinfo.
1682 $mimetype = mimeinfo('type', $filename);
1684 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1685 if (!$mimetype || $mimetype === 'document/unknown') {
1686 $mimetype = 'application/octet-stream';
1689 return $mimetype;
1693 * Obtains information about a filetype based on its extension. Will
1694 * use a default if no information is present about that particular
1695 * extension.
1697 * @category files
1698 * @param string $element Desired information (usually 'icon'
1699 * for icon filename or 'type' for MIME type. Can also be
1700 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1701 * @param string $filename Filename we're looking up
1702 * @return string Requested piece of information from array
1704 function mimeinfo($element, $filename) {
1705 global $CFG;
1706 $mimeinfo = & get_mimetypes_array();
1707 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1709 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1710 if (empty($filetype)) {
1711 $filetype = 'xxx'; // file without extension
1713 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1714 $iconsize = max(array(16, (int)$iconsizematch[1]));
1715 $filenames = array($mimeinfo['xxx']['icon']);
1716 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1717 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1719 // find the file with the closest size, first search for specific icon then for default icon
1720 foreach ($filenames as $filename) {
1721 foreach ($iconpostfixes as $size => $postfix) {
1722 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1723 if ($iconsize >= $size &&
1724 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1725 return $filename.$postfix;
1729 } else if (isset($mimeinfo[$filetype][$element])) {
1730 return $mimeinfo[$filetype][$element];
1731 } else if (isset($mimeinfo['xxx'][$element])) {
1732 return $mimeinfo['xxx'][$element]; // By default
1733 } else {
1734 return null;
1739 * Obtains information about a filetype based on the MIME type rather than
1740 * the other way around.
1742 * @category files
1743 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1744 * @param string $mimetype MIME type we're looking up
1745 * @return string Requested piece of information from array
1747 function mimeinfo_from_type($element, $mimetype) {
1748 /* array of cached mimetype->extension associations */
1749 static $cached = array();
1750 $mimeinfo = & get_mimetypes_array();
1752 if (!array_key_exists($mimetype, $cached)) {
1753 $cached[$mimetype] = null;
1754 foreach($mimeinfo as $filetype => $values) {
1755 if ($values['type'] == $mimetype) {
1756 if ($cached[$mimetype] === null) {
1757 $cached[$mimetype] = '.'.$filetype;
1759 if (!empty($values['defaulticon'])) {
1760 $cached[$mimetype] = '.'.$filetype;
1761 break;
1765 if (empty($cached[$mimetype])) {
1766 $cached[$mimetype] = '.xxx';
1769 if ($element === 'extension') {
1770 return $cached[$mimetype];
1771 } else {
1772 return mimeinfo($element, $cached[$mimetype]);
1777 * Return the relative icon path for a given file
1779 * Usage:
1780 * <code>
1781 * // $file - instance of stored_file or file_info
1782 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1783 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1784 * </code>
1785 * or
1786 * <code>
1787 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1788 * </code>
1790 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1791 * and $file->mimetype are expected)
1792 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1793 * @return string
1795 function file_file_icon($file, $size = null) {
1796 if (!is_object($file)) {
1797 $file = (object)$file;
1799 if (isset($file->filename)) {
1800 $filename = $file->filename;
1801 } else if (method_exists($file, 'get_filename')) {
1802 $filename = $file->get_filename();
1803 } else if (method_exists($file, 'get_visible_name')) {
1804 $filename = $file->get_visible_name();
1805 } else {
1806 $filename = '';
1808 if (isset($file->mimetype)) {
1809 $mimetype = $file->mimetype;
1810 } else if (method_exists($file, 'get_mimetype')) {
1811 $mimetype = $file->get_mimetype();
1812 } else {
1813 $mimetype = '';
1815 $mimetypes = &get_mimetypes_array();
1816 if ($filename) {
1817 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1818 if ($extension && !empty($mimetypes[$extension])) {
1819 // if file name has known extension, return icon for this extension
1820 return file_extension_icon($filename, $size);
1823 return file_mimetype_icon($mimetype, $size);
1827 * Return the relative icon path for a folder image
1829 * Usage:
1830 * <code>
1831 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1832 * echo html_writer::empty_tag('img', array('src' => $icon));
1833 * </code>
1834 * or
1835 * <code>
1836 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1837 * </code>
1839 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1840 * @return string
1842 function file_folder_icon($iconsize = null) {
1843 global $CFG;
1844 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1845 static $cached = array();
1846 $iconsize = max(array(16, (int)$iconsize));
1847 if (!array_key_exists($iconsize, $cached)) {
1848 foreach ($iconpostfixes as $size => $postfix) {
1849 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1850 if ($iconsize >= $size &&
1851 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1852 $cached[$iconsize] = 'f/folder'.$postfix;
1853 break;
1857 return $cached[$iconsize];
1861 * Returns the relative icon path for a given mime type
1863 * This function should be used in conjunction with $OUTPUT->image_url to produce
1864 * a return the full path to an icon.
1866 * <code>
1867 * $mimetype = 'image/jpg';
1868 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1869 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1870 * </code>
1872 * @category files
1873 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1874 * to conform with that.
1875 * @param string $mimetype The mimetype to fetch an icon for
1876 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1877 * @return string The relative path to the icon
1879 function file_mimetype_icon($mimetype, $size = NULL) {
1880 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1884 * Returns the relative icon path for a given file name
1886 * This function should be used in conjunction with $OUTPUT->image_url to produce
1887 * a return the full path to an icon.
1889 * <code>
1890 * $filename = '.jpg';
1891 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1892 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1893 * </code>
1895 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1896 * to conform with that.
1897 * @todo MDL-31074 Implement $size
1898 * @category files
1899 * @param string $filename The filename to get the icon for
1900 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1901 * @return string
1903 function file_extension_icon($filename, $size = NULL) {
1904 return 'f/'.mimeinfo('icon'.$size, $filename);
1908 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1909 * mimetypes.php language file.
1911 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1912 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1913 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1914 * @param bool $capitalise If true, capitalises first character of result
1915 * @return string Text description
1917 function get_mimetype_description($obj, $capitalise=false) {
1918 $filename = $mimetype = '';
1919 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1920 // this is an instance of stored_file
1921 $mimetype = $obj->get_mimetype();
1922 $filename = $obj->get_filename();
1923 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1924 // this is an instance of file_info
1925 $mimetype = $obj->get_mimetype();
1926 $filename = $obj->get_visible_name();
1927 } else if (is_array($obj) || is_object ($obj)) {
1928 $obj = (array)$obj;
1929 if (!empty($obj['filename'])) {
1930 $filename = $obj['filename'];
1932 if (!empty($obj['mimetype'])) {
1933 $mimetype = $obj['mimetype'];
1935 } else {
1936 $mimetype = $obj;
1938 $mimetypefromext = mimeinfo('type', $filename);
1939 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1940 // if file has a known extension, overwrite the specified mimetype
1941 $mimetype = $mimetypefromext;
1943 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1944 if (empty($extension)) {
1945 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1946 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1947 } else {
1948 $mimetypestr = mimeinfo('string', $filename);
1950 $chunks = explode('/', $mimetype, 2);
1951 $chunks[] = '';
1952 $attr = array(
1953 'mimetype' => $mimetype,
1954 'ext' => $extension,
1955 'mimetype1' => $chunks[0],
1956 'mimetype2' => $chunks[1],
1958 $a = array();
1959 foreach ($attr as $key => $value) {
1960 $a[$key] = $value;
1961 $a[strtoupper($key)] = strtoupper($value);
1962 $a[ucfirst($key)] = ucfirst($value);
1965 // MIME types may include + symbol but this is not permitted in string ids.
1966 $safemimetype = str_replace('+', '_', $mimetype);
1967 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1968 $customdescription = mimeinfo('customdescription', $filename);
1969 if ($customdescription) {
1970 // Call format_string on the custom description so that multilang
1971 // filter can be used (if enabled on system context). We use system
1972 // context because it is possible that the page context might not have
1973 // been defined yet.
1974 $result = format_string($customdescription, true,
1975 array('context' => context_system::instance()));
1976 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1977 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1978 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1979 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1980 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1981 $result = get_string('default', 'mimetypes', (object)$a);
1982 } else {
1983 $result = $mimetype;
1985 if ($capitalise) {
1986 $result=ucfirst($result);
1988 return $result;
1992 * Returns array of elements of type $element in type group(s)
1994 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1995 * @param string|array $groups one group or array of groups/extensions/mimetypes
1996 * @return array
1998 function file_get_typegroup($element, $groups) {
1999 static $cached = array();
2000 if (!is_array($groups)) {
2001 $groups = array($groups);
2003 if (!array_key_exists($element, $cached)) {
2004 $cached[$element] = array();
2006 $result = array();
2007 foreach ($groups as $group) {
2008 if (!array_key_exists($group, $cached[$element])) {
2009 // retrieive and cache all elements of type $element for group $group
2010 $mimeinfo = & get_mimetypes_array();
2011 $cached[$element][$group] = array();
2012 foreach ($mimeinfo as $extension => $value) {
2013 $value['extension'] = '.'.$extension;
2014 if (empty($value[$element])) {
2015 continue;
2017 if (($group === '.'.$extension || $group === $value['type'] ||
2018 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
2019 !in_array($value[$element], $cached[$element][$group])) {
2020 $cached[$element][$group][] = $value[$element];
2024 $result = array_merge($result, $cached[$element][$group]);
2026 return array_values(array_unique($result));
2030 * Checks if file with name $filename has one of the extensions in groups $groups
2032 * @see get_mimetypes_array()
2033 * @param string $filename name of the file to check
2034 * @param string|array $groups one group or array of groups to check
2035 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2036 * file mimetype is in mimetypes in groups $groups
2037 * @return bool
2039 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2040 $extension = pathinfo($filename, PATHINFO_EXTENSION);
2041 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2042 return true;
2044 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2048 * Checks if mimetype $mimetype belongs to one of the groups $groups
2050 * @see get_mimetypes_array()
2051 * @param string $mimetype
2052 * @param string|array $groups one group or array of groups to check
2053 * @return bool
2055 function file_mimetype_in_typegroup($mimetype, $groups) {
2056 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2060 * Requested file is not found or not accessible, does not return, terminates script
2062 * @global stdClass $CFG
2063 * @global stdClass $COURSE
2065 function send_file_not_found() {
2066 global $CFG, $COURSE;
2068 // Allow cross-origin requests only for Web Services.
2069 // This allow to receive requests done by Web Workers or webapps in different domains.
2070 if (WS_SERVER) {
2071 header('Access-Control-Allow-Origin: *');
2074 send_header_404();
2075 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
2078 * Helper function to send correct 404 for server.
2080 function send_header_404() {
2081 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2082 header("Status: 404 Not Found");
2083 } else {
2084 header('HTTP/1.0 404 not found');
2089 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2090 * platforms). This wrapper uses readfile for small files and custom code for
2091 * large ones.
2093 * @param string $path Path to file
2094 * @param int $filesize Size of file (if left out, will get it automatically)
2095 * @return int|bool Size read (will always be $filesize) or false if failed
2097 function readfile_allow_large($path, $filesize = -1) {
2098 // Automatically get size if not specified.
2099 if ($filesize === -1) {
2100 $filesize = filesize($path);
2102 if ($filesize <= 2147483647) {
2103 // If the file is up to 2^31 - 1, send it normally using readfile.
2104 return readfile($path);
2105 } else {
2106 // For large files, read and output in 64KB chunks.
2107 $handle = fopen($path, 'r');
2108 if ($handle === false) {
2109 return false;
2111 $left = $filesize;
2112 while ($left > 0) {
2113 $size = min($left, 65536);
2114 $buffer = fread($handle, $size);
2115 if ($buffer === false) {
2116 return false;
2118 echo $buffer;
2119 $left -= $size;
2121 return $filesize;
2126 * Enhanced readfile() with optional acceleration.
2127 * @param string|stored_file $file
2128 * @param string $mimetype
2129 * @param bool $accelerate
2130 * @return void
2132 function readfile_accel($file, $mimetype, $accelerate) {
2133 global $CFG;
2135 if ($mimetype === 'text/plain') {
2136 // there is no encoding specified in text files, we need something consistent
2137 header('Content-Type: text/plain; charset=utf-8');
2138 } else {
2139 header('Content-Type: '.$mimetype);
2142 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2143 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2145 if (is_object($file)) {
2146 header('Etag: "' . $file->get_contenthash() . '"');
2147 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2148 header('HTTP/1.1 304 Not Modified');
2149 return;
2153 // if etag present for stored file rely on it exclusively
2154 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2155 // get unixtime of request header; clip extra junk off first
2156 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2157 if ($since && $since >= $lastmodified) {
2158 header('HTTP/1.1 304 Not Modified');
2159 return;
2163 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2164 header('Accept-Ranges: bytes');
2165 } else {
2166 header('Accept-Ranges: none');
2169 if ($accelerate) {
2170 if (is_object($file)) {
2171 $fs = get_file_storage();
2172 if ($fs->supports_xsendfile()) {
2173 if ($fs->xsendfile_file($file)) {
2174 return;
2177 } else {
2178 if (!empty($CFG->xsendfile)) {
2179 require_once("$CFG->libdir/xsendfilelib.php");
2180 if (xsendfile($file)) {
2181 return;
2187 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2189 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2191 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2193 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2194 // byteserving stuff - for acrobat reader and download accelerators
2195 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2196 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2197 $ranges = false;
2198 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2199 foreach ($ranges as $key=>$value) {
2200 if ($ranges[$key][1] == '') {
2201 //suffix case
2202 $ranges[$key][1] = $filesize - $ranges[$key][2];
2203 $ranges[$key][2] = $filesize - 1;
2204 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2205 //fix range length
2206 $ranges[$key][2] = $filesize - 1;
2208 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2209 //invalid byte-range ==> ignore header
2210 $ranges = false;
2211 break;
2213 //prepare multipart header
2214 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2215 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2217 } else {
2218 $ranges = false;
2220 if ($ranges) {
2221 if (is_object($file)) {
2222 $handle = $file->get_content_file_handle();
2223 if ($handle === false) {
2224 throw new file_exception('storedfilecannotreadfile', $file->get_filename());
2226 } else {
2227 $handle = fopen($file, 'rb');
2228 if ($handle === false) {
2229 throw new file_exception('cannotopenfile', $file);
2232 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2237 header('Content-Length: ' . $filesize);
2239 if (!empty($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] === 'HEAD') {
2240 exit;
2243 while (ob_get_level()) {
2244 $handlerstack = ob_list_handlers();
2245 $activehandler = array_pop($handlerstack);
2246 if ($activehandler === 'default output handler') {
2247 // We do not expect any content in the buffer when we are serving files.
2248 $buffercontents = ob_get_clean();
2249 if ($buffercontents !== '') {
2250 error_log('Non-empty default output handler buffer detected while serving the file ' . $file);
2252 } else {
2253 // Some handlers such as zlib output compression may have file signature buffered - flush it.
2254 ob_end_flush();
2258 // send the whole file content
2259 if (is_object($file)) {
2260 $file->readfile();
2261 } else {
2262 if (readfile_allow_large($file, $filesize) === false) {
2263 throw new file_exception('cannotopenfile', $file);
2269 * Similar to readfile_accel() but designed for strings.
2270 * @param string $string
2271 * @param string $mimetype
2272 * @param bool $accelerate Ignored
2273 * @return void
2275 function readstring_accel($string, $mimetype, $accelerate = false) {
2276 global $CFG;
2278 if ($mimetype === 'text/plain') {
2279 // there is no encoding specified in text files, we need something consistent
2280 header('Content-Type: text/plain; charset=utf-8');
2281 } else {
2282 header('Content-Type: '.$mimetype);
2284 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2285 header('Accept-Ranges: none');
2286 header('Content-Length: '.strlen($string));
2287 echo $string;
2291 * Handles the sending of temporary file to user, download is forced.
2292 * File is deleted after abort or successful sending, does not return, script terminated
2294 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2295 * @param string $filename proposed file name when saving file
2296 * @param bool $pathisstring If the path is string
2298 function send_temp_file($path, $filename, $pathisstring=false) {
2299 global $CFG;
2301 // Guess the file's MIME type.
2302 $mimetype = get_mimetype_for_sending($filename);
2304 // close session - not needed anymore
2305 \core\session\manager::write_close();
2307 if (!$pathisstring) {
2308 if (!file_exists($path)) {
2309 send_header_404();
2310 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2312 // executed after normal finish or abort
2313 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2316 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2317 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2318 $filename = urlencode($filename);
2321 // If this file was requested from a form, then mark download as complete.
2322 \core_form\util::form_download_complete();
2324 header('Content-Disposition: attachment; filename="'.$filename.'"');
2325 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2326 header('Cache-Control: private, max-age=10, no-transform');
2327 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2328 header('Pragma: ');
2329 } else { //normal http - prevent caching at all cost
2330 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2331 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2332 header('Pragma: no-cache');
2335 // send the contents - we can not accelerate this because the file will be deleted asap
2336 if ($pathisstring) {
2337 readstring_accel($path, $mimetype);
2338 } else {
2339 readfile_accel($path, $mimetype, false);
2340 @unlink($path);
2343 die; //no more chars to output
2347 * Internal callback function used by send_temp_file()
2349 * @param string $path
2351 function send_temp_file_finished($path) {
2352 if (file_exists($path)) {
2353 @unlink($path);
2358 * Serve content which is not meant to be cached.
2360 * This is only intended to be used for volatile public files, for instance
2361 * when development is enabled, or when caching is not required on a public resource.
2363 * @param string $content Raw content.
2364 * @param string $filename The file name.
2365 * @return void
2367 function send_content_uncached($content, $filename) {
2368 $mimetype = mimeinfo('type', $filename);
2369 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2371 header('Content-Disposition: inline; filename="' . $filename . '"');
2372 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2373 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2374 header('Pragma: ');
2375 header('Accept-Ranges: none');
2376 header('Content-Type: ' . $mimetype . $charset);
2377 header('Content-Length: ' . strlen($content));
2379 echo $content;
2380 die();
2384 * Safely save content to a certain path.
2386 * This function tries hard to be atomic by first copying the content
2387 * to a separate file, and then moving the file across. It also prevents
2388 * the user to abort a request to prevent half-safed files.
2390 * This function is intended to be used when saving some content to cache like
2391 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2393 * @param string $content The file content.
2394 * @param string $destination The absolute path of the final file.
2395 * @return void
2397 function file_safe_save_content($content, $destination) {
2398 global $CFG;
2400 clearstatcache();
2401 if (!file_exists(dirname($destination))) {
2402 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2405 // Prevent serving of incomplete file from concurrent request,
2406 // the rename() should be more atomic than fwrite().
2407 ignore_user_abort(true);
2408 if ($fp = fopen($destination . '.tmp', 'xb')) {
2409 fwrite($fp, $content);
2410 fclose($fp);
2411 rename($destination . '.tmp', $destination);
2412 @chmod($destination, $CFG->filepermissions);
2413 @unlink($destination . '.tmp'); // Just in case anything fails.
2415 ignore_user_abort(false);
2416 if (connection_aborted()) {
2417 die();
2422 * Handles the sending of file data to the user's browser, including support for
2423 * byteranges etc.
2425 * @category files
2426 * @param string|stored_file $path Path of file on disk (including real filename),
2427 * or actual content of file as string,
2428 * or stored_file object
2429 * @param string $filename Filename to send
2430 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2431 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2432 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2433 * Forced to false when $path is a stored_file object.
2434 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2435 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2436 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2437 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2438 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2439 * and should not be reopened.
2440 * @param array $options An array of options, currently accepts:
2441 * - (string) cacheability: public, or private.
2442 * - (string|null) immutable
2443 * @return null script execution stopped unless $dontdie is true
2445 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2446 $dontdie=false, array $options = array()) {
2447 global $CFG, $COURSE;
2449 if ($dontdie) {
2450 ignore_user_abort(true);
2453 if ($lifetime === 'default' or is_null($lifetime)) {
2454 $lifetime = $CFG->filelifetime;
2457 if (is_object($path)) {
2458 $pathisstring = false;
2461 \core\session\manager::write_close(); // Unlock session during file serving.
2463 // Use given MIME type if specified, otherwise guess it.
2464 if (!$mimetype || $mimetype === 'document/unknown') {
2465 $mimetype = get_mimetype_for_sending($filename);
2468 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2469 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2470 $filename = rawurlencode($filename);
2473 if ($forcedownload) {
2474 header('Content-Disposition: attachment; filename="'.$filename.'"');
2476 // If this file was requested from a form, then mark download as complete.
2477 \core_form\util::form_download_complete();
2478 } else if ($mimetype !== 'application/x-shockwave-flash') {
2479 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2480 // as an upload and enforces security that may prevent the file from being loaded.
2482 header('Content-Disposition: inline; filename="'.$filename.'"');
2485 if ($lifetime > 0) {
2486 $immutable = '';
2487 if (!empty($options['immutable'])) {
2488 $immutable = ', immutable';
2489 // Overwrite lifetime accordingly:
2490 // 90 days only - based on Moodle point release cadence being every 3 months.
2491 $lifetimemin = 60 * 60 * 24 * 90;
2492 $lifetime = max($lifetime, $lifetimemin);
2494 $cacheability = ' public,';
2495 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2496 // This file must be cache-able by both browsers and proxies.
2497 $cacheability = ' public,';
2498 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2499 // This file must be cache-able only by browsers.
2500 $cacheability = ' private,';
2501 } else if (isloggedin() and !isguestuser()) {
2502 // By default, under the conditions above, this file must be cache-able only by browsers.
2503 $cacheability = ' private,';
2505 $nobyteserving = false;
2506 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2507 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2508 header('Pragma: ');
2510 } else { // Do not cache files in proxies and browsers
2511 $nobyteserving = true;
2512 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2513 header('Cache-Control: private, max-age=10, no-transform');
2514 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2515 header('Pragma: ');
2516 } else { //normal http - prevent caching at all cost
2517 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2518 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2519 header('Pragma: no-cache');
2523 if (empty($filter)) {
2524 // send the contents
2525 if ($pathisstring) {
2526 readstring_accel($path, $mimetype);
2527 } else {
2528 readfile_accel($path, $mimetype, !$dontdie);
2531 } else {
2532 // Try to put the file through filters
2533 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2534 $options = new stdClass();
2535 $options->noclean = true;
2536 $options->nocache = true; // temporary workaround for MDL-5136
2537 if (is_object($path)) {
2538 $text = $path->get_content();
2539 } else if ($pathisstring) {
2540 $text = $path;
2541 } else {
2542 $text = implode('', file($path));
2544 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2546 readstring_accel($output, $mimetype);
2548 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2549 // only filter text if filter all files is selected
2550 $options = new stdClass();
2551 $options->newlines = false;
2552 $options->noclean = true;
2553 if (is_object($path)) {
2554 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2555 } else if ($pathisstring) {
2556 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2557 } else {
2558 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2560 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2562 readstring_accel($output, $mimetype);
2564 } else {
2565 // send the contents
2566 if ($pathisstring) {
2567 readstring_accel($path, $mimetype);
2568 } else {
2569 readfile_accel($path, $mimetype, !$dontdie);
2573 if ($dontdie) {
2574 return;
2576 die; //no more chars to output!!!
2580 * Handles the sending of file data to the user's browser, including support for
2581 * byteranges etc.
2583 * The $options parameter supports the following keys:
2584 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2585 * (string|null) filename - overrides the implicit filename
2586 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2587 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2588 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2589 * and should not be reopened
2590 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2591 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2592 * defaults to "public".
2593 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2594 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2596 * @category files
2597 * @param stored_file $stored_file local file object
2598 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2599 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2600 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2601 * @param array $options additional options affecting the file serving
2602 * @return null script execution stopped unless $options['dontdie'] is true
2604 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2605 global $CFG, $COURSE;
2607 if (empty($options['filename'])) {
2608 $filename = null;
2609 } else {
2610 $filename = $options['filename'];
2613 if (empty($options['dontdie'])) {
2614 $dontdie = false;
2615 } else {
2616 $dontdie = true;
2619 if ($lifetime === 'default' or is_null($lifetime)) {
2620 $lifetime = $CFG->filelifetime;
2623 if (!empty($options['preview'])) {
2624 // replace the file with its preview
2625 $fs = get_file_storage();
2626 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2627 if (!$preview_file) {
2628 // unable to create a preview of the file, send its default mime icon instead
2629 if ($options['preview'] === 'tinyicon') {
2630 $size = 24;
2631 } else if ($options['preview'] === 'thumb') {
2632 $size = 90;
2633 } else {
2634 $size = 256;
2636 $fileicon = file_file_icon($stored_file, $size);
2637 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2638 } else {
2639 // preview images have fixed cache lifetime and they ignore forced download
2640 // (they are generated by GD and therefore they are considered reasonably safe).
2641 $stored_file = $preview_file;
2642 $lifetime = DAYSECS;
2643 $filter = 0;
2644 $forcedownload = false;
2648 // handle external resource
2649 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2650 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2651 die;
2654 if (!$stored_file or $stored_file->is_directory()) {
2655 // nothing to serve
2656 if ($dontdie) {
2657 return;
2659 die;
2662 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2664 // Use given MIME type if specified.
2665 $mimetype = $stored_file->get_mimetype();
2667 // Allow cross-origin requests only for Web Services.
2668 // This allow to receive requests done by Web Workers or webapps in different domains.
2669 if (WS_SERVER) {
2670 header('Access-Control-Allow-Origin: *');
2673 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2677 * Recursively delete the file or folder with path $location. That is,
2678 * if it is a file delete it. If it is a folder, delete all its content
2679 * then delete it. If $location does not exist to start, that is not
2680 * considered an error.
2682 * @param string $location the path to remove.
2683 * @return bool
2685 function fulldelete($location) {
2686 if (empty($location)) {
2687 // extra safety against wrong param
2688 return false;
2690 if (is_dir($location)) {
2691 if (!$currdir = opendir($location)) {
2692 return false;
2694 while (false !== ($file = readdir($currdir))) {
2695 if ($file <> ".." && $file <> ".") {
2696 $fullfile = $location."/".$file;
2697 if (is_dir($fullfile)) {
2698 if (!fulldelete($fullfile)) {
2699 return false;
2701 } else {
2702 if (!unlink($fullfile)) {
2703 return false;
2708 closedir($currdir);
2709 if (! rmdir($location)) {
2710 return false;
2713 } else if (file_exists($location)) {
2714 if (!unlink($location)) {
2715 return false;
2718 return true;
2722 * Send requested byterange of file.
2724 * @param resource $handle A file handle
2725 * @param string $mimetype The mimetype for the output
2726 * @param array $ranges An array of ranges to send
2727 * @param string $filesize The size of the content if only one range is used
2729 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2730 // better turn off any kind of compression and buffering
2731 ini_set('zlib.output_compression', 'Off');
2733 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2734 if ($handle === false) {
2735 die;
2737 if (count($ranges) == 1) { //only one range requested
2738 $length = $ranges[0][2] - $ranges[0][1] + 1;
2739 header('HTTP/1.1 206 Partial content');
2740 header('Content-Length: '.$length);
2741 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2742 header('Content-Type: '.$mimetype);
2744 while(@ob_get_level()) {
2745 if (!@ob_end_flush()) {
2746 break;
2750 fseek($handle, $ranges[0][1]);
2751 while (!feof($handle) && $length > 0) {
2752 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2753 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2754 echo $buffer;
2755 flush();
2756 $length -= strlen($buffer);
2758 fclose($handle);
2759 die;
2760 } else { // multiple ranges requested - not tested much
2761 $totallength = 0;
2762 foreach($ranges as $range) {
2763 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2765 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2766 header('HTTP/1.1 206 Partial content');
2767 header('Content-Length: '.$totallength);
2768 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2770 while(@ob_get_level()) {
2771 if (!@ob_end_flush()) {
2772 break;
2776 foreach($ranges as $range) {
2777 $length = $range[2] - $range[1] + 1;
2778 echo $range[0];
2779 fseek($handle, $range[1]);
2780 while (!feof($handle) && $length > 0) {
2781 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2782 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2783 echo $buffer;
2784 flush();
2785 $length -= strlen($buffer);
2788 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2789 fclose($handle);
2790 die;
2795 * Tells whether the filename is executable.
2797 * @link http://php.net/manual/en/function.is-executable.php
2798 * @link https://bugs.php.net/bug.php?id=41062
2799 * @param string $filename Path to the file.
2800 * @return bool True if the filename exists and is executable; otherwise, false.
2802 function file_is_executable($filename) {
2803 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2804 if (is_executable($filename)) {
2805 return true;
2806 } else {
2807 $fileext = strrchr($filename, '.');
2808 // If we have an extension we can check if it is listed as executable.
2809 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2810 $winpathext = strtolower(getenv('PATHEXT'));
2811 $winpathexts = explode(';', $winpathext);
2813 return in_array(strtolower($fileext), $winpathexts);
2816 return false;
2818 } else {
2819 return is_executable($filename);
2824 * Overwrite an existing file in a draft area.
2826 * @param stored_file $newfile the new file with the new content and meta-data
2827 * @param stored_file $existingfile the file that will be overwritten
2828 * @throws moodle_exception
2829 * @since Moodle 3.2
2831 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2832 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2833 throw new coding_exception('The file to overwrite is not in a draft area.');
2836 $fs = get_file_storage();
2837 // Remember original file source field.
2838 $source = @unserialize($existingfile->get_source());
2839 // Remember the original sortorder.
2840 $sortorder = $existingfile->get_sortorder();
2841 if ($newfile->is_external_file()) {
2842 // New file is a reference. Check that existing file does not have any other files referencing to it
2843 if (isset($source->original) && $fs->search_references_count($source->original)) {
2844 throw new moodle_exception('errordoublereference', 'repository');
2848 // Delete existing file to release filename.
2849 $newfilerecord = array(
2850 'contextid' => $existingfile->get_contextid(),
2851 'component' => 'user',
2852 'filearea' => 'draft',
2853 'itemid' => $existingfile->get_itemid(),
2854 'timemodified' => time()
2856 $existingfile->delete();
2858 // Create new file.
2859 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2860 // Preserve original file location (stored in source field) for handling references.
2861 if (isset($source->original)) {
2862 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2863 $newfilesource = new stdClass();
2865 $newfilesource->original = $source->original;
2866 $newfile->set_source(serialize($newfilesource));
2868 $newfile->set_sortorder($sortorder);
2872 * Add files from a draft area into a final area.
2874 * Most of the time you do not want to use this. It is intended to be used
2875 * by asynchronous services which cannot direcly manipulate a final
2876 * area through a draft area. Instead they add files to a new draft
2877 * area and merge that new draft into the final area when ready.
2879 * @param int $draftitemid the id of the draft area to use.
2880 * @param int $contextid this parameter and the next two identify the file area to save to.
2881 * @param string $component component name
2882 * @param string $filearea indentifies the file area
2883 * @param int $itemid identifies the item id or false for all items in the file area
2884 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2885 * @see file_save_draft_area_files
2886 * @since Moodle 3.2
2888 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2889 array $options = null) {
2890 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2891 $finaldraftid = 0;
2892 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2893 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2894 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2898 * Merge files from two draftarea areas.
2900 * This does not handle conflict resolution, files in the destination area which appear
2901 * to be more recent will be kept disregarding the intended ones.
2903 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2904 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2905 * @throws coding_exception
2906 * @since Moodle 3.2
2908 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2909 global $USER;
2911 $fs = get_file_storage();
2912 $contextid = context_user::instance($USER->id)->id;
2914 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2915 throw new coding_exception('Nothing to merge or area does not belong to current user');
2918 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2920 // Get hashes of the files to merge.
2921 $newhashes = array();
2922 foreach ($filestomerge as $filetomerge) {
2923 $filepath = $filetomerge->get_filepath();
2924 $filename = $filetomerge->get_filename();
2926 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2927 $newhashes[$newhash] = $filetomerge;
2930 // Calculate wich files must be added.
2931 foreach ($currentfiles as $file) {
2932 $filehash = $file->get_pathnamehash();
2933 // One file to be merged already exists.
2934 if (isset($newhashes[$filehash])) {
2935 $updatedfile = $newhashes[$filehash];
2937 // Avoid race conditions.
2938 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2939 // The existing file is more recent, do not copy the suposedly "new" one.
2940 unset($newhashes[$filehash]);
2941 continue;
2943 // Update existing file (not only content, meta-data too).
2944 file_overwrite_existing_draftfile($updatedfile, $file);
2945 unset($newhashes[$filehash]);
2949 foreach ($newhashes as $newfile) {
2950 $newfilerecord = array(
2951 'contextid' => $contextid,
2952 'component' => 'user',
2953 'filearea' => 'draft',
2954 'itemid' => $mergeintodraftid,
2955 'timemodified' => time()
2958 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2963 * RESTful cURL class
2965 * This is a wrapper class for curl, it is quite easy to use:
2966 * <code>
2967 * $c = new curl;
2968 * // enable cache
2969 * $c = new curl(array('cache'=>true));
2970 * // enable cookie
2971 * $c = new curl(array('cookie'=>true));
2972 * // enable proxy
2973 * $c = new curl(array('proxy'=>true));
2975 * // HTTP GET Method
2976 * $html = $c->get('http://example.com');
2977 * // HTTP POST Method
2978 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2979 * // HTTP PUT Method
2980 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2981 * </code>
2983 * @package core_files
2984 * @category files
2985 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2986 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2988 class curl {
2989 /** @var bool Caches http request contents */
2990 public $cache = false;
2991 /** @var bool Uses proxy, null means automatic based on URL */
2992 public $proxy = null;
2993 /** @var string library version */
2994 public $version = '0.4 dev';
2995 /** @var array http's response */
2996 public $response = array();
2997 /** @var array Raw response headers, needed for BC in download_file_content(). */
2998 public $rawresponse = array();
2999 /** @var array http header */
3000 public $header = array();
3001 /** @var string cURL information */
3002 public $info;
3003 /** @var string error */
3004 public $error;
3005 /** @var int error code */
3006 public $errno;
3007 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
3008 public $emulateredirects = null;
3010 /** @var array cURL options */
3011 private $options;
3013 /** @var string Proxy host */
3014 private $proxy_host = '';
3015 /** @var string Proxy auth */
3016 private $proxy_auth = '';
3017 /** @var string Proxy type */
3018 private $proxy_type = '';
3019 /** @var bool Debug mode on */
3020 private $debug = false;
3021 /** @var bool|string Path to cookie file */
3022 private $cookie = false;
3023 /** @var bool tracks multiple headers in response - redirect detection */
3024 private $responsefinished = false;
3025 /** @var security helper class, responsible for checking host/ports against allowed/blocked entries.*/
3026 private $securityhelper;
3027 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
3028 private $ignoresecurity;
3029 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
3030 private static $mockresponses = [];
3033 * Curl constructor.
3035 * Allowed settings are:
3036 * proxy: (bool) use proxy server, null means autodetect non-local from url
3037 * debug: (bool) use debug output
3038 * cookie: (string) path to cookie file, false if none
3039 * cache: (bool) use cache
3040 * module_cache: (string) type of cache
3041 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3042 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3044 * @param array $settings
3046 public function __construct($settings = array()) {
3047 global $CFG;
3048 if (!function_exists('curl_init')) {
3049 $this->error = 'cURL module must be enabled!';
3050 trigger_error($this->error, E_USER_ERROR);
3051 return false;
3054 // All settings of this class should be init here.
3055 $this->resetopt();
3056 if (!empty($settings['debug'])) {
3057 $this->debug = true;
3059 if (!empty($settings['cookie'])) {
3060 if($settings['cookie'] === true) {
3061 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3062 } else {
3063 $this->cookie = $settings['cookie'];
3066 if (!empty($settings['cache'])) {
3067 if (class_exists('curl_cache')) {
3068 if (!empty($settings['module_cache'])) {
3069 $this->cache = new curl_cache($settings['module_cache']);
3070 } else {
3071 $this->cache = new curl_cache('misc');
3075 if (!empty($CFG->proxyhost)) {
3076 if (empty($CFG->proxyport)) {
3077 $this->proxy_host = $CFG->proxyhost;
3078 } else {
3079 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3081 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3082 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3083 $this->setopt(array(
3084 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3085 'proxyuserpwd'=>$this->proxy_auth));
3087 if (!empty($CFG->proxytype)) {
3088 if ($CFG->proxytype == 'SOCKS5') {
3089 $this->proxy_type = CURLPROXY_SOCKS5;
3090 } else {
3091 $this->proxy_type = CURLPROXY_HTTP;
3092 $this->setopt(array('httpproxytunnel'=>false));
3094 $this->setopt(array('proxytype'=>$this->proxy_type));
3097 if (isset($settings['proxy'])) {
3098 $this->proxy = $settings['proxy'];
3100 } else {
3101 $this->proxy = false;
3104 if (!isset($this->emulateredirects)) {
3105 $this->emulateredirects = ini_get('open_basedir');
3108 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3109 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3110 $this->set_security($settings['securityhelper']);
3111 } else {
3112 $this->set_security(new \core\files\curl_security_helper());
3114 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3118 * Resets the CURL options that have already been set
3120 public function resetopt() {
3121 $this->options = array();
3122 $this->options['CURLOPT_USERAGENT'] = \core_useragent::get_moodlebot_useragent();
3123 // True to include the header in the output
3124 $this->options['CURLOPT_HEADER'] = 0;
3125 // True to Exclude the body from the output
3126 $this->options['CURLOPT_NOBODY'] = 0;
3127 // Redirect ny default.
3128 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
3129 $this->options['CURLOPT_MAXREDIRS'] = 10;
3130 $this->options['CURLOPT_ENCODING'] = '';
3131 // TRUE to return the transfer as a string of the return
3132 // value of curl_exec() instead of outputting it out directly.
3133 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
3134 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
3135 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
3136 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
3138 if ($cacert = self::get_cacert()) {
3139 $this->options['CURLOPT_CAINFO'] = $cacert;
3144 * Get the location of ca certificates.
3145 * @return string absolute file path or empty if default used
3147 public static function get_cacert() {
3148 global $CFG;
3150 // Bundle in dataroot always wins.
3151 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3152 return realpath("$CFG->dataroot/moodleorgca.crt");
3155 // Next comes the default from php.ini
3156 $cacert = ini_get('curl.cainfo');
3157 if (!empty($cacert) and is_readable($cacert)) {
3158 return realpath($cacert);
3161 // Windows PHP does not have any certs, we need to use something.
3162 if ($CFG->ostype === 'WINDOWS') {
3163 if (is_readable("$CFG->libdir/cacert.pem")) {
3164 return realpath("$CFG->libdir/cacert.pem");
3168 // Use default, this should work fine on all properly configured *nix systems.
3169 return null;
3173 * Reset Cookie
3175 public function resetcookie() {
3176 if (!empty($this->cookie)) {
3177 if (is_file($this->cookie)) {
3178 $fp = fopen($this->cookie, 'w');
3179 if (!empty($fp)) {
3180 fwrite($fp, '');
3181 fclose($fp);
3188 * Set curl options.
3190 * Do not use the curl constants to define the options, pass a string
3191 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3192 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3194 * @param array $options If array is null, this function will reset the options to default value.
3195 * @return void
3196 * @throws coding_exception If an option uses constant value instead of option name.
3198 public function setopt($options = array()) {
3199 if (is_array($options)) {
3200 foreach ($options as $name => $val) {
3201 if (!is_string($name)) {
3202 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3204 if (stripos($name, 'CURLOPT_') === false) {
3205 $name = strtoupper('CURLOPT_'.$name);
3206 } else {
3207 $name = strtoupper($name);
3209 $this->options[$name] = $val;
3215 * Reset http method
3217 public function cleanopt() {
3218 unset($this->options['CURLOPT_HTTPGET']);
3219 unset($this->options['CURLOPT_POST']);
3220 unset($this->options['CURLOPT_POSTFIELDS']);
3221 unset($this->options['CURLOPT_PUT']);
3222 unset($this->options['CURLOPT_INFILE']);
3223 unset($this->options['CURLOPT_INFILESIZE']);
3224 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3225 unset($this->options['CURLOPT_FILE']);
3229 * Resets the HTTP Request headers (to prepare for the new request)
3231 public function resetHeader() {
3232 $this->header = array();
3236 * Set HTTP Request Header
3238 * @param array $header
3240 public function setHeader($header) {
3241 if (is_array($header)) {
3242 foreach ($header as $v) {
3243 $this->setHeader($v);
3245 } else {
3246 // Remove newlines, they are not allowed in headers.
3247 $newvalue = preg_replace('/[\r\n]/', '', $header);
3248 if (!in_array($newvalue, $this->header)) {
3249 $this->header[] = $newvalue;
3255 * Get HTTP Response Headers
3256 * @return array of arrays
3258 public function getResponse() {
3259 return $this->response;
3263 * Get raw HTTP Response Headers
3264 * @return array of strings
3266 public function get_raw_response() {
3267 return $this->rawresponse;
3271 * private callback function
3272 * Formatting HTTP Response Header
3274 * We only keep the last headers returned. For example during a redirect the
3275 * redirect headers will not appear in {@link self::getResponse()}, if you need
3276 * to use those headers, refer to {@link self::get_raw_response()}.
3278 * @param resource $ch Apparently not used
3279 * @param string $header
3280 * @return int The strlen of the header
3282 private function formatHeader($ch, $header) {
3283 $this->rawresponse[] = $header;
3285 if (trim($header, "\r\n") === '') {
3286 // This must be the last header.
3287 $this->responsefinished = true;
3290 if (strlen($header) > 2) {
3291 if ($this->responsefinished) {
3292 // We still have headers after the supposedly last header, we must be
3293 // in a redirect so let's empty the response to keep the last headers.
3294 $this->responsefinished = false;
3295 $this->response = array();
3297 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3298 $key = rtrim($parts[0], ':');
3299 $value = isset($parts[1]) ? $parts[1] : null;
3300 if (!empty($this->response[$key])) {
3301 if (is_array($this->response[$key])) {
3302 $this->response[$key][] = $value;
3303 } else {
3304 $tmp = $this->response[$key];
3305 $this->response[$key] = array();
3306 $this->response[$key][] = $tmp;
3307 $this->response[$key][] = $value;
3310 } else {
3311 $this->response[$key] = $value;
3314 return strlen($header);
3318 * Set options for individual curl instance
3320 * @param resource $curl A curl handle
3321 * @param array $options
3322 * @return resource The curl handle
3324 private function apply_opt($curl, $options) {
3325 // Clean up
3326 $this->cleanopt();
3327 // set cookie
3328 if (!empty($this->cookie) || !empty($options['cookie'])) {
3329 $this->setopt(array('cookiejar'=>$this->cookie,
3330 'cookiefile'=>$this->cookie
3334 // Bypass proxy if required.
3335 if ($this->proxy === null) {
3336 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3337 $proxy = false;
3338 } else {
3339 $proxy = true;
3341 } else {
3342 $proxy = (bool)$this->proxy;
3345 // Set proxy.
3346 if ($proxy) {
3347 $options['CURLOPT_PROXY'] = $this->proxy_host;
3348 } else {
3349 unset($this->options['CURLOPT_PROXY']);
3352 $this->setopt($options);
3354 // Reset before set options.
3355 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3357 // Setting the User-Agent based on options provided.
3358 $useragent = '';
3360 if (!empty($options['CURLOPT_USERAGENT'])) {
3361 $useragent = $options['CURLOPT_USERAGENT'];
3362 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3363 $useragent = $this->options['CURLOPT_USERAGENT'];
3364 } else {
3365 $useragent = \core_useragent::get_moodlebot_useragent();
3368 // Set headers.
3369 if (empty($this->header)) {
3370 $this->setHeader(array(
3371 'User-Agent: ' . $useragent,
3372 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3373 'Connection: keep-alive'
3375 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3376 // Remove old User-Agent if one existed.
3377 // We have to partial search since we don't know what the original User-Agent is.
3378 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3379 $key = array_keys($match)[0];
3380 unset($this->header[$key]);
3382 $this->setHeader(array('User-Agent: ' . $useragent));
3384 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3386 if ($this->debug) {
3387 echo '<h1>Options</h1>';
3388 var_dump($this->options);
3389 echo '<h1>Header</h1>';
3390 var_dump($this->header);
3393 // Do not allow infinite redirects.
3394 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3395 $this->options['CURLOPT_MAXREDIRS'] = 0;
3396 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3397 $this->options['CURLOPT_MAXREDIRS'] = 100;
3398 } else {
3399 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3402 // Make sure we always know if redirects expected.
3403 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3404 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3407 // Limit the protocols to HTTP and HTTPS.
3408 if (defined('CURLOPT_PROTOCOLS')) {
3409 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3410 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3413 // Set options.
3414 foreach($this->options as $name => $val) {
3415 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3416 // The redirects are emulated elsewhere.
3417 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3418 continue;
3420 $name = constant($name);
3421 curl_setopt($curl, $name, $val);
3424 return $curl;
3428 * Download multiple files in parallel
3430 * Calls {@link multi()} with specific download headers
3432 * <code>
3433 * $c = new curl();
3434 * $file1 = fopen('a', 'wb');
3435 * $file2 = fopen('b', 'wb');
3436 * $c->download(array(
3437 * array('url'=>'http://localhost/', 'file'=>$file1),
3438 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3439 * ));
3440 * fclose($file1);
3441 * fclose($file2);
3442 * </code>
3444 * or
3446 * <code>
3447 * $c = new curl();
3448 * $c->download(array(
3449 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3450 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3451 * ));
3452 * </code>
3454 * @param array $requests An array of files to request {
3455 * url => url to download the file [required]
3456 * file => file handler, or
3457 * filepath => file path
3459 * If 'file' and 'filepath' parameters are both specified in one request, the
3460 * open file handle in the 'file' parameter will take precedence and 'filepath'
3461 * will be ignored.
3463 * @param array $options An array of options to set
3464 * @return array An array of results
3466 public function download($requests, $options = array()) {
3467 $options['RETURNTRANSFER'] = false;
3468 return $this->multi($requests, $options);
3472 * Returns the current curl security helper.
3474 * @return \core\files\curl_security_helper instance.
3476 public function get_security() {
3477 return $this->securityhelper;
3481 * Sets the curl security helper.
3483 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3484 * @return bool true if the security helper could be set, false otherwise.
3486 public function set_security($securityobject) {
3487 if ($securityobject instanceof \core\files\curl_security_helper) {
3488 $this->securityhelper = $securityobject;
3489 return true;
3491 return false;
3495 * Multi HTTP Requests
3496 * This function could run multi-requests in parallel.
3498 * @param array $requests An array of files to request
3499 * @param array $options An array of options to set
3500 * @return array An array of results
3502 protected function multi($requests, $options = array()) {
3503 $count = count($requests);
3504 $handles = array();
3505 $results = array();
3506 $main = curl_multi_init();
3507 for ($i = 0; $i < $count; $i++) {
3508 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3509 // open file
3510 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3511 $requests[$i]['auto-handle'] = true;
3513 foreach($requests[$i] as $n=>$v) {
3514 $options[$n] = $v;
3516 $handles[$i] = curl_init($requests[$i]['url']);
3517 $this->apply_opt($handles[$i], $options);
3518 curl_multi_add_handle($main, $handles[$i]);
3520 $running = 0;
3521 do {
3522 curl_multi_exec($main, $running);
3523 } while($running > 0);
3524 for ($i = 0; $i < $count; $i++) {
3525 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3526 $results[] = true;
3527 } else {
3528 $results[] = curl_multi_getcontent($handles[$i]);
3530 curl_multi_remove_handle($main, $handles[$i]);
3532 curl_multi_close($main);
3534 for ($i = 0; $i < $count; $i++) {
3535 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3536 // close file handler if file is opened in this function
3537 fclose($requests[$i]['file']);
3540 return $results;
3544 * Helper function to reset the request state vars.
3546 * @return void.
3548 protected function reset_request_state_vars() {
3549 $this->info = array();
3550 $this->error = '';
3551 $this->errno = 0;
3552 $this->response = array();
3553 $this->rawresponse = array();
3554 $this->responsefinished = false;
3558 * For use only in unit tests - we can pre-set the next curl response.
3559 * This is useful for unit testing APIs that call external systems.
3560 * @param string $response
3562 public static function mock_response($response) {
3563 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3564 array_push(self::$mockresponses, $response);
3565 } else {
3566 throw new coding_exception('mock_response function is only available for unit tests.');
3571 * check_securityhelper_blocklist.
3572 * Checks whether the given URL is blocked by checking both plugin's security helpers
3573 * and core curl security helper or any curl security helper that passed to curl class constructor.
3574 * If ignoresecurity is set to true, skip checking and consider the url is not blocked.
3575 * This augments all installed plugin's security helpers if there is any.
3577 * @param string $url the url to check.
3578 * @return string - an error message if URL is blocked or null if URL is not blocked.
3580 protected function check_securityhelper_blocklist(string $url): ?string {
3582 // If curl security is not enabled, do not proceed.
3583 if ($this->ignoresecurity) {
3584 return null;
3587 // Augment all installed plugin's security helpers if there is any.
3588 // The plugin's function has to be defined as plugintype_pluginname_security_helper in pluginname/lib.php file.
3589 $plugintypes = get_plugins_with_function('curl_security_helper');
3591 // If any of the security helper's function returns true, treat as URL is blocked.
3592 foreach ($plugintypes as $plugins) {
3593 foreach ($plugins as $pluginfunction) {
3594 // Get curl security helper object from plugin lib.php.
3595 $pluginsecurityhelper = $pluginfunction();
3596 if ($pluginsecurityhelper instanceof \core\files\curl_security_helper_base) {
3597 if ($pluginsecurityhelper->url_is_blocked($url)) {
3598 $this->error = $pluginsecurityhelper->get_blocked_url_string();
3599 return $this->error;
3605 // Check if the URL is blocked in core curl_security_helper or
3606 // curl security helper that passed to curl class constructor.
3607 if ($this->securityhelper->url_is_blocked($url)) {
3608 $this->error = $this->securityhelper->get_blocked_url_string();
3609 return $this->error;
3612 return null;
3616 * Single HTTP Request
3618 * @param string $url The URL to request
3619 * @param array $options
3620 * @return bool
3622 protected function request($url, $options = array()) {
3623 // Reset here so that the data is valid when result returned from cache, or if we return due to a blocked URL hit.
3624 $this->reset_request_state_vars();
3626 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3627 if ($mockresponse = array_pop(self::$mockresponses)) {
3628 $this->info = [ 'http_code' => 200 ];
3629 return $mockresponse;
3633 // This will only check the base url. In the case of redirects, the blocking check is also after the curl_exec.
3634 $urlisblocked = $this->check_securityhelper_blocklist($url);
3635 if (!is_null($urlisblocked)) {
3636 return $urlisblocked;
3639 // Set the URL as a curl option.
3640 $this->setopt(array('CURLOPT_URL' => $url));
3642 // Create curl instance.
3643 $curl = curl_init();
3645 $this->apply_opt($curl, $options);
3646 if ($this->cache && $ret = $this->cache->get($this->options)) {
3647 return $ret;
3650 $ret = curl_exec($curl);
3651 $this->info = curl_getinfo($curl);
3652 $this->error = curl_error($curl);
3653 $this->errno = curl_errno($curl);
3654 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3656 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the list of blocked list too.
3657 if (intval($this->info['redirect_count']) > 0) {
3658 $urlisblocked = $this->check_securityhelper_blocklist($this->info['url']);
3659 if (!is_null($urlisblocked)) {
3660 $this->reset_request_state_vars();
3661 curl_close($curl);
3662 return $urlisblocked;
3666 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3667 $redirects = 0;
3669 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3671 if ($this->info['http_code'] == 301) {
3672 // Moved Permanently - repeat the same request on new URL.
3674 } else if ($this->info['http_code'] == 302) {
3675 // Found - the standard redirect - repeat the same request on new URL.
3677 } else if ($this->info['http_code'] == 303) {
3678 // 303 See Other - repeat only if GET, do not bother with POSTs.
3679 if (empty($this->options['CURLOPT_HTTPGET'])) {
3680 break;
3683 } else if ($this->info['http_code'] == 307) {
3684 // Temporary Redirect - must repeat using the same request type.
3686 } else if ($this->info['http_code'] == 308) {
3687 // Permanent Redirect - must repeat using the same request type.
3689 } else {
3690 // Some other http code means do not retry!
3691 break;
3694 $redirects++;
3696 $redirecturl = null;
3697 if (isset($this->info['redirect_url'])) {
3698 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3699 $redirecturl = $this->info['redirect_url'];
3702 if (!$redirecturl) {
3703 foreach ($this->response as $k => $v) {
3704 if (strtolower($k) === 'location') {
3705 $redirecturl = $v;
3706 break;
3709 if (preg_match('|^https?://|i', $redirecturl)) {
3710 // Great, this is the correct location format!
3712 } else if ($redirecturl) {
3713 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3714 if (strpos($redirecturl, '/') === 0) {
3715 // Relative to server root - just guess.
3716 $pos = strpos('/', $current, 8);
3717 if ($pos === false) {
3718 $redirecturl = $current.$redirecturl;
3719 } else {
3720 $redirecturl = substr($current, 0, $pos).$redirecturl;
3722 } else {
3723 // Relative to current script.
3724 $redirecturl = dirname($current).'/'.$redirecturl;
3729 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3730 $ret = curl_exec($curl);
3732 $this->info = curl_getinfo($curl);
3733 $this->error = curl_error($curl);
3734 $this->errno = curl_errno($curl);
3736 $this->info['redirect_count'] = $redirects;
3738 if ($this->info['http_code'] === 200) {
3739 // Finally this is what we wanted.
3740 break;
3742 if ($this->errno != CURLE_OK) {
3743 // Something wrong is going on.
3744 break;
3747 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3748 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3749 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3753 if ($this->cache) {
3754 $this->cache->set($this->options, $ret);
3757 if ($this->debug) {
3758 echo '<h1>Return Data</h1>';
3759 var_dump($ret);
3760 echo '<h1>Info</h1>';
3761 var_dump($this->info);
3762 echo '<h1>Error</h1>';
3763 var_dump($this->error);
3766 curl_close($curl);
3768 if (empty($this->error)) {
3769 return $ret;
3770 } else {
3771 return $this->error;
3772 // exception is not ajax friendly
3773 //throw new moodle_exception($this->error, 'curl');
3778 * HTTP HEAD method
3780 * @see request()
3782 * @param string $url
3783 * @param array $options
3784 * @return bool
3786 public function head($url, $options = array()) {
3787 $options['CURLOPT_HTTPGET'] = 0;
3788 $options['CURLOPT_HEADER'] = 1;
3789 $options['CURLOPT_NOBODY'] = 1;
3790 return $this->request($url, $options);
3794 * HTTP PATCH method
3796 * @param string $url
3797 * @param array|string $params
3798 * @param array $options
3799 * @return bool
3801 public function patch($url, $params = '', $options = array()) {
3802 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3803 if (is_array($params)) {
3804 $this->_tmp_file_post_params = array();
3805 foreach ($params as $key => $value) {
3806 if ($value instanceof stored_file) {
3807 $value->add_to_curl_request($this, $key);
3808 } else {
3809 $this->_tmp_file_post_params[$key] = $value;
3812 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3813 unset($this->_tmp_file_post_params);
3814 } else {
3815 // The variable $params is the raw post data.
3816 $options['CURLOPT_POSTFIELDS'] = $params;
3818 return $this->request($url, $options);
3822 * HTTP POST method
3824 * @param string $url
3825 * @param array|string $params
3826 * @param array $options
3827 * @return bool
3829 public function post($url, $params = '', $options = array()) {
3830 $options['CURLOPT_POST'] = 1;
3831 if (is_array($params)) {
3832 $this->_tmp_file_post_params = array();
3833 foreach ($params as $key => $value) {
3834 if ($value instanceof stored_file) {
3835 $value->add_to_curl_request($this, $key);
3836 } else {
3837 $this->_tmp_file_post_params[$key] = $value;
3840 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3841 unset($this->_tmp_file_post_params);
3842 } else {
3843 // $params is the raw post data
3844 $options['CURLOPT_POSTFIELDS'] = $params;
3846 return $this->request($url, $options);
3850 * HTTP GET method
3852 * @param string $url
3853 * @param array $params
3854 * @param array $options
3855 * @return bool
3857 public function get($url, $params = array(), $options = array()) {
3858 $options['CURLOPT_HTTPGET'] = 1;
3860 if (!empty($params)) {
3861 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3862 $url .= http_build_query($params, '', '&');
3864 return $this->request($url, $options);
3868 * Downloads one file and writes it to the specified file handler
3870 * <code>
3871 * $c = new curl();
3872 * $file = fopen('savepath', 'w');
3873 * $result = $c->download_one('http://localhost/', null,
3874 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3875 * fclose($file);
3876 * $download_info = $c->get_info();
3877 * if ($result === true) {
3878 * // file downloaded successfully
3879 * } else {
3880 * $error_text = $result;
3881 * $error_code = $c->get_errno();
3883 * </code>
3885 * <code>
3886 * $c = new curl();
3887 * $result = $c->download_one('http://localhost/', null,
3888 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3889 * // ... see above, no need to close handle and remove file if unsuccessful
3890 * </code>
3892 * @param string $url
3893 * @param array|null $params key-value pairs to be added to $url as query string
3894 * @param array $options request options. Must include either 'file' or 'filepath'
3895 * @return bool|string true on success or error string on failure
3897 public function download_one($url, $params, $options = array()) {
3898 $options['CURLOPT_HTTPGET'] = 1;
3899 if (!empty($params)) {
3900 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3901 $url .= http_build_query($params, '', '&');
3903 if (!empty($options['filepath']) && empty($options['file'])) {
3904 // open file
3905 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3906 $this->errno = 100;
3907 return get_string('cannotwritefile', 'error', $options['filepath']);
3909 $filepath = $options['filepath'];
3911 unset($options['filepath']);
3912 $result = $this->request($url, $options);
3913 if (isset($filepath)) {
3914 fclose($options['file']);
3915 if ($result !== true) {
3916 unlink($filepath);
3919 return $result;
3923 * HTTP PUT method
3925 * @param string $url
3926 * @param array $params
3927 * @param array $options
3928 * @return bool
3930 public function put($url, $params = array(), $options = array()) {
3931 $file = '';
3932 $fp = false;
3933 if (isset($params['file'])) {
3934 $file = $params['file'];
3935 if (is_file($file)) {
3936 $fp = fopen($file, 'r');
3937 $size = filesize($file);
3938 $options['CURLOPT_PUT'] = 1;
3939 $options['CURLOPT_INFILESIZE'] = $size;
3940 $options['CURLOPT_INFILE'] = $fp;
3941 } else {
3942 return null;
3944 if (!isset($this->options['CURLOPT_USERPWD'])) {
3945 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3947 } else {
3948 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3949 $options['CURLOPT_POSTFIELDS'] = $params;
3952 $ret = $this->request($url, $options);
3953 if ($fp !== false) {
3954 fclose($fp);
3956 return $ret;
3960 * HTTP DELETE method
3962 * @param string $url
3963 * @param array $param
3964 * @param array $options
3965 * @return bool
3967 public function delete($url, $param = array(), $options = array()) {
3968 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3969 if (!isset($options['CURLOPT_USERPWD'])) {
3970 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3972 $ret = $this->request($url, $options);
3973 return $ret;
3977 * HTTP TRACE method
3979 * @param string $url
3980 * @param array $options
3981 * @return bool
3983 public function trace($url, $options = array()) {
3984 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3985 $ret = $this->request($url, $options);
3986 return $ret;
3990 * HTTP OPTIONS method
3992 * @param string $url
3993 * @param array $options
3994 * @return bool
3996 public function options($url, $options = array()) {
3997 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3998 $ret = $this->request($url, $options);
3999 return $ret;
4003 * Get curl information
4005 * @return string
4007 public function get_info() {
4008 return $this->info;
4012 * Get curl error code
4014 * @return int
4016 public function get_errno() {
4017 return $this->errno;
4021 * When using a proxy, an additional HTTP response code may appear at
4022 * the start of the header. For example, when using https over a proxy
4023 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
4024 * also possible and some may come with their own headers.
4026 * If using the return value containing all headers, this function can be
4027 * called to remove unwanted doubles.
4029 * Note that it is not possible to distinguish this situation from valid
4030 * data unless you know the actual response part (below the headers)
4031 * will not be included in this string, or else will not 'look like' HTTP
4032 * headers. As a result it is not safe to call this function for general
4033 * data.
4035 * @param string $input Input HTTP response
4036 * @return string HTTP response with additional headers stripped if any
4038 public static function strip_double_headers($input) {
4039 // I have tried to make this regular expression as specific as possible
4040 // to avoid any case where it does weird stuff if you happen to put
4041 // HTTP/1.1 200 at the start of any line in your RSS file. This should
4042 // also make it faster because it can abandon regex processing as soon
4043 // as it hits something that doesn't look like an http header. The
4044 // header definition is taken from RFC 822, except I didn't support
4045 // folding which is never used in practice.
4046 $crlf = "\r\n";
4047 return preg_replace(
4048 // HTTP version and status code (ignore value of code).
4049 '~^HTTP/1\..*' . $crlf .
4050 // Header name: character between 33 and 126 decimal, except colon.
4051 // Colon. Header value: any character except \r and \n. CRLF.
4052 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
4053 // Headers are terminated by another CRLF (blank line).
4054 $crlf .
4055 // Second HTTP status code, this time must be 200.
4056 '(HTTP/1.[01] 200 )~', '$1', $input);
4061 * This class is used by cURL class, use case:
4063 * <code>
4064 * $CFG->repositorycacheexpire = 120;
4065 * $CFG->curlcache = 120;
4067 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
4068 * $ret = $c->get('http://www.google.com');
4069 * </code>
4071 * @package core_files
4072 * @copyright Dongsheng Cai <dongsheng@moodle.com>
4073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4075 class curl_cache {
4076 /** @var string Path to cache directory */
4077 public $dir = '';
4080 * Constructor
4082 * @global stdClass $CFG
4083 * @param string $module which module is using curl_cache
4085 public function __construct($module = 'repository') {
4086 global $CFG;
4087 if (!empty($module)) {
4088 $this->dir = $CFG->cachedir.'/'.$module.'/';
4089 } else {
4090 $this->dir = $CFG->cachedir.'/misc/';
4092 if (!file_exists($this->dir)) {
4093 mkdir($this->dir, $CFG->directorypermissions, true);
4095 if ($module == 'repository') {
4096 if (empty($CFG->repositorycacheexpire)) {
4097 $CFG->repositorycacheexpire = 120;
4099 $this->ttl = $CFG->repositorycacheexpire;
4100 } else {
4101 if (empty($CFG->curlcache)) {
4102 $CFG->curlcache = 120;
4104 $this->ttl = $CFG->curlcache;
4109 * Get cached value
4111 * @global stdClass $CFG
4112 * @global stdClass $USER
4113 * @param mixed $param
4114 * @return bool|string
4116 public function get($param) {
4117 global $CFG, $USER;
4118 $this->cleanup($this->ttl);
4119 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4120 if(file_exists($this->dir.$filename)) {
4121 $lasttime = filemtime($this->dir.$filename);
4122 if (time()-$lasttime > $this->ttl) {
4123 return false;
4124 } else {
4125 $fp = fopen($this->dir.$filename, 'r');
4126 $size = filesize($this->dir.$filename);
4127 $content = fread($fp, $size);
4128 return unserialize($content);
4131 return false;
4135 * Set cache value
4137 * @global object $CFG
4138 * @global object $USER
4139 * @param mixed $param
4140 * @param mixed $val
4142 public function set($param, $val) {
4143 global $CFG, $USER;
4144 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4145 $fp = fopen($this->dir.$filename, 'w');
4146 fwrite($fp, serialize($val));
4147 fclose($fp);
4148 @chmod($this->dir.$filename, $CFG->filepermissions);
4152 * Remove cache files
4154 * @param int $expire The number of seconds before expiry
4156 public function cleanup($expire) {
4157 if ($dir = opendir($this->dir)) {
4158 while (false !== ($file = readdir($dir))) {
4159 if(!is_dir($file) && $file != '.' && $file != '..') {
4160 $lasttime = @filemtime($this->dir.$file);
4161 if (time() - $lasttime > $expire) {
4162 @unlink($this->dir.$file);
4166 closedir($dir);
4170 * delete current user's cache file
4172 * @global object $CFG
4173 * @global object $USER
4175 public function refresh() {
4176 global $CFG, $USER;
4177 if ($dir = opendir($this->dir)) {
4178 while (false !== ($file = readdir($dir))) {
4179 if (!is_dir($file) && $file != '.' && $file != '..') {
4180 if (strpos($file, 'u'.$USER->id.'_') !== false) {
4181 @unlink($this->dir.$file);
4190 * This function delegates file serving to individual plugins
4192 * @param string $relativepath
4193 * @param bool $forcedownload
4194 * @param null|string $preview the preview mode, defaults to serving the original file
4195 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4196 * offline (e.g. mobile app).
4197 * @param bool $embed Whether this file will be served embed into an iframe.
4198 * @todo MDL-31088 file serving improments
4200 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4201 global $DB, $CFG, $USER;
4202 // relative path must start with '/'
4203 if (!$relativepath) {
4204 print_error('invalidargorconf');
4205 } else if ($relativepath[0] != '/') {
4206 print_error('pathdoesnotstartslash');
4209 // extract relative path components
4210 $args = explode('/', ltrim($relativepath, '/'));
4212 if (count($args) < 3) { // always at least context, component and filearea
4213 print_error('invalidarguments');
4216 $contextid = (int)array_shift($args);
4217 $component = clean_param(array_shift($args), PARAM_COMPONENT);
4218 $filearea = clean_param(array_shift($args), PARAM_AREA);
4220 list($context, $course, $cm) = get_context_info_array($contextid);
4222 $fs = get_file_storage();
4224 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4226 // ========================================================================================================================
4227 if ($component === 'blog') {
4228 // Blog file serving
4229 if ($context->contextlevel != CONTEXT_SYSTEM) {
4230 send_file_not_found();
4232 if ($filearea !== 'attachment' and $filearea !== 'post') {
4233 send_file_not_found();
4236 if (empty($CFG->enableblogs)) {
4237 print_error('siteblogdisable', 'blog');
4240 $entryid = (int)array_shift($args);
4241 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4242 send_file_not_found();
4244 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4245 require_login();
4246 if (isguestuser()) {
4247 print_error('noguest');
4249 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4250 if ($USER->id != $entry->userid) {
4251 send_file_not_found();
4256 if ($entry->publishstate === 'public') {
4257 if ($CFG->forcelogin) {
4258 require_login();
4261 } else if ($entry->publishstate === 'site') {
4262 require_login();
4263 //ok
4264 } else if ($entry->publishstate === 'draft') {
4265 require_login();
4266 if ($USER->id != $entry->userid) {
4267 send_file_not_found();
4271 $filename = array_pop($args);
4272 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4274 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4275 send_file_not_found();
4278 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4280 // ========================================================================================================================
4281 } else if ($component === 'grade') {
4283 require_once($CFG->libdir . '/grade/constants.php');
4285 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4286 // Global gradebook files
4287 if ($CFG->forcelogin) {
4288 require_login();
4291 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4293 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4294 send_file_not_found();
4297 \core\session\manager::write_close(); // Unlock session during file serving.
4298 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4300 } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4301 if ($context->contextlevel != CONTEXT_MODULE) {
4302 send_file_not_found();
4305 require_login($course, false);
4307 $gradeid = (int) array_shift($args);
4308 $filename = array_pop($args);
4309 if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4310 $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4311 } else {
4312 $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4315 if (!$grade) {
4316 send_file_not_found();
4319 $iscurrentuser = $USER->id == $grade->userid;
4321 if (!$iscurrentuser) {
4322 $coursecontext = context_course::instance($course->id);
4323 if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4324 send_file_not_found();
4328 $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4330 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4331 send_file_not_found();
4334 \core\session\manager::write_close(); // Unlock session during file serving.
4335 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4336 } else {
4337 send_file_not_found();
4340 // ========================================================================================================================
4341 } else if ($component === 'tag') {
4342 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4344 // All tag descriptions are going to be public but we still need to respect forcelogin
4345 if ($CFG->forcelogin) {
4346 require_login();
4349 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4351 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4352 send_file_not_found();
4355 \core\session\manager::write_close(); // Unlock session during file serving.
4356 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4358 } else {
4359 send_file_not_found();
4361 // ========================================================================================================================
4362 } else if ($component === 'badges') {
4363 require_once($CFG->libdir . '/badgeslib.php');
4365 $badgeid = (int)array_shift($args);
4366 $badge = new badge($badgeid);
4367 $filename = array_pop($args);
4369 if ($filearea === 'badgeimage') {
4370 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4371 send_file_not_found();
4373 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4374 send_file_not_found();
4377 \core\session\manager::write_close();
4378 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4379 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4380 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4381 send_file_not_found();
4384 \core\session\manager::write_close();
4385 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4387 // ========================================================================================================================
4388 } else if ($component === 'calendar') {
4389 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4391 // All events here are public the one requirement is that we respect forcelogin
4392 if ($CFG->forcelogin) {
4393 require_login();
4396 // Get the event if from the args array
4397 $eventid = array_shift($args);
4399 // Load the event from the database
4400 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4401 send_file_not_found();
4404 // Get the file and serve if successful
4405 $filename = array_pop($args);
4406 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4407 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4408 send_file_not_found();
4411 \core\session\manager::write_close(); // Unlock session during file serving.
4412 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4414 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4416 // Must be logged in, if they are not then they obviously can't be this user
4417 require_login();
4419 // Don't want guests here, potentially saves a DB call
4420 if (isguestuser()) {
4421 send_file_not_found();
4424 // Get the event if from the args array
4425 $eventid = array_shift($args);
4427 // Load the event from the database - user id must match
4428 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4429 send_file_not_found();
4432 // Get the file and serve if successful
4433 $filename = array_pop($args);
4434 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4435 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4436 send_file_not_found();
4439 \core\session\manager::write_close(); // Unlock session during file serving.
4440 send_stored_file($file, 0, 0, true, $sendfileoptions);
4442 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4444 // Respect forcelogin and require login unless this is the site.... it probably
4445 // should NEVER be the site
4446 if ($CFG->forcelogin || $course->id != SITEID) {
4447 require_login($course);
4450 // Must be able to at least view the course. This does not apply to the front page.
4451 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4452 //TODO: hmm, do we really want to block guests here?
4453 send_file_not_found();
4456 // Get the event id
4457 $eventid = array_shift($args);
4459 // Load the event from the database we need to check whether it is
4460 // a) valid course event
4461 // b) a group event
4462 // Group events use the course context (there is no group context)
4463 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4464 send_file_not_found();
4467 // If its a group event require either membership of view all groups capability
4468 if ($event->eventtype === 'group') {
4469 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4470 send_file_not_found();
4472 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4473 // Ok. Please note that the event type 'site' still uses a course context.
4474 } else {
4475 // Some other type.
4476 send_file_not_found();
4479 // If we get this far we can serve the file
4480 $filename = array_pop($args);
4481 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4482 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4483 send_file_not_found();
4486 \core\session\manager::write_close(); // Unlock session during file serving.
4487 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4489 } else {
4490 send_file_not_found();
4493 // ========================================================================================================================
4494 } else if ($component === 'user') {
4495 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4496 if (count($args) == 1) {
4497 $themename = theme_config::DEFAULT_THEME;
4498 $filename = array_shift($args);
4499 } else {
4500 $themename = array_shift($args);
4501 $filename = array_shift($args);
4504 // fix file name automatically
4505 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4506 $filename = 'f1';
4509 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4510 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4511 // protect images if login required and not logged in;
4512 // also if login is required for profile images and is not logged in or guest
4513 // do not use require_login() because it is expensive and not suitable here anyway
4514 $theme = theme_config::load($themename);
4515 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4518 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4519 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4520 if ($filename === 'f3') {
4521 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4522 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4523 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4528 if (!$file) {
4529 // bad reference - try to prevent future retries as hard as possible!
4530 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4531 if ($user->picture > 0) {
4532 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4535 // no redirect here because it is not cached
4536 $theme = theme_config::load($themename);
4537 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4538 send_file($imagefile, basename($imagefile), 60*60*24*14);
4541 $options = $sendfileoptions;
4542 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4543 // Profile images should be cache-able by both browsers and proxies according
4544 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4545 $options['cacheability'] = 'public';
4547 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4549 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4550 require_login();
4552 if (isguestuser()) {
4553 send_file_not_found();
4556 if ($USER->id !== $context->instanceid) {
4557 send_file_not_found();
4560 $filename = array_pop($args);
4561 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4562 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4563 send_file_not_found();
4566 \core\session\manager::write_close(); // Unlock session during file serving.
4567 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4569 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4571 if ($CFG->forcelogin) {
4572 require_login();
4575 $userid = $context->instanceid;
4577 if ($USER->id == $userid) {
4578 // always can access own
4580 } else if (!empty($CFG->forceloginforprofiles)) {
4581 require_login();
4583 if (isguestuser()) {
4584 send_file_not_found();
4587 // we allow access to site profile of all course contacts (usually teachers)
4588 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4589 send_file_not_found();
4592 $canview = false;
4593 if (has_capability('moodle/user:viewdetails', $context)) {
4594 $canview = true;
4595 } else {
4596 $courses = enrol_get_my_courses();
4599 while (!$canview && count($courses) > 0) {
4600 $course = array_shift($courses);
4601 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4602 $canview = true;
4607 $filename = array_pop($args);
4608 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4609 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4610 send_file_not_found();
4613 \core\session\manager::write_close(); // Unlock session during file serving.
4614 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4616 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4617 $userid = (int)array_shift($args);
4618 $usercontext = context_user::instance($userid);
4620 if ($CFG->forcelogin) {
4621 require_login();
4624 if (!empty($CFG->forceloginforprofiles)) {
4625 require_login();
4626 if (isguestuser()) {
4627 print_error('noguest');
4630 //TODO: review this logic of user profile access prevention
4631 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4632 print_error('usernotavailable');
4634 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4635 print_error('cannotviewprofile');
4637 if (!is_enrolled($context, $userid)) {
4638 print_error('notenrolledprofile');
4640 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4641 print_error('groupnotamember');
4645 $filename = array_pop($args);
4646 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4647 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4648 send_file_not_found();
4651 \core\session\manager::write_close(); // Unlock session during file serving.
4652 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4654 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4655 require_login();
4657 if (isguestuser()) {
4658 send_file_not_found();
4660 $userid = $context->instanceid;
4662 if ($USER->id != $userid) {
4663 send_file_not_found();
4666 $filename = array_pop($args);
4667 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4668 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4669 send_file_not_found();
4672 \core\session\manager::write_close(); // Unlock session during file serving.
4673 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4675 } else {
4676 send_file_not_found();
4679 // ========================================================================================================================
4680 } else if ($component === 'coursecat') {
4681 if ($context->contextlevel != CONTEXT_COURSECAT) {
4682 send_file_not_found();
4685 if ($filearea === 'description') {
4686 if ($CFG->forcelogin) {
4687 // no login necessary - unless login forced everywhere
4688 require_login();
4691 // Check if user can view this category.
4692 if (!core_course_category::get($context->instanceid, IGNORE_MISSING)) {
4693 send_file_not_found();
4696 $filename = array_pop($args);
4697 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4698 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4699 send_file_not_found();
4702 \core\session\manager::write_close(); // Unlock session during file serving.
4703 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4704 } else {
4705 send_file_not_found();
4708 // ========================================================================================================================
4709 } else if ($component === 'course') {
4710 if ($context->contextlevel != CONTEXT_COURSE) {
4711 send_file_not_found();
4714 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4715 if ($CFG->forcelogin) {
4716 require_login();
4719 $filename = array_pop($args);
4720 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4721 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4722 send_file_not_found();
4725 \core\session\manager::write_close(); // Unlock session during file serving.
4726 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4728 } else if ($filearea === 'section') {
4729 if ($CFG->forcelogin) {
4730 require_login($course);
4731 } else if ($course->id != SITEID) {
4732 require_login($course);
4735 $sectionid = (int)array_shift($args);
4737 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4738 send_file_not_found();
4741 $filename = array_pop($args);
4742 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4743 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4744 send_file_not_found();
4747 \core\session\manager::write_close(); // Unlock session during file serving.
4748 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4750 } else {
4751 send_file_not_found();
4754 } else if ($component === 'cohort') {
4756 $cohortid = (int)array_shift($args);
4757 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4758 $cohortcontext = context::instance_by_id($cohort->contextid);
4760 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4761 if ($context->id != $cohort->contextid &&
4762 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4763 send_file_not_found();
4766 // User is able to access cohort if they have view cap on cohort level or
4767 // the cohort is visible and they have view cap on course level.
4768 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4769 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4771 if ($filearea === 'description' && $canview) {
4772 $filename = array_pop($args);
4773 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4774 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4775 && !$file->is_directory()) {
4776 \core\session\manager::write_close(); // Unlock session during file serving.
4777 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4781 send_file_not_found();
4783 } else if ($component === 'group') {
4784 if ($context->contextlevel != CONTEXT_COURSE) {
4785 send_file_not_found();
4788 require_course_login($course, true, null, false);
4790 $groupid = (int)array_shift($args);
4792 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4793 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4794 // do not allow access to separate group info if not member or teacher
4795 send_file_not_found();
4798 if ($filearea === 'description') {
4800 require_login($course);
4802 $filename = array_pop($args);
4803 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4804 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4805 send_file_not_found();
4808 \core\session\manager::write_close(); // Unlock session during file serving.
4809 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4811 } else if ($filearea === 'icon') {
4812 $filename = array_pop($args);
4814 if ($filename !== 'f1' and $filename !== 'f2') {
4815 send_file_not_found();
4817 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4818 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4819 send_file_not_found();
4823 \core\session\manager::write_close(); // Unlock session during file serving.
4824 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4826 } else {
4827 send_file_not_found();
4830 } else if ($component === 'grouping') {
4831 if ($context->contextlevel != CONTEXT_COURSE) {
4832 send_file_not_found();
4835 require_login($course);
4837 $groupingid = (int)array_shift($args);
4839 // note: everybody has access to grouping desc images for now
4840 if ($filearea === 'description') {
4842 $filename = array_pop($args);
4843 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4844 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4845 send_file_not_found();
4848 \core\session\manager::write_close(); // Unlock session during file serving.
4849 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4851 } else {
4852 send_file_not_found();
4855 // ========================================================================================================================
4856 } else if ($component === 'backup') {
4857 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4858 require_login($course);
4859 require_capability('moodle/backup:downloadfile', $context);
4861 $filename = array_pop($args);
4862 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4863 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4864 send_file_not_found();
4867 \core\session\manager::write_close(); // Unlock session during file serving.
4868 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4870 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4871 require_login($course);
4872 require_capability('moodle/backup:downloadfile', $context);
4874 $sectionid = (int)array_shift($args);
4876 $filename = array_pop($args);
4877 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4878 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4879 send_file_not_found();
4882 \core\session\manager::write_close();
4883 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4885 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4886 require_login($course, false, $cm);
4887 require_capability('moodle/backup:downloadfile', $context);
4889 $filename = array_pop($args);
4890 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4891 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4892 send_file_not_found();
4895 \core\session\manager::write_close();
4896 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4898 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4899 // Backup files that were generated by the automated backup systems.
4901 require_login($course);
4902 require_capability('moodle/backup:downloadfile', $context);
4903 require_capability('moodle/restore:userinfo', $context);
4905 $filename = array_pop($args);
4906 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4907 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4908 send_file_not_found();
4911 \core\session\manager::write_close(); // Unlock session during file serving.
4912 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4914 } else {
4915 send_file_not_found();
4918 // ========================================================================================================================
4919 } else if ($component === 'question') {
4920 require_once($CFG->libdir . '/questionlib.php');
4921 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4922 send_file_not_found();
4924 // ========================================================================================================================
4925 } else if ($component === 'grading') {
4926 if ($filearea === 'description') {
4927 // files embedded into the form definition description
4929 if ($context->contextlevel == CONTEXT_SYSTEM) {
4930 require_login();
4932 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4933 require_login($course, false, $cm);
4935 } else {
4936 send_file_not_found();
4939 $formid = (int)array_shift($args);
4941 $sql = "SELECT ga.id
4942 FROM {grading_areas} ga
4943 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4944 WHERE gd.id = ? AND ga.contextid = ?";
4945 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4947 if (!$areaid) {
4948 send_file_not_found();
4951 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4953 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4954 send_file_not_found();
4957 \core\session\manager::write_close(); // Unlock session during file serving.
4958 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4960 } else if ($component === 'contentbank') {
4961 if ($filearea != 'public' || isguestuser()) {
4962 send_file_not_found();
4965 if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
4966 require_login();
4967 } else if ($context->contextlevel == CONTEXT_COURSE) {
4968 require_login($course);
4969 } else {
4970 send_file_not_found();
4973 $itemid = (int)array_shift($args);
4974 $filename = array_pop($args);
4975 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4976 if (!$file = $fs->get_file($context->id, $component, $filearea, $itemid, $filepath, $filename) or
4977 $file->is_directory()) {
4978 send_file_not_found();
4981 \core\session\manager::write_close(); // Unlock session during file serving.
4982 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4983 } else if (strpos($component, 'mod_') === 0) {
4984 $modname = substr($component, 4);
4985 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4986 send_file_not_found();
4988 require_once("$CFG->dirroot/mod/$modname/lib.php");
4990 if ($context->contextlevel == CONTEXT_MODULE) {
4991 if ($cm->modname !== $modname) {
4992 // somebody tries to gain illegal access, cm type must match the component!
4993 send_file_not_found();
4997 if ($filearea === 'intro') {
4998 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4999 send_file_not_found();
5002 // Require login to the course first (without login to the module).
5003 require_course_login($course, true);
5005 // Now check if module is available OR it is restricted but the intro is shown on the course page.
5006 $cminfo = cm_info::create($cm);
5007 if (!$cminfo->uservisible) {
5008 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
5009 // Module intro is not visible on the course page and module is not available, show access error.
5010 require_course_login($course, true, $cminfo);
5014 // all users may access it
5015 $filename = array_pop($args);
5016 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5017 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
5018 send_file_not_found();
5021 // finally send the file
5022 send_stored_file($file, null, 0, false, $sendfileoptions);
5025 $filefunction = $component.'_pluginfile';
5026 $filefunctionold = $modname.'_pluginfile';
5027 if (function_exists($filefunction)) {
5028 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5029 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5030 } else if (function_exists($filefunctionold)) {
5031 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5032 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5035 send_file_not_found();
5037 // ========================================================================================================================
5038 } else if (strpos($component, 'block_') === 0) {
5039 $blockname = substr($component, 6);
5040 // note: no more class methods in blocks please, that is ....
5041 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
5042 send_file_not_found();
5044 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
5046 if ($context->contextlevel == CONTEXT_BLOCK) {
5047 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
5048 if ($birecord->blockname !== $blockname) {
5049 // somebody tries to gain illegal access, cm type must match the component!
5050 send_file_not_found();
5053 if ($context->get_course_context(false)) {
5054 // If block is in course context, then check if user has capability to access course.
5055 require_course_login($course);
5056 } else if ($CFG->forcelogin) {
5057 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
5058 require_login();
5061 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
5062 // User can't access file, if block is hidden or doesn't have block:view capability
5063 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
5064 send_file_not_found();
5066 } else {
5067 $birecord = null;
5070 $filefunction = $component.'_pluginfile';
5071 if (function_exists($filefunction)) {
5072 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5073 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5076 send_file_not_found();
5078 // ========================================================================================================================
5079 } else if (strpos($component, '_') === false) {
5080 // all core subsystems have to be specified above, no more guessing here!
5081 send_file_not_found();
5083 } else {
5084 // try to serve general plugin file in arbitrary context
5085 $dir = core_component::get_component_directory($component);
5086 if (!file_exists("$dir/lib.php")) {
5087 send_file_not_found();
5089 include_once("$dir/lib.php");
5091 $filefunction = $component.'_pluginfile';
5092 if (function_exists($filefunction)) {
5093 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5094 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5097 send_file_not_found();