Merge branch 'MDL-66614_36' of https://github.com/timhunt/moodle into MOODLE_36_STABLE
[moodle.git] / lib / filelib.php
blobaaff01fd36202c5a11450d24b5411c307dffcbd4
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for file handling.
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 /**
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
42 /**
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56 global $CFG;
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
65 if ($forcedownload) {
66 $return .= '?forcedownload=1';
68 } else {
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
71 if ($forcedownload) {
72 $return .= '&amp;forcedownload=1';
76 if ($https) {
77 $return = str_replace('http://', 'https://', $return);
80 return $return;
83 /**
84 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
92 * @return bool
94 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
95 global $DB;
97 if (!isset($itemid)) {
98 // Not initialised yet.
99 return false;
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
114 * displayed.
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
118 * @category files
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id != $context->id) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
161 $contextid = null;
162 $itemid = null;
163 if (!isset($data)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
176 } else {
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
183 } else {
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
195 } else {
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
199 return $data;
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
213 * @category files
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
240 if (!isset($options['removeorphaneddrafts'])) {
241 $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
244 if ($options['trusttext']) {
245 $data->{$field.'trust'} = trusttext_trusted($context);
246 } else {
247 $data->{$field.'trust'} = 0;
250 $editor = $data->{$field.'_editor'};
252 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
253 $data->{$field} = $editor['text'];
254 } else {
255 // Clean the user drafts area of any files not referenced in the editor text.
256 if ($options['removeorphaneddrafts']) {
257 file_remove_editor_orphaned_files($editor);
259 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
261 $data->{$field.'format'} = $editor['format'];
263 return $data;
267 * Saves text and files modified by Editor formslib element
269 * @category files
270 * @param stdClass $data $database entry field
271 * @param string $field name of data field
272 * @param array $options various options
273 * @param stdClass $context context - must already exist
274 * @param string $component
275 * @param string $filearea file area name
276 * @param int $itemid must already exist, usually means data is in db
277 * @return stdClass modified data obejct
279 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
280 $options = (array)$options;
281 if (!isset($options['subdirs'])) {
282 $options['subdirs'] = false;
284 if (is_null($itemid) or is_null($context)) {
285 $itemid = null;
286 $contextid = null;
287 } else {
288 $contextid = $context->id;
291 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
292 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
293 $data->{$field.'_filemanager'} = $draftid_editor;
295 return $data;
299 * Saves files modified by File manager formslib element
301 * @todo MDL-31073 review this function
302 * @category files
303 * @param stdClass $data $database entry field
304 * @param string $field name of data field
305 * @param array $options various options
306 * @param stdClass $context context - must already exist
307 * @param string $component
308 * @param string $filearea file area name
309 * @param int $itemid must already exist, usually means data is in db
310 * @return stdClass modified data obejct
312 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
313 $options = (array)$options;
314 if (!isset($options['subdirs'])) {
315 $options['subdirs'] = false;
317 if (!isset($options['maxfiles'])) {
318 $options['maxfiles'] = -1; // unlimited
320 if (!isset($options['maxbytes'])) {
321 $options['maxbytes'] = 0; // unlimited
324 if (empty($data->{$field.'_filemanager'})) {
325 $data->$field = '';
327 } else {
328 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
329 $fs = get_file_storage();
331 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
332 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
333 } else {
334 $data->$field = '';
338 return $data;
342 * Generate a draft itemid
344 * @category files
345 * @global moodle_database $DB
346 * @global stdClass $USER
347 * @return int a random but available draft itemid that can be used to create a new draft
348 * file area.
350 function file_get_unused_draft_itemid() {
351 global $DB, $USER;
353 if (isguestuser() or !isloggedin()) {
354 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
355 print_error('noguest');
358 $contextid = context_user::instance($USER->id)->id;
360 $fs = get_file_storage();
361 $draftitemid = rand(1, 999999999);
362 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
363 $draftitemid = rand(1, 999999999);
366 return $draftitemid;
370 * Initialise a draft file area from a real one by copying the files. A draft
371 * area will be created if one does not already exist. Normally you should
372 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
374 * @category files
375 * @global stdClass $CFG
376 * @global stdClass $USER
377 * @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.
378 * @param int $contextid This parameter and the next two identify the file area to copy files from.
379 * @param string $component
380 * @param string $filearea helps indentify the file area.
381 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
382 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
383 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
384 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
386 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
387 global $CFG, $USER, $CFG;
389 $options = (array)$options;
390 if (!isset($options['subdirs'])) {
391 $options['subdirs'] = false;
393 if (!isset($options['forcehttps'])) {
394 $options['forcehttps'] = false;
397 $usercontext = context_user::instance($USER->id);
398 $fs = get_file_storage();
400 if (empty($draftitemid)) {
401 // create a new area and copy existing files into
402 $draftitemid = file_get_unused_draft_itemid();
403 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
404 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
405 foreach ($files as $file) {
406 if ($file->is_directory() and $file->get_filepath() === '/') {
407 // we need a way to mark the age of each draft area,
408 // by not copying the root dir we force it to be created automatically with current timestamp
409 continue;
411 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
412 continue;
414 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
415 // XXX: This is a hack for file manager (MDL-28666)
416 // File manager needs to know the original file information before copying
417 // to draft area, so we append these information in mdl_files.source field
418 // {@link file_storage::search_references()}
419 // {@link file_storage::search_references_count()}
420 $sourcefield = $file->get_source();
421 $newsourcefield = new stdClass;
422 $newsourcefield->source = $sourcefield;
423 $original = new stdClass;
424 $original->contextid = $contextid;
425 $original->component = $component;
426 $original->filearea = $filearea;
427 $original->itemid = $itemid;
428 $original->filename = $file->get_filename();
429 $original->filepath = $file->get_filepath();
430 $newsourcefield->original = file_storage::pack_reference($original);
431 $draftfile->set_source(serialize($newsourcefield));
432 // End of file manager hack
435 if (!is_null($text)) {
436 // at this point there should not be any draftfile links yet,
437 // because this is a new text from database that should still contain the @@pluginfile@@ links
438 // this happens when developers forget to post process the text
439 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
441 } else {
442 // nothing to do
445 if (is_null($text)) {
446 return null;
449 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
450 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
454 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
455 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
456 * in the @@PLUGINFILE@@ form.
458 * @param string $text The content that may contain ULRs in need of rewriting.
459 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
460 * @param int $contextid This parameter and the next two identify the file area to use.
461 * @param string $component
462 * @param string $filearea helps identify the file area.
463 * @param int $itemid helps identify the file area.
464 * @param array $options
465 * bool $options.forcehttps Force the user of https
466 * bool $options.reverse Reverse the behaviour of the function
467 * bool $options.includetoken Use a token for authentication
468 * string The processed text.
470 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
471 global $CFG, $USER;
473 $options = (array)$options;
474 if (!isset($options['forcehttps'])) {
475 $options['forcehttps'] = false;
478 $baseurl = "{$CFG->wwwroot}/{$file}";
479 if (!empty($options['includetoken'])) {
480 $token = get_user_key('core_files', $USER->id);
481 $finalfile = basename($file);
482 $tokenfile = "token{$finalfile}";
483 $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
484 $baseurl = "{$CFG->wwwroot}/{$file}";
486 if (!$CFG->slasharguments) {
487 $baseurl .= "?token={$token}&file=";
488 } else {
489 $baseurl .= "/{$token}";
493 $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
495 if ($itemid !== null) {
496 $baseurl .= "$itemid/";
499 if ($options['forcehttps']) {
500 $baseurl = str_replace('http://', 'https://', $baseurl);
503 if (!empty($options['reverse'])) {
504 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
505 } else {
506 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
511 * Returns information about files in a draft area.
513 * @global stdClass $CFG
514 * @global stdClass $USER
515 * @param int $draftitemid the draft area item id.
516 * @param string $filepath path to the directory from which the information have to be retrieved.
517 * @return array with the following entries:
518 * 'filecount' => number of files in the draft area.
519 * 'filesize' => total size of the files in the draft area.
520 * 'foldercount' => number of folders in the draft area.
521 * 'filesize_without_references' => total size of the area excluding file references.
522 * (more information will be added as needed).
524 function file_get_draft_area_info($draftitemid, $filepath = '/') {
525 global $USER;
527 $usercontext = context_user::instance($USER->id);
528 return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
532 * Returns information about files in an area.
534 * @param int $contextid context id
535 * @param string $component component
536 * @param string $filearea file area name
537 * @param int $itemid item id or all files if not specified
538 * @param string $filepath path to the directory from which the information have to be retrieved.
539 * @return array with the following entries:
540 * 'filecount' => number of files in the area.
541 * 'filesize' => total size of the files in the area.
542 * 'foldercount' => number of folders in the area.
543 * 'filesize_without_references' => total size of the area excluding file references.
544 * @since Moodle 3.4
546 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
548 $fs = get_file_storage();
550 $results = array(
551 'filecount' => 0,
552 'foldercount' => 0,
553 'filesize' => 0,
554 'filesize_without_references' => 0
557 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
559 foreach ($draftfiles as $file) {
560 if ($file->is_directory()) {
561 $results['foldercount'] += 1;
562 } else {
563 $results['filecount'] += 1;
566 $filesize = $file->get_filesize();
567 $results['filesize'] += $filesize;
568 if (!$file->is_external_file()) {
569 $results['filesize_without_references'] += $filesize;
573 return $results;
577 * Returns whether a draft area has exceeded/will exceed its size limit.
579 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
581 * @param int $draftitemid the draft area item id.
582 * @param int $areamaxbytes the maximum size allowed in this draft area.
583 * @param int $newfilesize the size that would be added to the current area.
584 * @param bool $includereferences true to include the size of the references in the area size.
585 * @return bool true if the area will/has exceeded its limit.
586 * @since Moodle 2.4
588 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
589 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
590 $draftinfo = file_get_draft_area_info($draftitemid);
591 $areasize = $draftinfo['filesize_without_references'];
592 if ($includereferences) {
593 $areasize = $draftinfo['filesize'];
595 if ($areasize + $newfilesize > $areamaxbytes) {
596 return true;
599 return false;
603 * Get used space of files
604 * @global moodle_database $DB
605 * @global stdClass $USER
606 * @return int total bytes
608 function file_get_user_used_space() {
609 global $DB, $USER;
611 $usercontext = context_user::instance($USER->id);
612 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
613 JOIN (SELECT contenthash, filename, MAX(id) AS id
614 FROM {files}
615 WHERE contextid = ? AND component = ? AND filearea != ?
616 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
617 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
618 $record = $DB->get_record_sql($sql, $params);
619 return (int)$record->totalbytes;
623 * Convert any string to a valid filepath
624 * @todo review this function
625 * @param string $str
626 * @return string path
628 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
629 if ($str == '/' or empty($str)) {
630 return '/';
631 } else {
632 return '/'.trim($str, '/').'/';
637 * Generate a folder tree of draft area of current USER recursively
639 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
640 * @param int $draftitemid
641 * @param string $filepath
642 * @param mixed $data
644 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
645 global $USER, $OUTPUT, $CFG;
646 $data->children = array();
647 $context = context_user::instance($USER->id);
648 $fs = get_file_storage();
649 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
650 foreach ($files as $file) {
651 if ($file->is_directory()) {
652 $item = new stdClass();
653 $item->sortorder = $file->get_sortorder();
654 $item->filepath = $file->get_filepath();
656 $foldername = explode('/', trim($item->filepath, '/'));
657 $item->fullname = trim(array_pop($foldername), '/');
659 $item->id = uniqid();
660 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
661 $data->children[] = $item;
662 } else {
663 continue;
670 * Listing all files (including folders) in current path (draft area)
671 * used by file manager
672 * @param int $draftitemid
673 * @param string $filepath
674 * @return stdClass
676 function file_get_drafarea_files($draftitemid, $filepath = '/') {
677 global $USER, $OUTPUT, $CFG;
679 $context = context_user::instance($USER->id);
680 $fs = get_file_storage();
682 $data = new stdClass();
683 $data->path = array();
684 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
686 // will be used to build breadcrumb
687 $trail = '/';
688 if ($filepath !== '/') {
689 $filepath = file_correct_filepath($filepath);
690 $parts = explode('/', $filepath);
691 foreach ($parts as $part) {
692 if ($part != '' && $part != null) {
693 $trail .= ($part.'/');
694 $data->path[] = array('name'=>$part, 'path'=>$trail);
699 $list = array();
700 $maxlength = 12;
701 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
702 foreach ($files as $file) {
703 $item = new stdClass();
704 $item->filename = $file->get_filename();
705 $item->filepath = $file->get_filepath();
706 $item->fullname = trim($item->filename, '/');
707 $filesize = $file->get_filesize();
708 $item->size = $filesize ? $filesize : null;
709 $item->filesize = $filesize ? display_size($filesize) : '';
711 $item->sortorder = $file->get_sortorder();
712 $item->author = $file->get_author();
713 $item->license = $file->get_license();
714 $item->datemodified = $file->get_timemodified();
715 $item->datecreated = $file->get_timecreated();
716 $item->isref = $file->is_external_file();
717 if ($item->isref && $file->get_status() == 666) {
718 $item->originalmissing = true;
720 // find the file this draft file was created from and count all references in local
721 // system pointing to that file
722 $source = @unserialize($file->get_source());
723 if (isset($source->original)) {
724 $item->refcount = $fs->search_references_count($source->original);
727 if ($file->is_directory()) {
728 $item->filesize = 0;
729 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
730 $item->type = 'folder';
731 $foldername = explode('/', trim($item->filepath, '/'));
732 $item->fullname = trim(array_pop($foldername), '/');
733 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
734 } else {
735 // do NOT use file browser here!
736 $item->mimetype = get_mimetype_description($file);
737 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
738 $item->type = 'zip';
739 } else {
740 $item->type = 'file';
742 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
743 $item->url = $itemurl->out();
744 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
745 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
747 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
748 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
749 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
750 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
751 // used by the widget to display a warning about the problem files.
752 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
753 $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
754 if ($item->status == 0) {
755 if ($imageinfo = $file->get_imageinfo()) {
756 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
757 'oid' => $file->get_timemodified()));
758 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
759 $item->image_width = $imageinfo['width'];
760 $item->image_height = $imageinfo['height'];
764 $list[] = $item;
767 $data->itemid = $draftitemid;
768 $data->list = $list;
769 return $data;
773 * Returns all of the files in the draftarea.
775 * @param int $draftitemid The draft item ID
776 * @param string $filepath path for the uploaded files.
777 * @return array An array of files associated with this draft item id.
779 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
780 $files = [];
781 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
782 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
784 if (!empty($draftfiles)) {
785 foreach ($draftfiles->list as $draftfile) {
786 if ($draftfile->type == 'file') {
787 $files[] = $draftfile;
791 if (isset($draftfiles->children)) {
792 foreach ($draftfiles->children as $draftfile) {
793 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
797 return $files;
801 * Returns draft area itemid for a given element.
803 * @category files
804 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
805 * @return int the itemid, or 0 if there is not one yet.
807 function file_get_submitted_draft_itemid($elname) {
808 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
809 if (!isset($_REQUEST[$elname])) {
810 return 0;
812 if (is_array($_REQUEST[$elname])) {
813 $param = optional_param_array($elname, 0, PARAM_INT);
814 if (!empty($param['itemid'])) {
815 $param = $param['itemid'];
816 } else {
817 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
818 return false;
821 } else {
822 $param = optional_param($elname, 0, PARAM_INT);
825 if ($param) {
826 require_sesskey();
829 return $param;
833 * Restore the original source field from draft files
835 * Do not use this function because it makes field files.source inconsistent
836 * for draft area files. This function will be deprecated in 2.6
838 * @param stored_file $storedfile This only works with draft files
839 * @return stored_file
841 function file_restore_source_field_from_draft_file($storedfile) {
842 $source = @unserialize($storedfile->get_source());
843 if (!empty($source)) {
844 if (is_object($source)) {
845 $restoredsource = $source->source;
846 $storedfile->set_source($restoredsource);
847 } else {
848 throw new moodle_exception('invalidsourcefield', 'error');
851 return $storedfile;
855 * Removes those files from the user drafts filearea which are not referenced in the editor text.
857 * @param stdClass $editor The online text editor element from the submitted form data.
859 function file_remove_editor_orphaned_files($editor) {
860 global $CFG, $USER;
862 // Find those draft files included in the text, and generate their hashes.
863 $context = context_user::instance($USER->id);
864 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
865 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
866 preg_match_all($pattern, $editor['text'], $matches);
867 $usedfilehashes = [];
868 foreach ($matches[1] as $matchedfilename) {
869 $matchedfilename = urldecode($matchedfilename);
870 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
871 $matchedfilename);
874 // Now, compare the hashes of all draft files, and remove those which don't match used files.
875 $fs = get_file_storage();
876 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
877 foreach ($files as $file) {
878 $tmphash = $file->get_pathnamehash();
879 if (!in_array($tmphash, $usedfilehashes)) {
880 $file->delete();
886 * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
887 * content from another draft area it's possible for a single textarea to reference multiple draft areas.
889 * @category files
890 * @param int $draftitemid the id of the primary draft area.
891 * @param int $usercontextid the user's context id.
892 * @param string $text some html content that needs to have files copied to the correct draft area.
893 * @param bool $forcehttps force https urls.
895 * @return string $text html content modified with new draft links
897 function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
898 if (is_null($text)) {
899 return null;
902 $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
904 // No draft areas to rewrite.
905 if (empty($urls)) {
906 return $text;
909 foreach ($urls as $url) {
910 // Do not process the "home" draft area.
911 if ($url['itemid'] == $draftitemid) {
912 continue;
915 // Decode the filename.
916 $filename = urldecode($url['filename']);
918 // Copy the file.
919 file_copy_file_to_file_area($url, $filename, $draftitemid);
921 // Rewrite draft area.
922 $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
924 return $text;
928 * Rewrites a file area in arbitrary text.
930 * @param array $file General information about the file.
931 * @param int $newid The new file area itemid.
932 * @param string $text The text to rewrite.
933 * @param bool $forcehttps force https urls.
934 * @return string The rewritten text.
936 function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
937 global $CFG;
939 $wwwroot = $CFG->wwwroot;
940 if ($forcehttps) {
941 $wwwroot = str_replace('http://', 'https://', $wwwroot);
944 $search = [
945 $wwwroot,
946 $file['urlbase'],
947 $file['contextid'],
948 $file['component'],
949 $file['filearea'],
950 $file['itemid'],
951 $file['filename']
953 $replace = [
954 $wwwroot,
955 $file['urlbase'],
956 $file['contextid'],
957 $file['component'],
958 $file['filearea'],
959 $newid,
960 $file['filename']
963 $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
964 return $text;
968 * Copies a file from one file area to another.
970 * @param array $file Information about the file to be copied.
971 * @param string $filename The filename.
972 * @param int $itemid The new file area.
974 function file_copy_file_to_file_area($file, $filename, $itemid) {
975 $fs = get_file_storage();
977 // Load the current file in the old draft area.
978 $fileinfo = array(
979 'component' => $file['component'],
980 'filearea' => $file['filearea'],
981 'itemid' => $file['itemid'],
982 'contextid' => $file['contextid'],
983 'filepath' => '/',
984 'filename' => $filename
986 $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
987 $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
988 $newfileinfo = array(
989 'component' => $file['component'],
990 'filearea' => $file['filearea'],
991 'itemid' => $itemid,
992 'contextid' => $file['contextid'],
993 'filepath' => '/',
994 'filename' => $filename
997 $newcontextid = $newfileinfo['contextid'];
998 $newcomponent = $newfileinfo['component'];
999 $newfilearea = $newfileinfo['filearea'];
1000 $newitemid = $newfileinfo['itemid'];
1001 $newfilepath = $newfileinfo['filepath'];
1002 $newfilename = $newfileinfo['filename'];
1004 // Check if the file exists.
1005 if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1006 $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1011 * Saves files from a draft file area to a real one (merging the list of files).
1012 * Can rewrite URLs in some content at the same time if desired.
1014 * @category files
1015 * @global stdClass $USER
1016 * @param int $draftitemid the id of the draft area to use. Normally obtained
1017 * from file_get_submitted_draft_itemid('elementname') or similar.
1018 * @param int $contextid This parameter and the next two identify the file area to save to.
1019 * @param string $component
1020 * @param string $filearea indentifies the file area.
1021 * @param int $itemid helps identifies the file area.
1022 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1023 * @param string $text some html content that needs to have embedded links rewritten
1024 * to the @@PLUGINFILE@@ form for saving in the database.
1025 * @param bool $forcehttps force https urls.
1026 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1028 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1029 global $USER;
1031 $usercontext = context_user::instance($USER->id);
1032 $fs = get_file_storage();
1034 $options = (array)$options;
1035 if (!isset($options['subdirs'])) {
1036 $options['subdirs'] = false;
1038 if (!isset($options['maxfiles'])) {
1039 $options['maxfiles'] = -1; // unlimited
1041 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
1042 $options['maxbytes'] = 0; // unlimited
1044 if (!isset($options['areamaxbytes'])) {
1045 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
1047 $allowreferences = true;
1048 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
1049 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1050 // this is not exactly right. BUT there are many places in code where filemanager options
1051 // are not passed to file_save_draft_area_files()
1052 $allowreferences = false;
1055 // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1056 // areas and need to be copied into the current draft area.
1057 $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
1059 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1060 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1061 // anything at all in the next area.
1062 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1063 return null;
1066 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
1067 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1069 // One file in filearea means it is empty (it has only top-level directory '.').
1070 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
1071 // we have to merge old and new files - we want to keep file ids for files that were not changed
1072 // we change time modified for all new and changed files, we keep time created as is
1074 $newhashes = array();
1075 $filecount = 0;
1076 $context = context::instance_by_id($contextid, MUST_EXIST);
1077 foreach ($draftfiles as $file) {
1078 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1079 continue;
1081 if (!$allowreferences && $file->is_external_file()) {
1082 continue;
1084 if (!$file->is_directory()) {
1085 // Check to see if this file was uploaded by someone who can ignore the file size limits.
1086 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1087 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1088 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1089 // Oversized file.
1090 continue;
1092 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1093 // more files - should not get here at all
1094 continue;
1096 $filecount++;
1098 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1099 $newhashes[$newhash] = $file;
1102 // Loop through oldfiles and decide which we need to delete and which to update.
1103 // After this cycle the array $newhashes will only contain the files that need to be added.
1104 foreach ($oldfiles as $oldfile) {
1105 $oldhash = $oldfile->get_pathnamehash();
1106 if (!isset($newhashes[$oldhash])) {
1107 // delete files not needed any more - deleted by user
1108 $oldfile->delete();
1109 continue;
1112 $newfile = $newhashes[$oldhash];
1113 // Now we know that we have $oldfile and $newfile for the same path.
1114 // Let's check if we can update this file or we need to delete and create.
1115 if ($newfile->is_directory()) {
1116 // Directories are always ok to just update.
1117 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
1118 // File has the 'original' - we need to update the file (it may even have not been changed at all).
1119 $original = file_storage::unpack_reference($source->original);
1120 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
1121 // Very odd, original points to another file. Delete and create file.
1122 $oldfile->delete();
1123 continue;
1125 } else {
1126 // The same file name but absence of 'original' means that file was deteled and uploaded again.
1127 // By deleting and creating new file we properly manage all existing references.
1128 $oldfile->delete();
1129 continue;
1132 // status changed, we delete old file, and create a new one
1133 if ($oldfile->get_status() != $newfile->get_status()) {
1134 // file was changed, use updated with new timemodified data
1135 $oldfile->delete();
1136 // This file will be added later
1137 continue;
1140 // Updated author
1141 if ($oldfile->get_author() != $newfile->get_author()) {
1142 $oldfile->set_author($newfile->get_author());
1144 // Updated license
1145 if ($oldfile->get_license() != $newfile->get_license()) {
1146 $oldfile->set_license($newfile->get_license());
1149 // Updated file source
1150 // Field files.source for draftarea files contains serialised object with source and original information.
1151 // We only store the source part of it for non-draft file area.
1152 $newsource = $newfile->get_source();
1153 if ($source = @unserialize($newfile->get_source())) {
1154 $newsource = $source->source;
1156 if ($oldfile->get_source() !== $newsource) {
1157 $oldfile->set_source($newsource);
1160 // Updated sort order
1161 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1162 $oldfile->set_sortorder($newfile->get_sortorder());
1165 // Update file timemodified
1166 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1167 $oldfile->set_timemodified($newfile->get_timemodified());
1170 // Replaced file content
1171 if (!$oldfile->is_directory() &&
1172 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1173 $oldfile->get_filesize() != $newfile->get_filesize() ||
1174 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1175 $oldfile->get_userid() != $newfile->get_userid())) {
1176 $oldfile->replace_file_with($newfile);
1179 // unchanged file or directory - we keep it as is
1180 unset($newhashes[$oldhash]);
1183 // Add fresh file or the file which has changed status
1184 // the size and subdirectory tests are extra safety only, the UI should prevent it
1185 foreach ($newhashes as $file) {
1186 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1187 if ($source = @unserialize($file->get_source())) {
1188 // Field files.source for draftarea files contains serialised object with source and original information.
1189 // We only store the source part of it for non-draft file area.
1190 $file_record['source'] = $source->source;
1193 if ($file->is_external_file()) {
1194 $repoid = $file->get_repository_id();
1195 if (!empty($repoid)) {
1196 $context = context::instance_by_id($contextid, MUST_EXIST);
1197 $repo = repository::get_repository_by_id($repoid, $context);
1198 if (!empty($options)) {
1199 $repo->options = $options;
1201 $file_record['repositoryid'] = $repoid;
1202 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1203 // to the file store. E.g. transfer ownership of the file to a system account etc.
1204 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1206 $file_record['reference'] = $reference;
1210 $fs->create_file_from_storedfile($file_record, $file);
1214 // note: do not purge the draft area - we clean up areas later in cron,
1215 // the reason is that user might press submit twice and they would loose the files,
1216 // also sometimes we might want to use hacks that save files into two different areas
1218 if (is_null($text)) {
1219 return null;
1220 } else {
1221 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1226 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1227 * ready to be saved in the database. Normally, this is done automatically by
1228 * {@link file_save_draft_area_files()}.
1230 * @category files
1231 * @param string $text the content to process.
1232 * @param int $draftitemid the draft file area the content was using.
1233 * @param bool $forcehttps whether the content contains https URLs. Default false.
1234 * @return string the processed content.
1236 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1237 global $CFG, $USER;
1239 $usercontext = context_user::instance($USER->id);
1241 $wwwroot = $CFG->wwwroot;
1242 if ($forcehttps) {
1243 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1246 // relink embedded files if text submitted - no absolute links allowed in database!
1247 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1249 if (strpos($text, 'draftfile.php?file=') !== false) {
1250 $matches = array();
1251 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1252 if ($matches) {
1253 foreach ($matches[0] as $match) {
1254 $replace = str_ireplace('%2F', '/', $match);
1255 $text = str_replace($match, $replace, $text);
1258 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1261 return $text;
1265 * Set file sort order
1267 * @global moodle_database $DB
1268 * @param int $contextid the context id
1269 * @param string $component file component
1270 * @param string $filearea file area.
1271 * @param int $itemid itemid.
1272 * @param string $filepath file path.
1273 * @param string $filename file name.
1274 * @param int $sortorder the sort order of file.
1275 * @return bool
1277 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1278 global $DB;
1279 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1280 if ($file_record = $DB->get_record('files', $conditions)) {
1281 $sortorder = (int)$sortorder;
1282 $file_record->sortorder = $sortorder;
1283 $DB->update_record('files', $file_record);
1284 return true;
1286 return false;
1290 * reset file sort order number to 0
1291 * @global moodle_database $DB
1292 * @param int $contextid the context id
1293 * @param string $component
1294 * @param string $filearea file area.
1295 * @param int|bool $itemid itemid.
1296 * @return bool
1298 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1299 global $DB;
1301 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1302 if ($itemid !== false) {
1303 $conditions['itemid'] = $itemid;
1306 $file_records = $DB->get_records('files', $conditions);
1307 foreach ($file_records as $file_record) {
1308 $file_record->sortorder = 0;
1309 $DB->update_record('files', $file_record);
1311 return true;
1315 * Returns description of upload error
1317 * @param int $errorcode found in $_FILES['filename.ext']['error']
1318 * @return string error description string, '' if ok
1320 function file_get_upload_error($errorcode) {
1322 switch ($errorcode) {
1323 case 0: // UPLOAD_ERR_OK - no error
1324 $errmessage = '';
1325 break;
1327 case 1: // UPLOAD_ERR_INI_SIZE
1328 $errmessage = get_string('uploadserverlimit');
1329 break;
1331 case 2: // UPLOAD_ERR_FORM_SIZE
1332 $errmessage = get_string('uploadformlimit');
1333 break;
1335 case 3: // UPLOAD_ERR_PARTIAL
1336 $errmessage = get_string('uploadpartialfile');
1337 break;
1339 case 4: // UPLOAD_ERR_NO_FILE
1340 $errmessage = get_string('uploadnofilefound');
1341 break;
1343 // Note: there is no error with a value of 5
1345 case 6: // UPLOAD_ERR_NO_TMP_DIR
1346 $errmessage = get_string('uploadnotempdir');
1347 break;
1349 case 7: // UPLOAD_ERR_CANT_WRITE
1350 $errmessage = get_string('uploadcantwrite');
1351 break;
1353 case 8: // UPLOAD_ERR_EXTENSION
1354 $errmessage = get_string('uploadextension');
1355 break;
1357 default:
1358 $errmessage = get_string('uploadproblem');
1361 return $errmessage;
1365 * Recursive function formating an array in POST parameter
1366 * @param array $arraydata - the array that we are going to format and add into &$data array
1367 * @param string $currentdata - a row of the final postdata array at instant T
1368 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1369 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1371 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1372 foreach ($arraydata as $k=>$v) {
1373 $newcurrentdata = $currentdata;
1374 if (is_array($v)) { //the value is an array, call the function recursively
1375 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1376 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1377 } else { //add the POST parameter to the $data array
1378 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1384 * Transform a PHP array into POST parameter
1385 * (see the recursive function format_array_postdata_for_curlcall)
1386 * @param array $postdata
1387 * @return array containing all POST parameters (1 row = 1 POST parameter)
1389 function format_postdata_for_curlcall($postdata) {
1390 $data = array();
1391 foreach ($postdata as $k=>$v) {
1392 if (is_array($v)) {
1393 $currentdata = urlencode($k);
1394 format_array_postdata_for_curlcall($v, $currentdata, $data);
1395 } else {
1396 $data[] = urlencode($k).'='.urlencode($v);
1399 $convertedpostdata = implode('&', $data);
1400 return $convertedpostdata;
1404 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1405 * Due to security concerns only downloads from http(s) sources are supported.
1407 * @category files
1408 * @param string $url file url starting with http(s)://
1409 * @param array $headers http headers, null if none. If set, should be an
1410 * associative array of header name => value pairs.
1411 * @param array $postdata array means use POST request with given parameters
1412 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1413 * (if false, just returns content)
1414 * @param int $timeout timeout for complete download process including all file transfer
1415 * (default 5 minutes)
1416 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1417 * usually happens if the remote server is completely down (default 20 seconds);
1418 * may not work when using proxy
1419 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1420 * Only use this when already in a trusted location.
1421 * @param string $tofile store the downloaded content to file instead of returning it.
1422 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1423 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1424 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1425 * if file downloaded into $tofile successfully or the file content as a string.
1427 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1428 global $CFG;
1430 // Only http and https links supported.
1431 if (!preg_match('|^https?://|i', $url)) {
1432 if ($fullresponse) {
1433 $response = new stdClass();
1434 $response->status = 0;
1435 $response->headers = array();
1436 $response->response_code = 'Invalid protocol specified in url';
1437 $response->results = '';
1438 $response->error = 'Invalid protocol specified in url';
1439 return $response;
1440 } else {
1441 return false;
1445 $options = array();
1447 $headers2 = array();
1448 if (is_array($headers)) {
1449 foreach ($headers as $key => $value) {
1450 if (is_numeric($key)) {
1451 $headers2[] = $value;
1452 } else {
1453 $headers2[] = "$key: $value";
1458 if ($skipcertverify) {
1459 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1460 } else {
1461 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1464 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1466 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1467 $options['CURLOPT_MAXREDIRS'] = 5;
1469 // Use POST if requested.
1470 if (is_array($postdata)) {
1471 $postdata = format_postdata_for_curlcall($postdata);
1472 } else if (empty($postdata)) {
1473 $postdata = null;
1476 // Optionally attempt to get more correct timeout by fetching the file size.
1477 if (!isset($CFG->curltimeoutkbitrate)) {
1478 // Use very slow rate of 56kbps as a timeout speed when not set.
1479 $bitrate = 56;
1480 } else {
1481 $bitrate = $CFG->curltimeoutkbitrate;
1483 if ($calctimeout and !isset($postdata)) {
1484 $curl = new curl();
1485 $curl->setHeader($headers2);
1487 $curl->head($url, $postdata, $options);
1489 $info = $curl->get_info();
1490 $error_no = $curl->get_errno();
1491 if (!$error_no && $info['download_content_length'] > 0) {
1492 // No curl errors - adjust for large files only - take max timeout.
1493 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1497 $curl = new curl();
1498 $curl->setHeader($headers2);
1500 $options['CURLOPT_RETURNTRANSFER'] = true;
1501 $options['CURLOPT_NOBODY'] = false;
1502 $options['CURLOPT_TIMEOUT'] = $timeout;
1504 if ($tofile) {
1505 $fh = fopen($tofile, 'w');
1506 if (!$fh) {
1507 if ($fullresponse) {
1508 $response = new stdClass();
1509 $response->status = 0;
1510 $response->headers = array();
1511 $response->response_code = 'Can not write to file';
1512 $response->results = false;
1513 $response->error = 'Can not write to file';
1514 return $response;
1515 } else {
1516 return false;
1519 $options['CURLOPT_FILE'] = $fh;
1522 if (isset($postdata)) {
1523 $content = $curl->post($url, $postdata, $options);
1524 } else {
1525 $content = $curl->get($url, null, $options);
1528 if ($tofile) {
1529 fclose($fh);
1530 @chmod($tofile, $CFG->filepermissions);
1534 // Try to detect encoding problems.
1535 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1536 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1537 $result = curl_exec($ch);
1541 $info = $curl->get_info();
1542 $error_no = $curl->get_errno();
1543 $rawheaders = $curl->get_raw_response();
1545 if ($error_no) {
1546 $error = $content;
1547 if (!$fullresponse) {
1548 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1549 return false;
1552 $response = new stdClass();
1553 if ($error_no == 28) {
1554 $response->status = '-100'; // Mimic snoopy.
1555 } else {
1556 $response->status = '0';
1558 $response->headers = array();
1559 $response->response_code = $error;
1560 $response->results = false;
1561 $response->error = $error;
1562 return $response;
1565 if ($tofile) {
1566 $content = true;
1569 if (empty($info['http_code'])) {
1570 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1571 $response = new stdClass();
1572 $response->status = '0';
1573 $response->headers = array();
1574 $response->response_code = 'Unknown cURL error';
1575 $response->results = false; // do NOT change this, we really want to ignore the result!
1576 $response->error = 'Unknown cURL error';
1578 } else {
1579 $response = new stdClass();
1580 $response->status = (string)$info['http_code'];
1581 $response->headers = $rawheaders;
1582 $response->results = $content;
1583 $response->error = '';
1585 // There might be multiple headers on redirect, find the status of the last one.
1586 $firstline = true;
1587 foreach ($rawheaders as $line) {
1588 if ($firstline) {
1589 $response->response_code = $line;
1590 $firstline = false;
1592 if (trim($line, "\r\n") === '') {
1593 $firstline = true;
1598 if ($fullresponse) {
1599 return $response;
1602 if ($info['http_code'] != 200) {
1603 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1604 return false;
1606 return $response->results;
1610 * Returns a list of information about file types based on extensions.
1612 * The following elements expected in value array for each extension:
1613 * 'type' - mimetype
1614 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1615 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1616 * also files with bigger sizes under names
1617 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1618 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1619 * commonly used in moodle the following groups:
1620 * - web_image - image that can be included as <img> in HTML
1621 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1622 * - video - file that can be imported as video in text editor
1623 * - audio - file that can be imported as audio in text editor
1624 * - archive - we can extract files from this archive
1625 * - spreadsheet - used for portfolio format
1626 * - document - used for portfolio format
1627 * - presentation - used for portfolio format
1628 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1629 * human-readable description for this filetype;
1630 * Function {@link get_mimetype_description()} first looks at the presence of string for
1631 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1632 * attribute, if not found returns the value of 'type';
1633 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1634 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1635 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1637 * @category files
1638 * @return array List of information about file types based on extensions.
1639 * Associative array of extension (lower-case) to associative array
1640 * from 'element name' to data. Current element names are 'type' and 'icon'.
1641 * Unknown types should use the 'xxx' entry which includes defaults.
1643 function &get_mimetypes_array() {
1644 // Get types from the core_filetypes function, which includes caching.
1645 return core_filetypes::get_types();
1649 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1651 * This function retrieves a file's MIME type for a file that will be sent to the user.
1652 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1653 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1654 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1656 * @param string $filename The file's filename.
1657 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1659 function get_mimetype_for_sending($filename = '') {
1660 // Guess the file's MIME type using mimeinfo.
1661 $mimetype = mimeinfo('type', $filename);
1663 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1664 if (!$mimetype || $mimetype === 'document/unknown') {
1665 $mimetype = 'application/octet-stream';
1668 return $mimetype;
1672 * Obtains information about a filetype based on its extension. Will
1673 * use a default if no information is present about that particular
1674 * extension.
1676 * @category files
1677 * @param string $element Desired information (usually 'icon'
1678 * for icon filename or 'type' for MIME type. Can also be
1679 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1680 * @param string $filename Filename we're looking up
1681 * @return string Requested piece of information from array
1683 function mimeinfo($element, $filename) {
1684 global $CFG;
1685 $mimeinfo = & get_mimetypes_array();
1686 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1688 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1689 if (empty($filetype)) {
1690 $filetype = 'xxx'; // file without extension
1692 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1693 $iconsize = max(array(16, (int)$iconsizematch[1]));
1694 $filenames = array($mimeinfo['xxx']['icon']);
1695 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1696 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1698 // find the file with the closest size, first search for specific icon then for default icon
1699 foreach ($filenames as $filename) {
1700 foreach ($iconpostfixes as $size => $postfix) {
1701 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1702 if ($iconsize >= $size &&
1703 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1704 return $filename.$postfix;
1708 } else if (isset($mimeinfo[$filetype][$element])) {
1709 return $mimeinfo[$filetype][$element];
1710 } else if (isset($mimeinfo['xxx'][$element])) {
1711 return $mimeinfo['xxx'][$element]; // By default
1712 } else {
1713 return null;
1718 * Obtains information about a filetype based on the MIME type rather than
1719 * the other way around.
1721 * @category files
1722 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1723 * @param string $mimetype MIME type we're looking up
1724 * @return string Requested piece of information from array
1726 function mimeinfo_from_type($element, $mimetype) {
1727 /* array of cached mimetype->extension associations */
1728 static $cached = array();
1729 $mimeinfo = & get_mimetypes_array();
1731 if (!array_key_exists($mimetype, $cached)) {
1732 $cached[$mimetype] = null;
1733 foreach($mimeinfo as $filetype => $values) {
1734 if ($values['type'] == $mimetype) {
1735 if ($cached[$mimetype] === null) {
1736 $cached[$mimetype] = '.'.$filetype;
1738 if (!empty($values['defaulticon'])) {
1739 $cached[$mimetype] = '.'.$filetype;
1740 break;
1744 if (empty($cached[$mimetype])) {
1745 $cached[$mimetype] = '.xxx';
1748 if ($element === 'extension') {
1749 return $cached[$mimetype];
1750 } else {
1751 return mimeinfo($element, $cached[$mimetype]);
1756 * Return the relative icon path for a given file
1758 * Usage:
1759 * <code>
1760 * // $file - instance of stored_file or file_info
1761 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1762 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1763 * </code>
1764 * or
1765 * <code>
1766 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1767 * </code>
1769 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1770 * and $file->mimetype are expected)
1771 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1772 * @return string
1774 function file_file_icon($file, $size = null) {
1775 if (!is_object($file)) {
1776 $file = (object)$file;
1778 if (isset($file->filename)) {
1779 $filename = $file->filename;
1780 } else if (method_exists($file, 'get_filename')) {
1781 $filename = $file->get_filename();
1782 } else if (method_exists($file, 'get_visible_name')) {
1783 $filename = $file->get_visible_name();
1784 } else {
1785 $filename = '';
1787 if (isset($file->mimetype)) {
1788 $mimetype = $file->mimetype;
1789 } else if (method_exists($file, 'get_mimetype')) {
1790 $mimetype = $file->get_mimetype();
1791 } else {
1792 $mimetype = '';
1794 $mimetypes = &get_mimetypes_array();
1795 if ($filename) {
1796 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1797 if ($extension && !empty($mimetypes[$extension])) {
1798 // if file name has known extension, return icon for this extension
1799 return file_extension_icon($filename, $size);
1802 return file_mimetype_icon($mimetype, $size);
1806 * Return the relative icon path for a folder image
1808 * Usage:
1809 * <code>
1810 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1811 * echo html_writer::empty_tag('img', array('src' => $icon));
1812 * </code>
1813 * or
1814 * <code>
1815 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1816 * </code>
1818 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1819 * @return string
1821 function file_folder_icon($iconsize = null) {
1822 global $CFG;
1823 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1824 static $cached = array();
1825 $iconsize = max(array(16, (int)$iconsize));
1826 if (!array_key_exists($iconsize, $cached)) {
1827 foreach ($iconpostfixes as $size => $postfix) {
1828 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1829 if ($iconsize >= $size &&
1830 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1831 $cached[$iconsize] = 'f/folder'.$postfix;
1832 break;
1836 return $cached[$iconsize];
1840 * Returns the relative icon path for a given mime type
1842 * This function should be used in conjunction with $OUTPUT->image_url to produce
1843 * a return the full path to an icon.
1845 * <code>
1846 * $mimetype = 'image/jpg';
1847 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1848 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1849 * </code>
1851 * @category files
1852 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1853 * to conform with that.
1854 * @param string $mimetype The mimetype to fetch an icon for
1855 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1856 * @return string The relative path to the icon
1858 function file_mimetype_icon($mimetype, $size = NULL) {
1859 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1863 * Returns the relative icon path for a given file name
1865 * This function should be used in conjunction with $OUTPUT->image_url to produce
1866 * a return the full path to an icon.
1868 * <code>
1869 * $filename = '.jpg';
1870 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1871 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1872 * </code>
1874 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1875 * to conform with that.
1876 * @todo MDL-31074 Implement $size
1877 * @category files
1878 * @param string $filename The filename to get the icon for
1879 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1880 * @return string
1882 function file_extension_icon($filename, $size = NULL) {
1883 return 'f/'.mimeinfo('icon'.$size, $filename);
1887 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1888 * mimetypes.php language file.
1890 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1891 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1892 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1893 * @param bool $capitalise If true, capitalises first character of result
1894 * @return string Text description
1896 function get_mimetype_description($obj, $capitalise=false) {
1897 $filename = $mimetype = '';
1898 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1899 // this is an instance of stored_file
1900 $mimetype = $obj->get_mimetype();
1901 $filename = $obj->get_filename();
1902 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1903 // this is an instance of file_info
1904 $mimetype = $obj->get_mimetype();
1905 $filename = $obj->get_visible_name();
1906 } else if (is_array($obj) || is_object ($obj)) {
1907 $obj = (array)$obj;
1908 if (!empty($obj['filename'])) {
1909 $filename = $obj['filename'];
1911 if (!empty($obj['mimetype'])) {
1912 $mimetype = $obj['mimetype'];
1914 } else {
1915 $mimetype = $obj;
1917 $mimetypefromext = mimeinfo('type', $filename);
1918 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1919 // if file has a known extension, overwrite the specified mimetype
1920 $mimetype = $mimetypefromext;
1922 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1923 if (empty($extension)) {
1924 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1925 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1926 } else {
1927 $mimetypestr = mimeinfo('string', $filename);
1929 $chunks = explode('/', $mimetype, 2);
1930 $chunks[] = '';
1931 $attr = array(
1932 'mimetype' => $mimetype,
1933 'ext' => $extension,
1934 'mimetype1' => $chunks[0],
1935 'mimetype2' => $chunks[1],
1937 $a = array();
1938 foreach ($attr as $key => $value) {
1939 $a[$key] = $value;
1940 $a[strtoupper($key)] = strtoupper($value);
1941 $a[ucfirst($key)] = ucfirst($value);
1944 // MIME types may include + symbol but this is not permitted in string ids.
1945 $safemimetype = str_replace('+', '_', $mimetype);
1946 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1947 $customdescription = mimeinfo('customdescription', $filename);
1948 if ($customdescription) {
1949 // Call format_string on the custom description so that multilang
1950 // filter can be used (if enabled on system context). We use system
1951 // context because it is possible that the page context might not have
1952 // been defined yet.
1953 $result = format_string($customdescription, true,
1954 array('context' => context_system::instance()));
1955 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1956 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1957 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1958 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1959 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1960 $result = get_string('default', 'mimetypes', (object)$a);
1961 } else {
1962 $result = $mimetype;
1964 if ($capitalise) {
1965 $result=ucfirst($result);
1967 return $result;
1971 * Returns array of elements of type $element in type group(s)
1973 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1974 * @param string|array $groups one group or array of groups/extensions/mimetypes
1975 * @return array
1977 function file_get_typegroup($element, $groups) {
1978 static $cached = array();
1979 if (!is_array($groups)) {
1980 $groups = array($groups);
1982 if (!array_key_exists($element, $cached)) {
1983 $cached[$element] = array();
1985 $result = array();
1986 foreach ($groups as $group) {
1987 if (!array_key_exists($group, $cached[$element])) {
1988 // retrieive and cache all elements of type $element for group $group
1989 $mimeinfo = & get_mimetypes_array();
1990 $cached[$element][$group] = array();
1991 foreach ($mimeinfo as $extension => $value) {
1992 $value['extension'] = '.'.$extension;
1993 if (empty($value[$element])) {
1994 continue;
1996 if (($group === '.'.$extension || $group === $value['type'] ||
1997 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1998 !in_array($value[$element], $cached[$element][$group])) {
1999 $cached[$element][$group][] = $value[$element];
2003 $result = array_merge($result, $cached[$element][$group]);
2005 return array_values(array_unique($result));
2009 * Checks if file with name $filename has one of the extensions in groups $groups
2011 * @see get_mimetypes_array()
2012 * @param string $filename name of the file to check
2013 * @param string|array $groups one group or array of groups to check
2014 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2015 * file mimetype is in mimetypes in groups $groups
2016 * @return bool
2018 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2019 $extension = pathinfo($filename, PATHINFO_EXTENSION);
2020 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2021 return true;
2023 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2027 * Checks if mimetype $mimetype belongs to one of the groups $groups
2029 * @see get_mimetypes_array()
2030 * @param string $mimetype
2031 * @param string|array $groups one group or array of groups to check
2032 * @return bool
2034 function file_mimetype_in_typegroup($mimetype, $groups) {
2035 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2039 * Requested file is not found or not accessible, does not return, terminates script
2041 * @global stdClass $CFG
2042 * @global stdClass $COURSE
2044 function send_file_not_found() {
2045 global $CFG, $COURSE;
2047 // Allow cross-origin requests only for Web Services.
2048 // This allow to receive requests done by Web Workers or webapps in different domains.
2049 if (WS_SERVER) {
2050 header('Access-Control-Allow-Origin: *');
2053 send_header_404();
2054 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
2057 * Helper function to send correct 404 for server.
2059 function send_header_404() {
2060 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2061 header("Status: 404 Not Found");
2062 } else {
2063 header('HTTP/1.0 404 not found');
2068 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2069 * platforms). This wrapper uses readfile for small files and custom code for
2070 * large ones.
2072 * @param string $path Path to file
2073 * @param int $filesize Size of file (if left out, will get it automatically)
2074 * @return int|bool Size read (will always be $filesize) or false if failed
2076 function readfile_allow_large($path, $filesize = -1) {
2077 // Automatically get size if not specified.
2078 if ($filesize === -1) {
2079 $filesize = filesize($path);
2081 if ($filesize <= 2147483647) {
2082 // If the file is up to 2^31 - 1, send it normally using readfile.
2083 return readfile($path);
2084 } else {
2085 // For large files, read and output in 64KB chunks.
2086 $handle = fopen($path, 'r');
2087 if ($handle === false) {
2088 return false;
2090 $left = $filesize;
2091 while ($left > 0) {
2092 $size = min($left, 65536);
2093 $buffer = fread($handle, $size);
2094 if ($buffer === false) {
2095 return false;
2097 echo $buffer;
2098 $left -= $size;
2100 return $filesize;
2105 * Enhanced readfile() with optional acceleration.
2106 * @param string|stored_file $file
2107 * @param string $mimetype
2108 * @param bool $accelerate
2109 * @return void
2111 function readfile_accel($file, $mimetype, $accelerate) {
2112 global $CFG;
2114 if ($mimetype === 'text/plain') {
2115 // there is no encoding specified in text files, we need something consistent
2116 header('Content-Type: text/plain; charset=utf-8');
2117 } else {
2118 header('Content-Type: '.$mimetype);
2121 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2122 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2124 if (is_object($file)) {
2125 header('Etag: "' . $file->get_contenthash() . '"');
2126 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2127 header('HTTP/1.1 304 Not Modified');
2128 return;
2132 // if etag present for stored file rely on it exclusively
2133 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2134 // get unixtime of request header; clip extra junk off first
2135 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2136 if ($since && $since >= $lastmodified) {
2137 header('HTTP/1.1 304 Not Modified');
2138 return;
2142 if ($accelerate and !empty($CFG->xsendfile)) {
2143 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2144 header('Accept-Ranges: bytes');
2145 } else {
2146 header('Accept-Ranges: none');
2149 if (is_object($file)) {
2150 $fs = get_file_storage();
2151 if ($fs->xsendfile($file->get_contenthash())) {
2152 return;
2155 } else {
2156 require_once("$CFG->libdir/xsendfilelib.php");
2157 if (xsendfile($file)) {
2158 return;
2163 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2165 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2167 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2168 header('Accept-Ranges: bytes');
2170 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2171 // byteserving stuff - for acrobat reader and download accelerators
2172 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2173 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2174 $ranges = false;
2175 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2176 foreach ($ranges as $key=>$value) {
2177 if ($ranges[$key][1] == '') {
2178 //suffix case
2179 $ranges[$key][1] = $filesize - $ranges[$key][2];
2180 $ranges[$key][2] = $filesize - 1;
2181 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2182 //fix range length
2183 $ranges[$key][2] = $filesize - 1;
2185 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2186 //invalid byte-range ==> ignore header
2187 $ranges = false;
2188 break;
2190 //prepare multipart header
2191 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2192 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2194 } else {
2195 $ranges = false;
2197 if ($ranges) {
2198 if (is_object($file)) {
2199 $handle = $file->get_content_file_handle();
2200 } else {
2201 $handle = fopen($file, 'rb');
2203 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2206 } else {
2207 // Do not byteserve
2208 header('Accept-Ranges: none');
2211 header('Content-Length: '.$filesize);
2213 if ($filesize > 10000000) {
2214 // for large files try to flush and close all buffers to conserve memory
2215 while(@ob_get_level()) {
2216 if (!@ob_end_flush()) {
2217 break;
2222 // send the whole file content
2223 if (is_object($file)) {
2224 $file->readfile();
2225 } else {
2226 readfile_allow_large($file, $filesize);
2231 * Similar to readfile_accel() but designed for strings.
2232 * @param string $string
2233 * @param string $mimetype
2234 * @param bool $accelerate
2235 * @return void
2237 function readstring_accel($string, $mimetype, $accelerate) {
2238 global $CFG;
2240 if ($mimetype === 'text/plain') {
2241 // there is no encoding specified in text files, we need something consistent
2242 header('Content-Type: text/plain; charset=utf-8');
2243 } else {
2244 header('Content-Type: '.$mimetype);
2246 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2247 header('Accept-Ranges: none');
2249 if ($accelerate and !empty($CFG->xsendfile)) {
2250 $fs = get_file_storage();
2251 if ($fs->xsendfile(sha1($string))) {
2252 return;
2256 header('Content-Length: '.strlen($string));
2257 echo $string;
2261 * Handles the sending of temporary file to user, download is forced.
2262 * File is deleted after abort or successful sending, does not return, script terminated
2264 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2265 * @param string $filename proposed file name when saving file
2266 * @param bool $pathisstring If the path is string
2268 function send_temp_file($path, $filename, $pathisstring=false) {
2269 global $CFG;
2271 // Guess the file's MIME type.
2272 $mimetype = get_mimetype_for_sending($filename);
2274 // close session - not needed anymore
2275 \core\session\manager::write_close();
2277 if (!$pathisstring) {
2278 if (!file_exists($path)) {
2279 send_header_404();
2280 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2282 // executed after normal finish or abort
2283 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2286 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2287 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2288 $filename = urlencode($filename);
2291 header('Content-Disposition: attachment; filename="'.$filename.'"');
2292 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2293 header('Cache-Control: private, max-age=10, no-transform');
2294 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2295 header('Pragma: ');
2296 } else { //normal http - prevent caching at all cost
2297 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2298 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2299 header('Pragma: no-cache');
2302 // send the contents - we can not accelerate this because the file will be deleted asap
2303 if ($pathisstring) {
2304 readstring_accel($path, $mimetype, false);
2305 } else {
2306 readfile_accel($path, $mimetype, false);
2307 @unlink($path);
2310 die; //no more chars to output
2314 * Internal callback function used by send_temp_file()
2316 * @param string $path
2318 function send_temp_file_finished($path) {
2319 if (file_exists($path)) {
2320 @unlink($path);
2325 * Serve content which is not meant to be cached.
2327 * This is only intended to be used for volatile public files, for instance
2328 * when development is enabled, or when caching is not required on a public resource.
2330 * @param string $content Raw content.
2331 * @param string $filename The file name.
2332 * @return void
2334 function send_content_uncached($content, $filename) {
2335 $mimetype = mimeinfo('type', $filename);
2336 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2338 header('Content-Disposition: inline; filename="' . $filename . '"');
2339 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2340 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2341 header('Pragma: ');
2342 header('Accept-Ranges: none');
2343 header('Content-Type: ' . $mimetype . $charset);
2344 header('Content-Length: ' . strlen($content));
2346 echo $content;
2347 die();
2351 * Safely save content to a certain path.
2353 * This function tries hard to be atomic by first copying the content
2354 * to a separate file, and then moving the file across. It also prevents
2355 * the user to abort a request to prevent half-safed files.
2357 * This function is intended to be used when saving some content to cache like
2358 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2360 * @param string $content The file content.
2361 * @param string $destination The absolute path of the final file.
2362 * @return void
2364 function file_safe_save_content($content, $destination) {
2365 global $CFG;
2367 clearstatcache();
2368 if (!file_exists(dirname($destination))) {
2369 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2372 // Prevent serving of incomplete file from concurrent request,
2373 // the rename() should be more atomic than fwrite().
2374 ignore_user_abort(true);
2375 if ($fp = fopen($destination . '.tmp', 'xb')) {
2376 fwrite($fp, $content);
2377 fclose($fp);
2378 rename($destination . '.tmp', $destination);
2379 @chmod($destination, $CFG->filepermissions);
2380 @unlink($destination . '.tmp'); // Just in case anything fails.
2382 ignore_user_abort(false);
2383 if (connection_aborted()) {
2384 die();
2389 * Handles the sending of file data to the user's browser, including support for
2390 * byteranges etc.
2392 * @category files
2393 * @param string|stored_file $path Path of file on disk (including real filename),
2394 * or actual content of file as string,
2395 * or stored_file object
2396 * @param string $filename Filename to send
2397 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2398 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2399 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2400 * Forced to false when $path is a stored_file object.
2401 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2402 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2403 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2404 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2405 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2406 * and should not be reopened.
2407 * @param array $options An array of options, currently accepts:
2408 * - (string) cacheability: public, or private.
2409 * - (string|null) immutable
2410 * @return null script execution stopped unless $dontdie is true
2412 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2413 $dontdie=false, array $options = array()) {
2414 global $CFG, $COURSE;
2416 if ($dontdie) {
2417 ignore_user_abort(true);
2420 if ($lifetime === 'default' or is_null($lifetime)) {
2421 $lifetime = $CFG->filelifetime;
2424 if (is_object($path)) {
2425 $pathisstring = false;
2428 \core\session\manager::write_close(); // Unlock session during file serving.
2430 // Use given MIME type if specified, otherwise guess it.
2431 if (!$mimetype || $mimetype === 'document/unknown') {
2432 $mimetype = get_mimetype_for_sending($filename);
2435 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2436 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2437 $filename = rawurlencode($filename);
2440 if ($forcedownload) {
2441 header('Content-Disposition: attachment; filename="'.$filename.'"');
2442 } else if ($mimetype !== 'application/x-shockwave-flash') {
2443 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2444 // as an upload and enforces security that may prevent the file from being loaded.
2446 header('Content-Disposition: inline; filename="'.$filename.'"');
2449 if ($lifetime > 0) {
2450 $immutable = '';
2451 if (!empty($options['immutable'])) {
2452 $immutable = ', immutable';
2453 // Overwrite lifetime accordingly:
2454 // 90 days only - based on Moodle point release cadence being every 3 months.
2455 $lifetimemin = 60 * 60 * 24 * 90;
2456 $lifetime = max($lifetime, $lifetimemin);
2458 $cacheability = ' public,';
2459 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2460 // This file must be cache-able by both browsers and proxies.
2461 $cacheability = ' public,';
2462 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2463 // This file must be cache-able only by browsers.
2464 $cacheability = ' private,';
2465 } else if (isloggedin() and !isguestuser()) {
2466 // By default, under the conditions above, this file must be cache-able only by browsers.
2467 $cacheability = ' private,';
2469 $nobyteserving = false;
2470 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2471 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2472 header('Pragma: ');
2474 } else { // Do not cache files in proxies and browsers
2475 $nobyteserving = true;
2476 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2477 header('Cache-Control: private, max-age=10, no-transform');
2478 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2479 header('Pragma: ');
2480 } else { //normal http - prevent caching at all cost
2481 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2482 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2483 header('Pragma: no-cache');
2487 if (empty($filter)) {
2488 // send the contents
2489 if ($pathisstring) {
2490 readstring_accel($path, $mimetype, !$dontdie);
2491 } else {
2492 readfile_accel($path, $mimetype, !$dontdie);
2495 } else {
2496 // Try to put the file through filters
2497 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2498 $options = new stdClass();
2499 $options->noclean = true;
2500 $options->nocache = true; // temporary workaround for MDL-5136
2501 if (is_object($path)) {
2502 $text = $path->get_content();
2503 } else if ($pathisstring) {
2504 $text = $path;
2505 } else {
2506 $text = implode('', file($path));
2508 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2510 readstring_accel($output, $mimetype, false);
2512 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2513 // only filter text if filter all files is selected
2514 $options = new stdClass();
2515 $options->newlines = false;
2516 $options->noclean = true;
2517 if (is_object($path)) {
2518 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2519 } else if ($pathisstring) {
2520 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2521 } else {
2522 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2524 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2526 readstring_accel($output, $mimetype, false);
2528 } else {
2529 // send the contents
2530 if ($pathisstring) {
2531 readstring_accel($path, $mimetype, !$dontdie);
2532 } else {
2533 readfile_accel($path, $mimetype, !$dontdie);
2537 if ($dontdie) {
2538 return;
2540 die; //no more chars to output!!!
2544 * Handles the sending of file data to the user's browser, including support for
2545 * byteranges etc.
2547 * The $options parameter supports the following keys:
2548 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2549 * (string|null) filename - overrides the implicit filename
2550 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2551 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2552 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2553 * and should not be reopened
2554 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2555 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2556 * defaults to "public".
2557 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2558 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2560 * @category files
2561 * @param stored_file $stored_file local file object
2562 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2563 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2564 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2565 * @param array $options additional options affecting the file serving
2566 * @return null script execution stopped unless $options['dontdie'] is true
2568 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2569 global $CFG, $COURSE;
2571 if (empty($options['filename'])) {
2572 $filename = null;
2573 } else {
2574 $filename = $options['filename'];
2577 if (empty($options['dontdie'])) {
2578 $dontdie = false;
2579 } else {
2580 $dontdie = true;
2583 if ($lifetime === 'default' or is_null($lifetime)) {
2584 $lifetime = $CFG->filelifetime;
2587 if (!empty($options['preview'])) {
2588 // replace the file with its preview
2589 $fs = get_file_storage();
2590 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2591 if (!$preview_file) {
2592 // unable to create a preview of the file, send its default mime icon instead
2593 if ($options['preview'] === 'tinyicon') {
2594 $size = 24;
2595 } else if ($options['preview'] === 'thumb') {
2596 $size = 90;
2597 } else {
2598 $size = 256;
2600 $fileicon = file_file_icon($stored_file, $size);
2601 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2602 } else {
2603 // preview images have fixed cache lifetime and they ignore forced download
2604 // (they are generated by GD and therefore they are considered reasonably safe).
2605 $stored_file = $preview_file;
2606 $lifetime = DAYSECS;
2607 $filter = 0;
2608 $forcedownload = false;
2612 // handle external resource
2613 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2614 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2615 die;
2618 if (!$stored_file or $stored_file->is_directory()) {
2619 // nothing to serve
2620 if ($dontdie) {
2621 return;
2623 die;
2626 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2628 // Use given MIME type if specified.
2629 $mimetype = $stored_file->get_mimetype();
2631 // Allow cross-origin requests only for Web Services.
2632 // This allow to receive requests done by Web Workers or webapps in different domains.
2633 if (WS_SERVER) {
2634 header('Access-Control-Allow-Origin: *');
2637 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2641 * Recursively delete the file or folder with path $location. That is,
2642 * if it is a file delete it. If it is a folder, delete all its content
2643 * then delete it. If $location does not exist to start, that is not
2644 * considered an error.
2646 * @param string $location the path to remove.
2647 * @return bool
2649 function fulldelete($location) {
2650 if (empty($location)) {
2651 // extra safety against wrong param
2652 return false;
2654 if (is_dir($location)) {
2655 if (!$currdir = opendir($location)) {
2656 return false;
2658 while (false !== ($file = readdir($currdir))) {
2659 if ($file <> ".." && $file <> ".") {
2660 $fullfile = $location."/".$file;
2661 if (is_dir($fullfile)) {
2662 if (!fulldelete($fullfile)) {
2663 return false;
2665 } else {
2666 if (!unlink($fullfile)) {
2667 return false;
2672 closedir($currdir);
2673 if (! rmdir($location)) {
2674 return false;
2677 } else if (file_exists($location)) {
2678 if (!unlink($location)) {
2679 return false;
2682 return true;
2686 * Send requested byterange of file.
2688 * @param resource $handle A file handle
2689 * @param string $mimetype The mimetype for the output
2690 * @param array $ranges An array of ranges to send
2691 * @param string $filesize The size of the content if only one range is used
2693 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2694 // better turn off any kind of compression and buffering
2695 ini_set('zlib.output_compression', 'Off');
2697 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2698 if ($handle === false) {
2699 die;
2701 if (count($ranges) == 1) { //only one range requested
2702 $length = $ranges[0][2] - $ranges[0][1] + 1;
2703 header('HTTP/1.1 206 Partial content');
2704 header('Content-Length: '.$length);
2705 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2706 header('Content-Type: '.$mimetype);
2708 while(@ob_get_level()) {
2709 if (!@ob_end_flush()) {
2710 break;
2714 fseek($handle, $ranges[0][1]);
2715 while (!feof($handle) && $length > 0) {
2716 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2717 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2718 echo $buffer;
2719 flush();
2720 $length -= strlen($buffer);
2722 fclose($handle);
2723 die;
2724 } else { // multiple ranges requested - not tested much
2725 $totallength = 0;
2726 foreach($ranges as $range) {
2727 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2729 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2730 header('HTTP/1.1 206 Partial content');
2731 header('Content-Length: '.$totallength);
2732 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2734 while(@ob_get_level()) {
2735 if (!@ob_end_flush()) {
2736 break;
2740 foreach($ranges as $range) {
2741 $length = $range[2] - $range[1] + 1;
2742 echo $range[0];
2743 fseek($handle, $range[1]);
2744 while (!feof($handle) && $length > 0) {
2745 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2746 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2747 echo $buffer;
2748 flush();
2749 $length -= strlen($buffer);
2752 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2753 fclose($handle);
2754 die;
2759 * Tells whether the filename is executable.
2761 * @link http://php.net/manual/en/function.is-executable.php
2762 * @link https://bugs.php.net/bug.php?id=41062
2763 * @param string $filename Path to the file.
2764 * @return bool True if the filename exists and is executable; otherwise, false.
2766 function file_is_executable($filename) {
2767 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2768 if (is_executable($filename)) {
2769 return true;
2770 } else {
2771 $fileext = strrchr($filename, '.');
2772 // If we have an extension we can check if it is listed as executable.
2773 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2774 $winpathext = strtolower(getenv('PATHEXT'));
2775 $winpathexts = explode(';', $winpathext);
2777 return in_array(strtolower($fileext), $winpathexts);
2780 return false;
2782 } else {
2783 return is_executable($filename);
2788 * Overwrite an existing file in a draft area.
2790 * @param stored_file $newfile the new file with the new content and meta-data
2791 * @param stored_file $existingfile the file that will be overwritten
2792 * @throws moodle_exception
2793 * @since Moodle 3.2
2795 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2796 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2797 throw new coding_exception('The file to overwrite is not in a draft area.');
2800 $fs = get_file_storage();
2801 // Remember original file source field.
2802 $source = @unserialize($existingfile->get_source());
2803 // Remember the original sortorder.
2804 $sortorder = $existingfile->get_sortorder();
2805 if ($newfile->is_external_file()) {
2806 // New file is a reference. Check that existing file does not have any other files referencing to it
2807 if (isset($source->original) && $fs->search_references_count($source->original)) {
2808 throw new moodle_exception('errordoublereference', 'repository');
2812 // Delete existing file to release filename.
2813 $newfilerecord = array(
2814 'contextid' => $existingfile->get_contextid(),
2815 'component' => 'user',
2816 'filearea' => 'draft',
2817 'itemid' => $existingfile->get_itemid(),
2818 'timemodified' => time()
2820 $existingfile->delete();
2822 // Create new file.
2823 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2824 // Preserve original file location (stored in source field) for handling references.
2825 if (isset($source->original)) {
2826 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2827 $newfilesource = new stdClass();
2829 $newfilesource->original = $source->original;
2830 $newfile->set_source(serialize($newfilesource));
2832 $newfile->set_sortorder($sortorder);
2836 * Add files from a draft area into a final area.
2838 * Most of the time you do not want to use this. It is intended to be used
2839 * by asynchronous services which cannot direcly manipulate a final
2840 * area through a draft area. Instead they add files to a new draft
2841 * area and merge that new draft into the final area when ready.
2843 * @param int $draftitemid the id of the draft area to use.
2844 * @param int $contextid this parameter and the next two identify the file area to save to.
2845 * @param string $component component name
2846 * @param string $filearea indentifies the file area
2847 * @param int $itemid identifies the item id or false for all items in the file area
2848 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2849 * @see file_save_draft_area_files
2850 * @since Moodle 3.2
2852 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2853 array $options = null) {
2854 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2855 $finaldraftid = 0;
2856 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2857 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2858 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2862 * Merge files from two draftarea areas.
2864 * This does not handle conflict resolution, files in the destination area which appear
2865 * to be more recent will be kept disregarding the intended ones.
2867 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2868 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2869 * @throws coding_exception
2870 * @since Moodle 3.2
2872 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2873 global $USER;
2875 $fs = get_file_storage();
2876 $contextid = context_user::instance($USER->id)->id;
2878 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2879 throw new coding_exception('Nothing to merge or area does not belong to current user');
2882 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2884 // Get hashes of the files to merge.
2885 $newhashes = array();
2886 foreach ($filestomerge as $filetomerge) {
2887 $filepath = $filetomerge->get_filepath();
2888 $filename = $filetomerge->get_filename();
2890 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2891 $newhashes[$newhash] = $filetomerge;
2894 // Calculate wich files must be added.
2895 foreach ($currentfiles as $file) {
2896 $filehash = $file->get_pathnamehash();
2897 // One file to be merged already exists.
2898 if (isset($newhashes[$filehash])) {
2899 $updatedfile = $newhashes[$filehash];
2901 // Avoid race conditions.
2902 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2903 // The existing file is more recent, do not copy the suposedly "new" one.
2904 unset($newhashes[$filehash]);
2905 continue;
2907 // Update existing file (not only content, meta-data too).
2908 file_overwrite_existing_draftfile($updatedfile, $file);
2909 unset($newhashes[$filehash]);
2913 foreach ($newhashes as $newfile) {
2914 $newfilerecord = array(
2915 'contextid' => $contextid,
2916 'component' => 'user',
2917 'filearea' => 'draft',
2918 'itemid' => $mergeintodraftid,
2919 'timemodified' => time()
2922 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2927 * RESTful cURL class
2929 * This is a wrapper class for curl, it is quite easy to use:
2930 * <code>
2931 * $c = new curl;
2932 * // enable cache
2933 * $c = new curl(array('cache'=>true));
2934 * // enable cookie
2935 * $c = new curl(array('cookie'=>true));
2936 * // enable proxy
2937 * $c = new curl(array('proxy'=>true));
2939 * // HTTP GET Method
2940 * $html = $c->get('http://example.com');
2941 * // HTTP POST Method
2942 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2943 * // HTTP PUT Method
2944 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2945 * </code>
2947 * @package core_files
2948 * @category files
2949 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2950 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2952 class curl {
2953 /** @var bool Caches http request contents */
2954 public $cache = false;
2955 /** @var bool Uses proxy, null means automatic based on URL */
2956 public $proxy = null;
2957 /** @var string library version */
2958 public $version = '0.4 dev';
2959 /** @var array http's response */
2960 public $response = array();
2961 /** @var array Raw response headers, needed for BC in download_file_content(). */
2962 public $rawresponse = array();
2963 /** @var array http header */
2964 public $header = array();
2965 /** @var string cURL information */
2966 public $info;
2967 /** @var string error */
2968 public $error;
2969 /** @var int error code */
2970 public $errno;
2971 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2972 public $emulateredirects = null;
2974 /** @var array cURL options */
2975 private $options;
2977 /** @var string Proxy host */
2978 private $proxy_host = '';
2979 /** @var string Proxy auth */
2980 private $proxy_auth = '';
2981 /** @var string Proxy type */
2982 private $proxy_type = '';
2983 /** @var bool Debug mode on */
2984 private $debug = false;
2985 /** @var bool|string Path to cookie file */
2986 private $cookie = false;
2987 /** @var bool tracks multiple headers in response - redirect detection */
2988 private $responsefinished = false;
2989 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2990 private $securityhelper;
2991 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2992 private $ignoresecurity;
2993 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
2994 private static $mockresponses = [];
2997 * Curl constructor.
2999 * Allowed settings are:
3000 * proxy: (bool) use proxy server, null means autodetect non-local from url
3001 * debug: (bool) use debug output
3002 * cookie: (string) path to cookie file, false if none
3003 * cache: (bool) use cache
3004 * module_cache: (string) type of cache
3005 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3006 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3008 * @param array $settings
3010 public function __construct($settings = array()) {
3011 global $CFG;
3012 if (!function_exists('curl_init')) {
3013 $this->error = 'cURL module must be enabled!';
3014 trigger_error($this->error, E_USER_ERROR);
3015 return false;
3018 // All settings of this class should be init here.
3019 $this->resetopt();
3020 if (!empty($settings['debug'])) {
3021 $this->debug = true;
3023 if (!empty($settings['cookie'])) {
3024 if($settings['cookie'] === true) {
3025 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3026 } else {
3027 $this->cookie = $settings['cookie'];
3030 if (!empty($settings['cache'])) {
3031 if (class_exists('curl_cache')) {
3032 if (!empty($settings['module_cache'])) {
3033 $this->cache = new curl_cache($settings['module_cache']);
3034 } else {
3035 $this->cache = new curl_cache('misc');
3039 if (!empty($CFG->proxyhost)) {
3040 if (empty($CFG->proxyport)) {
3041 $this->proxy_host = $CFG->proxyhost;
3042 } else {
3043 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3045 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3046 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3047 $this->setopt(array(
3048 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3049 'proxyuserpwd'=>$this->proxy_auth));
3051 if (!empty($CFG->proxytype)) {
3052 if ($CFG->proxytype == 'SOCKS5') {
3053 $this->proxy_type = CURLPROXY_SOCKS5;
3054 } else {
3055 $this->proxy_type = CURLPROXY_HTTP;
3056 $this->setopt(array('httpproxytunnel'=>false));
3058 $this->setopt(array('proxytype'=>$this->proxy_type));
3061 if (isset($settings['proxy'])) {
3062 $this->proxy = $settings['proxy'];
3064 } else {
3065 $this->proxy = false;
3068 if (!isset($this->emulateredirects)) {
3069 $this->emulateredirects = ini_get('open_basedir');
3072 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3073 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3074 $this->set_security($settings['securityhelper']);
3075 } else {
3076 $this->set_security(new \core\files\curl_security_helper());
3078 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3082 * Resets the CURL options that have already been set
3084 public function resetopt() {
3085 $this->options = array();
3086 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
3087 // True to include the header in the output
3088 $this->options['CURLOPT_HEADER'] = 0;
3089 // True to Exclude the body from the output
3090 $this->options['CURLOPT_NOBODY'] = 0;
3091 // Redirect ny default.
3092 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
3093 $this->options['CURLOPT_MAXREDIRS'] = 10;
3094 $this->options['CURLOPT_ENCODING'] = '';
3095 // TRUE to return the transfer as a string of the return
3096 // value of curl_exec() instead of outputting it out directly.
3097 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
3098 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
3099 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
3100 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
3102 if ($cacert = self::get_cacert()) {
3103 $this->options['CURLOPT_CAINFO'] = $cacert;
3108 * Get the location of ca certificates.
3109 * @return string absolute file path or empty if default used
3111 public static function get_cacert() {
3112 global $CFG;
3114 // Bundle in dataroot always wins.
3115 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3116 return realpath("$CFG->dataroot/moodleorgca.crt");
3119 // Next comes the default from php.ini
3120 $cacert = ini_get('curl.cainfo');
3121 if (!empty($cacert) and is_readable($cacert)) {
3122 return realpath($cacert);
3125 // Windows PHP does not have any certs, we need to use something.
3126 if ($CFG->ostype === 'WINDOWS') {
3127 if (is_readable("$CFG->libdir/cacert.pem")) {
3128 return realpath("$CFG->libdir/cacert.pem");
3132 // Use default, this should work fine on all properly configured *nix systems.
3133 return null;
3137 * Reset Cookie
3139 public function resetcookie() {
3140 if (!empty($this->cookie)) {
3141 if (is_file($this->cookie)) {
3142 $fp = fopen($this->cookie, 'w');
3143 if (!empty($fp)) {
3144 fwrite($fp, '');
3145 fclose($fp);
3152 * Set curl options.
3154 * Do not use the curl constants to define the options, pass a string
3155 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3156 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3158 * @param array $options If array is null, this function will reset the options to default value.
3159 * @return void
3160 * @throws coding_exception If an option uses constant value instead of option name.
3162 public function setopt($options = array()) {
3163 if (is_array($options)) {
3164 foreach ($options as $name => $val) {
3165 if (!is_string($name)) {
3166 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3168 if (stripos($name, 'CURLOPT_') === false) {
3169 $name = strtoupper('CURLOPT_'.$name);
3170 } else {
3171 $name = strtoupper($name);
3173 $this->options[$name] = $val;
3179 * Reset http method
3181 public function cleanopt() {
3182 unset($this->options['CURLOPT_HTTPGET']);
3183 unset($this->options['CURLOPT_POST']);
3184 unset($this->options['CURLOPT_POSTFIELDS']);
3185 unset($this->options['CURLOPT_PUT']);
3186 unset($this->options['CURLOPT_INFILE']);
3187 unset($this->options['CURLOPT_INFILESIZE']);
3188 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3189 unset($this->options['CURLOPT_FILE']);
3193 * Resets the HTTP Request headers (to prepare for the new request)
3195 public function resetHeader() {
3196 $this->header = array();
3200 * Set HTTP Request Header
3202 * @param array $header
3204 public function setHeader($header) {
3205 if (is_array($header)) {
3206 foreach ($header as $v) {
3207 $this->setHeader($v);
3209 } else {
3210 // Remove newlines, they are not allowed in headers.
3211 $newvalue = preg_replace('/[\r\n]/', '', $header);
3212 if (!in_array($newvalue, $this->header)) {
3213 $this->header[] = $newvalue;
3219 * Get HTTP Response Headers
3220 * @return array of arrays
3222 public function getResponse() {
3223 return $this->response;
3227 * Get raw HTTP Response Headers
3228 * @return array of strings
3230 public function get_raw_response() {
3231 return $this->rawresponse;
3235 * private callback function
3236 * Formatting HTTP Response Header
3238 * We only keep the last headers returned. For example during a redirect the
3239 * redirect headers will not appear in {@link self::getResponse()}, if you need
3240 * to use those headers, refer to {@link self::get_raw_response()}.
3242 * @param resource $ch Apparently not used
3243 * @param string $header
3244 * @return int The strlen of the header
3246 private function formatHeader($ch, $header) {
3247 $this->rawresponse[] = $header;
3249 if (trim($header, "\r\n") === '') {
3250 // This must be the last header.
3251 $this->responsefinished = true;
3254 if (strlen($header) > 2) {
3255 if ($this->responsefinished) {
3256 // We still have headers after the supposedly last header, we must be
3257 // in a redirect so let's empty the response to keep the last headers.
3258 $this->responsefinished = false;
3259 $this->response = array();
3261 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3262 $key = rtrim($parts[0], ':');
3263 $value = isset($parts[1]) ? $parts[1] : null;
3264 if (!empty($this->response[$key])) {
3265 if (is_array($this->response[$key])) {
3266 $this->response[$key][] = $value;
3267 } else {
3268 $tmp = $this->response[$key];
3269 $this->response[$key] = array();
3270 $this->response[$key][] = $tmp;
3271 $this->response[$key][] = $value;
3274 } else {
3275 $this->response[$key] = $value;
3278 return strlen($header);
3282 * Set options for individual curl instance
3284 * @param resource $curl A curl handle
3285 * @param array $options
3286 * @return resource The curl handle
3288 private function apply_opt($curl, $options) {
3289 // Clean up
3290 $this->cleanopt();
3291 // set cookie
3292 if (!empty($this->cookie) || !empty($options['cookie'])) {
3293 $this->setopt(array('cookiejar'=>$this->cookie,
3294 'cookiefile'=>$this->cookie
3298 // Bypass proxy if required.
3299 if ($this->proxy === null) {
3300 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3301 $proxy = false;
3302 } else {
3303 $proxy = true;
3305 } else {
3306 $proxy = (bool)$this->proxy;
3309 // Set proxy.
3310 if ($proxy) {
3311 $options['CURLOPT_PROXY'] = $this->proxy_host;
3312 } else {
3313 unset($this->options['CURLOPT_PROXY']);
3316 $this->setopt($options);
3318 // Reset before set options.
3319 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3321 // Setting the User-Agent based on options provided.
3322 $useragent = '';
3324 if (!empty($options['CURLOPT_USERAGENT'])) {
3325 $useragent = $options['CURLOPT_USERAGENT'];
3326 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3327 $useragent = $this->options['CURLOPT_USERAGENT'];
3328 } else {
3329 $useragent = 'MoodleBot/1.0';
3332 // Set headers.
3333 if (empty($this->header)) {
3334 $this->setHeader(array(
3335 'User-Agent: ' . $useragent,
3336 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3337 'Connection: keep-alive'
3339 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3340 // Remove old User-Agent if one existed.
3341 // We have to partial search since we don't know what the original User-Agent is.
3342 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3343 $key = array_keys($match)[0];
3344 unset($this->header[$key]);
3346 $this->setHeader(array('User-Agent: ' . $useragent));
3348 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3350 if ($this->debug) {
3351 echo '<h1>Options</h1>';
3352 var_dump($this->options);
3353 echo '<h1>Header</h1>';
3354 var_dump($this->header);
3357 // Do not allow infinite redirects.
3358 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3359 $this->options['CURLOPT_MAXREDIRS'] = 0;
3360 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3361 $this->options['CURLOPT_MAXREDIRS'] = 100;
3362 } else {
3363 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3366 // Make sure we always know if redirects expected.
3367 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3368 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3371 // Limit the protocols to HTTP and HTTPS.
3372 if (defined('CURLOPT_PROTOCOLS')) {
3373 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3374 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3377 // Set options.
3378 foreach($this->options as $name => $val) {
3379 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3380 // The redirects are emulated elsewhere.
3381 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3382 continue;
3384 $name = constant($name);
3385 curl_setopt($curl, $name, $val);
3388 return $curl;
3392 * Download multiple files in parallel
3394 * Calls {@link multi()} with specific download headers
3396 * <code>
3397 * $c = new curl();
3398 * $file1 = fopen('a', 'wb');
3399 * $file2 = fopen('b', 'wb');
3400 * $c->download(array(
3401 * array('url'=>'http://localhost/', 'file'=>$file1),
3402 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3403 * ));
3404 * fclose($file1);
3405 * fclose($file2);
3406 * </code>
3408 * or
3410 * <code>
3411 * $c = new curl();
3412 * $c->download(array(
3413 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3414 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3415 * ));
3416 * </code>
3418 * @param array $requests An array of files to request {
3419 * url => url to download the file [required]
3420 * file => file handler, or
3421 * filepath => file path
3423 * If 'file' and 'filepath' parameters are both specified in one request, the
3424 * open file handle in the 'file' parameter will take precedence and 'filepath'
3425 * will be ignored.
3427 * @param array $options An array of options to set
3428 * @return array An array of results
3430 public function download($requests, $options = array()) {
3431 $options['RETURNTRANSFER'] = false;
3432 return $this->multi($requests, $options);
3436 * Returns the current curl security helper.
3438 * @return \core\files\curl_security_helper instance.
3440 public function get_security() {
3441 return $this->securityhelper;
3445 * Sets the curl security helper.
3447 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3448 * @return bool true if the security helper could be set, false otherwise.
3450 public function set_security($securityobject) {
3451 if ($securityobject instanceof \core\files\curl_security_helper) {
3452 $this->securityhelper = $securityobject;
3453 return true;
3455 return false;
3459 * Multi HTTP Requests
3460 * This function could run multi-requests in parallel.
3462 * @param array $requests An array of files to request
3463 * @param array $options An array of options to set
3464 * @return array An array of results
3466 protected function multi($requests, $options = array()) {
3467 $count = count($requests);
3468 $handles = array();
3469 $results = array();
3470 $main = curl_multi_init();
3471 for ($i = 0; $i < $count; $i++) {
3472 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3473 // open file
3474 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3475 $requests[$i]['auto-handle'] = true;
3477 foreach($requests[$i] as $n=>$v) {
3478 $options[$n] = $v;
3480 $handles[$i] = curl_init($requests[$i]['url']);
3481 $this->apply_opt($handles[$i], $options);
3482 curl_multi_add_handle($main, $handles[$i]);
3484 $running = 0;
3485 do {
3486 curl_multi_exec($main, $running);
3487 } while($running > 0);
3488 for ($i = 0; $i < $count; $i++) {
3489 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3490 $results[] = true;
3491 } else {
3492 $results[] = curl_multi_getcontent($handles[$i]);
3494 curl_multi_remove_handle($main, $handles[$i]);
3496 curl_multi_close($main);
3498 for ($i = 0; $i < $count; $i++) {
3499 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3500 // close file handler if file is opened in this function
3501 fclose($requests[$i]['file']);
3504 return $results;
3508 * Helper function to reset the request state vars.
3510 * @return void.
3512 protected function reset_request_state_vars() {
3513 $this->info = array();
3514 $this->error = '';
3515 $this->errno = 0;
3516 $this->response = array();
3517 $this->rawresponse = array();
3518 $this->responsefinished = false;
3522 * For use only in unit tests - we can pre-set the next curl response.
3523 * This is useful for unit testing APIs that call external systems.
3524 * @param string $response
3526 public static function mock_response($response) {
3527 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3528 array_push(self::$mockresponses, $response);
3529 } else {
3530 throw new coding_exception('mock_response function is only available for unit tests.');
3535 * Single HTTP Request
3537 * @param string $url The URL to request
3538 * @param array $options
3539 * @return bool
3541 protected function request($url, $options = array()) {
3542 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3543 $this->reset_request_state_vars();
3545 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3546 if ($mockresponse = array_pop(self::$mockresponses)) {
3547 $this->info = [ 'http_code' => 200 ];
3548 return $mockresponse;
3552 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3553 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3554 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3555 $this->error = $this->securityhelper->get_blocked_url_string();
3556 return $this->error;
3559 // Set the URL as a curl option.
3560 $this->setopt(array('CURLOPT_URL' => $url));
3562 // Create curl instance.
3563 $curl = curl_init();
3565 $this->apply_opt($curl, $options);
3566 if ($this->cache && $ret = $this->cache->get($this->options)) {
3567 return $ret;
3570 $ret = curl_exec($curl);
3571 $this->info = curl_getinfo($curl);
3572 $this->error = curl_error($curl);
3573 $this->errno = curl_errno($curl);
3574 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3576 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3577 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3578 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3579 $this->reset_request_state_vars();
3580 $this->error = $this->securityhelper->get_blocked_url_string();
3581 curl_close($curl);
3582 return $this->error;
3585 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3586 $redirects = 0;
3588 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3590 if ($this->info['http_code'] == 301) {
3591 // Moved Permanently - repeat the same request on new URL.
3593 } else if ($this->info['http_code'] == 302) {
3594 // Found - the standard redirect - repeat the same request on new URL.
3596 } else if ($this->info['http_code'] == 303) {
3597 // 303 See Other - repeat only if GET, do not bother with POSTs.
3598 if (empty($this->options['CURLOPT_HTTPGET'])) {
3599 break;
3602 } else if ($this->info['http_code'] == 307) {
3603 // Temporary Redirect - must repeat using the same request type.
3605 } else if ($this->info['http_code'] == 308) {
3606 // Permanent Redirect - must repeat using the same request type.
3608 } else {
3609 // Some other http code means do not retry!
3610 break;
3613 $redirects++;
3615 $redirecturl = null;
3616 if (isset($this->info['redirect_url'])) {
3617 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3618 $redirecturl = $this->info['redirect_url'];
3621 if (!$redirecturl) {
3622 foreach ($this->response as $k => $v) {
3623 if (strtolower($k) === 'location') {
3624 $redirecturl = $v;
3625 break;
3628 if (preg_match('|^https?://|i', $redirecturl)) {
3629 // Great, this is the correct location format!
3631 } else if ($redirecturl) {
3632 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3633 if (strpos($redirecturl, '/') === 0) {
3634 // Relative to server root - just guess.
3635 $pos = strpos('/', $current, 8);
3636 if ($pos === false) {
3637 $redirecturl = $current.$redirecturl;
3638 } else {
3639 $redirecturl = substr($current, 0, $pos).$redirecturl;
3641 } else {
3642 // Relative to current script.
3643 $redirecturl = dirname($current).'/'.$redirecturl;
3648 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3649 $ret = curl_exec($curl);
3651 $this->info = curl_getinfo($curl);
3652 $this->error = curl_error($curl);
3653 $this->errno = curl_errno($curl);
3655 $this->info['redirect_count'] = $redirects;
3657 if ($this->info['http_code'] === 200) {
3658 // Finally this is what we wanted.
3659 break;
3661 if ($this->errno != CURLE_OK) {
3662 // Something wrong is going on.
3663 break;
3666 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3667 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3668 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3672 if ($this->cache) {
3673 $this->cache->set($this->options, $ret);
3676 if ($this->debug) {
3677 echo '<h1>Return Data</h1>';
3678 var_dump($ret);
3679 echo '<h1>Info</h1>';
3680 var_dump($this->info);
3681 echo '<h1>Error</h1>';
3682 var_dump($this->error);
3685 curl_close($curl);
3687 if (empty($this->error)) {
3688 return $ret;
3689 } else {
3690 return $this->error;
3691 // exception is not ajax friendly
3692 //throw new moodle_exception($this->error, 'curl');
3697 * HTTP HEAD method
3699 * @see request()
3701 * @param string $url
3702 * @param array $options
3703 * @return bool
3705 public function head($url, $options = array()) {
3706 $options['CURLOPT_HTTPGET'] = 0;
3707 $options['CURLOPT_HEADER'] = 1;
3708 $options['CURLOPT_NOBODY'] = 1;
3709 return $this->request($url, $options);
3713 * HTTP PATCH method
3715 * @param string $url
3716 * @param array|string $params
3717 * @param array $options
3718 * @return bool
3720 public function patch($url, $params = '', $options = array()) {
3721 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3722 if (is_array($params)) {
3723 $this->_tmp_file_post_params = array();
3724 foreach ($params as $key => $value) {
3725 if ($value instanceof stored_file) {
3726 $value->add_to_curl_request($this, $key);
3727 } else {
3728 $this->_tmp_file_post_params[$key] = $value;
3731 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3732 unset($this->_tmp_file_post_params);
3733 } else {
3734 // The variable $params is the raw post data.
3735 $options['CURLOPT_POSTFIELDS'] = $params;
3737 return $this->request($url, $options);
3741 * HTTP POST method
3743 * @param string $url
3744 * @param array|string $params
3745 * @param array $options
3746 * @return bool
3748 public function post($url, $params = '', $options = array()) {
3749 $options['CURLOPT_POST'] = 1;
3750 if (is_array($params)) {
3751 $this->_tmp_file_post_params = array();
3752 foreach ($params as $key => $value) {
3753 if ($value instanceof stored_file) {
3754 $value->add_to_curl_request($this, $key);
3755 } else {
3756 $this->_tmp_file_post_params[$key] = $value;
3759 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3760 unset($this->_tmp_file_post_params);
3761 } else {
3762 // $params is the raw post data
3763 $options['CURLOPT_POSTFIELDS'] = $params;
3765 return $this->request($url, $options);
3769 * HTTP GET method
3771 * @param string $url
3772 * @param array $params
3773 * @param array $options
3774 * @return bool
3776 public function get($url, $params = array(), $options = array()) {
3777 $options['CURLOPT_HTTPGET'] = 1;
3779 if (!empty($params)) {
3780 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3781 $url .= http_build_query($params, '', '&');
3783 return $this->request($url, $options);
3787 * Downloads one file and writes it to the specified file handler
3789 * <code>
3790 * $c = new curl();
3791 * $file = fopen('savepath', 'w');
3792 * $result = $c->download_one('http://localhost/', null,
3793 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3794 * fclose($file);
3795 * $download_info = $c->get_info();
3796 * if ($result === true) {
3797 * // file downloaded successfully
3798 * } else {
3799 * $error_text = $result;
3800 * $error_code = $c->get_errno();
3802 * </code>
3804 * <code>
3805 * $c = new curl();
3806 * $result = $c->download_one('http://localhost/', null,
3807 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3808 * // ... see above, no need to close handle and remove file if unsuccessful
3809 * </code>
3811 * @param string $url
3812 * @param array|null $params key-value pairs to be added to $url as query string
3813 * @param array $options request options. Must include either 'file' or 'filepath'
3814 * @return bool|string true on success or error string on failure
3816 public function download_one($url, $params, $options = array()) {
3817 $options['CURLOPT_HTTPGET'] = 1;
3818 if (!empty($params)) {
3819 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3820 $url .= http_build_query($params, '', '&');
3822 if (!empty($options['filepath']) && empty($options['file'])) {
3823 // open file
3824 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3825 $this->errno = 100;
3826 return get_string('cannotwritefile', 'error', $options['filepath']);
3828 $filepath = $options['filepath'];
3830 unset($options['filepath']);
3831 $result = $this->request($url, $options);
3832 if (isset($filepath)) {
3833 fclose($options['file']);
3834 if ($result !== true) {
3835 unlink($filepath);
3838 return $result;
3842 * HTTP PUT method
3844 * @param string $url
3845 * @param array $params
3846 * @param array $options
3847 * @return bool
3849 public function put($url, $params = array(), $options = array()) {
3850 $file = '';
3851 $fp = false;
3852 if (isset($params['file'])) {
3853 $file = $params['file'];
3854 if (is_file($file)) {
3855 $fp = fopen($file, 'r');
3856 $size = filesize($file);
3857 $options['CURLOPT_PUT'] = 1;
3858 $options['CURLOPT_INFILESIZE'] = $size;
3859 $options['CURLOPT_INFILE'] = $fp;
3860 } else {
3861 return null;
3863 if (!isset($this->options['CURLOPT_USERPWD'])) {
3864 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3866 } else {
3867 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3868 $options['CURLOPT_POSTFIELDS'] = $params;
3871 $ret = $this->request($url, $options);
3872 if ($fp !== false) {
3873 fclose($fp);
3875 return $ret;
3879 * HTTP DELETE method
3881 * @param string $url
3882 * @param array $param
3883 * @param array $options
3884 * @return bool
3886 public function delete($url, $param = array(), $options = array()) {
3887 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3888 if (!isset($options['CURLOPT_USERPWD'])) {
3889 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3891 $ret = $this->request($url, $options);
3892 return $ret;
3896 * HTTP TRACE method
3898 * @param string $url
3899 * @param array $options
3900 * @return bool
3902 public function trace($url, $options = array()) {
3903 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3904 $ret = $this->request($url, $options);
3905 return $ret;
3909 * HTTP OPTIONS method
3911 * @param string $url
3912 * @param array $options
3913 * @return bool
3915 public function options($url, $options = array()) {
3916 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3917 $ret = $this->request($url, $options);
3918 return $ret;
3922 * Get curl information
3924 * @return string
3926 public function get_info() {
3927 return $this->info;
3931 * Get curl error code
3933 * @return int
3935 public function get_errno() {
3936 return $this->errno;
3940 * When using a proxy, an additional HTTP response code may appear at
3941 * the start of the header. For example, when using https over a proxy
3942 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3943 * also possible and some may come with their own headers.
3945 * If using the return value containing all headers, this function can be
3946 * called to remove unwanted doubles.
3948 * Note that it is not possible to distinguish this situation from valid
3949 * data unless you know the actual response part (below the headers)
3950 * will not be included in this string, or else will not 'look like' HTTP
3951 * headers. As a result it is not safe to call this function for general
3952 * data.
3954 * @param string $input Input HTTP response
3955 * @return string HTTP response with additional headers stripped if any
3957 public static function strip_double_headers($input) {
3958 // I have tried to make this regular expression as specific as possible
3959 // to avoid any case where it does weird stuff if you happen to put
3960 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3961 // also make it faster because it can abandon regex processing as soon
3962 // as it hits something that doesn't look like an http header. The
3963 // header definition is taken from RFC 822, except I didn't support
3964 // folding which is never used in practice.
3965 $crlf = "\r\n";
3966 return preg_replace(
3967 // HTTP version and status code (ignore value of code).
3968 '~^HTTP/1\..*' . $crlf .
3969 // Header name: character between 33 and 126 decimal, except colon.
3970 // Colon. Header value: any character except \r and \n. CRLF.
3971 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3972 // Headers are terminated by another CRLF (blank line).
3973 $crlf .
3974 // Second HTTP status code, this time must be 200.
3975 '(HTTP/1.[01] 200 )~', '$1', $input);
3980 * This class is used by cURL class, use case:
3982 * <code>
3983 * $CFG->repositorycacheexpire = 120;
3984 * $CFG->curlcache = 120;
3986 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3987 * $ret = $c->get('http://www.google.com');
3988 * </code>
3990 * @package core_files
3991 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3992 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3994 class curl_cache {
3995 /** @var string Path to cache directory */
3996 public $dir = '';
3999 * Constructor
4001 * @global stdClass $CFG
4002 * @param string $module which module is using curl_cache
4004 public function __construct($module = 'repository') {
4005 global $CFG;
4006 if (!empty($module)) {
4007 $this->dir = $CFG->cachedir.'/'.$module.'/';
4008 } else {
4009 $this->dir = $CFG->cachedir.'/misc/';
4011 if (!file_exists($this->dir)) {
4012 mkdir($this->dir, $CFG->directorypermissions, true);
4014 if ($module == 'repository') {
4015 if (empty($CFG->repositorycacheexpire)) {
4016 $CFG->repositorycacheexpire = 120;
4018 $this->ttl = $CFG->repositorycacheexpire;
4019 } else {
4020 if (empty($CFG->curlcache)) {
4021 $CFG->curlcache = 120;
4023 $this->ttl = $CFG->curlcache;
4028 * Get cached value
4030 * @global stdClass $CFG
4031 * @global stdClass $USER
4032 * @param mixed $param
4033 * @return bool|string
4035 public function get($param) {
4036 global $CFG, $USER;
4037 $this->cleanup($this->ttl);
4038 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4039 if(file_exists($this->dir.$filename)) {
4040 $lasttime = filemtime($this->dir.$filename);
4041 if (time()-$lasttime > $this->ttl) {
4042 return false;
4043 } else {
4044 $fp = fopen($this->dir.$filename, 'r');
4045 $size = filesize($this->dir.$filename);
4046 $content = fread($fp, $size);
4047 return unserialize($content);
4050 return false;
4054 * Set cache value
4056 * @global object $CFG
4057 * @global object $USER
4058 * @param mixed $param
4059 * @param mixed $val
4061 public function set($param, $val) {
4062 global $CFG, $USER;
4063 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4064 $fp = fopen($this->dir.$filename, 'w');
4065 fwrite($fp, serialize($val));
4066 fclose($fp);
4067 @chmod($this->dir.$filename, $CFG->filepermissions);
4071 * Remove cache files
4073 * @param int $expire The number of seconds before expiry
4075 public function cleanup($expire) {
4076 if ($dir = opendir($this->dir)) {
4077 while (false !== ($file = readdir($dir))) {
4078 if(!is_dir($file) && $file != '.' && $file != '..') {
4079 $lasttime = @filemtime($this->dir.$file);
4080 if (time() - $lasttime > $expire) {
4081 @unlink($this->dir.$file);
4085 closedir($dir);
4089 * delete current user's cache file
4091 * @global object $CFG
4092 * @global object $USER
4094 public function refresh() {
4095 global $CFG, $USER;
4096 if ($dir = opendir($this->dir)) {
4097 while (false !== ($file = readdir($dir))) {
4098 if (!is_dir($file) && $file != '.' && $file != '..') {
4099 if (strpos($file, 'u'.$USER->id.'_') !== false) {
4100 @unlink($this->dir.$file);
4109 * This function delegates file serving to individual plugins
4111 * @param string $relativepath
4112 * @param bool $forcedownload
4113 * @param null|string $preview the preview mode, defaults to serving the original file
4114 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4115 * offline (e.g. mobile app).
4116 * @param bool $embed Whether this file will be served embed into an iframe.
4117 * @todo MDL-31088 file serving improments
4119 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4120 global $DB, $CFG, $USER;
4121 // relative path must start with '/'
4122 if (!$relativepath) {
4123 print_error('invalidargorconf');
4124 } else if ($relativepath[0] != '/') {
4125 print_error('pathdoesnotstartslash');
4128 // extract relative path components
4129 $args = explode('/', ltrim($relativepath, '/'));
4131 if (count($args) < 3) { // always at least context, component and filearea
4132 print_error('invalidarguments');
4135 $contextid = (int)array_shift($args);
4136 $component = clean_param(array_shift($args), PARAM_COMPONENT);
4137 $filearea = clean_param(array_shift($args), PARAM_AREA);
4139 list($context, $course, $cm) = get_context_info_array($contextid);
4141 $fs = get_file_storage();
4143 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4145 // ========================================================================================================================
4146 if ($component === 'blog') {
4147 // Blog file serving
4148 if ($context->contextlevel != CONTEXT_SYSTEM) {
4149 send_file_not_found();
4151 if ($filearea !== 'attachment' and $filearea !== 'post') {
4152 send_file_not_found();
4155 if (empty($CFG->enableblogs)) {
4156 print_error('siteblogdisable', 'blog');
4159 $entryid = (int)array_shift($args);
4160 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4161 send_file_not_found();
4163 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4164 require_login();
4165 if (isguestuser()) {
4166 print_error('noguest');
4168 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4169 if ($USER->id != $entry->userid) {
4170 send_file_not_found();
4175 if ($entry->publishstate === 'public') {
4176 if ($CFG->forcelogin) {
4177 require_login();
4180 } else if ($entry->publishstate === 'site') {
4181 require_login();
4182 //ok
4183 } else if ($entry->publishstate === 'draft') {
4184 require_login();
4185 if ($USER->id != $entry->userid) {
4186 send_file_not_found();
4190 $filename = array_pop($args);
4191 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4193 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4194 send_file_not_found();
4197 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4199 // ========================================================================================================================
4200 } else if ($component === 'grade') {
4202 require_once($CFG->libdir . '/grade/constants.php');
4204 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4205 // Global gradebook files
4206 if ($CFG->forcelogin) {
4207 require_login();
4210 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4212 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4213 send_file_not_found();
4216 \core\session\manager::write_close(); // Unlock session during file serving.
4217 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4219 } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4220 if ($context->contextlevel != CONTEXT_MODULE) {
4221 send_file_not_found();
4224 require_login($course, false);
4226 $gradeid = (int) array_shift($args);
4227 $filename = array_pop($args);
4228 if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4229 $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4230 } else {
4231 $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4234 if (!$grade) {
4235 send_file_not_found();
4238 $iscurrentuser = $USER->id == $grade->userid;
4240 if (!$iscurrentuser) {
4241 $coursecontext = context_course::instance($course->id);
4242 if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4243 send_file_not_found();
4247 $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4249 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4250 send_file_not_found();
4253 \core\session\manager::write_close(); // Unlock session during file serving.
4254 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4255 } else {
4256 send_file_not_found();
4259 // ========================================================================================================================
4260 } else if ($component === 'tag') {
4261 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4263 // All tag descriptions are going to be public but we still need to respect forcelogin
4264 if ($CFG->forcelogin) {
4265 require_login();
4268 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4270 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4271 send_file_not_found();
4274 \core\session\manager::write_close(); // Unlock session during file serving.
4275 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4277 } else {
4278 send_file_not_found();
4280 // ========================================================================================================================
4281 } else if ($component === 'badges') {
4282 require_once($CFG->libdir . '/badgeslib.php');
4284 $badgeid = (int)array_shift($args);
4285 $badge = new badge($badgeid);
4286 $filename = array_pop($args);
4288 if ($filearea === 'badgeimage') {
4289 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4290 send_file_not_found();
4292 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4293 send_file_not_found();
4296 \core\session\manager::write_close();
4297 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4298 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4299 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4300 send_file_not_found();
4303 \core\session\manager::write_close();
4304 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4306 // ========================================================================================================================
4307 } else if ($component === 'calendar') {
4308 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4310 // All events here are public the one requirement is that we respect forcelogin
4311 if ($CFG->forcelogin) {
4312 require_login();
4315 // Get the event if from the args array
4316 $eventid = array_shift($args);
4318 // Load the event from the database
4319 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4320 send_file_not_found();
4323 // Get the file and serve if successful
4324 $filename = array_pop($args);
4325 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4326 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4327 send_file_not_found();
4330 \core\session\manager::write_close(); // Unlock session during file serving.
4331 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4333 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4335 // Must be logged in, if they are not then they obviously can't be this user
4336 require_login();
4338 // Don't want guests here, potentially saves a DB call
4339 if (isguestuser()) {
4340 send_file_not_found();
4343 // Get the event if from the args array
4344 $eventid = array_shift($args);
4346 // Load the event from the database - user id must match
4347 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4348 send_file_not_found();
4351 // Get the file and serve if successful
4352 $filename = array_pop($args);
4353 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4354 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4355 send_file_not_found();
4358 \core\session\manager::write_close(); // Unlock session during file serving.
4359 send_stored_file($file, 0, 0, true, $sendfileoptions);
4361 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4363 // Respect forcelogin and require login unless this is the site.... it probably
4364 // should NEVER be the site
4365 if ($CFG->forcelogin || $course->id != SITEID) {
4366 require_login($course);
4369 // Must be able to at least view the course. This does not apply to the front page.
4370 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4371 //TODO: hmm, do we really want to block guests here?
4372 send_file_not_found();
4375 // Get the event id
4376 $eventid = array_shift($args);
4378 // Load the event from the database we need to check whether it is
4379 // a) valid course event
4380 // b) a group event
4381 // Group events use the course context (there is no group context)
4382 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4383 send_file_not_found();
4386 // If its a group event require either membership of view all groups capability
4387 if ($event->eventtype === 'group') {
4388 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4389 send_file_not_found();
4391 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4392 // Ok. Please note that the event type 'site' still uses a course context.
4393 } else {
4394 // Some other type.
4395 send_file_not_found();
4398 // If we get this far we can serve the file
4399 $filename = array_pop($args);
4400 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4401 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4402 send_file_not_found();
4405 \core\session\manager::write_close(); // Unlock session during file serving.
4406 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4408 } else {
4409 send_file_not_found();
4412 // ========================================================================================================================
4413 } else if ($component === 'user') {
4414 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4415 if (count($args) == 1) {
4416 $themename = theme_config::DEFAULT_THEME;
4417 $filename = array_shift($args);
4418 } else {
4419 $themename = array_shift($args);
4420 $filename = array_shift($args);
4423 // fix file name automatically
4424 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4425 $filename = 'f1';
4428 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4429 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4430 // protect images if login required and not logged in;
4431 // also if login is required for profile images and is not logged in or guest
4432 // do not use require_login() because it is expensive and not suitable here anyway
4433 $theme = theme_config::load($themename);
4434 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4437 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4438 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4439 if ($filename === 'f3') {
4440 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4441 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4442 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4447 if (!$file) {
4448 // bad reference - try to prevent future retries as hard as possible!
4449 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4450 if ($user->picture > 0) {
4451 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4454 // no redirect here because it is not cached
4455 $theme = theme_config::load($themename);
4456 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4457 send_file($imagefile, basename($imagefile), 60*60*24*14);
4460 $options = $sendfileoptions;
4461 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4462 // Profile images should be cache-able by both browsers and proxies according
4463 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4464 $options['cacheability'] = 'public';
4466 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4468 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4469 require_login();
4471 if (isguestuser()) {
4472 send_file_not_found();
4475 if ($USER->id !== $context->instanceid) {
4476 send_file_not_found();
4479 $filename = array_pop($args);
4480 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4481 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4482 send_file_not_found();
4485 \core\session\manager::write_close(); // Unlock session during file serving.
4486 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4488 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4490 if ($CFG->forcelogin) {
4491 require_login();
4494 $userid = $context->instanceid;
4496 if ($USER->id == $userid) {
4497 // always can access own
4499 } else if (!empty($CFG->forceloginforprofiles)) {
4500 require_login();
4502 if (isguestuser()) {
4503 send_file_not_found();
4506 // we allow access to site profile of all course contacts (usually teachers)
4507 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4508 send_file_not_found();
4511 $canview = false;
4512 if (has_capability('moodle/user:viewdetails', $context)) {
4513 $canview = true;
4514 } else {
4515 $courses = enrol_get_my_courses();
4518 while (!$canview && count($courses) > 0) {
4519 $course = array_shift($courses);
4520 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4521 $canview = true;
4526 $filename = array_pop($args);
4527 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4528 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4529 send_file_not_found();
4532 \core\session\manager::write_close(); // Unlock session during file serving.
4533 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4535 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4536 $userid = (int)array_shift($args);
4537 $usercontext = context_user::instance($userid);
4539 if ($CFG->forcelogin) {
4540 require_login();
4543 if (!empty($CFG->forceloginforprofiles)) {
4544 require_login();
4545 if (isguestuser()) {
4546 print_error('noguest');
4549 //TODO: review this logic of user profile access prevention
4550 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4551 print_error('usernotavailable');
4553 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4554 print_error('cannotviewprofile');
4556 if (!is_enrolled($context, $userid)) {
4557 print_error('notenrolledprofile');
4559 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4560 print_error('groupnotamember');
4564 $filename = array_pop($args);
4565 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4566 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4567 send_file_not_found();
4570 \core\session\manager::write_close(); // Unlock session during file serving.
4571 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4573 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4574 require_login();
4576 if (isguestuser()) {
4577 send_file_not_found();
4579 $userid = $context->instanceid;
4581 if ($USER->id != $userid) {
4582 send_file_not_found();
4585 $filename = array_pop($args);
4586 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4587 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4588 send_file_not_found();
4591 \core\session\manager::write_close(); // Unlock session during file serving.
4592 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4594 } else {
4595 send_file_not_found();
4598 // ========================================================================================================================
4599 } else if ($component === 'coursecat') {
4600 if ($context->contextlevel != CONTEXT_COURSECAT) {
4601 send_file_not_found();
4604 if ($filearea === 'description') {
4605 if ($CFG->forcelogin) {
4606 // no login necessary - unless login forced everywhere
4607 require_login();
4610 // Check if user can view this category.
4611 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4612 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid));
4613 if (!$coursecatvisible) {
4614 send_file_not_found();
4618 $filename = array_pop($args);
4619 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4620 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4621 send_file_not_found();
4624 \core\session\manager::write_close(); // Unlock session during file serving.
4625 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4626 } else {
4627 send_file_not_found();
4630 // ========================================================================================================================
4631 } else if ($component === 'course') {
4632 if ($context->contextlevel != CONTEXT_COURSE) {
4633 send_file_not_found();
4636 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4637 if ($CFG->forcelogin) {
4638 require_login();
4641 $filename = array_pop($args);
4642 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4643 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4644 send_file_not_found();
4647 \core\session\manager::write_close(); // Unlock session during file serving.
4648 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4650 } else if ($filearea === 'section') {
4651 if ($CFG->forcelogin) {
4652 require_login($course);
4653 } else if ($course->id != SITEID) {
4654 require_login($course);
4657 $sectionid = (int)array_shift($args);
4659 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4660 send_file_not_found();
4663 $filename = array_pop($args);
4664 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4665 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4666 send_file_not_found();
4669 \core\session\manager::write_close(); // Unlock session during file serving.
4670 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4672 } else {
4673 send_file_not_found();
4676 } else if ($component === 'cohort') {
4678 $cohortid = (int)array_shift($args);
4679 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4680 $cohortcontext = context::instance_by_id($cohort->contextid);
4682 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4683 if ($context->id != $cohort->contextid &&
4684 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4685 send_file_not_found();
4688 // User is able to access cohort if they have view cap on cohort level or
4689 // the cohort is visible and they have view cap on course level.
4690 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4691 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4693 if ($filearea === 'description' && $canview) {
4694 $filename = array_pop($args);
4695 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4696 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4697 && !$file->is_directory()) {
4698 \core\session\manager::write_close(); // Unlock session during file serving.
4699 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4703 send_file_not_found();
4705 } else if ($component === 'group') {
4706 if ($context->contextlevel != CONTEXT_COURSE) {
4707 send_file_not_found();
4710 require_course_login($course, true, null, false);
4712 $groupid = (int)array_shift($args);
4714 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4715 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4716 // do not allow access to separate group info if not member or teacher
4717 send_file_not_found();
4720 if ($filearea === 'description') {
4722 require_login($course);
4724 $filename = array_pop($args);
4725 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4726 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4727 send_file_not_found();
4730 \core\session\manager::write_close(); // Unlock session during file serving.
4731 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4733 } else if ($filearea === 'icon') {
4734 $filename = array_pop($args);
4736 if ($filename !== 'f1' and $filename !== 'f2') {
4737 send_file_not_found();
4739 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4740 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4741 send_file_not_found();
4745 \core\session\manager::write_close(); // Unlock session during file serving.
4746 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4748 } else {
4749 send_file_not_found();
4752 } else if ($component === 'grouping') {
4753 if ($context->contextlevel != CONTEXT_COURSE) {
4754 send_file_not_found();
4757 require_login($course);
4759 $groupingid = (int)array_shift($args);
4761 // note: everybody has access to grouping desc images for now
4762 if ($filearea === 'description') {
4764 $filename = array_pop($args);
4765 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4766 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4767 send_file_not_found();
4770 \core\session\manager::write_close(); // Unlock session during file serving.
4771 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4773 } else {
4774 send_file_not_found();
4777 // ========================================================================================================================
4778 } else if ($component === 'backup') {
4779 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4780 require_login($course);
4781 require_capability('moodle/backup:downloadfile', $context);
4783 $filename = array_pop($args);
4784 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4785 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4786 send_file_not_found();
4789 \core\session\manager::write_close(); // Unlock session during file serving.
4790 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4792 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4793 require_login($course);
4794 require_capability('moodle/backup:downloadfile', $context);
4796 $sectionid = (int)array_shift($args);
4798 $filename = array_pop($args);
4799 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4800 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4801 send_file_not_found();
4804 \core\session\manager::write_close();
4805 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4807 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4808 require_login($course, false, $cm);
4809 require_capability('moodle/backup:downloadfile', $context);
4811 $filename = array_pop($args);
4812 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4813 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4814 send_file_not_found();
4817 \core\session\manager::write_close();
4818 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4820 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4821 // Backup files that were generated by the automated backup systems.
4823 require_login($course);
4824 require_capability('moodle/backup:downloadfile', $context);
4825 require_capability('moodle/restore:userinfo', $context);
4827 $filename = array_pop($args);
4828 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4829 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4830 send_file_not_found();
4833 \core\session\manager::write_close(); // Unlock session during file serving.
4834 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4836 } else {
4837 send_file_not_found();
4840 // ========================================================================================================================
4841 } else if ($component === 'question') {
4842 require_once($CFG->libdir . '/questionlib.php');
4843 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4844 send_file_not_found();
4846 // ========================================================================================================================
4847 } else if ($component === 'grading') {
4848 if ($filearea === 'description') {
4849 // files embedded into the form definition description
4851 if ($context->contextlevel == CONTEXT_SYSTEM) {
4852 require_login();
4854 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4855 require_login($course, false, $cm);
4857 } else {
4858 send_file_not_found();
4861 $formid = (int)array_shift($args);
4863 $sql = "SELECT ga.id
4864 FROM {grading_areas} ga
4865 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4866 WHERE gd.id = ? AND ga.contextid = ?";
4867 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4869 if (!$areaid) {
4870 send_file_not_found();
4873 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4875 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4876 send_file_not_found();
4879 \core\session\manager::write_close(); // Unlock session during file serving.
4880 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4883 // ========================================================================================================================
4884 } else if (strpos($component, 'mod_') === 0) {
4885 $modname = substr($component, 4);
4886 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4887 send_file_not_found();
4889 require_once("$CFG->dirroot/mod/$modname/lib.php");
4891 if ($context->contextlevel == CONTEXT_MODULE) {
4892 if ($cm->modname !== $modname) {
4893 // somebody tries to gain illegal access, cm type must match the component!
4894 send_file_not_found();
4898 if ($filearea === 'intro') {
4899 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4900 send_file_not_found();
4903 // Require login to the course first (without login to the module).
4904 require_course_login($course, true);
4906 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4907 $cminfo = cm_info::create($cm);
4908 if (!$cminfo->uservisible) {
4909 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
4910 // Module intro is not visible on the course page and module is not available, show access error.
4911 require_course_login($course, true, $cminfo);
4915 // all users may access it
4916 $filename = array_pop($args);
4917 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4918 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4919 send_file_not_found();
4922 // finally send the file
4923 send_stored_file($file, null, 0, false, $sendfileoptions);
4926 $filefunction = $component.'_pluginfile';
4927 $filefunctionold = $modname.'_pluginfile';
4928 if (function_exists($filefunction)) {
4929 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4930 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4931 } else if (function_exists($filefunctionold)) {
4932 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4933 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4936 send_file_not_found();
4938 // ========================================================================================================================
4939 } else if (strpos($component, 'block_') === 0) {
4940 $blockname = substr($component, 6);
4941 // note: no more class methods in blocks please, that is ....
4942 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4943 send_file_not_found();
4945 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4947 if ($context->contextlevel == CONTEXT_BLOCK) {
4948 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4949 if ($birecord->blockname !== $blockname) {
4950 // somebody tries to gain illegal access, cm type must match the component!
4951 send_file_not_found();
4954 if ($context->get_course_context(false)) {
4955 // If block is in course context, then check if user has capability to access course.
4956 require_course_login($course);
4957 } else if ($CFG->forcelogin) {
4958 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4959 require_login();
4962 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4963 // User can't access file, if block is hidden or doesn't have block:view capability
4964 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4965 send_file_not_found();
4967 } else {
4968 $birecord = null;
4971 $filefunction = $component.'_pluginfile';
4972 if (function_exists($filefunction)) {
4973 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4974 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4977 send_file_not_found();
4979 // ========================================================================================================================
4980 } else if (strpos($component, '_') === false) {
4981 // all core subsystems have to be specified above, no more guessing here!
4982 send_file_not_found();
4984 } else {
4985 // try to serve general plugin file in arbitrary context
4986 $dir = core_component::get_component_directory($component);
4987 if (!file_exists("$dir/lib.php")) {
4988 send_file_not_found();
4990 include_once("$dir/lib.php");
4992 $filefunction = $component.'_pluginfile';
4993 if (function_exists($filefunction)) {
4994 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4995 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4998 send_file_not_found();