on-demand release 3.8dev+
[moodle.git] / lib / filelib.php
blobc541731829fc6a165e81e8efe687df78cdc8504f
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 * - video - file that can be imported as video in text editor
1643 * - audio - file that can be imported as audio in text editor
1644 * - archive - we can extract files from this archive
1645 * - spreadsheet - used for portfolio format
1646 * - document - used for portfolio format
1647 * - presentation - used for portfolio format
1648 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1649 * human-readable description for this filetype;
1650 * Function {@link get_mimetype_description()} first looks at the presence of string for
1651 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1652 * attribute, if not found returns the value of 'type';
1653 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1654 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1655 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1657 * @category files
1658 * @return array List of information about file types based on extensions.
1659 * Associative array of extension (lower-case) to associative array
1660 * from 'element name' to data. Current element names are 'type' and 'icon'.
1661 * Unknown types should use the 'xxx' entry which includes defaults.
1663 function &get_mimetypes_array() {
1664 // Get types from the core_filetypes function, which includes caching.
1665 return core_filetypes::get_types();
1669 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1671 * This function retrieves a file's MIME type for a file that will be sent to the user.
1672 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1673 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1674 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1676 * @param string $filename The file's filename.
1677 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1679 function get_mimetype_for_sending($filename = '') {
1680 // Guess the file's MIME type using mimeinfo.
1681 $mimetype = mimeinfo('type', $filename);
1683 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1684 if (!$mimetype || $mimetype === 'document/unknown') {
1685 $mimetype = 'application/octet-stream';
1688 return $mimetype;
1692 * Obtains information about a filetype based on its extension. Will
1693 * use a default if no information is present about that particular
1694 * extension.
1696 * @category files
1697 * @param string $element Desired information (usually 'icon'
1698 * for icon filename or 'type' for MIME type. Can also be
1699 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1700 * @param string $filename Filename we're looking up
1701 * @return string Requested piece of information from array
1703 function mimeinfo($element, $filename) {
1704 global $CFG;
1705 $mimeinfo = & get_mimetypes_array();
1706 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1708 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1709 if (empty($filetype)) {
1710 $filetype = 'xxx'; // file without extension
1712 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1713 $iconsize = max(array(16, (int)$iconsizematch[1]));
1714 $filenames = array($mimeinfo['xxx']['icon']);
1715 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1716 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1718 // find the file with the closest size, first search for specific icon then for default icon
1719 foreach ($filenames as $filename) {
1720 foreach ($iconpostfixes as $size => $postfix) {
1721 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1722 if ($iconsize >= $size &&
1723 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1724 return $filename.$postfix;
1728 } else if (isset($mimeinfo[$filetype][$element])) {
1729 return $mimeinfo[$filetype][$element];
1730 } else if (isset($mimeinfo['xxx'][$element])) {
1731 return $mimeinfo['xxx'][$element]; // By default
1732 } else {
1733 return null;
1738 * Obtains information about a filetype based on the MIME type rather than
1739 * the other way around.
1741 * @category files
1742 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1743 * @param string $mimetype MIME type we're looking up
1744 * @return string Requested piece of information from array
1746 function mimeinfo_from_type($element, $mimetype) {
1747 /* array of cached mimetype->extension associations */
1748 static $cached = array();
1749 $mimeinfo = & get_mimetypes_array();
1751 if (!array_key_exists($mimetype, $cached)) {
1752 $cached[$mimetype] = null;
1753 foreach($mimeinfo as $filetype => $values) {
1754 if ($values['type'] == $mimetype) {
1755 if ($cached[$mimetype] === null) {
1756 $cached[$mimetype] = '.'.$filetype;
1758 if (!empty($values['defaulticon'])) {
1759 $cached[$mimetype] = '.'.$filetype;
1760 break;
1764 if (empty($cached[$mimetype])) {
1765 $cached[$mimetype] = '.xxx';
1768 if ($element === 'extension') {
1769 return $cached[$mimetype];
1770 } else {
1771 return mimeinfo($element, $cached[$mimetype]);
1776 * Return the relative icon path for a given file
1778 * Usage:
1779 * <code>
1780 * // $file - instance of stored_file or file_info
1781 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1782 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1783 * </code>
1784 * or
1785 * <code>
1786 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1787 * </code>
1789 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1790 * and $file->mimetype are expected)
1791 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1792 * @return string
1794 function file_file_icon($file, $size = null) {
1795 if (!is_object($file)) {
1796 $file = (object)$file;
1798 if (isset($file->filename)) {
1799 $filename = $file->filename;
1800 } else if (method_exists($file, 'get_filename')) {
1801 $filename = $file->get_filename();
1802 } else if (method_exists($file, 'get_visible_name')) {
1803 $filename = $file->get_visible_name();
1804 } else {
1805 $filename = '';
1807 if (isset($file->mimetype)) {
1808 $mimetype = $file->mimetype;
1809 } else if (method_exists($file, 'get_mimetype')) {
1810 $mimetype = $file->get_mimetype();
1811 } else {
1812 $mimetype = '';
1814 $mimetypes = &get_mimetypes_array();
1815 if ($filename) {
1816 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1817 if ($extension && !empty($mimetypes[$extension])) {
1818 // if file name has known extension, return icon for this extension
1819 return file_extension_icon($filename, $size);
1822 return file_mimetype_icon($mimetype, $size);
1826 * Return the relative icon path for a folder image
1828 * Usage:
1829 * <code>
1830 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1831 * echo html_writer::empty_tag('img', array('src' => $icon));
1832 * </code>
1833 * or
1834 * <code>
1835 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1836 * </code>
1838 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1839 * @return string
1841 function file_folder_icon($iconsize = null) {
1842 global $CFG;
1843 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1844 static $cached = array();
1845 $iconsize = max(array(16, (int)$iconsize));
1846 if (!array_key_exists($iconsize, $cached)) {
1847 foreach ($iconpostfixes as $size => $postfix) {
1848 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1849 if ($iconsize >= $size &&
1850 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1851 $cached[$iconsize] = 'f/folder'.$postfix;
1852 break;
1856 return $cached[$iconsize];
1860 * Returns the relative icon path for a given mime type
1862 * This function should be used in conjunction with $OUTPUT->image_url to produce
1863 * a return the full path to an icon.
1865 * <code>
1866 * $mimetype = 'image/jpg';
1867 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1868 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1869 * </code>
1871 * @category files
1872 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1873 * to conform with that.
1874 * @param string $mimetype The mimetype to fetch an icon for
1875 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1876 * @return string The relative path to the icon
1878 function file_mimetype_icon($mimetype, $size = NULL) {
1879 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1883 * Returns the relative icon path for a given file name
1885 * This function should be used in conjunction with $OUTPUT->image_url to produce
1886 * a return the full path to an icon.
1888 * <code>
1889 * $filename = '.jpg';
1890 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1891 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1892 * </code>
1894 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1895 * to conform with that.
1896 * @todo MDL-31074 Implement $size
1897 * @category files
1898 * @param string $filename The filename to get the icon for
1899 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1900 * @return string
1902 function file_extension_icon($filename, $size = NULL) {
1903 return 'f/'.mimeinfo('icon'.$size, $filename);
1907 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1908 * mimetypes.php language file.
1910 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1911 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1912 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1913 * @param bool $capitalise If true, capitalises first character of result
1914 * @return string Text description
1916 function get_mimetype_description($obj, $capitalise=false) {
1917 $filename = $mimetype = '';
1918 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1919 // this is an instance of stored_file
1920 $mimetype = $obj->get_mimetype();
1921 $filename = $obj->get_filename();
1922 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1923 // this is an instance of file_info
1924 $mimetype = $obj->get_mimetype();
1925 $filename = $obj->get_visible_name();
1926 } else if (is_array($obj) || is_object ($obj)) {
1927 $obj = (array)$obj;
1928 if (!empty($obj['filename'])) {
1929 $filename = $obj['filename'];
1931 if (!empty($obj['mimetype'])) {
1932 $mimetype = $obj['mimetype'];
1934 } else {
1935 $mimetype = $obj;
1937 $mimetypefromext = mimeinfo('type', $filename);
1938 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1939 // if file has a known extension, overwrite the specified mimetype
1940 $mimetype = $mimetypefromext;
1942 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1943 if (empty($extension)) {
1944 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1945 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1946 } else {
1947 $mimetypestr = mimeinfo('string', $filename);
1949 $chunks = explode('/', $mimetype, 2);
1950 $chunks[] = '';
1951 $attr = array(
1952 'mimetype' => $mimetype,
1953 'ext' => $extension,
1954 'mimetype1' => $chunks[0],
1955 'mimetype2' => $chunks[1],
1957 $a = array();
1958 foreach ($attr as $key => $value) {
1959 $a[$key] = $value;
1960 $a[strtoupper($key)] = strtoupper($value);
1961 $a[ucfirst($key)] = ucfirst($value);
1964 // MIME types may include + symbol but this is not permitted in string ids.
1965 $safemimetype = str_replace('+', '_', $mimetype);
1966 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1967 $customdescription = mimeinfo('customdescription', $filename);
1968 if ($customdescription) {
1969 // Call format_string on the custom description so that multilang
1970 // filter can be used (if enabled on system context). We use system
1971 // context because it is possible that the page context might not have
1972 // been defined yet.
1973 $result = format_string($customdescription, true,
1974 array('context' => context_system::instance()));
1975 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1976 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1977 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1978 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1979 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1980 $result = get_string('default', 'mimetypes', (object)$a);
1981 } else {
1982 $result = $mimetype;
1984 if ($capitalise) {
1985 $result=ucfirst($result);
1987 return $result;
1991 * Returns array of elements of type $element in type group(s)
1993 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1994 * @param string|array $groups one group or array of groups/extensions/mimetypes
1995 * @return array
1997 function file_get_typegroup($element, $groups) {
1998 static $cached = array();
1999 if (!is_array($groups)) {
2000 $groups = array($groups);
2002 if (!array_key_exists($element, $cached)) {
2003 $cached[$element] = array();
2005 $result = array();
2006 foreach ($groups as $group) {
2007 if (!array_key_exists($group, $cached[$element])) {
2008 // retrieive and cache all elements of type $element for group $group
2009 $mimeinfo = & get_mimetypes_array();
2010 $cached[$element][$group] = array();
2011 foreach ($mimeinfo as $extension => $value) {
2012 $value['extension'] = '.'.$extension;
2013 if (empty($value[$element])) {
2014 continue;
2016 if (($group === '.'.$extension || $group === $value['type'] ||
2017 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
2018 !in_array($value[$element], $cached[$element][$group])) {
2019 $cached[$element][$group][] = $value[$element];
2023 $result = array_merge($result, $cached[$element][$group]);
2025 return array_values(array_unique($result));
2029 * Checks if file with name $filename has one of the extensions in groups $groups
2031 * @see get_mimetypes_array()
2032 * @param string $filename name of the file to check
2033 * @param string|array $groups one group or array of groups to check
2034 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2035 * file mimetype is in mimetypes in groups $groups
2036 * @return bool
2038 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2039 $extension = pathinfo($filename, PATHINFO_EXTENSION);
2040 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2041 return true;
2043 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2047 * Checks if mimetype $mimetype belongs to one of the groups $groups
2049 * @see get_mimetypes_array()
2050 * @param string $mimetype
2051 * @param string|array $groups one group or array of groups to check
2052 * @return bool
2054 function file_mimetype_in_typegroup($mimetype, $groups) {
2055 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2059 * Requested file is not found or not accessible, does not return, terminates script
2061 * @global stdClass $CFG
2062 * @global stdClass $COURSE
2064 function send_file_not_found() {
2065 global $CFG, $COURSE;
2067 // Allow cross-origin requests only for Web Services.
2068 // This allow to receive requests done by Web Workers or webapps in different domains.
2069 if (WS_SERVER) {
2070 header('Access-Control-Allow-Origin: *');
2073 send_header_404();
2074 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
2077 * Helper function to send correct 404 for server.
2079 function send_header_404() {
2080 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2081 header("Status: 404 Not Found");
2082 } else {
2083 header('HTTP/1.0 404 not found');
2088 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2089 * platforms). This wrapper uses readfile for small files and custom code for
2090 * large ones.
2092 * @param string $path Path to file
2093 * @param int $filesize Size of file (if left out, will get it automatically)
2094 * @return int|bool Size read (will always be $filesize) or false if failed
2096 function readfile_allow_large($path, $filesize = -1) {
2097 // Automatically get size if not specified.
2098 if ($filesize === -1) {
2099 $filesize = filesize($path);
2101 if ($filesize <= 2147483647) {
2102 // If the file is up to 2^31 - 1, send it normally using readfile.
2103 return readfile($path);
2104 } else {
2105 // For large files, read and output in 64KB chunks.
2106 $handle = fopen($path, 'r');
2107 if ($handle === false) {
2108 return false;
2110 $left = $filesize;
2111 while ($left > 0) {
2112 $size = min($left, 65536);
2113 $buffer = fread($handle, $size);
2114 if ($buffer === false) {
2115 return false;
2117 echo $buffer;
2118 $left -= $size;
2120 return $filesize;
2125 * Enhanced readfile() with optional acceleration.
2126 * @param string|stored_file $file
2127 * @param string $mimetype
2128 * @param bool $accelerate
2129 * @return void
2131 function readfile_accel($file, $mimetype, $accelerate) {
2132 global $CFG;
2134 if ($mimetype === 'text/plain') {
2135 // there is no encoding specified in text files, we need something consistent
2136 header('Content-Type: text/plain; charset=utf-8');
2137 } else {
2138 header('Content-Type: '.$mimetype);
2141 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2142 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2144 if (is_object($file)) {
2145 header('Etag: "' . $file->get_contenthash() . '"');
2146 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2147 header('HTTP/1.1 304 Not Modified');
2148 return;
2152 // if etag present for stored file rely on it exclusively
2153 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2154 // get unixtime of request header; clip extra junk off first
2155 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2156 if ($since && $since >= $lastmodified) {
2157 header('HTTP/1.1 304 Not Modified');
2158 return;
2162 if ($accelerate and !empty($CFG->xsendfile)) {
2163 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2164 header('Accept-Ranges: bytes');
2165 } else {
2166 header('Accept-Ranges: none');
2169 if (is_object($file)) {
2170 $fs = get_file_storage();
2171 if ($fs->xsendfile($file->get_contenthash())) {
2172 return;
2175 } else {
2176 require_once("$CFG->libdir/xsendfilelib.php");
2177 if (xsendfile($file)) {
2178 return;
2183 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2185 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2187 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2188 header('Accept-Ranges: bytes');
2190 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2191 // byteserving stuff - for acrobat reader and download accelerators
2192 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2193 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2194 $ranges = false;
2195 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2196 foreach ($ranges as $key=>$value) {
2197 if ($ranges[$key][1] == '') {
2198 //suffix case
2199 $ranges[$key][1] = $filesize - $ranges[$key][2];
2200 $ranges[$key][2] = $filesize - 1;
2201 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2202 //fix range length
2203 $ranges[$key][2] = $filesize - 1;
2205 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2206 //invalid byte-range ==> ignore header
2207 $ranges = false;
2208 break;
2210 //prepare multipart header
2211 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2212 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2214 } else {
2215 $ranges = false;
2217 if ($ranges) {
2218 if (is_object($file)) {
2219 $handle = $file->get_content_file_handle();
2220 } else {
2221 $handle = fopen($file, 'rb');
2223 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2226 } else {
2227 // Do not byteserve
2228 header('Accept-Ranges: none');
2231 header('Content-Length: '.$filesize);
2233 if ($filesize > 10000000) {
2234 // for large files try to flush and close all buffers to conserve memory
2235 while(@ob_get_level()) {
2236 if (!@ob_end_flush()) {
2237 break;
2242 // send the whole file content
2243 if (is_object($file)) {
2244 $file->readfile();
2245 } else {
2246 readfile_allow_large($file, $filesize);
2251 * Similar to readfile_accel() but designed for strings.
2252 * @param string $string
2253 * @param string $mimetype
2254 * @param bool $accelerate
2255 * @return void
2257 function readstring_accel($string, $mimetype, $accelerate) {
2258 global $CFG;
2260 if ($mimetype === 'text/plain') {
2261 // there is no encoding specified in text files, we need something consistent
2262 header('Content-Type: text/plain; charset=utf-8');
2263 } else {
2264 header('Content-Type: '.$mimetype);
2266 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2267 header('Accept-Ranges: none');
2269 if ($accelerate and !empty($CFG->xsendfile)) {
2270 $fs = get_file_storage();
2271 if ($fs->xsendfile(sha1($string))) {
2272 return;
2276 header('Content-Length: '.strlen($string));
2277 echo $string;
2281 * Handles the sending of temporary file to user, download is forced.
2282 * File is deleted after abort or successful sending, does not return, script terminated
2284 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2285 * @param string $filename proposed file name when saving file
2286 * @param bool $pathisstring If the path is string
2288 function send_temp_file($path, $filename, $pathisstring=false) {
2289 global $CFG;
2291 // Guess the file's MIME type.
2292 $mimetype = get_mimetype_for_sending($filename);
2294 // close session - not needed anymore
2295 \core\session\manager::write_close();
2297 if (!$pathisstring) {
2298 if (!file_exists($path)) {
2299 send_header_404();
2300 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2302 // executed after normal finish or abort
2303 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2306 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2307 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2308 $filename = urlencode($filename);
2311 header('Content-Disposition: attachment; filename="'.$filename.'"');
2312 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2313 header('Cache-Control: private, max-age=10, no-transform');
2314 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2315 header('Pragma: ');
2316 } else { //normal http - prevent caching at all cost
2317 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2318 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2319 header('Pragma: no-cache');
2322 // send the contents - we can not accelerate this because the file will be deleted asap
2323 if ($pathisstring) {
2324 readstring_accel($path, $mimetype, false);
2325 } else {
2326 readfile_accel($path, $mimetype, false);
2327 @unlink($path);
2330 die; //no more chars to output
2334 * Internal callback function used by send_temp_file()
2336 * @param string $path
2338 function send_temp_file_finished($path) {
2339 if (file_exists($path)) {
2340 @unlink($path);
2345 * Serve content which is not meant to be cached.
2347 * This is only intended to be used for volatile public files, for instance
2348 * when development is enabled, or when caching is not required on a public resource.
2350 * @param string $content Raw content.
2351 * @param string $filename The file name.
2352 * @return void
2354 function send_content_uncached($content, $filename) {
2355 $mimetype = mimeinfo('type', $filename);
2356 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2358 header('Content-Disposition: inline; filename="' . $filename . '"');
2359 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2360 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2361 header('Pragma: ');
2362 header('Accept-Ranges: none');
2363 header('Content-Type: ' . $mimetype . $charset);
2364 header('Content-Length: ' . strlen($content));
2366 echo $content;
2367 die();
2371 * Safely save content to a certain path.
2373 * This function tries hard to be atomic by first copying the content
2374 * to a separate file, and then moving the file across. It also prevents
2375 * the user to abort a request to prevent half-safed files.
2377 * This function is intended to be used when saving some content to cache like
2378 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2380 * @param string $content The file content.
2381 * @param string $destination The absolute path of the final file.
2382 * @return void
2384 function file_safe_save_content($content, $destination) {
2385 global $CFG;
2387 clearstatcache();
2388 if (!file_exists(dirname($destination))) {
2389 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2392 // Prevent serving of incomplete file from concurrent request,
2393 // the rename() should be more atomic than fwrite().
2394 ignore_user_abort(true);
2395 if ($fp = fopen($destination . '.tmp', 'xb')) {
2396 fwrite($fp, $content);
2397 fclose($fp);
2398 rename($destination . '.tmp', $destination);
2399 @chmod($destination, $CFG->filepermissions);
2400 @unlink($destination . '.tmp'); // Just in case anything fails.
2402 ignore_user_abort(false);
2403 if (connection_aborted()) {
2404 die();
2409 * Handles the sending of file data to the user's browser, including support for
2410 * byteranges etc.
2412 * @category files
2413 * @param string|stored_file $path Path of file on disk (including real filename),
2414 * or actual content of file as string,
2415 * or stored_file object
2416 * @param string $filename Filename to send
2417 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2418 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2419 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2420 * Forced to false when $path is a stored_file object.
2421 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2422 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2423 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2424 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2425 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2426 * and should not be reopened.
2427 * @param array $options An array of options, currently accepts:
2428 * - (string) cacheability: public, or private.
2429 * - (string|null) immutable
2430 * @return null script execution stopped unless $dontdie is true
2432 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2433 $dontdie=false, array $options = array()) {
2434 global $CFG, $COURSE;
2436 if ($dontdie) {
2437 ignore_user_abort(true);
2440 if ($lifetime === 'default' or is_null($lifetime)) {
2441 $lifetime = $CFG->filelifetime;
2444 if (is_object($path)) {
2445 $pathisstring = false;
2448 \core\session\manager::write_close(); // Unlock session during file serving.
2450 // Use given MIME type if specified, otherwise guess it.
2451 if (!$mimetype || $mimetype === 'document/unknown') {
2452 $mimetype = get_mimetype_for_sending($filename);
2455 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2456 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2457 $filename = rawurlencode($filename);
2460 if ($forcedownload) {
2461 header('Content-Disposition: attachment; filename="'.$filename.'"');
2462 } else if ($mimetype !== 'application/x-shockwave-flash') {
2463 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2464 // as an upload and enforces security that may prevent the file from being loaded.
2466 header('Content-Disposition: inline; filename="'.$filename.'"');
2469 if ($lifetime > 0) {
2470 $immutable = '';
2471 if (!empty($options['immutable'])) {
2472 $immutable = ', immutable';
2473 // Overwrite lifetime accordingly:
2474 // 90 days only - based on Moodle point release cadence being every 3 months.
2475 $lifetimemin = 60 * 60 * 24 * 90;
2476 $lifetime = max($lifetime, $lifetimemin);
2478 $cacheability = ' public,';
2479 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2480 // This file must be cache-able by both browsers and proxies.
2481 $cacheability = ' public,';
2482 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2483 // This file must be cache-able only by browsers.
2484 $cacheability = ' private,';
2485 } else if (isloggedin() and !isguestuser()) {
2486 // By default, under the conditions above, this file must be cache-able only by browsers.
2487 $cacheability = ' private,';
2489 $nobyteserving = false;
2490 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2491 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2492 header('Pragma: ');
2494 } else { // Do not cache files in proxies and browsers
2495 $nobyteserving = true;
2496 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2497 header('Cache-Control: private, max-age=10, no-transform');
2498 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2499 header('Pragma: ');
2500 } else { //normal http - prevent caching at all cost
2501 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2502 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2503 header('Pragma: no-cache');
2507 if (empty($filter)) {
2508 // send the contents
2509 if ($pathisstring) {
2510 readstring_accel($path, $mimetype, !$dontdie);
2511 } else {
2512 readfile_accel($path, $mimetype, !$dontdie);
2515 } else {
2516 // Try to put the file through filters
2517 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2518 $options = new stdClass();
2519 $options->noclean = true;
2520 $options->nocache = true; // temporary workaround for MDL-5136
2521 if (is_object($path)) {
2522 $text = $path->get_content();
2523 } else if ($pathisstring) {
2524 $text = $path;
2525 } else {
2526 $text = implode('', file($path));
2528 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2530 readstring_accel($output, $mimetype, false);
2532 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2533 // only filter text if filter all files is selected
2534 $options = new stdClass();
2535 $options->newlines = false;
2536 $options->noclean = true;
2537 if (is_object($path)) {
2538 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2539 } else if ($pathisstring) {
2540 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2541 } else {
2542 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2544 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2546 readstring_accel($output, $mimetype, false);
2548 } else {
2549 // send the contents
2550 if ($pathisstring) {
2551 readstring_accel($path, $mimetype, !$dontdie);
2552 } else {
2553 readfile_accel($path, $mimetype, !$dontdie);
2557 if ($dontdie) {
2558 return;
2560 die; //no more chars to output!!!
2564 * Handles the sending of file data to the user's browser, including support for
2565 * byteranges etc.
2567 * The $options parameter supports the following keys:
2568 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2569 * (string|null) filename - overrides the implicit filename
2570 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2571 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2572 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2573 * and should not be reopened
2574 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2575 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2576 * defaults to "public".
2577 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2578 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2580 * @category files
2581 * @param stored_file $stored_file local file object
2582 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2583 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2584 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2585 * @param array $options additional options affecting the file serving
2586 * @return null script execution stopped unless $options['dontdie'] is true
2588 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2589 global $CFG, $COURSE;
2591 if (empty($options['filename'])) {
2592 $filename = null;
2593 } else {
2594 $filename = $options['filename'];
2597 if (empty($options['dontdie'])) {
2598 $dontdie = false;
2599 } else {
2600 $dontdie = true;
2603 if ($lifetime === 'default' or is_null($lifetime)) {
2604 $lifetime = $CFG->filelifetime;
2607 if (!empty($options['preview'])) {
2608 // replace the file with its preview
2609 $fs = get_file_storage();
2610 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2611 if (!$preview_file) {
2612 // unable to create a preview of the file, send its default mime icon instead
2613 if ($options['preview'] === 'tinyicon') {
2614 $size = 24;
2615 } else if ($options['preview'] === 'thumb') {
2616 $size = 90;
2617 } else {
2618 $size = 256;
2620 $fileicon = file_file_icon($stored_file, $size);
2621 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2622 } else {
2623 // preview images have fixed cache lifetime and they ignore forced download
2624 // (they are generated by GD and therefore they are considered reasonably safe).
2625 $stored_file = $preview_file;
2626 $lifetime = DAYSECS;
2627 $filter = 0;
2628 $forcedownload = false;
2632 // handle external resource
2633 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2634 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2635 die;
2638 if (!$stored_file or $stored_file->is_directory()) {
2639 // nothing to serve
2640 if ($dontdie) {
2641 return;
2643 die;
2646 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2648 // Use given MIME type if specified.
2649 $mimetype = $stored_file->get_mimetype();
2651 // Allow cross-origin requests only for Web Services.
2652 // This allow to receive requests done by Web Workers or webapps in different domains.
2653 if (WS_SERVER) {
2654 header('Access-Control-Allow-Origin: *');
2657 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2661 * Recursively delete the file or folder with path $location. That is,
2662 * if it is a file delete it. If it is a folder, delete all its content
2663 * then delete it. If $location does not exist to start, that is not
2664 * considered an error.
2666 * @param string $location the path to remove.
2667 * @return bool
2669 function fulldelete($location) {
2670 if (empty($location)) {
2671 // extra safety against wrong param
2672 return false;
2674 if (is_dir($location)) {
2675 if (!$currdir = opendir($location)) {
2676 return false;
2678 while (false !== ($file = readdir($currdir))) {
2679 if ($file <> ".." && $file <> ".") {
2680 $fullfile = $location."/".$file;
2681 if (is_dir($fullfile)) {
2682 if (!fulldelete($fullfile)) {
2683 return false;
2685 } else {
2686 if (!unlink($fullfile)) {
2687 return false;
2692 closedir($currdir);
2693 if (! rmdir($location)) {
2694 return false;
2697 } else if (file_exists($location)) {
2698 if (!unlink($location)) {
2699 return false;
2702 return true;
2706 * Send requested byterange of file.
2708 * @param resource $handle A file handle
2709 * @param string $mimetype The mimetype for the output
2710 * @param array $ranges An array of ranges to send
2711 * @param string $filesize The size of the content if only one range is used
2713 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2714 // better turn off any kind of compression and buffering
2715 ini_set('zlib.output_compression', 'Off');
2717 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2718 if ($handle === false) {
2719 die;
2721 if (count($ranges) == 1) { //only one range requested
2722 $length = $ranges[0][2] - $ranges[0][1] + 1;
2723 header('HTTP/1.1 206 Partial content');
2724 header('Content-Length: '.$length);
2725 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2726 header('Content-Type: '.$mimetype);
2728 while(@ob_get_level()) {
2729 if (!@ob_end_flush()) {
2730 break;
2734 fseek($handle, $ranges[0][1]);
2735 while (!feof($handle) && $length > 0) {
2736 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2737 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2738 echo $buffer;
2739 flush();
2740 $length -= strlen($buffer);
2742 fclose($handle);
2743 die;
2744 } else { // multiple ranges requested - not tested much
2745 $totallength = 0;
2746 foreach($ranges as $range) {
2747 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2749 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2750 header('HTTP/1.1 206 Partial content');
2751 header('Content-Length: '.$totallength);
2752 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2754 while(@ob_get_level()) {
2755 if (!@ob_end_flush()) {
2756 break;
2760 foreach($ranges as $range) {
2761 $length = $range[2] - $range[1] + 1;
2762 echo $range[0];
2763 fseek($handle, $range[1]);
2764 while (!feof($handle) && $length > 0) {
2765 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2766 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2767 echo $buffer;
2768 flush();
2769 $length -= strlen($buffer);
2772 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2773 fclose($handle);
2774 die;
2779 * Tells whether the filename is executable.
2781 * @link http://php.net/manual/en/function.is-executable.php
2782 * @link https://bugs.php.net/bug.php?id=41062
2783 * @param string $filename Path to the file.
2784 * @return bool True if the filename exists and is executable; otherwise, false.
2786 function file_is_executable($filename) {
2787 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2788 if (is_executable($filename)) {
2789 return true;
2790 } else {
2791 $fileext = strrchr($filename, '.');
2792 // If we have an extension we can check if it is listed as executable.
2793 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2794 $winpathext = strtolower(getenv('PATHEXT'));
2795 $winpathexts = explode(';', $winpathext);
2797 return in_array(strtolower($fileext), $winpathexts);
2800 return false;
2802 } else {
2803 return is_executable($filename);
2808 * Overwrite an existing file in a draft area.
2810 * @param stored_file $newfile the new file with the new content and meta-data
2811 * @param stored_file $existingfile the file that will be overwritten
2812 * @throws moodle_exception
2813 * @since Moodle 3.2
2815 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2816 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2817 throw new coding_exception('The file to overwrite is not in a draft area.');
2820 $fs = get_file_storage();
2821 // Remember original file source field.
2822 $source = @unserialize($existingfile->get_source());
2823 // Remember the original sortorder.
2824 $sortorder = $existingfile->get_sortorder();
2825 if ($newfile->is_external_file()) {
2826 // New file is a reference. Check that existing file does not have any other files referencing to it
2827 if (isset($source->original) && $fs->search_references_count($source->original)) {
2828 throw new moodle_exception('errordoublereference', 'repository');
2832 // Delete existing file to release filename.
2833 $newfilerecord = array(
2834 'contextid' => $existingfile->get_contextid(),
2835 'component' => 'user',
2836 'filearea' => 'draft',
2837 'itemid' => $existingfile->get_itemid(),
2838 'timemodified' => time()
2840 $existingfile->delete();
2842 // Create new file.
2843 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2844 // Preserve original file location (stored in source field) for handling references.
2845 if (isset($source->original)) {
2846 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2847 $newfilesource = new stdClass();
2849 $newfilesource->original = $source->original;
2850 $newfile->set_source(serialize($newfilesource));
2852 $newfile->set_sortorder($sortorder);
2856 * Add files from a draft area into a final area.
2858 * Most of the time you do not want to use this. It is intended to be used
2859 * by asynchronous services which cannot direcly manipulate a final
2860 * area through a draft area. Instead they add files to a new draft
2861 * area and merge that new draft into the final area when ready.
2863 * @param int $draftitemid the id of the draft area to use.
2864 * @param int $contextid this parameter and the next two identify the file area to save to.
2865 * @param string $component component name
2866 * @param string $filearea indentifies the file area
2867 * @param int $itemid identifies the item id or false for all items in the file area
2868 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2869 * @see file_save_draft_area_files
2870 * @since Moodle 3.2
2872 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2873 array $options = null) {
2874 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2875 $finaldraftid = 0;
2876 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2877 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2878 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2882 * Merge files from two draftarea areas.
2884 * This does not handle conflict resolution, files in the destination area which appear
2885 * to be more recent will be kept disregarding the intended ones.
2887 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2888 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2889 * @throws coding_exception
2890 * @since Moodle 3.2
2892 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2893 global $USER;
2895 $fs = get_file_storage();
2896 $contextid = context_user::instance($USER->id)->id;
2898 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2899 throw new coding_exception('Nothing to merge or area does not belong to current user');
2902 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2904 // Get hashes of the files to merge.
2905 $newhashes = array();
2906 foreach ($filestomerge as $filetomerge) {
2907 $filepath = $filetomerge->get_filepath();
2908 $filename = $filetomerge->get_filename();
2910 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2911 $newhashes[$newhash] = $filetomerge;
2914 // Calculate wich files must be added.
2915 foreach ($currentfiles as $file) {
2916 $filehash = $file->get_pathnamehash();
2917 // One file to be merged already exists.
2918 if (isset($newhashes[$filehash])) {
2919 $updatedfile = $newhashes[$filehash];
2921 // Avoid race conditions.
2922 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2923 // The existing file is more recent, do not copy the suposedly "new" one.
2924 unset($newhashes[$filehash]);
2925 continue;
2927 // Update existing file (not only content, meta-data too).
2928 file_overwrite_existing_draftfile($updatedfile, $file);
2929 unset($newhashes[$filehash]);
2933 foreach ($newhashes as $newfile) {
2934 $newfilerecord = array(
2935 'contextid' => $contextid,
2936 'component' => 'user',
2937 'filearea' => 'draft',
2938 'itemid' => $mergeintodraftid,
2939 'timemodified' => time()
2942 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2947 * RESTful cURL class
2949 * This is a wrapper class for curl, it is quite easy to use:
2950 * <code>
2951 * $c = new curl;
2952 * // enable cache
2953 * $c = new curl(array('cache'=>true));
2954 * // enable cookie
2955 * $c = new curl(array('cookie'=>true));
2956 * // enable proxy
2957 * $c = new curl(array('proxy'=>true));
2959 * // HTTP GET Method
2960 * $html = $c->get('http://example.com');
2961 * // HTTP POST Method
2962 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2963 * // HTTP PUT Method
2964 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2965 * </code>
2967 * @package core_files
2968 * @category files
2969 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2970 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2972 class curl {
2973 /** @var bool Caches http request contents */
2974 public $cache = false;
2975 /** @var bool Uses proxy, null means automatic based on URL */
2976 public $proxy = null;
2977 /** @var string library version */
2978 public $version = '0.4 dev';
2979 /** @var array http's response */
2980 public $response = array();
2981 /** @var array Raw response headers, needed for BC in download_file_content(). */
2982 public $rawresponse = array();
2983 /** @var array http header */
2984 public $header = array();
2985 /** @var string cURL information */
2986 public $info;
2987 /** @var string error */
2988 public $error;
2989 /** @var int error code */
2990 public $errno;
2991 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2992 public $emulateredirects = null;
2994 /** @var array cURL options */
2995 private $options;
2997 /** @var string Proxy host */
2998 private $proxy_host = '';
2999 /** @var string Proxy auth */
3000 private $proxy_auth = '';
3001 /** @var string Proxy type */
3002 private $proxy_type = '';
3003 /** @var bool Debug mode on */
3004 private $debug = false;
3005 /** @var bool|string Path to cookie file */
3006 private $cookie = false;
3007 /** @var bool tracks multiple headers in response - redirect detection */
3008 private $responsefinished = false;
3009 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
3010 private $securityhelper;
3011 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
3012 private $ignoresecurity;
3013 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
3014 private static $mockresponses = [];
3017 * Curl constructor.
3019 * Allowed settings are:
3020 * proxy: (bool) use proxy server, null means autodetect non-local from url
3021 * debug: (bool) use debug output
3022 * cookie: (string) path to cookie file, false if none
3023 * cache: (bool) use cache
3024 * module_cache: (string) type of cache
3025 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3026 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3028 * @param array $settings
3030 public function __construct($settings = array()) {
3031 global $CFG;
3032 if (!function_exists('curl_init')) {
3033 $this->error = 'cURL module must be enabled!';
3034 trigger_error($this->error, E_USER_ERROR);
3035 return false;
3038 // All settings of this class should be init here.
3039 $this->resetopt();
3040 if (!empty($settings['debug'])) {
3041 $this->debug = true;
3043 if (!empty($settings['cookie'])) {
3044 if($settings['cookie'] === true) {
3045 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3046 } else {
3047 $this->cookie = $settings['cookie'];
3050 if (!empty($settings['cache'])) {
3051 if (class_exists('curl_cache')) {
3052 if (!empty($settings['module_cache'])) {
3053 $this->cache = new curl_cache($settings['module_cache']);
3054 } else {
3055 $this->cache = new curl_cache('misc');
3059 if (!empty($CFG->proxyhost)) {
3060 if (empty($CFG->proxyport)) {
3061 $this->proxy_host = $CFG->proxyhost;
3062 } else {
3063 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3065 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3066 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3067 $this->setopt(array(
3068 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3069 'proxyuserpwd'=>$this->proxy_auth));
3071 if (!empty($CFG->proxytype)) {
3072 if ($CFG->proxytype == 'SOCKS5') {
3073 $this->proxy_type = CURLPROXY_SOCKS5;
3074 } else {
3075 $this->proxy_type = CURLPROXY_HTTP;
3076 $this->setopt(array('httpproxytunnel'=>false));
3078 $this->setopt(array('proxytype'=>$this->proxy_type));
3081 if (isset($settings['proxy'])) {
3082 $this->proxy = $settings['proxy'];
3084 } else {
3085 $this->proxy = false;
3088 if (!isset($this->emulateredirects)) {
3089 $this->emulateredirects = ini_get('open_basedir');
3092 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3093 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3094 $this->set_security($settings['securityhelper']);
3095 } else {
3096 $this->set_security(new \core\files\curl_security_helper());
3098 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3102 * Resets the CURL options that have already been set
3104 public function resetopt() {
3105 $this->options = array();
3106 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
3107 // True to include the header in the output
3108 $this->options['CURLOPT_HEADER'] = 0;
3109 // True to Exclude the body from the output
3110 $this->options['CURLOPT_NOBODY'] = 0;
3111 // Redirect ny default.
3112 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
3113 $this->options['CURLOPT_MAXREDIRS'] = 10;
3114 $this->options['CURLOPT_ENCODING'] = '';
3115 // TRUE to return the transfer as a string of the return
3116 // value of curl_exec() instead of outputting it out directly.
3117 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
3118 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
3119 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
3120 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
3122 if ($cacert = self::get_cacert()) {
3123 $this->options['CURLOPT_CAINFO'] = $cacert;
3128 * Get the location of ca certificates.
3129 * @return string absolute file path or empty if default used
3131 public static function get_cacert() {
3132 global $CFG;
3134 // Bundle in dataroot always wins.
3135 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3136 return realpath("$CFG->dataroot/moodleorgca.crt");
3139 // Next comes the default from php.ini
3140 $cacert = ini_get('curl.cainfo');
3141 if (!empty($cacert) and is_readable($cacert)) {
3142 return realpath($cacert);
3145 // Windows PHP does not have any certs, we need to use something.
3146 if ($CFG->ostype === 'WINDOWS') {
3147 if (is_readable("$CFG->libdir/cacert.pem")) {
3148 return realpath("$CFG->libdir/cacert.pem");
3152 // Use default, this should work fine on all properly configured *nix systems.
3153 return null;
3157 * Reset Cookie
3159 public function resetcookie() {
3160 if (!empty($this->cookie)) {
3161 if (is_file($this->cookie)) {
3162 $fp = fopen($this->cookie, 'w');
3163 if (!empty($fp)) {
3164 fwrite($fp, '');
3165 fclose($fp);
3172 * Set curl options.
3174 * Do not use the curl constants to define the options, pass a string
3175 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3176 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3178 * @param array $options If array is null, this function will reset the options to default value.
3179 * @return void
3180 * @throws coding_exception If an option uses constant value instead of option name.
3182 public function setopt($options = array()) {
3183 if (is_array($options)) {
3184 foreach ($options as $name => $val) {
3185 if (!is_string($name)) {
3186 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3188 if (stripos($name, 'CURLOPT_') === false) {
3189 $name = strtoupper('CURLOPT_'.$name);
3190 } else {
3191 $name = strtoupper($name);
3193 $this->options[$name] = $val;
3199 * Reset http method
3201 public function cleanopt() {
3202 unset($this->options['CURLOPT_HTTPGET']);
3203 unset($this->options['CURLOPT_POST']);
3204 unset($this->options['CURLOPT_POSTFIELDS']);
3205 unset($this->options['CURLOPT_PUT']);
3206 unset($this->options['CURLOPT_INFILE']);
3207 unset($this->options['CURLOPT_INFILESIZE']);
3208 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3209 unset($this->options['CURLOPT_FILE']);
3213 * Resets the HTTP Request headers (to prepare for the new request)
3215 public function resetHeader() {
3216 $this->header = array();
3220 * Set HTTP Request Header
3222 * @param array $header
3224 public function setHeader($header) {
3225 if (is_array($header)) {
3226 foreach ($header as $v) {
3227 $this->setHeader($v);
3229 } else {
3230 // Remove newlines, they are not allowed in headers.
3231 $newvalue = preg_replace('/[\r\n]/', '', $header);
3232 if (!in_array($newvalue, $this->header)) {
3233 $this->header[] = $newvalue;
3239 * Get HTTP Response Headers
3240 * @return array of arrays
3242 public function getResponse() {
3243 return $this->response;
3247 * Get raw HTTP Response Headers
3248 * @return array of strings
3250 public function get_raw_response() {
3251 return $this->rawresponse;
3255 * private callback function
3256 * Formatting HTTP Response Header
3258 * We only keep the last headers returned. For example during a redirect the
3259 * redirect headers will not appear in {@link self::getResponse()}, if you need
3260 * to use those headers, refer to {@link self::get_raw_response()}.
3262 * @param resource $ch Apparently not used
3263 * @param string $header
3264 * @return int The strlen of the header
3266 private function formatHeader($ch, $header) {
3267 $this->rawresponse[] = $header;
3269 if (trim($header, "\r\n") === '') {
3270 // This must be the last header.
3271 $this->responsefinished = true;
3274 if (strlen($header) > 2) {
3275 if ($this->responsefinished) {
3276 // We still have headers after the supposedly last header, we must be
3277 // in a redirect so let's empty the response to keep the last headers.
3278 $this->responsefinished = false;
3279 $this->response = array();
3281 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3282 $key = rtrim($parts[0], ':');
3283 $value = isset($parts[1]) ? $parts[1] : null;
3284 if (!empty($this->response[$key])) {
3285 if (is_array($this->response[$key])) {
3286 $this->response[$key][] = $value;
3287 } else {
3288 $tmp = $this->response[$key];
3289 $this->response[$key] = array();
3290 $this->response[$key][] = $tmp;
3291 $this->response[$key][] = $value;
3294 } else {
3295 $this->response[$key] = $value;
3298 return strlen($header);
3302 * Set options for individual curl instance
3304 * @param resource $curl A curl handle
3305 * @param array $options
3306 * @return resource The curl handle
3308 private function apply_opt($curl, $options) {
3309 // Clean up
3310 $this->cleanopt();
3311 // set cookie
3312 if (!empty($this->cookie) || !empty($options['cookie'])) {
3313 $this->setopt(array('cookiejar'=>$this->cookie,
3314 'cookiefile'=>$this->cookie
3318 // Bypass proxy if required.
3319 if ($this->proxy === null) {
3320 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3321 $proxy = false;
3322 } else {
3323 $proxy = true;
3325 } else {
3326 $proxy = (bool)$this->proxy;
3329 // Set proxy.
3330 if ($proxy) {
3331 $options['CURLOPT_PROXY'] = $this->proxy_host;
3332 } else {
3333 unset($this->options['CURLOPT_PROXY']);
3336 $this->setopt($options);
3338 // Reset before set options.
3339 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3341 // Setting the User-Agent based on options provided.
3342 $useragent = '';
3344 if (!empty($options['CURLOPT_USERAGENT'])) {
3345 $useragent = $options['CURLOPT_USERAGENT'];
3346 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3347 $useragent = $this->options['CURLOPT_USERAGENT'];
3348 } else {
3349 $useragent = 'MoodleBot/1.0';
3352 // Set headers.
3353 if (empty($this->header)) {
3354 $this->setHeader(array(
3355 'User-Agent: ' . $useragent,
3356 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3357 'Connection: keep-alive'
3359 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3360 // Remove old User-Agent if one existed.
3361 // We have to partial search since we don't know what the original User-Agent is.
3362 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3363 $key = array_keys($match)[0];
3364 unset($this->header[$key]);
3366 $this->setHeader(array('User-Agent: ' . $useragent));
3368 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3370 if ($this->debug) {
3371 echo '<h1>Options</h1>';
3372 var_dump($this->options);
3373 echo '<h1>Header</h1>';
3374 var_dump($this->header);
3377 // Do not allow infinite redirects.
3378 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3379 $this->options['CURLOPT_MAXREDIRS'] = 0;
3380 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3381 $this->options['CURLOPT_MAXREDIRS'] = 100;
3382 } else {
3383 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3386 // Make sure we always know if redirects expected.
3387 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3388 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3391 // Limit the protocols to HTTP and HTTPS.
3392 if (defined('CURLOPT_PROTOCOLS')) {
3393 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3394 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3397 // Set options.
3398 foreach($this->options as $name => $val) {
3399 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3400 // The redirects are emulated elsewhere.
3401 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3402 continue;
3404 $name = constant($name);
3405 curl_setopt($curl, $name, $val);
3408 return $curl;
3412 * Download multiple files in parallel
3414 * Calls {@link multi()} with specific download headers
3416 * <code>
3417 * $c = new curl();
3418 * $file1 = fopen('a', 'wb');
3419 * $file2 = fopen('b', 'wb');
3420 * $c->download(array(
3421 * array('url'=>'http://localhost/', 'file'=>$file1),
3422 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3423 * ));
3424 * fclose($file1);
3425 * fclose($file2);
3426 * </code>
3428 * or
3430 * <code>
3431 * $c = new curl();
3432 * $c->download(array(
3433 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3434 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3435 * ));
3436 * </code>
3438 * @param array $requests An array of files to request {
3439 * url => url to download the file [required]
3440 * file => file handler, or
3441 * filepath => file path
3443 * If 'file' and 'filepath' parameters are both specified in one request, the
3444 * open file handle in the 'file' parameter will take precedence and 'filepath'
3445 * will be ignored.
3447 * @param array $options An array of options to set
3448 * @return array An array of results
3450 public function download($requests, $options = array()) {
3451 $options['RETURNTRANSFER'] = false;
3452 return $this->multi($requests, $options);
3456 * Returns the current curl security helper.
3458 * @return \core\files\curl_security_helper instance.
3460 public function get_security() {
3461 return $this->securityhelper;
3465 * Sets the curl security helper.
3467 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3468 * @return bool true if the security helper could be set, false otherwise.
3470 public function set_security($securityobject) {
3471 if ($securityobject instanceof \core\files\curl_security_helper) {
3472 $this->securityhelper = $securityobject;
3473 return true;
3475 return false;
3479 * Multi HTTP Requests
3480 * This function could run multi-requests in parallel.
3482 * @param array $requests An array of files to request
3483 * @param array $options An array of options to set
3484 * @return array An array of results
3486 protected function multi($requests, $options = array()) {
3487 $count = count($requests);
3488 $handles = array();
3489 $results = array();
3490 $main = curl_multi_init();
3491 for ($i = 0; $i < $count; $i++) {
3492 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3493 // open file
3494 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3495 $requests[$i]['auto-handle'] = true;
3497 foreach($requests[$i] as $n=>$v) {
3498 $options[$n] = $v;
3500 $handles[$i] = curl_init($requests[$i]['url']);
3501 $this->apply_opt($handles[$i], $options);
3502 curl_multi_add_handle($main, $handles[$i]);
3504 $running = 0;
3505 do {
3506 curl_multi_exec($main, $running);
3507 } while($running > 0);
3508 for ($i = 0; $i < $count; $i++) {
3509 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3510 $results[] = true;
3511 } else {
3512 $results[] = curl_multi_getcontent($handles[$i]);
3514 curl_multi_remove_handle($main, $handles[$i]);
3516 curl_multi_close($main);
3518 for ($i = 0; $i < $count; $i++) {
3519 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3520 // close file handler if file is opened in this function
3521 fclose($requests[$i]['file']);
3524 return $results;
3528 * Helper function to reset the request state vars.
3530 * @return void.
3532 protected function reset_request_state_vars() {
3533 $this->info = array();
3534 $this->error = '';
3535 $this->errno = 0;
3536 $this->response = array();
3537 $this->rawresponse = array();
3538 $this->responsefinished = false;
3542 * For use only in unit tests - we can pre-set the next curl response.
3543 * This is useful for unit testing APIs that call external systems.
3544 * @param string $response
3546 public static function mock_response($response) {
3547 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3548 array_push(self::$mockresponses, $response);
3549 } else {
3550 throw new coding_exception('mock_response function is only available for unit tests.');
3555 * Single HTTP Request
3557 * @param string $url The URL to request
3558 * @param array $options
3559 * @return bool
3561 protected function request($url, $options = array()) {
3562 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3563 $this->reset_request_state_vars();
3565 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3566 if ($mockresponse = array_pop(self::$mockresponses)) {
3567 $this->info = [ 'http_code' => 200 ];
3568 return $mockresponse;
3572 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3573 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3574 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3575 $this->error = $this->securityhelper->get_blocked_url_string();
3576 return $this->error;
3579 // Set the URL as a curl option.
3580 $this->setopt(array('CURLOPT_URL' => $url));
3582 // Create curl instance.
3583 $curl = curl_init();
3585 $this->apply_opt($curl, $options);
3586 if ($this->cache && $ret = $this->cache->get($this->options)) {
3587 return $ret;
3590 $ret = curl_exec($curl);
3591 $this->info = curl_getinfo($curl);
3592 $this->error = curl_error($curl);
3593 $this->errno = curl_errno($curl);
3594 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3596 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3597 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3598 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3599 $this->reset_request_state_vars();
3600 $this->error = $this->securityhelper->get_blocked_url_string();
3601 curl_close($curl);
3602 return $this->error;
3605 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3606 $redirects = 0;
3608 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3610 if ($this->info['http_code'] == 301) {
3611 // Moved Permanently - repeat the same request on new URL.
3613 } else if ($this->info['http_code'] == 302) {
3614 // Found - the standard redirect - repeat the same request on new URL.
3616 } else if ($this->info['http_code'] == 303) {
3617 // 303 See Other - repeat only if GET, do not bother with POSTs.
3618 if (empty($this->options['CURLOPT_HTTPGET'])) {
3619 break;
3622 } else if ($this->info['http_code'] == 307) {
3623 // Temporary Redirect - must repeat using the same request type.
3625 } else if ($this->info['http_code'] == 308) {
3626 // Permanent Redirect - must repeat using the same request type.
3628 } else {
3629 // Some other http code means do not retry!
3630 break;
3633 $redirects++;
3635 $redirecturl = null;
3636 if (isset($this->info['redirect_url'])) {
3637 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3638 $redirecturl = $this->info['redirect_url'];
3641 if (!$redirecturl) {
3642 foreach ($this->response as $k => $v) {
3643 if (strtolower($k) === 'location') {
3644 $redirecturl = $v;
3645 break;
3648 if (preg_match('|^https?://|i', $redirecturl)) {
3649 // Great, this is the correct location format!
3651 } else if ($redirecturl) {
3652 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3653 if (strpos($redirecturl, '/') === 0) {
3654 // Relative to server root - just guess.
3655 $pos = strpos('/', $current, 8);
3656 if ($pos === false) {
3657 $redirecturl = $current.$redirecturl;
3658 } else {
3659 $redirecturl = substr($current, 0, $pos).$redirecturl;
3661 } else {
3662 // Relative to current script.
3663 $redirecturl = dirname($current).'/'.$redirecturl;
3668 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3669 $ret = curl_exec($curl);
3671 $this->info = curl_getinfo($curl);
3672 $this->error = curl_error($curl);
3673 $this->errno = curl_errno($curl);
3675 $this->info['redirect_count'] = $redirects;
3677 if ($this->info['http_code'] === 200) {
3678 // Finally this is what we wanted.
3679 break;
3681 if ($this->errno != CURLE_OK) {
3682 // Something wrong is going on.
3683 break;
3686 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3687 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3688 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3692 if ($this->cache) {
3693 $this->cache->set($this->options, $ret);
3696 if ($this->debug) {
3697 echo '<h1>Return Data</h1>';
3698 var_dump($ret);
3699 echo '<h1>Info</h1>';
3700 var_dump($this->info);
3701 echo '<h1>Error</h1>';
3702 var_dump($this->error);
3705 curl_close($curl);
3707 if (empty($this->error)) {
3708 return $ret;
3709 } else {
3710 return $this->error;
3711 // exception is not ajax friendly
3712 //throw new moodle_exception($this->error, 'curl');
3717 * HTTP HEAD method
3719 * @see request()
3721 * @param string $url
3722 * @param array $options
3723 * @return bool
3725 public function head($url, $options = array()) {
3726 $options['CURLOPT_HTTPGET'] = 0;
3727 $options['CURLOPT_HEADER'] = 1;
3728 $options['CURLOPT_NOBODY'] = 1;
3729 return $this->request($url, $options);
3733 * HTTP PATCH method
3735 * @param string $url
3736 * @param array|string $params
3737 * @param array $options
3738 * @return bool
3740 public function patch($url, $params = '', $options = array()) {
3741 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3742 if (is_array($params)) {
3743 $this->_tmp_file_post_params = array();
3744 foreach ($params as $key => $value) {
3745 if ($value instanceof stored_file) {
3746 $value->add_to_curl_request($this, $key);
3747 } else {
3748 $this->_tmp_file_post_params[$key] = $value;
3751 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3752 unset($this->_tmp_file_post_params);
3753 } else {
3754 // The variable $params is the raw post data.
3755 $options['CURLOPT_POSTFIELDS'] = $params;
3757 return $this->request($url, $options);
3761 * HTTP POST method
3763 * @param string $url
3764 * @param array|string $params
3765 * @param array $options
3766 * @return bool
3768 public function post($url, $params = '', $options = array()) {
3769 $options['CURLOPT_POST'] = 1;
3770 if (is_array($params)) {
3771 $this->_tmp_file_post_params = array();
3772 foreach ($params as $key => $value) {
3773 if ($value instanceof stored_file) {
3774 $value->add_to_curl_request($this, $key);
3775 } else {
3776 $this->_tmp_file_post_params[$key] = $value;
3779 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3780 unset($this->_tmp_file_post_params);
3781 } else {
3782 // $params is the raw post data
3783 $options['CURLOPT_POSTFIELDS'] = $params;
3785 return $this->request($url, $options);
3789 * HTTP GET method
3791 * @param string $url
3792 * @param array $params
3793 * @param array $options
3794 * @return bool
3796 public function get($url, $params = array(), $options = array()) {
3797 $options['CURLOPT_HTTPGET'] = 1;
3799 if (!empty($params)) {
3800 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3801 $url .= http_build_query($params, '', '&');
3803 return $this->request($url, $options);
3807 * Downloads one file and writes it to the specified file handler
3809 * <code>
3810 * $c = new curl();
3811 * $file = fopen('savepath', 'w');
3812 * $result = $c->download_one('http://localhost/', null,
3813 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3814 * fclose($file);
3815 * $download_info = $c->get_info();
3816 * if ($result === true) {
3817 * // file downloaded successfully
3818 * } else {
3819 * $error_text = $result;
3820 * $error_code = $c->get_errno();
3822 * </code>
3824 * <code>
3825 * $c = new curl();
3826 * $result = $c->download_one('http://localhost/', null,
3827 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3828 * // ... see above, no need to close handle and remove file if unsuccessful
3829 * </code>
3831 * @param string $url
3832 * @param array|null $params key-value pairs to be added to $url as query string
3833 * @param array $options request options. Must include either 'file' or 'filepath'
3834 * @return bool|string true on success or error string on failure
3836 public function download_one($url, $params, $options = array()) {
3837 $options['CURLOPT_HTTPGET'] = 1;
3838 if (!empty($params)) {
3839 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3840 $url .= http_build_query($params, '', '&');
3842 if (!empty($options['filepath']) && empty($options['file'])) {
3843 // open file
3844 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3845 $this->errno = 100;
3846 return get_string('cannotwritefile', 'error', $options['filepath']);
3848 $filepath = $options['filepath'];
3850 unset($options['filepath']);
3851 $result = $this->request($url, $options);
3852 if (isset($filepath)) {
3853 fclose($options['file']);
3854 if ($result !== true) {
3855 unlink($filepath);
3858 return $result;
3862 * HTTP PUT method
3864 * @param string $url
3865 * @param array $params
3866 * @param array $options
3867 * @return bool
3869 public function put($url, $params = array(), $options = array()) {
3870 $file = '';
3871 $fp = false;
3872 if (isset($params['file'])) {
3873 $file = $params['file'];
3874 if (is_file($file)) {
3875 $fp = fopen($file, 'r');
3876 $size = filesize($file);
3877 $options['CURLOPT_PUT'] = 1;
3878 $options['CURLOPT_INFILESIZE'] = $size;
3879 $options['CURLOPT_INFILE'] = $fp;
3880 } else {
3881 return null;
3883 if (!isset($this->options['CURLOPT_USERPWD'])) {
3884 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3886 } else {
3887 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3888 $options['CURLOPT_POSTFIELDS'] = $params;
3891 $ret = $this->request($url, $options);
3892 if ($fp !== false) {
3893 fclose($fp);
3895 return $ret;
3899 * HTTP DELETE method
3901 * @param string $url
3902 * @param array $param
3903 * @param array $options
3904 * @return bool
3906 public function delete($url, $param = array(), $options = array()) {
3907 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3908 if (!isset($options['CURLOPT_USERPWD'])) {
3909 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3911 $ret = $this->request($url, $options);
3912 return $ret;
3916 * HTTP TRACE method
3918 * @param string $url
3919 * @param array $options
3920 * @return bool
3922 public function trace($url, $options = array()) {
3923 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3924 $ret = $this->request($url, $options);
3925 return $ret;
3929 * HTTP OPTIONS method
3931 * @param string $url
3932 * @param array $options
3933 * @return bool
3935 public function options($url, $options = array()) {
3936 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3937 $ret = $this->request($url, $options);
3938 return $ret;
3942 * Get curl information
3944 * @return string
3946 public function get_info() {
3947 return $this->info;
3951 * Get curl error code
3953 * @return int
3955 public function get_errno() {
3956 return $this->errno;
3960 * When using a proxy, an additional HTTP response code may appear at
3961 * the start of the header. For example, when using https over a proxy
3962 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3963 * also possible and some may come with their own headers.
3965 * If using the return value containing all headers, this function can be
3966 * called to remove unwanted doubles.
3968 * Note that it is not possible to distinguish this situation from valid
3969 * data unless you know the actual response part (below the headers)
3970 * will not be included in this string, or else will not 'look like' HTTP
3971 * headers. As a result it is not safe to call this function for general
3972 * data.
3974 * @param string $input Input HTTP response
3975 * @return string HTTP response with additional headers stripped if any
3977 public static function strip_double_headers($input) {
3978 // I have tried to make this regular expression as specific as possible
3979 // to avoid any case where it does weird stuff if you happen to put
3980 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3981 // also make it faster because it can abandon regex processing as soon
3982 // as it hits something that doesn't look like an http header. The
3983 // header definition is taken from RFC 822, except I didn't support
3984 // folding which is never used in practice.
3985 $crlf = "\r\n";
3986 return preg_replace(
3987 // HTTP version and status code (ignore value of code).
3988 '~^HTTP/1\..*' . $crlf .
3989 // Header name: character between 33 and 126 decimal, except colon.
3990 // Colon. Header value: any character except \r and \n. CRLF.
3991 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3992 // Headers are terminated by another CRLF (blank line).
3993 $crlf .
3994 // Second HTTP status code, this time must be 200.
3995 '(HTTP/1.[01] 200 )~', '$1', $input);
4000 * This class is used by cURL class, use case:
4002 * <code>
4003 * $CFG->repositorycacheexpire = 120;
4004 * $CFG->curlcache = 120;
4006 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
4007 * $ret = $c->get('http://www.google.com');
4008 * </code>
4010 * @package core_files
4011 * @copyright Dongsheng Cai <dongsheng@moodle.com>
4012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4014 class curl_cache {
4015 /** @var string Path to cache directory */
4016 public $dir = '';
4019 * Constructor
4021 * @global stdClass $CFG
4022 * @param string $module which module is using curl_cache
4024 public function __construct($module = 'repository') {
4025 global $CFG;
4026 if (!empty($module)) {
4027 $this->dir = $CFG->cachedir.'/'.$module.'/';
4028 } else {
4029 $this->dir = $CFG->cachedir.'/misc/';
4031 if (!file_exists($this->dir)) {
4032 mkdir($this->dir, $CFG->directorypermissions, true);
4034 if ($module == 'repository') {
4035 if (empty($CFG->repositorycacheexpire)) {
4036 $CFG->repositorycacheexpire = 120;
4038 $this->ttl = $CFG->repositorycacheexpire;
4039 } else {
4040 if (empty($CFG->curlcache)) {
4041 $CFG->curlcache = 120;
4043 $this->ttl = $CFG->curlcache;
4048 * Get cached value
4050 * @global stdClass $CFG
4051 * @global stdClass $USER
4052 * @param mixed $param
4053 * @return bool|string
4055 public function get($param) {
4056 global $CFG, $USER;
4057 $this->cleanup($this->ttl);
4058 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4059 if(file_exists($this->dir.$filename)) {
4060 $lasttime = filemtime($this->dir.$filename);
4061 if (time()-$lasttime > $this->ttl) {
4062 return false;
4063 } else {
4064 $fp = fopen($this->dir.$filename, 'r');
4065 $size = filesize($this->dir.$filename);
4066 $content = fread($fp, $size);
4067 return unserialize($content);
4070 return false;
4074 * Set cache value
4076 * @global object $CFG
4077 * @global object $USER
4078 * @param mixed $param
4079 * @param mixed $val
4081 public function set($param, $val) {
4082 global $CFG, $USER;
4083 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4084 $fp = fopen($this->dir.$filename, 'w');
4085 fwrite($fp, serialize($val));
4086 fclose($fp);
4087 @chmod($this->dir.$filename, $CFG->filepermissions);
4091 * Remove cache files
4093 * @param int $expire The number of seconds before expiry
4095 public function cleanup($expire) {
4096 if ($dir = opendir($this->dir)) {
4097 while (false !== ($file = readdir($dir))) {
4098 if(!is_dir($file) && $file != '.' && $file != '..') {
4099 $lasttime = @filemtime($this->dir.$file);
4100 if (time() - $lasttime > $expire) {
4101 @unlink($this->dir.$file);
4105 closedir($dir);
4109 * delete current user's cache file
4111 * @global object $CFG
4112 * @global object $USER
4114 public function refresh() {
4115 global $CFG, $USER;
4116 if ($dir = opendir($this->dir)) {
4117 while (false !== ($file = readdir($dir))) {
4118 if (!is_dir($file) && $file != '.' && $file != '..') {
4119 if (strpos($file, 'u'.$USER->id.'_') !== false) {
4120 @unlink($this->dir.$file);
4129 * This function delegates file serving to individual plugins
4131 * @param string $relativepath
4132 * @param bool $forcedownload
4133 * @param null|string $preview the preview mode, defaults to serving the original file
4134 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4135 * offline (e.g. mobile app).
4136 * @param bool $embed Whether this file will be served embed into an iframe.
4137 * @todo MDL-31088 file serving improments
4139 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4140 global $DB, $CFG, $USER;
4141 // relative path must start with '/'
4142 if (!$relativepath) {
4143 print_error('invalidargorconf');
4144 } else if ($relativepath[0] != '/') {
4145 print_error('pathdoesnotstartslash');
4148 // extract relative path components
4149 $args = explode('/', ltrim($relativepath, '/'));
4151 if (count($args) < 3) { // always at least context, component and filearea
4152 print_error('invalidarguments');
4155 $contextid = (int)array_shift($args);
4156 $component = clean_param(array_shift($args), PARAM_COMPONENT);
4157 $filearea = clean_param(array_shift($args), PARAM_AREA);
4159 list($context, $course, $cm) = get_context_info_array($contextid);
4161 $fs = get_file_storage();
4163 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4165 // ========================================================================================================================
4166 if ($component === 'blog') {
4167 // Blog file serving
4168 if ($context->contextlevel != CONTEXT_SYSTEM) {
4169 send_file_not_found();
4171 if ($filearea !== 'attachment' and $filearea !== 'post') {
4172 send_file_not_found();
4175 if (empty($CFG->enableblogs)) {
4176 print_error('siteblogdisable', 'blog');
4179 $entryid = (int)array_shift($args);
4180 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4181 send_file_not_found();
4183 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4184 require_login();
4185 if (isguestuser()) {
4186 print_error('noguest');
4188 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4189 if ($USER->id != $entry->userid) {
4190 send_file_not_found();
4195 if ($entry->publishstate === 'public') {
4196 if ($CFG->forcelogin) {
4197 require_login();
4200 } else if ($entry->publishstate === 'site') {
4201 require_login();
4202 //ok
4203 } else if ($entry->publishstate === 'draft') {
4204 require_login();
4205 if ($USER->id != $entry->userid) {
4206 send_file_not_found();
4210 $filename = array_pop($args);
4211 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4213 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4214 send_file_not_found();
4217 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4219 // ========================================================================================================================
4220 } else if ($component === 'grade') {
4222 require_once($CFG->libdir . '/grade/constants.php');
4224 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4225 // Global gradebook files
4226 if ($CFG->forcelogin) {
4227 require_login();
4230 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4232 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4233 send_file_not_found();
4236 \core\session\manager::write_close(); // Unlock session during file serving.
4237 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4239 } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4240 if ($context->contextlevel != CONTEXT_MODULE) {
4241 send_file_not_found();
4244 require_login($course, false);
4246 $gradeid = (int) array_shift($args);
4247 $filename = array_pop($args);
4248 if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4249 $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4250 } else {
4251 $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4254 if (!$grade) {
4255 send_file_not_found();
4258 $iscurrentuser = $USER->id == $grade->userid;
4260 if (!$iscurrentuser) {
4261 $coursecontext = context_course::instance($course->id);
4262 if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4263 send_file_not_found();
4267 $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4269 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4270 send_file_not_found();
4273 \core\session\manager::write_close(); // Unlock session during file serving.
4274 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4275 } else {
4276 send_file_not_found();
4279 // ========================================================================================================================
4280 } else if ($component === 'tag') {
4281 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4283 // All tag descriptions are going to be public but we still need to respect forcelogin
4284 if ($CFG->forcelogin) {
4285 require_login();
4288 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4290 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4291 send_file_not_found();
4294 \core\session\manager::write_close(); // Unlock session during file serving.
4295 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4297 } else {
4298 send_file_not_found();
4300 // ========================================================================================================================
4301 } else if ($component === 'badges') {
4302 require_once($CFG->libdir . '/badgeslib.php');
4304 $badgeid = (int)array_shift($args);
4305 $badge = new badge($badgeid);
4306 $filename = array_pop($args);
4308 if ($filearea === 'badgeimage') {
4309 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4310 send_file_not_found();
4312 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4313 send_file_not_found();
4316 \core\session\manager::write_close();
4317 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4318 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4319 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4320 send_file_not_found();
4323 \core\session\manager::write_close();
4324 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4326 // ========================================================================================================================
4327 } else if ($component === 'calendar') {
4328 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4330 // All events here are public the one requirement is that we respect forcelogin
4331 if ($CFG->forcelogin) {
4332 require_login();
4335 // Get the event if from the args array
4336 $eventid = array_shift($args);
4338 // Load the event from the database
4339 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4340 send_file_not_found();
4343 // Get the file and serve if successful
4344 $filename = array_pop($args);
4345 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4346 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4347 send_file_not_found();
4350 \core\session\manager::write_close(); // Unlock session during file serving.
4351 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4353 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4355 // Must be logged in, if they are not then they obviously can't be this user
4356 require_login();
4358 // Don't want guests here, potentially saves a DB call
4359 if (isguestuser()) {
4360 send_file_not_found();
4363 // Get the event if from the args array
4364 $eventid = array_shift($args);
4366 // Load the event from the database - user id must match
4367 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4368 send_file_not_found();
4371 // Get the file and serve if successful
4372 $filename = array_pop($args);
4373 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4374 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4375 send_file_not_found();
4378 \core\session\manager::write_close(); // Unlock session during file serving.
4379 send_stored_file($file, 0, 0, true, $sendfileoptions);
4381 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4383 // Respect forcelogin and require login unless this is the site.... it probably
4384 // should NEVER be the site
4385 if ($CFG->forcelogin || $course->id != SITEID) {
4386 require_login($course);
4389 // Must be able to at least view the course. This does not apply to the front page.
4390 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4391 //TODO: hmm, do we really want to block guests here?
4392 send_file_not_found();
4395 // Get the event id
4396 $eventid = array_shift($args);
4398 // Load the event from the database we need to check whether it is
4399 // a) valid course event
4400 // b) a group event
4401 // Group events use the course context (there is no group context)
4402 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4403 send_file_not_found();
4406 // If its a group event require either membership of view all groups capability
4407 if ($event->eventtype === 'group') {
4408 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4409 send_file_not_found();
4411 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4412 // Ok. Please note that the event type 'site' still uses a course context.
4413 } else {
4414 // Some other type.
4415 send_file_not_found();
4418 // If we get this far we can serve the file
4419 $filename = array_pop($args);
4420 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4421 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4422 send_file_not_found();
4425 \core\session\manager::write_close(); // Unlock session during file serving.
4426 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4428 } else {
4429 send_file_not_found();
4432 // ========================================================================================================================
4433 } else if ($component === 'user') {
4434 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4435 if (count($args) == 1) {
4436 $themename = theme_config::DEFAULT_THEME;
4437 $filename = array_shift($args);
4438 } else {
4439 $themename = array_shift($args);
4440 $filename = array_shift($args);
4443 // fix file name automatically
4444 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4445 $filename = 'f1';
4448 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4449 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4450 // protect images if login required and not logged in;
4451 // also if login is required for profile images and is not logged in or guest
4452 // do not use require_login() because it is expensive and not suitable here anyway
4453 $theme = theme_config::load($themename);
4454 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4457 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4458 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4459 if ($filename === 'f3') {
4460 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4461 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4462 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4467 if (!$file) {
4468 // bad reference - try to prevent future retries as hard as possible!
4469 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4470 if ($user->picture > 0) {
4471 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4474 // no redirect here because it is not cached
4475 $theme = theme_config::load($themename);
4476 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4477 send_file($imagefile, basename($imagefile), 60*60*24*14);
4480 $options = $sendfileoptions;
4481 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4482 // Profile images should be cache-able by both browsers and proxies according
4483 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4484 $options['cacheability'] = 'public';
4486 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4488 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4489 require_login();
4491 if (isguestuser()) {
4492 send_file_not_found();
4495 if ($USER->id !== $context->instanceid) {
4496 send_file_not_found();
4499 $filename = array_pop($args);
4500 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4501 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4502 send_file_not_found();
4505 \core\session\manager::write_close(); // Unlock session during file serving.
4506 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4508 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4510 if ($CFG->forcelogin) {
4511 require_login();
4514 $userid = $context->instanceid;
4516 if ($USER->id == $userid) {
4517 // always can access own
4519 } else if (!empty($CFG->forceloginforprofiles)) {
4520 require_login();
4522 if (isguestuser()) {
4523 send_file_not_found();
4526 // we allow access to site profile of all course contacts (usually teachers)
4527 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4528 send_file_not_found();
4531 $canview = false;
4532 if (has_capability('moodle/user:viewdetails', $context)) {
4533 $canview = true;
4534 } else {
4535 $courses = enrol_get_my_courses();
4538 while (!$canview && count($courses) > 0) {
4539 $course = array_shift($courses);
4540 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4541 $canview = true;
4546 $filename = array_pop($args);
4547 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4548 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4549 send_file_not_found();
4552 \core\session\manager::write_close(); // Unlock session during file serving.
4553 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4555 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4556 $userid = (int)array_shift($args);
4557 $usercontext = context_user::instance($userid);
4559 if ($CFG->forcelogin) {
4560 require_login();
4563 if (!empty($CFG->forceloginforprofiles)) {
4564 require_login();
4565 if (isguestuser()) {
4566 print_error('noguest');
4569 //TODO: review this logic of user profile access prevention
4570 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4571 print_error('usernotavailable');
4573 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4574 print_error('cannotviewprofile');
4576 if (!is_enrolled($context, $userid)) {
4577 print_error('notenrolledprofile');
4579 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4580 print_error('groupnotamember');
4584 $filename = array_pop($args);
4585 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4586 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4587 send_file_not_found();
4590 \core\session\manager::write_close(); // Unlock session during file serving.
4591 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4593 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4594 require_login();
4596 if (isguestuser()) {
4597 send_file_not_found();
4599 $userid = $context->instanceid;
4601 if ($USER->id != $userid) {
4602 send_file_not_found();
4605 $filename = array_pop($args);
4606 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4607 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4608 send_file_not_found();
4611 \core\session\manager::write_close(); // Unlock session during file serving.
4612 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4614 } else {
4615 send_file_not_found();
4618 // ========================================================================================================================
4619 } else if ($component === 'coursecat') {
4620 if ($context->contextlevel != CONTEXT_COURSECAT) {
4621 send_file_not_found();
4624 if ($filearea === 'description') {
4625 if ($CFG->forcelogin) {
4626 // no login necessary - unless login forced everywhere
4627 require_login();
4630 // Check if user can view this category.
4631 if (!core_course_category::get($context->instanceid, IGNORE_MISSING)) {
4632 send_file_not_found();
4635 $filename = array_pop($args);
4636 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4637 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4638 send_file_not_found();
4641 \core\session\manager::write_close(); // Unlock session during file serving.
4642 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4643 } else {
4644 send_file_not_found();
4647 // ========================================================================================================================
4648 } else if ($component === 'course') {
4649 if ($context->contextlevel != CONTEXT_COURSE) {
4650 send_file_not_found();
4653 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4654 if ($CFG->forcelogin) {
4655 require_login();
4658 $filename = array_pop($args);
4659 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4660 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4661 send_file_not_found();
4664 \core\session\manager::write_close(); // Unlock session during file serving.
4665 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4667 } else if ($filearea === 'section') {
4668 if ($CFG->forcelogin) {
4669 require_login($course);
4670 } else if ($course->id != SITEID) {
4671 require_login($course);
4674 $sectionid = (int)array_shift($args);
4676 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4677 send_file_not_found();
4680 $filename = array_pop($args);
4681 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4682 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4683 send_file_not_found();
4686 \core\session\manager::write_close(); // Unlock session during file serving.
4687 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4689 } else {
4690 send_file_not_found();
4693 } else if ($component === 'cohort') {
4695 $cohortid = (int)array_shift($args);
4696 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4697 $cohortcontext = context::instance_by_id($cohort->contextid);
4699 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4700 if ($context->id != $cohort->contextid &&
4701 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4702 send_file_not_found();
4705 // User is able to access cohort if they have view cap on cohort level or
4706 // the cohort is visible and they have view cap on course level.
4707 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4708 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4710 if ($filearea === 'description' && $canview) {
4711 $filename = array_pop($args);
4712 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4713 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4714 && !$file->is_directory()) {
4715 \core\session\manager::write_close(); // Unlock session during file serving.
4716 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4720 send_file_not_found();
4722 } else if ($component === 'group') {
4723 if ($context->contextlevel != CONTEXT_COURSE) {
4724 send_file_not_found();
4727 require_course_login($course, true, null, false);
4729 $groupid = (int)array_shift($args);
4731 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4732 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4733 // do not allow access to separate group info if not member or teacher
4734 send_file_not_found();
4737 if ($filearea === 'description') {
4739 require_login($course);
4741 $filename = array_pop($args);
4742 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4743 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $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 if ($filearea === 'icon') {
4751 $filename = array_pop($args);
4753 if ($filename !== 'f1' and $filename !== 'f2') {
4754 send_file_not_found();
4756 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4757 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4758 send_file_not_found();
4762 \core\session\manager::write_close(); // Unlock session during file serving.
4763 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4765 } else {
4766 send_file_not_found();
4769 } else if ($component === 'grouping') {
4770 if ($context->contextlevel != CONTEXT_COURSE) {
4771 send_file_not_found();
4774 require_login($course);
4776 $groupingid = (int)array_shift($args);
4778 // note: everybody has access to grouping desc images for now
4779 if ($filearea === 'description') {
4781 $filename = array_pop($args);
4782 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4783 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4784 send_file_not_found();
4787 \core\session\manager::write_close(); // Unlock session during file serving.
4788 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4790 } else {
4791 send_file_not_found();
4794 // ========================================================================================================================
4795 } else if ($component === 'backup') {
4796 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4797 require_login($course);
4798 require_capability('moodle/backup:downloadfile', $context);
4800 $filename = array_pop($args);
4801 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4802 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4803 send_file_not_found();
4806 \core\session\manager::write_close(); // Unlock session during file serving.
4807 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4809 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4810 require_login($course);
4811 require_capability('moodle/backup:downloadfile', $context);
4813 $sectionid = (int)array_shift($args);
4815 $filename = array_pop($args);
4816 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4817 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4818 send_file_not_found();
4821 \core\session\manager::write_close();
4822 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4824 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4825 require_login($course, false, $cm);
4826 require_capability('moodle/backup:downloadfile', $context);
4828 $filename = array_pop($args);
4829 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4830 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4831 send_file_not_found();
4834 \core\session\manager::write_close();
4835 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4837 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4838 // Backup files that were generated by the automated backup systems.
4840 require_login($course);
4841 require_capability('moodle/backup:downloadfile', $context);
4842 require_capability('moodle/restore:userinfo', $context);
4844 $filename = array_pop($args);
4845 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4846 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4847 send_file_not_found();
4850 \core\session\manager::write_close(); // Unlock session during file serving.
4851 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4853 } else {
4854 send_file_not_found();
4857 // ========================================================================================================================
4858 } else if ($component === 'question') {
4859 require_once($CFG->libdir . '/questionlib.php');
4860 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4861 send_file_not_found();
4863 // ========================================================================================================================
4864 } else if ($component === 'grading') {
4865 if ($filearea === 'description') {
4866 // files embedded into the form definition description
4868 if ($context->contextlevel == CONTEXT_SYSTEM) {
4869 require_login();
4871 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4872 require_login($course, false, $cm);
4874 } else {
4875 send_file_not_found();
4878 $formid = (int)array_shift($args);
4880 $sql = "SELECT ga.id
4881 FROM {grading_areas} ga
4882 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4883 WHERE gd.id = ? AND ga.contextid = ?";
4884 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4886 if (!$areaid) {
4887 send_file_not_found();
4890 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4892 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4893 send_file_not_found();
4896 \core\session\manager::write_close(); // Unlock session during file serving.
4897 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4900 // ========================================================================================================================
4901 } else if (strpos($component, 'mod_') === 0) {
4902 $modname = substr($component, 4);
4903 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4904 send_file_not_found();
4906 require_once("$CFG->dirroot/mod/$modname/lib.php");
4908 if ($context->contextlevel == CONTEXT_MODULE) {
4909 if ($cm->modname !== $modname) {
4910 // somebody tries to gain illegal access, cm type must match the component!
4911 send_file_not_found();
4915 if ($filearea === 'intro') {
4916 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4917 send_file_not_found();
4920 // Require login to the course first (without login to the module).
4921 require_course_login($course, true);
4923 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4924 $cminfo = cm_info::create($cm);
4925 if (!$cminfo->uservisible) {
4926 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
4927 // Module intro is not visible on the course page and module is not available, show access error.
4928 require_course_login($course, true, $cminfo);
4932 // all users may access it
4933 $filename = array_pop($args);
4934 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4935 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4936 send_file_not_found();
4939 // finally send the file
4940 send_stored_file($file, null, 0, false, $sendfileoptions);
4943 $filefunction = $component.'_pluginfile';
4944 $filefunctionold = $modname.'_pluginfile';
4945 if (function_exists($filefunction)) {
4946 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4947 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4948 } else if (function_exists($filefunctionold)) {
4949 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4950 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4953 send_file_not_found();
4955 // ========================================================================================================================
4956 } else if (strpos($component, 'block_') === 0) {
4957 $blockname = substr($component, 6);
4958 // note: no more class methods in blocks please, that is ....
4959 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4960 send_file_not_found();
4962 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4964 if ($context->contextlevel == CONTEXT_BLOCK) {
4965 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4966 if ($birecord->blockname !== $blockname) {
4967 // somebody tries to gain illegal access, cm type must match the component!
4968 send_file_not_found();
4971 if ($context->get_course_context(false)) {
4972 // If block is in course context, then check if user has capability to access course.
4973 require_course_login($course);
4974 } else if ($CFG->forcelogin) {
4975 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4976 require_login();
4979 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4980 // User can't access file, if block is hidden or doesn't have block:view capability
4981 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4982 send_file_not_found();
4984 } else {
4985 $birecord = null;
4988 $filefunction = $component.'_pluginfile';
4989 if (function_exists($filefunction)) {
4990 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4991 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4994 send_file_not_found();
4996 // ========================================================================================================================
4997 } else if (strpos($component, '_') === false) {
4998 // all core subsystems have to be specified above, no more guessing here!
4999 send_file_not_found();
5001 } else {
5002 // try to serve general plugin file in arbitrary context
5003 $dir = core_component::get_component_directory($component);
5004 if (!file_exists("$dir/lib.php")) {
5005 send_file_not_found();
5007 include_once("$dir/lib.php");
5009 $filefunction = $component.'_pluginfile';
5010 if (function_exists($filefunction)) {
5011 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5012 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5015 send_file_not_found();