Merge branch 'MDL-57755_master' of https://github.com/t-schroeder/moodle
[moodle.git] / lib / filelib.php
blobc8e98f503dde004d216bf3323a97d57a764b3bc0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for file handling.
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
33 /**
34 * Do not process file merging when working with draft area files.
36 define('IGNORE_FILE_MERGE', -1);
38 /**
39 * Unlimited area size constant
41 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
43 require_once("$CFG->libdir/filestorage/file_exceptions.php");
44 require_once("$CFG->libdir/filestorage/file_storage.php");
45 require_once("$CFG->libdir/filestorage/zip_packer.php");
46 require_once("$CFG->libdir/filebrowser/file_browser.php");
48 /**
49 * Encodes file serving url
51 * @deprecated use moodle_url factory methods instead
53 * @todo MDL-31071 deprecate this function
54 * @global stdClass $CFG
55 * @param string $urlbase
56 * @param string $path /filearea/itemid/dir/dir/file.exe
57 * @param bool $forcedownload
58 * @param bool $https https url required
59 * @return string encoded file url
61 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
62 global $CFG;
64 //TODO: deprecate this
66 if ($CFG->slasharguments) {
67 $parts = explode('/', $path);
68 $parts = array_map('rawurlencode', $parts);
69 $path = implode('/', $parts);
70 $return = $urlbase.$path;
71 if ($forcedownload) {
72 $return .= '?forcedownload=1';
74 } else {
75 $path = rawurlencode($path);
76 $return = $urlbase.'?file='.$path;
77 if ($forcedownload) {
78 $return .= '&amp;forcedownload=1';
82 if ($https) {
83 $return = str_replace('http://', 'https://', $return);
86 return $return;
89 /**
90 * Detects if area contains subdirs,
91 * this is intended for file areas that are attached to content
92 * migrated from 1.x where subdirs were allowed everywhere.
94 * @param context $context
95 * @param string $component
96 * @param string $filearea
97 * @param string $itemid
98 * @return bool
100 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
101 global $DB;
103 if (!isset($itemid)) {
104 // Not initialised yet.
105 return false;
108 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
109 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
110 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
111 return $DB->record_exists_select('files', $select, $params);
115 * Prepares 'editor' formslib element from data in database
117 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
118 * function then copies the embedded files into draft area (assigning itemids automatically),
119 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
120 * displayed.
121 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
122 * your mform's set_data() supplying the object returned by this function.
124 * @category files
125 * @param stdClass $data database field that holds the html text with embedded media
126 * @param string $field the name of the database field that holds the html text with embedded media
127 * @param array $options editor options (like maxifiles, maxbytes etc.)
128 * @param stdClass $context context of the editor
129 * @param string $component
130 * @param string $filearea file area name
131 * @param int $itemid item id, required if item exists
132 * @return stdClass modified data object
134 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
135 $options = (array)$options;
136 if (!isset($options['trusttext'])) {
137 $options['trusttext'] = false;
139 if (!isset($options['forcehttps'])) {
140 $options['forcehttps'] = false;
142 if (!isset($options['subdirs'])) {
143 $options['subdirs'] = false;
145 if (!isset($options['maxfiles'])) {
146 $options['maxfiles'] = 0; // no files by default
148 if (!isset($options['noclean'])) {
149 $options['noclean'] = false;
152 //sanity check for passed context. This function doesn't expect $option['context'] to be set
153 //But this function is called before creating editor hence, this is one of the best places to check
154 //if context is used properly. This check notify developer that they missed passing context to editor.
155 if (isset($context) && !isset($options['context'])) {
156 //if $context is not null then make sure $option['context'] is also set.
157 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
158 } else if (isset($options['context']) && isset($context)) {
159 //If both are passed then they should be equal.
160 if ($options['context']->id != $context->id) {
161 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
162 throw new coding_exception($exceptionmsg);
166 if (is_null($itemid) or is_null($context)) {
167 $contextid = null;
168 $itemid = null;
169 if (!isset($data)) {
170 $data = new stdClass();
172 if (!isset($data->{$field})) {
173 $data->{$field} = '';
175 if (!isset($data->{$field.'format'})) {
176 $data->{$field.'format'} = editors_get_preferred_format();
178 if (!$options['noclean']) {
179 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
182 } else {
183 if ($options['trusttext']) {
184 // noclean ignored if trusttext enabled
185 if (!isset($data->{$field.'trust'})) {
186 $data->{$field.'trust'} = 0;
188 $data = trusttext_pre_edit($data, $field, $context);
189 } else {
190 if (!$options['noclean']) {
191 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
194 $contextid = $context->id;
197 if ($options['maxfiles'] != 0) {
198 $draftid_editor = file_get_submitted_draft_itemid($field);
199 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
200 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
201 } else {
202 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
205 return $data;
209 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
211 * This function moves files from draft area to the destination area and
212 * encodes URLs to the draft files so they can be safely saved into DB. The
213 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
214 * is the name of the database field to hold the wysiwyg editor content. The
215 * editor data comes as an array with text, format and itemid properties. This
216 * function automatically adds $data properties foobar, foobarformat and
217 * foobartrust, where foobar has URL to embedded files encoded.
219 * @category files
220 * @param stdClass $data raw data submitted by the form
221 * @param string $field name of the database field containing the html with embedded media files
222 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
223 * @param stdClass $context context, required for existing data
224 * @param string $component file component
225 * @param string $filearea file area name
226 * @param int $itemid item id, required if item exists
227 * @return stdClass modified data object
229 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
230 $options = (array)$options;
231 if (!isset($options['trusttext'])) {
232 $options['trusttext'] = false;
234 if (!isset($options['forcehttps'])) {
235 $options['forcehttps'] = false;
237 if (!isset($options['subdirs'])) {
238 $options['subdirs'] = false;
240 if (!isset($options['maxfiles'])) {
241 $options['maxfiles'] = 0; // no files by default
243 if (!isset($options['maxbytes'])) {
244 $options['maxbytes'] = 0; // unlimited
246 if (!isset($options['removeorphaneddrafts'])) {
247 $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
250 if ($options['trusttext']) {
251 $data->{$field.'trust'} = trusttext_trusted($context);
252 } else {
253 $data->{$field.'trust'} = 0;
256 $editor = $data->{$field.'_editor'};
258 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
259 $data->{$field} = $editor['text'];
260 } else {
261 // Clean the user drafts area of any files not referenced in the editor text.
262 if ($options['removeorphaneddrafts']) {
263 file_remove_editor_orphaned_files($editor);
265 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
267 $data->{$field.'format'} = $editor['format'];
269 return $data;
273 * Saves text and files modified by Editor formslib element
275 * @category files
276 * @param stdClass $data $database entry field
277 * @param string $field name of data field
278 * @param array $options various options
279 * @param stdClass $context context - must already exist
280 * @param string $component
281 * @param string $filearea file area name
282 * @param int $itemid must already exist, usually means data is in db
283 * @return stdClass modified data obejct
285 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
286 $options = (array)$options;
287 if (!isset($options['subdirs'])) {
288 $options['subdirs'] = false;
290 if (is_null($itemid) or is_null($context)) {
291 $itemid = null;
292 $contextid = null;
293 } else {
294 $contextid = $context->id;
297 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
298 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
299 $data->{$field.'_filemanager'} = $draftid_editor;
301 return $data;
305 * Saves files modified by File manager formslib element
307 * @todo MDL-31073 review this function
308 * @category files
309 * @param stdClass $data $database entry field
310 * @param string $field name of data field
311 * @param array $options various options
312 * @param stdClass $context context - must already exist
313 * @param string $component
314 * @param string $filearea file area name
315 * @param int $itemid must already exist, usually means data is in db
316 * @return stdClass modified data obejct
318 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
319 $options = (array)$options;
320 if (!isset($options['subdirs'])) {
321 $options['subdirs'] = false;
323 if (!isset($options['maxfiles'])) {
324 $options['maxfiles'] = -1; // unlimited
326 if (!isset($options['maxbytes'])) {
327 $options['maxbytes'] = 0; // unlimited
330 if (empty($data->{$field.'_filemanager'})) {
331 $data->$field = '';
333 } else {
334 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
335 $fs = get_file_storage();
337 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
338 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
339 } else {
340 $data->$field = '';
344 return $data;
348 * Generate a draft itemid
350 * @category files
351 * @global moodle_database $DB
352 * @global stdClass $USER
353 * @return int a random but available draft itemid that can be used to create a new draft
354 * file area.
356 function file_get_unused_draft_itemid() {
357 global $DB, $USER;
359 if (isguestuser() or !isloggedin()) {
360 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
361 print_error('noguest');
364 $contextid = context_user::instance($USER->id)->id;
366 $fs = get_file_storage();
367 $draftitemid = rand(1, 999999999);
368 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
369 $draftitemid = rand(1, 999999999);
372 return $draftitemid;
376 * Initialise a draft file area from a real one by copying the files. A draft
377 * area will be created if one does not already exist. Normally you should
378 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
380 * @category files
381 * @global stdClass $CFG
382 * @global stdClass $USER
383 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
384 * @param int $contextid This parameter and the next two identify the file area to copy files from.
385 * @param string $component
386 * @param string $filearea helps indentify the file area.
387 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
388 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
389 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
390 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
392 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
393 global $CFG, $USER, $CFG;
395 $options = (array)$options;
396 if (!isset($options['subdirs'])) {
397 $options['subdirs'] = false;
399 if (!isset($options['forcehttps'])) {
400 $options['forcehttps'] = false;
403 $usercontext = context_user::instance($USER->id);
404 $fs = get_file_storage();
406 if (empty($draftitemid)) {
407 // create a new area and copy existing files into
408 $draftitemid = file_get_unused_draft_itemid();
409 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
410 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
411 foreach ($files as $file) {
412 if ($file->is_directory() and $file->get_filepath() === '/') {
413 // we need a way to mark the age of each draft area,
414 // by not copying the root dir we force it to be created automatically with current timestamp
415 continue;
417 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
418 continue;
420 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
421 // XXX: This is a hack for file manager (MDL-28666)
422 // File manager needs to know the original file information before copying
423 // to draft area, so we append these information in mdl_files.source field
424 // {@link file_storage::search_references()}
425 // {@link file_storage::search_references_count()}
426 $sourcefield = $file->get_source();
427 $newsourcefield = new stdClass;
428 $newsourcefield->source = $sourcefield;
429 $original = new stdClass;
430 $original->contextid = $contextid;
431 $original->component = $component;
432 $original->filearea = $filearea;
433 $original->itemid = $itemid;
434 $original->filename = $file->get_filename();
435 $original->filepath = $file->get_filepath();
436 $newsourcefield->original = file_storage::pack_reference($original);
437 $draftfile->set_source(serialize($newsourcefield));
438 // End of file manager hack
441 if (!is_null($text)) {
442 // at this point there should not be any draftfile links yet,
443 // because this is a new text from database that should still contain the @@pluginfile@@ links
444 // this happens when developers forget to post process the text
445 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
447 } else {
448 // nothing to do
451 if (is_null($text)) {
452 return null;
455 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
456 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
460 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
461 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
462 * in the @@PLUGINFILE@@ form.
464 * @param string $text The content that may contain ULRs in need of rewriting.
465 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
466 * @param int $contextid This parameter and the next two identify the file area to use.
467 * @param string $component
468 * @param string $filearea helps identify the file area.
469 * @param int $itemid helps identify the file area.
470 * @param array $options
471 * bool $options.forcehttps Force the user of https
472 * bool $options.reverse Reverse the behaviour of the function
473 * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
474 * string The processed text.
476 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
477 global $CFG, $USER;
479 $options = (array)$options;
480 if (!isset($options['forcehttps'])) {
481 $options['forcehttps'] = false;
484 $baseurl = "{$CFG->wwwroot}/{$file}";
485 if (!empty($options['includetoken'])) {
486 $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
487 $token = get_user_key('core_files', $userid);
488 $finalfile = basename($file);
489 $tokenfile = "token{$finalfile}";
490 $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
491 $baseurl = "{$CFG->wwwroot}/{$file}";
493 if (!$CFG->slasharguments) {
494 $baseurl .= "?token={$token}&file=";
495 } else {
496 $baseurl .= "/{$token}";
500 $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
502 if ($itemid !== null) {
503 $baseurl .= "$itemid/";
506 if ($options['forcehttps']) {
507 $baseurl = str_replace('http://', 'https://', $baseurl);
510 if (!empty($options['reverse'])) {
511 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
512 } else {
513 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
518 * Returns information about files in a draft area.
520 * @global stdClass $CFG
521 * @global stdClass $USER
522 * @param int $draftitemid the draft area item id.
523 * @param string $filepath path to the directory from which the information have to be retrieved.
524 * @return array with the following entries:
525 * 'filecount' => number of files in the draft area.
526 * 'filesize' => total size of the files in the draft area.
527 * 'foldercount' => number of folders in the draft area.
528 * 'filesize_without_references' => total size of the area excluding file references.
529 * (more information will be added as needed).
531 function file_get_draft_area_info($draftitemid, $filepath = '/') {
532 global $USER;
534 $usercontext = context_user::instance($USER->id);
535 return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
539 * Returns information about files in an area.
541 * @param int $contextid context id
542 * @param string $component component
543 * @param string $filearea file area name
544 * @param int $itemid item id or all files if not specified
545 * @param string $filepath path to the directory from which the information have to be retrieved.
546 * @return array with the following entries:
547 * 'filecount' => number of files in the area.
548 * 'filesize' => total size of the files in the area.
549 * 'foldercount' => number of folders in the area.
550 * 'filesize_without_references' => total size of the area excluding file references.
551 * @since Moodle 3.4
553 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
555 $fs = get_file_storage();
557 $results = array(
558 'filecount' => 0,
559 'foldercount' => 0,
560 'filesize' => 0,
561 'filesize_without_references' => 0
564 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
566 foreach ($draftfiles as $file) {
567 if ($file->is_directory()) {
568 $results['foldercount'] += 1;
569 } else {
570 $results['filecount'] += 1;
573 $filesize = $file->get_filesize();
574 $results['filesize'] += $filesize;
575 if (!$file->is_external_file()) {
576 $results['filesize_without_references'] += $filesize;
580 return $results;
584 * Returns whether a draft area has exceeded/will exceed its size limit.
586 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
588 * @param int $draftitemid the draft area item id.
589 * @param int $areamaxbytes the maximum size allowed in this draft area.
590 * @param int $newfilesize the size that would be added to the current area.
591 * @param bool $includereferences true to include the size of the references in the area size.
592 * @return bool true if the area will/has exceeded its limit.
593 * @since Moodle 2.4
595 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
596 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
597 $draftinfo = file_get_draft_area_info($draftitemid);
598 $areasize = $draftinfo['filesize_without_references'];
599 if ($includereferences) {
600 $areasize = $draftinfo['filesize'];
602 if ($areasize + $newfilesize > $areamaxbytes) {
603 return true;
606 return false;
610 * Get used space of files
611 * @global moodle_database $DB
612 * @global stdClass $USER
613 * @return int total bytes
615 function file_get_user_used_space() {
616 global $DB, $USER;
618 $usercontext = context_user::instance($USER->id);
619 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
620 JOIN (SELECT contenthash, filename, MAX(id) AS id
621 FROM {files}
622 WHERE contextid = ? AND component = ? AND filearea != ?
623 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
624 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
625 $record = $DB->get_record_sql($sql, $params);
626 return (int)$record->totalbytes;
630 * Convert any string to a valid filepath
631 * @todo review this function
632 * @param string $str
633 * @return string path
635 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
636 if ($str == '/' or empty($str)) {
637 return '/';
638 } else {
639 return '/'.trim($str, '/').'/';
644 * Generate a folder tree of draft area of current USER recursively
646 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
647 * @param int $draftitemid
648 * @param string $filepath
649 * @param mixed $data
651 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
652 global $USER, $OUTPUT, $CFG;
653 $data->children = array();
654 $context = context_user::instance($USER->id);
655 $fs = get_file_storage();
656 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
657 foreach ($files as $file) {
658 if ($file->is_directory()) {
659 $item = new stdClass();
660 $item->sortorder = $file->get_sortorder();
661 $item->filepath = $file->get_filepath();
663 $foldername = explode('/', trim($item->filepath, '/'));
664 $item->fullname = trim(array_pop($foldername), '/');
666 $item->id = uniqid();
667 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
668 $data->children[] = $item;
669 } else {
670 continue;
677 * Listing all files (including folders) in current path (draft area)
678 * used by file manager
679 * @param int $draftitemid
680 * @param string $filepath
681 * @return stdClass
683 function file_get_drafarea_files($draftitemid, $filepath = '/') {
684 global $USER, $OUTPUT, $CFG;
686 $context = context_user::instance($USER->id);
687 $fs = get_file_storage();
689 $data = new stdClass();
690 $data->path = array();
691 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
693 // will be used to build breadcrumb
694 $trail = '/';
695 if ($filepath !== '/') {
696 $filepath = file_correct_filepath($filepath);
697 $parts = explode('/', $filepath);
698 foreach ($parts as $part) {
699 if ($part != '' && $part != null) {
700 $trail .= ($part.'/');
701 $data->path[] = array('name'=>$part, 'path'=>$trail);
706 $list = array();
707 $maxlength = 12;
708 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
709 foreach ($files as $file) {
710 $item = new stdClass();
711 $item->filename = $file->get_filename();
712 $item->filepath = $file->get_filepath();
713 $item->fullname = trim($item->filename, '/');
714 $filesize = $file->get_filesize();
715 $item->size = $filesize ? $filesize : null;
716 $item->filesize = $filesize ? display_size($filesize) : '';
718 $item->sortorder = $file->get_sortorder();
719 $item->author = $file->get_author();
720 $item->license = $file->get_license();
721 $item->datemodified = $file->get_timemodified();
722 $item->datecreated = $file->get_timecreated();
723 $item->isref = $file->is_external_file();
724 if ($item->isref && $file->get_status() == 666) {
725 $item->originalmissing = true;
727 // find the file this draft file was created from and count all references in local
728 // system pointing to that file
729 $source = @unserialize($file->get_source());
730 if (isset($source->original)) {
731 $item->refcount = $fs->search_references_count($source->original);
734 if ($file->is_directory()) {
735 $item->filesize = 0;
736 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
737 $item->type = 'folder';
738 $foldername = explode('/', trim($item->filepath, '/'));
739 $item->fullname = trim(array_pop($foldername), '/');
740 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
741 } else {
742 // do NOT use file browser here!
743 $item->mimetype = get_mimetype_description($file);
744 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
745 $item->type = 'zip';
746 } else {
747 $item->type = 'file';
749 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
750 $item->url = $itemurl->out();
751 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
752 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
754 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
755 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
756 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
757 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
758 // used by the widget to display a warning about the problem files.
759 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
760 $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
761 if ($item->status == 0) {
762 if ($imageinfo = $file->get_imageinfo()) {
763 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
764 'oid' => $file->get_timemodified()));
765 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
766 $item->image_width = $imageinfo['width'];
767 $item->image_height = $imageinfo['height'];
771 $list[] = $item;
774 $data->itemid = $draftitemid;
775 $data->list = $list;
776 return $data;
780 * Returns all of the files in the draftarea.
782 * @param int $draftitemid The draft item ID
783 * @param string $filepath path for the uploaded files.
784 * @return array An array of files associated with this draft item id.
786 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
787 $files = [];
788 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
789 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
791 if (!empty($draftfiles)) {
792 foreach ($draftfiles->list as $draftfile) {
793 if ($draftfile->type == 'file') {
794 $files[] = $draftfile;
798 if (isset($draftfiles->children)) {
799 foreach ($draftfiles->children as $draftfile) {
800 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
804 return $files;
808 * Returns draft area itemid for a given element.
810 * @category files
811 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
812 * @return int the itemid, or 0 if there is not one yet.
814 function file_get_submitted_draft_itemid($elname) {
815 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
816 if (!isset($_REQUEST[$elname])) {
817 return 0;
819 if (is_array($_REQUEST[$elname])) {
820 $param = optional_param_array($elname, 0, PARAM_INT);
821 if (!empty($param['itemid'])) {
822 $param = $param['itemid'];
823 } else {
824 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
825 return false;
828 } else {
829 $param = optional_param($elname, 0, PARAM_INT);
832 if ($param) {
833 require_sesskey();
836 return $param;
840 * Restore the original source field from draft files
842 * Do not use this function because it makes field files.source inconsistent
843 * for draft area files. This function will be deprecated in 2.6
845 * @param stored_file $storedfile This only works with draft files
846 * @return stored_file
848 function file_restore_source_field_from_draft_file($storedfile) {
849 $source = @unserialize($storedfile->get_source());
850 if (!empty($source)) {
851 if (is_object($source)) {
852 $restoredsource = $source->source;
853 $storedfile->set_source($restoredsource);
854 } else {
855 throw new moodle_exception('invalidsourcefield', 'error');
858 return $storedfile;
862 * Removes those files from the user drafts filearea which are not referenced in the editor text.
864 * @param stdClass $editor The online text editor element from the submitted form data.
866 function file_remove_editor_orphaned_files($editor) {
867 global $CFG, $USER;
869 // Find those draft files included in the text, and generate their hashes.
870 $context = context_user::instance($USER->id);
871 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
872 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
873 preg_match_all($pattern, $editor['text'], $matches);
874 $usedfilehashes = [];
875 foreach ($matches[1] as $matchedfilename) {
876 $matchedfilename = urldecode($matchedfilename);
877 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
878 $matchedfilename);
881 // Now, compare the hashes of all draft files, and remove those which don't match used files.
882 $fs = get_file_storage();
883 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
884 foreach ($files as $file) {
885 $tmphash = $file->get_pathnamehash();
886 if (!in_array($tmphash, $usedfilehashes)) {
887 $file->delete();
893 * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
894 * content from another draft area it's possible for a single textarea to reference multiple draft areas.
896 * @category files
897 * @param int $draftitemid the id of the primary draft area.
898 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
899 * @param int $usercontextid the user's context id.
900 * @param string $text some html content that needs to have files copied to the correct draft area.
901 * @param bool $forcehttps force https urls.
903 * @return string $text html content modified with new draft links
905 function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
906 if (is_null($text)) {
907 return null;
910 // Do not merge files, leave it as it was.
911 if ($draftitemid === IGNORE_FILE_MERGE) {
912 return null;
915 $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
917 // No draft areas to rewrite.
918 if (empty($urls)) {
919 return $text;
922 foreach ($urls as $url) {
923 // Do not process the "home" draft area.
924 if ($url['itemid'] == $draftitemid) {
925 continue;
928 // Decode the filename.
929 $filename = urldecode($url['filename']);
931 // Copy the file.
932 file_copy_file_to_file_area($url, $filename, $draftitemid);
934 // Rewrite draft area.
935 $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
937 return $text;
941 * Rewrites a file area in arbitrary text.
943 * @param array $file General information about the file.
944 * @param int $newid The new file area itemid.
945 * @param string $text The text to rewrite.
946 * @param bool $forcehttps force https urls.
947 * @return string The rewritten text.
949 function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
950 global $CFG;
952 $wwwroot = $CFG->wwwroot;
953 if ($forcehttps) {
954 $wwwroot = str_replace('http://', 'https://', $wwwroot);
957 $search = [
958 $wwwroot,
959 $file['urlbase'],
960 $file['contextid'],
961 $file['component'],
962 $file['filearea'],
963 $file['itemid'],
964 $file['filename']
966 $replace = [
967 $wwwroot,
968 $file['urlbase'],
969 $file['contextid'],
970 $file['component'],
971 $file['filearea'],
972 $newid,
973 $file['filename']
976 $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
977 return $text;
981 * Copies a file from one file area to another.
983 * @param array $file Information about the file to be copied.
984 * @param string $filename The filename.
985 * @param int $itemid The new file area.
987 function file_copy_file_to_file_area($file, $filename, $itemid) {
988 $fs = get_file_storage();
990 // Load the current file in the old draft area.
991 $fileinfo = array(
992 'component' => $file['component'],
993 'filearea' => $file['filearea'],
994 'itemid' => $file['itemid'],
995 'contextid' => $file['contextid'],
996 'filepath' => '/',
997 'filename' => $filename
999 $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
1000 $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
1001 $newfileinfo = array(
1002 'component' => $file['component'],
1003 'filearea' => $file['filearea'],
1004 'itemid' => $itemid,
1005 'contextid' => $file['contextid'],
1006 'filepath' => '/',
1007 'filename' => $filename
1010 $newcontextid = $newfileinfo['contextid'];
1011 $newcomponent = $newfileinfo['component'];
1012 $newfilearea = $newfileinfo['filearea'];
1013 $newitemid = $newfileinfo['itemid'];
1014 $newfilepath = $newfileinfo['filepath'];
1015 $newfilename = $newfileinfo['filename'];
1017 // Check if the file exists.
1018 if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1019 $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1024 * Saves files from a draft file area to a real one (merging the list of files).
1025 * Can rewrite URLs in some content at the same time if desired.
1027 * @category files
1028 * @global stdClass $USER
1029 * @param int $draftitemid the id of the draft area to use. Normally obtained
1030 * from file_get_submitted_draft_itemid('elementname') or similar.
1031 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
1032 * @param int $contextid This parameter and the next two identify the file area to save to.
1033 * @param string $component
1034 * @param string $filearea indentifies the file area.
1035 * @param int $itemid helps identifies the file area.
1036 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1037 * @param string $text some html content that needs to have embedded links rewritten
1038 * to the @@PLUGINFILE@@ form for saving in the database.
1039 * @param bool $forcehttps force https urls.
1040 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1042 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1043 global $USER;
1045 // Do not merge files, leave it as it was.
1046 if ($draftitemid === IGNORE_FILE_MERGE) {
1047 // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
1048 return $text;
1051 $usercontext = context_user::instance($USER->id);
1052 $fs = get_file_storage();
1054 $options = (array)$options;
1055 if (!isset($options['subdirs'])) {
1056 $options['subdirs'] = false;
1058 if (!isset($options['maxfiles'])) {
1059 $options['maxfiles'] = -1; // unlimited
1061 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
1062 $options['maxbytes'] = 0; // unlimited
1064 if (!isset($options['areamaxbytes'])) {
1065 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
1067 $allowreferences = true;
1068 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
1069 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1070 // this is not exactly right. BUT there are many places in code where filemanager options
1071 // are not passed to file_save_draft_area_files()
1072 $allowreferences = false;
1075 // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1076 // areas and need to be copied into the current draft area.
1077 $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
1079 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1080 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1081 // anything at all in the next area.
1082 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1083 return null;
1086 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
1087 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1089 // One file in filearea means it is empty (it has only top-level directory '.').
1090 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
1091 // we have to merge old and new files - we want to keep file ids for files that were not changed
1092 // we change time modified for all new and changed files, we keep time created as is
1094 $newhashes = array();
1095 $filecount = 0;
1096 $context = context::instance_by_id($contextid, MUST_EXIST);
1097 foreach ($draftfiles as $file) {
1098 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1099 continue;
1101 if (!$allowreferences && $file->is_external_file()) {
1102 continue;
1104 if (!$file->is_directory()) {
1105 // Check to see if this file was uploaded by someone who can ignore the file size limits.
1106 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1107 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1108 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1109 // Oversized file.
1110 continue;
1112 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1113 // more files - should not get here at all
1114 continue;
1116 $filecount++;
1118 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1119 $newhashes[$newhash] = $file;
1122 // Loop through oldfiles and decide which we need to delete and which to update.
1123 // After this cycle the array $newhashes will only contain the files that need to be added.
1124 foreach ($oldfiles as $oldfile) {
1125 $oldhash = $oldfile->get_pathnamehash();
1126 if (!isset($newhashes[$oldhash])) {
1127 // delete files not needed any more - deleted by user
1128 $oldfile->delete();
1129 continue;
1132 $newfile = $newhashes[$oldhash];
1133 // Now we know that we have $oldfile and $newfile for the same path.
1134 // Let's check if we can update this file or we need to delete and create.
1135 if ($newfile->is_directory()) {
1136 // Directories are always ok to just update.
1137 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
1138 // File has the 'original' - we need to update the file (it may even have not been changed at all).
1139 $original = file_storage::unpack_reference($source->original);
1140 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
1141 // Very odd, original points to another file. Delete and create file.
1142 $oldfile->delete();
1143 continue;
1145 } else {
1146 // The same file name but absence of 'original' means that file was deteled and uploaded again.
1147 // By deleting and creating new file we properly manage all existing references.
1148 $oldfile->delete();
1149 continue;
1152 // status changed, we delete old file, and create a new one
1153 if ($oldfile->get_status() != $newfile->get_status()) {
1154 // file was changed, use updated with new timemodified data
1155 $oldfile->delete();
1156 // This file will be added later
1157 continue;
1160 // Updated author
1161 if ($oldfile->get_author() != $newfile->get_author()) {
1162 $oldfile->set_author($newfile->get_author());
1164 // Updated license
1165 if ($oldfile->get_license() != $newfile->get_license()) {
1166 $oldfile->set_license($newfile->get_license());
1169 // Updated file source
1170 // Field files.source for draftarea files contains serialised object with source and original information.
1171 // We only store the source part of it for non-draft file area.
1172 $newsource = $newfile->get_source();
1173 if ($source = @unserialize($newfile->get_source())) {
1174 $newsource = $source->source;
1176 if ($oldfile->get_source() !== $newsource) {
1177 $oldfile->set_source($newsource);
1180 // Updated sort order
1181 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1182 $oldfile->set_sortorder($newfile->get_sortorder());
1185 // Update file timemodified
1186 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1187 $oldfile->set_timemodified($newfile->get_timemodified());
1190 // Replaced file content
1191 if (!$oldfile->is_directory() &&
1192 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1193 $oldfile->get_filesize() != $newfile->get_filesize() ||
1194 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1195 $oldfile->get_userid() != $newfile->get_userid())) {
1196 $oldfile->replace_file_with($newfile);
1199 // unchanged file or directory - we keep it as is
1200 unset($newhashes[$oldhash]);
1203 // Add fresh file or the file which has changed status
1204 // the size and subdirectory tests are extra safety only, the UI should prevent it
1205 foreach ($newhashes as $file) {
1206 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1207 if ($source = @unserialize($file->get_source())) {
1208 // Field files.source for draftarea files contains serialised object with source and original information.
1209 // We only store the source part of it for non-draft file area.
1210 $file_record['source'] = $source->source;
1213 if ($file->is_external_file()) {
1214 $repoid = $file->get_repository_id();
1215 if (!empty($repoid)) {
1216 $context = context::instance_by_id($contextid, MUST_EXIST);
1217 $repo = repository::get_repository_by_id($repoid, $context);
1218 if (!empty($options)) {
1219 $repo->options = $options;
1221 $file_record['repositoryid'] = $repoid;
1222 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1223 // to the file store. E.g. transfer ownership of the file to a system account etc.
1224 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1226 $file_record['reference'] = $reference;
1230 $fs->create_file_from_storedfile($file_record, $file);
1234 // note: do not purge the draft area - we clean up areas later in cron,
1235 // the reason is that user might press submit twice and they would loose the files,
1236 // also sometimes we might want to use hacks that save files into two different areas
1238 if (is_null($text)) {
1239 return null;
1240 } else {
1241 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1246 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1247 * ready to be saved in the database. Normally, this is done automatically by
1248 * {@link file_save_draft_area_files()}.
1250 * @category files
1251 * @param string $text the content to process.
1252 * @param int $draftitemid the draft file area the content was using.
1253 * @param bool $forcehttps whether the content contains https URLs. Default false.
1254 * @return string the processed content.
1256 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1257 global $CFG, $USER;
1259 $usercontext = context_user::instance($USER->id);
1261 $wwwroot = $CFG->wwwroot;
1262 if ($forcehttps) {
1263 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1266 // relink embedded files if text submitted - no absolute links allowed in database!
1267 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1269 if (strpos($text, 'draftfile.php?file=') !== false) {
1270 $matches = array();
1271 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1272 if ($matches) {
1273 foreach ($matches[0] as $match) {
1274 $replace = str_ireplace('%2F', '/', $match);
1275 $text = str_replace($match, $replace, $text);
1278 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1281 return $text;
1285 * Set file sort order
1287 * @global moodle_database $DB
1288 * @param int $contextid the context id
1289 * @param string $component file component
1290 * @param string $filearea file area.
1291 * @param int $itemid itemid.
1292 * @param string $filepath file path.
1293 * @param string $filename file name.
1294 * @param int $sortorder the sort order of file.
1295 * @return bool
1297 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1298 global $DB;
1299 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1300 if ($file_record = $DB->get_record('files', $conditions)) {
1301 $sortorder = (int)$sortorder;
1302 $file_record->sortorder = $sortorder;
1303 $DB->update_record('files', $file_record);
1304 return true;
1306 return false;
1310 * reset file sort order number to 0
1311 * @global moodle_database $DB
1312 * @param int $contextid the context id
1313 * @param string $component
1314 * @param string $filearea file area.
1315 * @param int|bool $itemid itemid.
1316 * @return bool
1318 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1319 global $DB;
1321 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1322 if ($itemid !== false) {
1323 $conditions['itemid'] = $itemid;
1326 $file_records = $DB->get_records('files', $conditions);
1327 foreach ($file_records as $file_record) {
1328 $file_record->sortorder = 0;
1329 $DB->update_record('files', $file_record);
1331 return true;
1335 * Returns description of upload error
1337 * @param int $errorcode found in $_FILES['filename.ext']['error']
1338 * @return string error description string, '' if ok
1340 function file_get_upload_error($errorcode) {
1342 switch ($errorcode) {
1343 case 0: // UPLOAD_ERR_OK - no error
1344 $errmessage = '';
1345 break;
1347 case 1: // UPLOAD_ERR_INI_SIZE
1348 $errmessage = get_string('uploadserverlimit');
1349 break;
1351 case 2: // UPLOAD_ERR_FORM_SIZE
1352 $errmessage = get_string('uploadformlimit');
1353 break;
1355 case 3: // UPLOAD_ERR_PARTIAL
1356 $errmessage = get_string('uploadpartialfile');
1357 break;
1359 case 4: // UPLOAD_ERR_NO_FILE
1360 $errmessage = get_string('uploadnofilefound');
1361 break;
1363 // Note: there is no error with a value of 5
1365 case 6: // UPLOAD_ERR_NO_TMP_DIR
1366 $errmessage = get_string('uploadnotempdir');
1367 break;
1369 case 7: // UPLOAD_ERR_CANT_WRITE
1370 $errmessage = get_string('uploadcantwrite');
1371 break;
1373 case 8: // UPLOAD_ERR_EXTENSION
1374 $errmessage = get_string('uploadextension');
1375 break;
1377 default:
1378 $errmessage = get_string('uploadproblem');
1381 return $errmessage;
1385 * Recursive function formating an array in POST parameter
1386 * @param array $arraydata - the array that we are going to format and add into &$data array
1387 * @param string $currentdata - a row of the final postdata array at instant T
1388 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1389 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1391 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1392 foreach ($arraydata as $k=>$v) {
1393 $newcurrentdata = $currentdata;
1394 if (is_array($v)) { //the value is an array, call the function recursively
1395 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1396 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1397 } else { //add the POST parameter to the $data array
1398 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1404 * Transform a PHP array into POST parameter
1405 * (see the recursive function format_array_postdata_for_curlcall)
1406 * @param array $postdata
1407 * @return array containing all POST parameters (1 row = 1 POST parameter)
1409 function format_postdata_for_curlcall($postdata) {
1410 $data = array();
1411 foreach ($postdata as $k=>$v) {
1412 if (is_array($v)) {
1413 $currentdata = urlencode($k);
1414 format_array_postdata_for_curlcall($v, $currentdata, $data);
1415 } else {
1416 $data[] = urlencode($k).'='.urlencode($v);
1419 $convertedpostdata = implode('&', $data);
1420 return $convertedpostdata;
1424 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1425 * Due to security concerns only downloads from http(s) sources are supported.
1427 * @category files
1428 * @param string $url file url starting with http(s)://
1429 * @param array $headers http headers, null if none. If set, should be an
1430 * associative array of header name => value pairs.
1431 * @param array $postdata array means use POST request with given parameters
1432 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1433 * (if false, just returns content)
1434 * @param int $timeout timeout for complete download process including all file transfer
1435 * (default 5 minutes)
1436 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1437 * usually happens if the remote server is completely down (default 20 seconds);
1438 * may not work when using proxy
1439 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1440 * Only use this when already in a trusted location.
1441 * @param string $tofile store the downloaded content to file instead of returning it.
1442 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1443 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1444 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1445 * if file downloaded into $tofile successfully or the file content as a string.
1447 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1448 global $CFG;
1450 // Only http and https links supported.
1451 if (!preg_match('|^https?://|i', $url)) {
1452 if ($fullresponse) {
1453 $response = new stdClass();
1454 $response->status = 0;
1455 $response->headers = array();
1456 $response->response_code = 'Invalid protocol specified in url';
1457 $response->results = '';
1458 $response->error = 'Invalid protocol specified in url';
1459 return $response;
1460 } else {
1461 return false;
1465 $options = array();
1467 $headers2 = array();
1468 if (is_array($headers)) {
1469 foreach ($headers as $key => $value) {
1470 if (is_numeric($key)) {
1471 $headers2[] = $value;
1472 } else {
1473 $headers2[] = "$key: $value";
1478 if ($skipcertverify) {
1479 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1480 } else {
1481 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1484 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1486 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1487 $options['CURLOPT_MAXREDIRS'] = 5;
1489 // Use POST if requested.
1490 if (is_array($postdata)) {
1491 $postdata = format_postdata_for_curlcall($postdata);
1492 } else if (empty($postdata)) {
1493 $postdata = null;
1496 // Optionally attempt to get more correct timeout by fetching the file size.
1497 if (!isset($CFG->curltimeoutkbitrate)) {
1498 // Use very slow rate of 56kbps as a timeout speed when not set.
1499 $bitrate = 56;
1500 } else {
1501 $bitrate = $CFG->curltimeoutkbitrate;
1503 if ($calctimeout and !isset($postdata)) {
1504 $curl = new curl();
1505 $curl->setHeader($headers2);
1507 $curl->head($url, $postdata, $options);
1509 $info = $curl->get_info();
1510 $error_no = $curl->get_errno();
1511 if (!$error_no && $info['download_content_length'] > 0) {
1512 // No curl errors - adjust for large files only - take max timeout.
1513 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1517 $curl = new curl();
1518 $curl->setHeader($headers2);
1520 $options['CURLOPT_RETURNTRANSFER'] = true;
1521 $options['CURLOPT_NOBODY'] = false;
1522 $options['CURLOPT_TIMEOUT'] = $timeout;
1524 if ($tofile) {
1525 $fh = fopen($tofile, 'w');
1526 if (!$fh) {
1527 if ($fullresponse) {
1528 $response = new stdClass();
1529 $response->status = 0;
1530 $response->headers = array();
1531 $response->response_code = 'Can not write to file';
1532 $response->results = false;
1533 $response->error = 'Can not write to file';
1534 return $response;
1535 } else {
1536 return false;
1539 $options['CURLOPT_FILE'] = $fh;
1542 if (isset($postdata)) {
1543 $content = $curl->post($url, $postdata, $options);
1544 } else {
1545 $content = $curl->get($url, null, $options);
1548 if ($tofile) {
1549 fclose($fh);
1550 @chmod($tofile, $CFG->filepermissions);
1554 // Try to detect encoding problems.
1555 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1556 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1557 $result = curl_exec($ch);
1561 $info = $curl->get_info();
1562 $error_no = $curl->get_errno();
1563 $rawheaders = $curl->get_raw_response();
1565 if ($error_no) {
1566 $error = $content;
1567 if (!$fullresponse) {
1568 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1569 return false;
1572 $response = new stdClass();
1573 if ($error_no == 28) {
1574 $response->status = '-100'; // Mimic snoopy.
1575 } else {
1576 $response->status = '0';
1578 $response->headers = array();
1579 $response->response_code = $error;
1580 $response->results = false;
1581 $response->error = $error;
1582 return $response;
1585 if ($tofile) {
1586 $content = true;
1589 if (empty($info['http_code'])) {
1590 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1591 $response = new stdClass();
1592 $response->status = '0';
1593 $response->headers = array();
1594 $response->response_code = 'Unknown cURL error';
1595 $response->results = false; // do NOT change this, we really want to ignore the result!
1596 $response->error = 'Unknown cURL error';
1598 } else {
1599 $response = new stdClass();
1600 $response->status = (string)$info['http_code'];
1601 $response->headers = $rawheaders;
1602 $response->results = $content;
1603 $response->error = '';
1605 // There might be multiple headers on redirect, find the status of the last one.
1606 $firstline = true;
1607 foreach ($rawheaders as $line) {
1608 if ($firstline) {
1609 $response->response_code = $line;
1610 $firstline = false;
1612 if (trim($line, "\r\n") === '') {
1613 $firstline = true;
1618 if ($fullresponse) {
1619 return $response;
1622 if ($info['http_code'] != 200) {
1623 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1624 return false;
1626 return $response->results;
1630 * Returns a list of information about file types based on extensions.
1632 * The following elements expected in value array for each extension:
1633 * 'type' - mimetype
1634 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1635 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1636 * also files with bigger sizes under names
1637 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1638 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1639 * commonly used in moodle the following groups:
1640 * - web_image - image that can be included as <img> in HTML
1641 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1642 * - video - file that can be imported as video in text editor
1643 * - audio - file that can be imported as audio in text editor
1644 * - archive - we can extract files from this archive
1645 * - spreadsheet - used for portfolio format
1646 * - document - used for portfolio format
1647 * - presentation - used for portfolio format
1648 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1649 * human-readable description for this filetype;
1650 * Function {@link get_mimetype_description()} first looks at the presence of string for
1651 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1652 * attribute, if not found returns the value of 'type';
1653 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1654 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1655 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1657 * @category files
1658 * @return array List of information about file types based on extensions.
1659 * Associative array of extension (lower-case) to associative array
1660 * from 'element name' to data. Current element names are 'type' and 'icon'.
1661 * Unknown types should use the 'xxx' entry which includes defaults.
1663 function &get_mimetypes_array() {
1664 // Get types from the core_filetypes function, which includes caching.
1665 return core_filetypes::get_types();
1669 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1671 * This function retrieves a file's MIME type for a file that will be sent to the user.
1672 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1673 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1674 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1676 * @param string $filename The file's filename.
1677 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1679 function get_mimetype_for_sending($filename = '') {
1680 // Guess the file's MIME type using mimeinfo.
1681 $mimetype = mimeinfo('type', $filename);
1683 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1684 if (!$mimetype || $mimetype === 'document/unknown') {
1685 $mimetype = 'application/octet-stream';
1688 return $mimetype;
1692 * Obtains information about a filetype based on its extension. Will
1693 * use a default if no information is present about that particular
1694 * extension.
1696 * @category files
1697 * @param string $element Desired information (usually 'icon'
1698 * for icon filename or 'type' for MIME type. Can also be
1699 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1700 * @param string $filename Filename we're looking up
1701 * @return string Requested piece of information from array
1703 function mimeinfo($element, $filename) {
1704 global $CFG;
1705 $mimeinfo = & get_mimetypes_array();
1706 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1708 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1709 if (empty($filetype)) {
1710 $filetype = 'xxx'; // file without extension
1712 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1713 $iconsize = max(array(16, (int)$iconsizematch[1]));
1714 $filenames = array($mimeinfo['xxx']['icon']);
1715 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1716 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1718 // find the file with the closest size, first search for specific icon then for default icon
1719 foreach ($filenames as $filename) {
1720 foreach ($iconpostfixes as $size => $postfix) {
1721 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1722 if ($iconsize >= $size &&
1723 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1724 return $filename.$postfix;
1728 } else if (isset($mimeinfo[$filetype][$element])) {
1729 return $mimeinfo[$filetype][$element];
1730 } else if (isset($mimeinfo['xxx'][$element])) {
1731 return $mimeinfo['xxx'][$element]; // By default
1732 } else {
1733 return null;
1738 * Obtains information about a filetype based on the MIME type rather than
1739 * the other way around.
1741 * @category files
1742 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1743 * @param string $mimetype MIME type we're looking up
1744 * @return string Requested piece of information from array
1746 function mimeinfo_from_type($element, $mimetype) {
1747 /* array of cached mimetype->extension associations */
1748 static $cached = array();
1749 $mimeinfo = & get_mimetypes_array();
1751 if (!array_key_exists($mimetype, $cached)) {
1752 $cached[$mimetype] = null;
1753 foreach($mimeinfo as $filetype => $values) {
1754 if ($values['type'] == $mimetype) {
1755 if ($cached[$mimetype] === null) {
1756 $cached[$mimetype] = '.'.$filetype;
1758 if (!empty($values['defaulticon'])) {
1759 $cached[$mimetype] = '.'.$filetype;
1760 break;
1764 if (empty($cached[$mimetype])) {
1765 $cached[$mimetype] = '.xxx';
1768 if ($element === 'extension') {
1769 return $cached[$mimetype];
1770 } else {
1771 return mimeinfo($element, $cached[$mimetype]);
1776 * Return the relative icon path for a given file
1778 * Usage:
1779 * <code>
1780 * // $file - instance of stored_file or file_info
1781 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1782 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1783 * </code>
1784 * or
1785 * <code>
1786 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1787 * </code>
1789 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1790 * and $file->mimetype are expected)
1791 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1792 * @return string
1794 function file_file_icon($file, $size = null) {
1795 if (!is_object($file)) {
1796 $file = (object)$file;
1798 if (isset($file->filename)) {
1799 $filename = $file->filename;
1800 } else if (method_exists($file, 'get_filename')) {
1801 $filename = $file->get_filename();
1802 } else if (method_exists($file, 'get_visible_name')) {
1803 $filename = $file->get_visible_name();
1804 } else {
1805 $filename = '';
1807 if (isset($file->mimetype)) {
1808 $mimetype = $file->mimetype;
1809 } else if (method_exists($file, 'get_mimetype')) {
1810 $mimetype = $file->get_mimetype();
1811 } else {
1812 $mimetype = '';
1814 $mimetypes = &get_mimetypes_array();
1815 if ($filename) {
1816 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1817 if ($extension && !empty($mimetypes[$extension])) {
1818 // if file name has known extension, return icon for this extension
1819 return file_extension_icon($filename, $size);
1822 return file_mimetype_icon($mimetype, $size);
1826 * Return the relative icon path for a folder image
1828 * Usage:
1829 * <code>
1830 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1831 * echo html_writer::empty_tag('img', array('src' => $icon));
1832 * </code>
1833 * or
1834 * <code>
1835 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1836 * </code>
1838 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1839 * @return string
1841 function file_folder_icon($iconsize = null) {
1842 global $CFG;
1843 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1844 static $cached = array();
1845 $iconsize = max(array(16, (int)$iconsize));
1846 if (!array_key_exists($iconsize, $cached)) {
1847 foreach ($iconpostfixes as $size => $postfix) {
1848 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1849 if ($iconsize >= $size &&
1850 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1851 $cached[$iconsize] = 'f/folder'.$postfix;
1852 break;
1856 return $cached[$iconsize];
1860 * Returns the relative icon path for a given mime type
1862 * This function should be used in conjunction with $OUTPUT->image_url to produce
1863 * a return the full path to an icon.
1865 * <code>
1866 * $mimetype = 'image/jpg';
1867 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1868 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1869 * </code>
1871 * @category files
1872 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1873 * to conform with that.
1874 * @param string $mimetype The mimetype to fetch an icon for
1875 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1876 * @return string The relative path to the icon
1878 function file_mimetype_icon($mimetype, $size = NULL) {
1879 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1883 * Returns the relative icon path for a given file name
1885 * This function should be used in conjunction with $OUTPUT->image_url to produce
1886 * a return the full path to an icon.
1888 * <code>
1889 * $filename = '.jpg';
1890 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1891 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1892 * </code>
1894 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1895 * to conform with that.
1896 * @todo MDL-31074 Implement $size
1897 * @category files
1898 * @param string $filename The filename to get the icon for
1899 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1900 * @return string
1902 function file_extension_icon($filename, $size = NULL) {
1903 return 'f/'.mimeinfo('icon'.$size, $filename);
1907 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1908 * mimetypes.php language file.
1910 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1911 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1912 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1913 * @param bool $capitalise If true, capitalises first character of result
1914 * @return string Text description
1916 function get_mimetype_description($obj, $capitalise=false) {
1917 $filename = $mimetype = '';
1918 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1919 // this is an instance of stored_file
1920 $mimetype = $obj->get_mimetype();
1921 $filename = $obj->get_filename();
1922 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1923 // this is an instance of file_info
1924 $mimetype = $obj->get_mimetype();
1925 $filename = $obj->get_visible_name();
1926 } else if (is_array($obj) || is_object ($obj)) {
1927 $obj = (array)$obj;
1928 if (!empty($obj['filename'])) {
1929 $filename = $obj['filename'];
1931 if (!empty($obj['mimetype'])) {
1932 $mimetype = $obj['mimetype'];
1934 } else {
1935 $mimetype = $obj;
1937 $mimetypefromext = mimeinfo('type', $filename);
1938 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1939 // if file has a known extension, overwrite the specified mimetype
1940 $mimetype = $mimetypefromext;
1942 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1943 if (empty($extension)) {
1944 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1945 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1946 } else {
1947 $mimetypestr = mimeinfo('string', $filename);
1949 $chunks = explode('/', $mimetype, 2);
1950 $chunks[] = '';
1951 $attr = array(
1952 'mimetype' => $mimetype,
1953 'ext' => $extension,
1954 'mimetype1' => $chunks[0],
1955 'mimetype2' => $chunks[1],
1957 $a = array();
1958 foreach ($attr as $key => $value) {
1959 $a[$key] = $value;
1960 $a[strtoupper($key)] = strtoupper($value);
1961 $a[ucfirst($key)] = ucfirst($value);
1964 // MIME types may include + symbol but this is not permitted in string ids.
1965 $safemimetype = str_replace('+', '_', $mimetype);
1966 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1967 $customdescription = mimeinfo('customdescription', $filename);
1968 if ($customdescription) {
1969 // Call format_string on the custom description so that multilang
1970 // filter can be used (if enabled on system context). We use system
1971 // context because it is possible that the page context might not have
1972 // been defined yet.
1973 $result = format_string($customdescription, true,
1974 array('context' => context_system::instance()));
1975 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1976 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1977 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1978 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1979 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1980 $result = get_string('default', 'mimetypes', (object)$a);
1981 } else {
1982 $result = $mimetype;
1984 if ($capitalise) {
1985 $result=ucfirst($result);
1987 return $result;
1991 * Returns array of elements of type $element in type group(s)
1993 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1994 * @param string|array $groups one group or array of groups/extensions/mimetypes
1995 * @return array
1997 function file_get_typegroup($element, $groups) {
1998 static $cached = array();
1999 if (!is_array($groups)) {
2000 $groups = array($groups);
2002 if (!array_key_exists($element, $cached)) {
2003 $cached[$element] = array();
2005 $result = array();
2006 foreach ($groups as $group) {
2007 if (!array_key_exists($group, $cached[$element])) {
2008 // retrieive and cache all elements of type $element for group $group
2009 $mimeinfo = & get_mimetypes_array();
2010 $cached[$element][$group] = array();
2011 foreach ($mimeinfo as $extension => $value) {
2012 $value['extension'] = '.'.$extension;
2013 if (empty($value[$element])) {
2014 continue;
2016 if (($group === '.'.$extension || $group === $value['type'] ||
2017 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
2018 !in_array($value[$element], $cached[$element][$group])) {
2019 $cached[$element][$group][] = $value[$element];
2023 $result = array_merge($result, $cached[$element][$group]);
2025 return array_values(array_unique($result));
2029 * Checks if file with name $filename has one of the extensions in groups $groups
2031 * @see get_mimetypes_array()
2032 * @param string $filename name of the file to check
2033 * @param string|array $groups one group or array of groups to check
2034 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2035 * file mimetype is in mimetypes in groups $groups
2036 * @return bool
2038 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2039 $extension = pathinfo($filename, PATHINFO_EXTENSION);
2040 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2041 return true;
2043 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2047 * Checks if mimetype $mimetype belongs to one of the groups $groups
2049 * @see get_mimetypes_array()
2050 * @param string $mimetype
2051 * @param string|array $groups one group or array of groups to check
2052 * @return bool
2054 function file_mimetype_in_typegroup($mimetype, $groups) {
2055 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2059 * Requested file is not found or not accessible, does not return, terminates script
2061 * @global stdClass $CFG
2062 * @global stdClass $COURSE
2064 function send_file_not_found() {
2065 global $CFG, $COURSE;
2067 // Allow cross-origin requests only for Web Services.
2068 // This allow to receive requests done by Web Workers or webapps in different domains.
2069 if (WS_SERVER) {
2070 header('Access-Control-Allow-Origin: *');
2073 send_header_404();
2074 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
2077 * Helper function to send correct 404 for server.
2079 function send_header_404() {
2080 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2081 header("Status: 404 Not Found");
2082 } else {
2083 header('HTTP/1.0 404 not found');
2088 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2089 * platforms). This wrapper uses readfile for small files and custom code for
2090 * large ones.
2092 * @param string $path Path to file
2093 * @param int $filesize Size of file (if left out, will get it automatically)
2094 * @return int|bool Size read (will always be $filesize) or false if failed
2096 function readfile_allow_large($path, $filesize = -1) {
2097 // Automatically get size if not specified.
2098 if ($filesize === -1) {
2099 $filesize = filesize($path);
2101 if ($filesize <= 2147483647) {
2102 // If the file is up to 2^31 - 1, send it normally using readfile.
2103 return readfile($path);
2104 } else {
2105 // For large files, read and output in 64KB chunks.
2106 $handle = fopen($path, 'r');
2107 if ($handle === false) {
2108 return false;
2110 $left = $filesize;
2111 while ($left > 0) {
2112 $size = min($left, 65536);
2113 $buffer = fread($handle, $size);
2114 if ($buffer === false) {
2115 return false;
2117 echo $buffer;
2118 $left -= $size;
2120 return $filesize;
2125 * Enhanced readfile() with optional acceleration.
2126 * @param string|stored_file $file
2127 * @param string $mimetype
2128 * @param bool $accelerate
2129 * @return void
2131 function readfile_accel($file, $mimetype, $accelerate) {
2132 global $CFG;
2134 if ($mimetype === 'text/plain') {
2135 // there is no encoding specified in text files, we need something consistent
2136 header('Content-Type: text/plain; charset=utf-8');
2137 } else {
2138 header('Content-Type: '.$mimetype);
2141 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2142 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2144 if (is_object($file)) {
2145 header('Etag: "' . $file->get_contenthash() . '"');
2146 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2147 header('HTTP/1.1 304 Not Modified');
2148 return;
2152 // if etag present for stored file rely on it exclusively
2153 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2154 // get unixtime of request header; clip extra junk off first
2155 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2156 if ($since && $since >= $lastmodified) {
2157 header('HTTP/1.1 304 Not Modified');
2158 return;
2162 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2163 header('Accept-Ranges: bytes');
2164 } else {
2165 header('Accept-Ranges: none');
2168 if ($accelerate) {
2169 if (is_object($file)) {
2170 $fs = get_file_storage();
2171 if ($fs->supports_xsendfile()) {
2172 if ($fs->xsendfile($file->get_contenthash())) {
2173 return;
2176 } else {
2177 if (!empty($CFG->xsendfile)) {
2178 require_once("$CFG->libdir/xsendfilelib.php");
2179 if (xsendfile($file)) {
2180 return;
2186 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2188 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2190 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2192 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2193 // byteserving stuff - for acrobat reader and download accelerators
2194 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2195 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2196 $ranges = false;
2197 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2198 foreach ($ranges as $key=>$value) {
2199 if ($ranges[$key][1] == '') {
2200 //suffix case
2201 $ranges[$key][1] = $filesize - $ranges[$key][2];
2202 $ranges[$key][2] = $filesize - 1;
2203 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2204 //fix range length
2205 $ranges[$key][2] = $filesize - 1;
2207 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2208 //invalid byte-range ==> ignore header
2209 $ranges = false;
2210 break;
2212 //prepare multipart header
2213 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2214 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2216 } else {
2217 $ranges = false;
2219 if ($ranges) {
2220 if (is_object($file)) {
2221 $handle = $file->get_content_file_handle();
2222 if ($handle === false) {
2223 throw new file_exception('storedfilecannotreadfile', $file->get_filename());
2225 } else {
2226 $handle = fopen($file, 'rb');
2227 if ($handle === false) {
2228 throw new file_exception('cannotopenfile', $file);
2231 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2236 if ($filesize > 10000000) {
2237 // for large files try to flush and close all buffers to conserve memory
2238 while(@ob_get_level()) {
2239 if (!@ob_end_flush()) {
2240 break;
2245 // Send this header after we have flushed the buffers so that if we fail
2246 // later can remove this because it wasn't sent.
2247 header('Content-Length: ' . $filesize);
2249 if (!empty($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] === 'HEAD') {
2250 exit;
2253 // send the whole file content
2254 if (is_object($file)) {
2255 $file->readfile();
2256 } else {
2257 if (readfile_allow_large($file, $filesize) === false) {
2258 throw new file_exception('cannotopenfile', $file);
2264 * Similar to readfile_accel() but designed for strings.
2265 * @param string $string
2266 * @param string $mimetype
2267 * @param bool $accelerate Ignored
2268 * @return void
2270 function readstring_accel($string, $mimetype, $accelerate = false) {
2271 global $CFG;
2273 if ($mimetype === 'text/plain') {
2274 // there is no encoding specified in text files, we need something consistent
2275 header('Content-Type: text/plain; charset=utf-8');
2276 } else {
2277 header('Content-Type: '.$mimetype);
2279 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2280 header('Accept-Ranges: none');
2281 header('Content-Length: '.strlen($string));
2282 echo $string;
2286 * Handles the sending of temporary file to user, download is forced.
2287 * File is deleted after abort or successful sending, does not return, script terminated
2289 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2290 * @param string $filename proposed file name when saving file
2291 * @param bool $pathisstring If the path is string
2293 function send_temp_file($path, $filename, $pathisstring=false) {
2294 global $CFG;
2296 // Guess the file's MIME type.
2297 $mimetype = get_mimetype_for_sending($filename);
2299 // close session - not needed anymore
2300 \core\session\manager::write_close();
2302 if (!$pathisstring) {
2303 if (!file_exists($path)) {
2304 send_header_404();
2305 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2307 // executed after normal finish or abort
2308 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2311 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2312 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2313 $filename = urlencode($filename);
2316 // If this file was requested from a form, then mark download as complete.
2317 \core_form\util::form_download_complete();
2319 header('Content-Disposition: attachment; filename="'.$filename.'"');
2320 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2321 header('Cache-Control: private, max-age=10, no-transform');
2322 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2323 header('Pragma: ');
2324 } else { //normal http - prevent caching at all cost
2325 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2326 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2327 header('Pragma: no-cache');
2330 // send the contents - we can not accelerate this because the file will be deleted asap
2331 if ($pathisstring) {
2332 readstring_accel($path, $mimetype);
2333 } else {
2334 readfile_accel($path, $mimetype, false);
2335 @unlink($path);
2338 die; //no more chars to output
2342 * Internal callback function used by send_temp_file()
2344 * @param string $path
2346 function send_temp_file_finished($path) {
2347 if (file_exists($path)) {
2348 @unlink($path);
2353 * Serve content which is not meant to be cached.
2355 * This is only intended to be used for volatile public files, for instance
2356 * when development is enabled, or when caching is not required on a public resource.
2358 * @param string $content Raw content.
2359 * @param string $filename The file name.
2360 * @return void
2362 function send_content_uncached($content, $filename) {
2363 $mimetype = mimeinfo('type', $filename);
2364 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2366 header('Content-Disposition: inline; filename="' . $filename . '"');
2367 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2368 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2369 header('Pragma: ');
2370 header('Accept-Ranges: none');
2371 header('Content-Type: ' . $mimetype . $charset);
2372 header('Content-Length: ' . strlen($content));
2374 echo $content;
2375 die();
2379 * Safely save content to a certain path.
2381 * This function tries hard to be atomic by first copying the content
2382 * to a separate file, and then moving the file across. It also prevents
2383 * the user to abort a request to prevent half-safed files.
2385 * This function is intended to be used when saving some content to cache like
2386 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2388 * @param string $content The file content.
2389 * @param string $destination The absolute path of the final file.
2390 * @return void
2392 function file_safe_save_content($content, $destination) {
2393 global $CFG;
2395 clearstatcache();
2396 if (!file_exists(dirname($destination))) {
2397 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2400 // Prevent serving of incomplete file from concurrent request,
2401 // the rename() should be more atomic than fwrite().
2402 ignore_user_abort(true);
2403 if ($fp = fopen($destination . '.tmp', 'xb')) {
2404 fwrite($fp, $content);
2405 fclose($fp);
2406 rename($destination . '.tmp', $destination);
2407 @chmod($destination, $CFG->filepermissions);
2408 @unlink($destination . '.tmp'); // Just in case anything fails.
2410 ignore_user_abort(false);
2411 if (connection_aborted()) {
2412 die();
2417 * Handles the sending of file data to the user's browser, including support for
2418 * byteranges etc.
2420 * @category files
2421 * @param string|stored_file $path Path of file on disk (including real filename),
2422 * or actual content of file as string,
2423 * or stored_file object
2424 * @param string $filename Filename to send
2425 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2426 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2427 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2428 * Forced to false when $path is a stored_file object.
2429 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2430 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2431 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2432 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2433 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2434 * and should not be reopened.
2435 * @param array $options An array of options, currently accepts:
2436 * - (string) cacheability: public, or private.
2437 * - (string|null) immutable
2438 * @return null script execution stopped unless $dontdie is true
2440 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2441 $dontdie=false, array $options = array()) {
2442 global $CFG, $COURSE;
2444 if ($dontdie) {
2445 ignore_user_abort(true);
2448 if ($lifetime === 'default' or is_null($lifetime)) {
2449 $lifetime = $CFG->filelifetime;
2452 if (is_object($path)) {
2453 $pathisstring = false;
2456 \core\session\manager::write_close(); // Unlock session during file serving.
2458 // Use given MIME type if specified, otherwise guess it.
2459 if (!$mimetype || $mimetype === 'document/unknown') {
2460 $mimetype = get_mimetype_for_sending($filename);
2463 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2464 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2465 $filename = rawurlencode($filename);
2468 if ($forcedownload) {
2469 header('Content-Disposition: attachment; filename="'.$filename.'"');
2471 // If this file was requested from a form, then mark download as complete.
2472 \core_form\util::form_download_complete();
2473 } else if ($mimetype !== 'application/x-shockwave-flash') {
2474 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2475 // as an upload and enforces security that may prevent the file from being loaded.
2477 header('Content-Disposition: inline; filename="'.$filename.'"');
2480 if ($lifetime > 0) {
2481 $immutable = '';
2482 if (!empty($options['immutable'])) {
2483 $immutable = ', immutable';
2484 // Overwrite lifetime accordingly:
2485 // 90 days only - based on Moodle point release cadence being every 3 months.
2486 $lifetimemin = 60 * 60 * 24 * 90;
2487 $lifetime = max($lifetime, $lifetimemin);
2489 $cacheability = ' public,';
2490 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2491 // This file must be cache-able by both browsers and proxies.
2492 $cacheability = ' public,';
2493 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2494 // This file must be cache-able only by browsers.
2495 $cacheability = ' private,';
2496 } else if (isloggedin() and !isguestuser()) {
2497 // By default, under the conditions above, this file must be cache-able only by browsers.
2498 $cacheability = ' private,';
2500 $nobyteserving = false;
2501 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2502 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2503 header('Pragma: ');
2505 } else { // Do not cache files in proxies and browsers
2506 $nobyteserving = true;
2507 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2508 header('Cache-Control: private, max-age=10, no-transform');
2509 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2510 header('Pragma: ');
2511 } else { //normal http - prevent caching at all cost
2512 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2513 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2514 header('Pragma: no-cache');
2518 if (empty($filter)) {
2519 // send the contents
2520 if ($pathisstring) {
2521 readstring_accel($path, $mimetype);
2522 } else {
2523 readfile_accel($path, $mimetype, !$dontdie);
2526 } else {
2527 // Try to put the file through filters
2528 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2529 $options = new stdClass();
2530 $options->noclean = true;
2531 $options->nocache = true; // temporary workaround for MDL-5136
2532 if (is_object($path)) {
2533 $text = $path->get_content();
2534 } else if ($pathisstring) {
2535 $text = $path;
2536 } else {
2537 $text = implode('', file($path));
2539 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2541 readstring_accel($output, $mimetype);
2543 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2544 // only filter text if filter all files is selected
2545 $options = new stdClass();
2546 $options->newlines = false;
2547 $options->noclean = true;
2548 if (is_object($path)) {
2549 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2550 } else if ($pathisstring) {
2551 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2552 } else {
2553 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2555 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2557 readstring_accel($output, $mimetype);
2559 } else {
2560 // send the contents
2561 if ($pathisstring) {
2562 readstring_accel($path, $mimetype);
2563 } else {
2564 readfile_accel($path, $mimetype, !$dontdie);
2568 if ($dontdie) {
2569 return;
2571 die; //no more chars to output!!!
2575 * Handles the sending of file data to the user's browser, including support for
2576 * byteranges etc.
2578 * The $options parameter supports the following keys:
2579 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2580 * (string|null) filename - overrides the implicit filename
2581 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2582 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2583 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2584 * and should not be reopened
2585 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2586 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2587 * defaults to "public".
2588 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2589 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2591 * @category files
2592 * @param stored_file $stored_file local file object
2593 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2594 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2595 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2596 * @param array $options additional options affecting the file serving
2597 * @return null script execution stopped unless $options['dontdie'] is true
2599 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2600 global $CFG, $COURSE;
2602 if (empty($options['filename'])) {
2603 $filename = null;
2604 } else {
2605 $filename = $options['filename'];
2608 if (empty($options['dontdie'])) {
2609 $dontdie = false;
2610 } else {
2611 $dontdie = true;
2614 if ($lifetime === 'default' or is_null($lifetime)) {
2615 $lifetime = $CFG->filelifetime;
2618 if (!empty($options['preview'])) {
2619 // replace the file with its preview
2620 $fs = get_file_storage();
2621 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2622 if (!$preview_file) {
2623 // unable to create a preview of the file, send its default mime icon instead
2624 if ($options['preview'] === 'tinyicon') {
2625 $size = 24;
2626 } else if ($options['preview'] === 'thumb') {
2627 $size = 90;
2628 } else {
2629 $size = 256;
2631 $fileicon = file_file_icon($stored_file, $size);
2632 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2633 } else {
2634 // preview images have fixed cache lifetime and they ignore forced download
2635 // (they are generated by GD and therefore they are considered reasonably safe).
2636 $stored_file = $preview_file;
2637 $lifetime = DAYSECS;
2638 $filter = 0;
2639 $forcedownload = false;
2643 // handle external resource
2644 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2645 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2646 die;
2649 if (!$stored_file or $stored_file->is_directory()) {
2650 // nothing to serve
2651 if ($dontdie) {
2652 return;
2654 die;
2657 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2659 // Use given MIME type if specified.
2660 $mimetype = $stored_file->get_mimetype();
2662 // Allow cross-origin requests only for Web Services.
2663 // This allow to receive requests done by Web Workers or webapps in different domains.
2664 if (WS_SERVER) {
2665 header('Access-Control-Allow-Origin: *');
2668 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2672 * Recursively delete the file or folder with path $location. That is,
2673 * if it is a file delete it. If it is a folder, delete all its content
2674 * then delete it. If $location does not exist to start, that is not
2675 * considered an error.
2677 * @param string $location the path to remove.
2678 * @return bool
2680 function fulldelete($location) {
2681 if (empty($location)) {
2682 // extra safety against wrong param
2683 return false;
2685 if (is_dir($location)) {
2686 if (!$currdir = opendir($location)) {
2687 return false;
2689 while (false !== ($file = readdir($currdir))) {
2690 if ($file <> ".." && $file <> ".") {
2691 $fullfile = $location."/".$file;
2692 if (is_dir($fullfile)) {
2693 if (!fulldelete($fullfile)) {
2694 return false;
2696 } else {
2697 if (!unlink($fullfile)) {
2698 return false;
2703 closedir($currdir);
2704 if (! rmdir($location)) {
2705 return false;
2708 } else if (file_exists($location)) {
2709 if (!unlink($location)) {
2710 return false;
2713 return true;
2717 * Send requested byterange of file.
2719 * @param resource $handle A file handle
2720 * @param string $mimetype The mimetype for the output
2721 * @param array $ranges An array of ranges to send
2722 * @param string $filesize The size of the content if only one range is used
2724 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2725 // better turn off any kind of compression and buffering
2726 ini_set('zlib.output_compression', 'Off');
2728 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2729 if ($handle === false) {
2730 die;
2732 if (count($ranges) == 1) { //only one range requested
2733 $length = $ranges[0][2] - $ranges[0][1] + 1;
2734 header('HTTP/1.1 206 Partial content');
2735 header('Content-Length: '.$length);
2736 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2737 header('Content-Type: '.$mimetype);
2739 while(@ob_get_level()) {
2740 if (!@ob_end_flush()) {
2741 break;
2745 fseek($handle, $ranges[0][1]);
2746 while (!feof($handle) && $length > 0) {
2747 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2748 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2749 echo $buffer;
2750 flush();
2751 $length -= strlen($buffer);
2753 fclose($handle);
2754 die;
2755 } else { // multiple ranges requested - not tested much
2756 $totallength = 0;
2757 foreach($ranges as $range) {
2758 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2760 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2761 header('HTTP/1.1 206 Partial content');
2762 header('Content-Length: '.$totallength);
2763 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2765 while(@ob_get_level()) {
2766 if (!@ob_end_flush()) {
2767 break;
2771 foreach($ranges as $range) {
2772 $length = $range[2] - $range[1] + 1;
2773 echo $range[0];
2774 fseek($handle, $range[1]);
2775 while (!feof($handle) && $length > 0) {
2776 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2777 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2778 echo $buffer;
2779 flush();
2780 $length -= strlen($buffer);
2783 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2784 fclose($handle);
2785 die;
2790 * Tells whether the filename is executable.
2792 * @link http://php.net/manual/en/function.is-executable.php
2793 * @link https://bugs.php.net/bug.php?id=41062
2794 * @param string $filename Path to the file.
2795 * @return bool True if the filename exists and is executable; otherwise, false.
2797 function file_is_executable($filename) {
2798 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2799 if (is_executable($filename)) {
2800 return true;
2801 } else {
2802 $fileext = strrchr($filename, '.');
2803 // If we have an extension we can check if it is listed as executable.
2804 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2805 $winpathext = strtolower(getenv('PATHEXT'));
2806 $winpathexts = explode(';', $winpathext);
2808 return in_array(strtolower($fileext), $winpathexts);
2811 return false;
2813 } else {
2814 return is_executable($filename);
2819 * Overwrite an existing file in a draft area.
2821 * @param stored_file $newfile the new file with the new content and meta-data
2822 * @param stored_file $existingfile the file that will be overwritten
2823 * @throws moodle_exception
2824 * @since Moodle 3.2
2826 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2827 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2828 throw new coding_exception('The file to overwrite is not in a draft area.');
2831 $fs = get_file_storage();
2832 // Remember original file source field.
2833 $source = @unserialize($existingfile->get_source());
2834 // Remember the original sortorder.
2835 $sortorder = $existingfile->get_sortorder();
2836 if ($newfile->is_external_file()) {
2837 // New file is a reference. Check that existing file does not have any other files referencing to it
2838 if (isset($source->original) && $fs->search_references_count($source->original)) {
2839 throw new moodle_exception('errordoublereference', 'repository');
2843 // Delete existing file to release filename.
2844 $newfilerecord = array(
2845 'contextid' => $existingfile->get_contextid(),
2846 'component' => 'user',
2847 'filearea' => 'draft',
2848 'itemid' => $existingfile->get_itemid(),
2849 'timemodified' => time()
2851 $existingfile->delete();
2853 // Create new file.
2854 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2855 // Preserve original file location (stored in source field) for handling references.
2856 if (isset($source->original)) {
2857 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2858 $newfilesource = new stdClass();
2860 $newfilesource->original = $source->original;
2861 $newfile->set_source(serialize($newfilesource));
2863 $newfile->set_sortorder($sortorder);
2867 * Add files from a draft area into a final area.
2869 * Most of the time you do not want to use this. It is intended to be used
2870 * by asynchronous services which cannot direcly manipulate a final
2871 * area through a draft area. Instead they add files to a new draft
2872 * area and merge that new draft into the final area when ready.
2874 * @param int $draftitemid the id of the draft area to use.
2875 * @param int $contextid this parameter and the next two identify the file area to save to.
2876 * @param string $component component name
2877 * @param string $filearea indentifies the file area
2878 * @param int $itemid identifies the item id or false for all items in the file area
2879 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2880 * @see file_save_draft_area_files
2881 * @since Moodle 3.2
2883 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2884 array $options = null) {
2885 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2886 $finaldraftid = 0;
2887 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2888 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2889 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2893 * Merge files from two draftarea areas.
2895 * This does not handle conflict resolution, files in the destination area which appear
2896 * to be more recent will be kept disregarding the intended ones.
2898 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2899 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2900 * @throws coding_exception
2901 * @since Moodle 3.2
2903 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2904 global $USER;
2906 $fs = get_file_storage();
2907 $contextid = context_user::instance($USER->id)->id;
2909 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2910 throw new coding_exception('Nothing to merge or area does not belong to current user');
2913 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2915 // Get hashes of the files to merge.
2916 $newhashes = array();
2917 foreach ($filestomerge as $filetomerge) {
2918 $filepath = $filetomerge->get_filepath();
2919 $filename = $filetomerge->get_filename();
2921 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2922 $newhashes[$newhash] = $filetomerge;
2925 // Calculate wich files must be added.
2926 foreach ($currentfiles as $file) {
2927 $filehash = $file->get_pathnamehash();
2928 // One file to be merged already exists.
2929 if (isset($newhashes[$filehash])) {
2930 $updatedfile = $newhashes[$filehash];
2932 // Avoid race conditions.
2933 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2934 // The existing file is more recent, do not copy the suposedly "new" one.
2935 unset($newhashes[$filehash]);
2936 continue;
2938 // Update existing file (not only content, meta-data too).
2939 file_overwrite_existing_draftfile($updatedfile, $file);
2940 unset($newhashes[$filehash]);
2944 foreach ($newhashes as $newfile) {
2945 $newfilerecord = array(
2946 'contextid' => $contextid,
2947 'component' => 'user',
2948 'filearea' => 'draft',
2949 'itemid' => $mergeintodraftid,
2950 'timemodified' => time()
2953 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2958 * RESTful cURL class
2960 * This is a wrapper class for curl, it is quite easy to use:
2961 * <code>
2962 * $c = new curl;
2963 * // enable cache
2964 * $c = new curl(array('cache'=>true));
2965 * // enable cookie
2966 * $c = new curl(array('cookie'=>true));
2967 * // enable proxy
2968 * $c = new curl(array('proxy'=>true));
2970 * // HTTP GET Method
2971 * $html = $c->get('http://example.com');
2972 * // HTTP POST Method
2973 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2974 * // HTTP PUT Method
2975 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2976 * </code>
2978 * @package core_files
2979 * @category files
2980 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2981 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2983 class curl {
2984 /** @var bool Caches http request contents */
2985 public $cache = false;
2986 /** @var bool Uses proxy, null means automatic based on URL */
2987 public $proxy = null;
2988 /** @var string library version */
2989 public $version = '0.4 dev';
2990 /** @var array http's response */
2991 public $response = array();
2992 /** @var array Raw response headers, needed for BC in download_file_content(). */
2993 public $rawresponse = array();
2994 /** @var array http header */
2995 public $header = array();
2996 /** @var string cURL information */
2997 public $info;
2998 /** @var string error */
2999 public $error;
3000 /** @var int error code */
3001 public $errno;
3002 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
3003 public $emulateredirects = null;
3005 /** @var array cURL options */
3006 private $options;
3008 /** @var string Proxy host */
3009 private $proxy_host = '';
3010 /** @var string Proxy auth */
3011 private $proxy_auth = '';
3012 /** @var string Proxy type */
3013 private $proxy_type = '';
3014 /** @var bool Debug mode on */
3015 private $debug = false;
3016 /** @var bool|string Path to cookie file */
3017 private $cookie = false;
3018 /** @var bool tracks multiple headers in response - redirect detection */
3019 private $responsefinished = false;
3020 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
3021 private $securityhelper;
3022 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
3023 private $ignoresecurity;
3024 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
3025 private static $mockresponses = [];
3028 * Curl constructor.
3030 * Allowed settings are:
3031 * proxy: (bool) use proxy server, null means autodetect non-local from url
3032 * debug: (bool) use debug output
3033 * cookie: (string) path to cookie file, false if none
3034 * cache: (bool) use cache
3035 * module_cache: (string) type of cache
3036 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3037 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3039 * @param array $settings
3041 public function __construct($settings = array()) {
3042 global $CFG;
3043 if (!function_exists('curl_init')) {
3044 $this->error = 'cURL module must be enabled!';
3045 trigger_error($this->error, E_USER_ERROR);
3046 return false;
3049 // All settings of this class should be init here.
3050 $this->resetopt();
3051 if (!empty($settings['debug'])) {
3052 $this->debug = true;
3054 if (!empty($settings['cookie'])) {
3055 if($settings['cookie'] === true) {
3056 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3057 } else {
3058 $this->cookie = $settings['cookie'];
3061 if (!empty($settings['cache'])) {
3062 if (class_exists('curl_cache')) {
3063 if (!empty($settings['module_cache'])) {
3064 $this->cache = new curl_cache($settings['module_cache']);
3065 } else {
3066 $this->cache = new curl_cache('misc');
3070 if (!empty($CFG->proxyhost)) {
3071 if (empty($CFG->proxyport)) {
3072 $this->proxy_host = $CFG->proxyhost;
3073 } else {
3074 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3076 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3077 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3078 $this->setopt(array(
3079 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3080 'proxyuserpwd'=>$this->proxy_auth));
3082 if (!empty($CFG->proxytype)) {
3083 if ($CFG->proxytype == 'SOCKS5') {
3084 $this->proxy_type = CURLPROXY_SOCKS5;
3085 } else {
3086 $this->proxy_type = CURLPROXY_HTTP;
3087 $this->setopt(array('httpproxytunnel'=>false));
3089 $this->setopt(array('proxytype'=>$this->proxy_type));
3092 if (isset($settings['proxy'])) {
3093 $this->proxy = $settings['proxy'];
3095 } else {
3096 $this->proxy = false;
3099 if (!isset($this->emulateredirects)) {
3100 $this->emulateredirects = ini_get('open_basedir');
3103 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3104 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3105 $this->set_security($settings['securityhelper']);
3106 } else {
3107 $this->set_security(new \core\files\curl_security_helper());
3109 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3113 * Resets the CURL options that have already been set
3115 public function resetopt() {
3116 $this->options = array();
3117 $this->options['CURLOPT_USERAGENT'] = \core_useragent::get_moodlebot_useragent();
3118 // True to include the header in the output
3119 $this->options['CURLOPT_HEADER'] = 0;
3120 // True to Exclude the body from the output
3121 $this->options['CURLOPT_NOBODY'] = 0;
3122 // Redirect ny default.
3123 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
3124 $this->options['CURLOPT_MAXREDIRS'] = 10;
3125 $this->options['CURLOPT_ENCODING'] = '';
3126 // TRUE to return the transfer as a string of the return
3127 // value of curl_exec() instead of outputting it out directly.
3128 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
3129 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
3130 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
3131 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
3133 if ($cacert = self::get_cacert()) {
3134 $this->options['CURLOPT_CAINFO'] = $cacert;
3139 * Get the location of ca certificates.
3140 * @return string absolute file path or empty if default used
3142 public static function get_cacert() {
3143 global $CFG;
3145 // Bundle in dataroot always wins.
3146 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3147 return realpath("$CFG->dataroot/moodleorgca.crt");
3150 // Next comes the default from php.ini
3151 $cacert = ini_get('curl.cainfo');
3152 if (!empty($cacert) and is_readable($cacert)) {
3153 return realpath($cacert);
3156 // Windows PHP does not have any certs, we need to use something.
3157 if ($CFG->ostype === 'WINDOWS') {
3158 if (is_readable("$CFG->libdir/cacert.pem")) {
3159 return realpath("$CFG->libdir/cacert.pem");
3163 // Use default, this should work fine on all properly configured *nix systems.
3164 return null;
3168 * Reset Cookie
3170 public function resetcookie() {
3171 if (!empty($this->cookie)) {
3172 if (is_file($this->cookie)) {
3173 $fp = fopen($this->cookie, 'w');
3174 if (!empty($fp)) {
3175 fwrite($fp, '');
3176 fclose($fp);
3183 * Set curl options.
3185 * Do not use the curl constants to define the options, pass a string
3186 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3187 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3189 * @param array $options If array is null, this function will reset the options to default value.
3190 * @return void
3191 * @throws coding_exception If an option uses constant value instead of option name.
3193 public function setopt($options = array()) {
3194 if (is_array($options)) {
3195 foreach ($options as $name => $val) {
3196 if (!is_string($name)) {
3197 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3199 if (stripos($name, 'CURLOPT_') === false) {
3200 $name = strtoupper('CURLOPT_'.$name);
3201 } else {
3202 $name = strtoupper($name);
3204 $this->options[$name] = $val;
3210 * Reset http method
3212 public function cleanopt() {
3213 unset($this->options['CURLOPT_HTTPGET']);
3214 unset($this->options['CURLOPT_POST']);
3215 unset($this->options['CURLOPT_POSTFIELDS']);
3216 unset($this->options['CURLOPT_PUT']);
3217 unset($this->options['CURLOPT_INFILE']);
3218 unset($this->options['CURLOPT_INFILESIZE']);
3219 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3220 unset($this->options['CURLOPT_FILE']);
3224 * Resets the HTTP Request headers (to prepare for the new request)
3226 public function resetHeader() {
3227 $this->header = array();
3231 * Set HTTP Request Header
3233 * @param array $header
3235 public function setHeader($header) {
3236 if (is_array($header)) {
3237 foreach ($header as $v) {
3238 $this->setHeader($v);
3240 } else {
3241 // Remove newlines, they are not allowed in headers.
3242 $newvalue = preg_replace('/[\r\n]/', '', $header);
3243 if (!in_array($newvalue, $this->header)) {
3244 $this->header[] = $newvalue;
3250 * Get HTTP Response Headers
3251 * @return array of arrays
3253 public function getResponse() {
3254 return $this->response;
3258 * Get raw HTTP Response Headers
3259 * @return array of strings
3261 public function get_raw_response() {
3262 return $this->rawresponse;
3266 * private callback function
3267 * Formatting HTTP Response Header
3269 * We only keep the last headers returned. For example during a redirect the
3270 * redirect headers will not appear in {@link self::getResponse()}, if you need
3271 * to use those headers, refer to {@link self::get_raw_response()}.
3273 * @param resource $ch Apparently not used
3274 * @param string $header
3275 * @return int The strlen of the header
3277 private function formatHeader($ch, $header) {
3278 $this->rawresponse[] = $header;
3280 if (trim($header, "\r\n") === '') {
3281 // This must be the last header.
3282 $this->responsefinished = true;
3285 if (strlen($header) > 2) {
3286 if ($this->responsefinished) {
3287 // We still have headers after the supposedly last header, we must be
3288 // in a redirect so let's empty the response to keep the last headers.
3289 $this->responsefinished = false;
3290 $this->response = array();
3292 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3293 $key = rtrim($parts[0], ':');
3294 $value = isset($parts[1]) ? $parts[1] : null;
3295 if (!empty($this->response[$key])) {
3296 if (is_array($this->response[$key])) {
3297 $this->response[$key][] = $value;
3298 } else {
3299 $tmp = $this->response[$key];
3300 $this->response[$key] = array();
3301 $this->response[$key][] = $tmp;
3302 $this->response[$key][] = $value;
3305 } else {
3306 $this->response[$key] = $value;
3309 return strlen($header);
3313 * Set options for individual curl instance
3315 * @param resource $curl A curl handle
3316 * @param array $options
3317 * @return resource The curl handle
3319 private function apply_opt($curl, $options) {
3320 // Clean up
3321 $this->cleanopt();
3322 // set cookie
3323 if (!empty($this->cookie) || !empty($options['cookie'])) {
3324 $this->setopt(array('cookiejar'=>$this->cookie,
3325 'cookiefile'=>$this->cookie
3329 // Bypass proxy if required.
3330 if ($this->proxy === null) {
3331 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3332 $proxy = false;
3333 } else {
3334 $proxy = true;
3336 } else {
3337 $proxy = (bool)$this->proxy;
3340 // Set proxy.
3341 if ($proxy) {
3342 $options['CURLOPT_PROXY'] = $this->proxy_host;
3343 } else {
3344 unset($this->options['CURLOPT_PROXY']);
3347 $this->setopt($options);
3349 // Reset before set options.
3350 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3352 // Setting the User-Agent based on options provided.
3353 $useragent = '';
3355 if (!empty($options['CURLOPT_USERAGENT'])) {
3356 $useragent = $options['CURLOPT_USERAGENT'];
3357 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3358 $useragent = $this->options['CURLOPT_USERAGENT'];
3359 } else {
3360 $useragent = \core_useragent::get_moodlebot_useragent();
3363 // Set headers.
3364 if (empty($this->header)) {
3365 $this->setHeader(array(
3366 'User-Agent: ' . $useragent,
3367 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3368 'Connection: keep-alive'
3370 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3371 // Remove old User-Agent if one existed.
3372 // We have to partial search since we don't know what the original User-Agent is.
3373 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3374 $key = array_keys($match)[0];
3375 unset($this->header[$key]);
3377 $this->setHeader(array('User-Agent: ' . $useragent));
3379 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3381 if ($this->debug) {
3382 echo '<h1>Options</h1>';
3383 var_dump($this->options);
3384 echo '<h1>Header</h1>';
3385 var_dump($this->header);
3388 // Do not allow infinite redirects.
3389 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3390 $this->options['CURLOPT_MAXREDIRS'] = 0;
3391 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3392 $this->options['CURLOPT_MAXREDIRS'] = 100;
3393 } else {
3394 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3397 // Make sure we always know if redirects expected.
3398 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3399 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3402 // Limit the protocols to HTTP and HTTPS.
3403 if (defined('CURLOPT_PROTOCOLS')) {
3404 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3405 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3408 // Set options.
3409 foreach($this->options as $name => $val) {
3410 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3411 // The redirects are emulated elsewhere.
3412 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3413 continue;
3415 $name = constant($name);
3416 curl_setopt($curl, $name, $val);
3419 return $curl;
3423 * Download multiple files in parallel
3425 * Calls {@link multi()} with specific download headers
3427 * <code>
3428 * $c = new curl();
3429 * $file1 = fopen('a', 'wb');
3430 * $file2 = fopen('b', 'wb');
3431 * $c->download(array(
3432 * array('url'=>'http://localhost/', 'file'=>$file1),
3433 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3434 * ));
3435 * fclose($file1);
3436 * fclose($file2);
3437 * </code>
3439 * or
3441 * <code>
3442 * $c = new curl();
3443 * $c->download(array(
3444 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3445 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3446 * ));
3447 * </code>
3449 * @param array $requests An array of files to request {
3450 * url => url to download the file [required]
3451 * file => file handler, or
3452 * filepath => file path
3454 * If 'file' and 'filepath' parameters are both specified in one request, the
3455 * open file handle in the 'file' parameter will take precedence and 'filepath'
3456 * will be ignored.
3458 * @param array $options An array of options to set
3459 * @return array An array of results
3461 public function download($requests, $options = array()) {
3462 $options['RETURNTRANSFER'] = false;
3463 return $this->multi($requests, $options);
3467 * Returns the current curl security helper.
3469 * @return \core\files\curl_security_helper instance.
3471 public function get_security() {
3472 return $this->securityhelper;
3476 * Sets the curl security helper.
3478 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3479 * @return bool true if the security helper could be set, false otherwise.
3481 public function set_security($securityobject) {
3482 if ($securityobject instanceof \core\files\curl_security_helper) {
3483 $this->securityhelper = $securityobject;
3484 return true;
3486 return false;
3490 * Multi HTTP Requests
3491 * This function could run multi-requests in parallel.
3493 * @param array $requests An array of files to request
3494 * @param array $options An array of options to set
3495 * @return array An array of results
3497 protected function multi($requests, $options = array()) {
3498 $count = count($requests);
3499 $handles = array();
3500 $results = array();
3501 $main = curl_multi_init();
3502 for ($i = 0; $i < $count; $i++) {
3503 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3504 // open file
3505 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3506 $requests[$i]['auto-handle'] = true;
3508 foreach($requests[$i] as $n=>$v) {
3509 $options[$n] = $v;
3511 $handles[$i] = curl_init($requests[$i]['url']);
3512 $this->apply_opt($handles[$i], $options);
3513 curl_multi_add_handle($main, $handles[$i]);
3515 $running = 0;
3516 do {
3517 curl_multi_exec($main, $running);
3518 } while($running > 0);
3519 for ($i = 0; $i < $count; $i++) {
3520 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3521 $results[] = true;
3522 } else {
3523 $results[] = curl_multi_getcontent($handles[$i]);
3525 curl_multi_remove_handle($main, $handles[$i]);
3527 curl_multi_close($main);
3529 for ($i = 0; $i < $count; $i++) {
3530 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3531 // close file handler if file is opened in this function
3532 fclose($requests[$i]['file']);
3535 return $results;
3539 * Helper function to reset the request state vars.
3541 * @return void.
3543 protected function reset_request_state_vars() {
3544 $this->info = array();
3545 $this->error = '';
3546 $this->errno = 0;
3547 $this->response = array();
3548 $this->rawresponse = array();
3549 $this->responsefinished = false;
3553 * For use only in unit tests - we can pre-set the next curl response.
3554 * This is useful for unit testing APIs that call external systems.
3555 * @param string $response
3557 public static function mock_response($response) {
3558 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3559 array_push(self::$mockresponses, $response);
3560 } else {
3561 throw new coding_exception('mock_response function is only available for unit tests.');
3566 * Single HTTP Request
3568 * @param string $url The URL to request
3569 * @param array $options
3570 * @return bool
3572 protected function request($url, $options = array()) {
3573 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3574 $this->reset_request_state_vars();
3576 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3577 if ($mockresponse = array_pop(self::$mockresponses)) {
3578 $this->info = [ 'http_code' => 200 ];
3579 return $mockresponse;
3583 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3584 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3585 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3586 $this->error = $this->securityhelper->get_blocked_url_string();
3587 return $this->error;
3590 // Set the URL as a curl option.
3591 $this->setopt(array('CURLOPT_URL' => $url));
3593 // Create curl instance.
3594 $curl = curl_init();
3596 $this->apply_opt($curl, $options);
3597 if ($this->cache && $ret = $this->cache->get($this->options)) {
3598 return $ret;
3601 $ret = curl_exec($curl);
3602 $this->info = curl_getinfo($curl);
3603 $this->error = curl_error($curl);
3604 $this->errno = curl_errno($curl);
3605 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3607 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3608 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3609 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3610 $this->reset_request_state_vars();
3611 $this->error = $this->securityhelper->get_blocked_url_string();
3612 curl_close($curl);
3613 return $this->error;
3616 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3617 $redirects = 0;
3619 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3621 if ($this->info['http_code'] == 301) {
3622 // Moved Permanently - repeat the same request on new URL.
3624 } else if ($this->info['http_code'] == 302) {
3625 // Found - the standard redirect - repeat the same request on new URL.
3627 } else if ($this->info['http_code'] == 303) {
3628 // 303 See Other - repeat only if GET, do not bother with POSTs.
3629 if (empty($this->options['CURLOPT_HTTPGET'])) {
3630 break;
3633 } else if ($this->info['http_code'] == 307) {
3634 // Temporary Redirect - must repeat using the same request type.
3636 } else if ($this->info['http_code'] == 308) {
3637 // Permanent Redirect - must repeat using the same request type.
3639 } else {
3640 // Some other http code means do not retry!
3641 break;
3644 $redirects++;
3646 $redirecturl = null;
3647 if (isset($this->info['redirect_url'])) {
3648 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3649 $redirecturl = $this->info['redirect_url'];
3652 if (!$redirecturl) {
3653 foreach ($this->response as $k => $v) {
3654 if (strtolower($k) === 'location') {
3655 $redirecturl = $v;
3656 break;
3659 if (preg_match('|^https?://|i', $redirecturl)) {
3660 // Great, this is the correct location format!
3662 } else if ($redirecturl) {
3663 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3664 if (strpos($redirecturl, '/') === 0) {
3665 // Relative to server root - just guess.
3666 $pos = strpos('/', $current, 8);
3667 if ($pos === false) {
3668 $redirecturl = $current.$redirecturl;
3669 } else {
3670 $redirecturl = substr($current, 0, $pos).$redirecturl;
3672 } else {
3673 // Relative to current script.
3674 $redirecturl = dirname($current).'/'.$redirecturl;
3679 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3680 $ret = curl_exec($curl);
3682 $this->info = curl_getinfo($curl);
3683 $this->error = curl_error($curl);
3684 $this->errno = curl_errno($curl);
3686 $this->info['redirect_count'] = $redirects;
3688 if ($this->info['http_code'] === 200) {
3689 // Finally this is what we wanted.
3690 break;
3692 if ($this->errno != CURLE_OK) {
3693 // Something wrong is going on.
3694 break;
3697 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3698 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3699 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3703 if ($this->cache) {
3704 $this->cache->set($this->options, $ret);
3707 if ($this->debug) {
3708 echo '<h1>Return Data</h1>';
3709 var_dump($ret);
3710 echo '<h1>Info</h1>';
3711 var_dump($this->info);
3712 echo '<h1>Error</h1>';
3713 var_dump($this->error);
3716 curl_close($curl);
3718 if (empty($this->error)) {
3719 return $ret;
3720 } else {
3721 return $this->error;
3722 // exception is not ajax friendly
3723 //throw new moodle_exception($this->error, 'curl');
3728 * HTTP HEAD method
3730 * @see request()
3732 * @param string $url
3733 * @param array $options
3734 * @return bool
3736 public function head($url, $options = array()) {
3737 $options['CURLOPT_HTTPGET'] = 0;
3738 $options['CURLOPT_HEADER'] = 1;
3739 $options['CURLOPT_NOBODY'] = 1;
3740 return $this->request($url, $options);
3744 * HTTP PATCH method
3746 * @param string $url
3747 * @param array|string $params
3748 * @param array $options
3749 * @return bool
3751 public function patch($url, $params = '', $options = array()) {
3752 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3753 if (is_array($params)) {
3754 $this->_tmp_file_post_params = array();
3755 foreach ($params as $key => $value) {
3756 if ($value instanceof stored_file) {
3757 $value->add_to_curl_request($this, $key);
3758 } else {
3759 $this->_tmp_file_post_params[$key] = $value;
3762 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3763 unset($this->_tmp_file_post_params);
3764 } else {
3765 // The variable $params is the raw post data.
3766 $options['CURLOPT_POSTFIELDS'] = $params;
3768 return $this->request($url, $options);
3772 * HTTP POST method
3774 * @param string $url
3775 * @param array|string $params
3776 * @param array $options
3777 * @return bool
3779 public function post($url, $params = '', $options = array()) {
3780 $options['CURLOPT_POST'] = 1;
3781 if (is_array($params)) {
3782 $this->_tmp_file_post_params = array();
3783 foreach ($params as $key => $value) {
3784 if ($value instanceof stored_file) {
3785 $value->add_to_curl_request($this, $key);
3786 } else {
3787 $this->_tmp_file_post_params[$key] = $value;
3790 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3791 unset($this->_tmp_file_post_params);
3792 } else {
3793 // $params is the raw post data
3794 $options['CURLOPT_POSTFIELDS'] = $params;
3796 return $this->request($url, $options);
3800 * HTTP GET method
3802 * @param string $url
3803 * @param array $params
3804 * @param array $options
3805 * @return bool
3807 public function get($url, $params = array(), $options = array()) {
3808 $options['CURLOPT_HTTPGET'] = 1;
3810 if (!empty($params)) {
3811 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3812 $url .= http_build_query($params, '', '&');
3814 return $this->request($url, $options);
3818 * Downloads one file and writes it to the specified file handler
3820 * <code>
3821 * $c = new curl();
3822 * $file = fopen('savepath', 'w');
3823 * $result = $c->download_one('http://localhost/', null,
3824 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3825 * fclose($file);
3826 * $download_info = $c->get_info();
3827 * if ($result === true) {
3828 * // file downloaded successfully
3829 * } else {
3830 * $error_text = $result;
3831 * $error_code = $c->get_errno();
3833 * </code>
3835 * <code>
3836 * $c = new curl();
3837 * $result = $c->download_one('http://localhost/', null,
3838 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3839 * // ... see above, no need to close handle and remove file if unsuccessful
3840 * </code>
3842 * @param string $url
3843 * @param array|null $params key-value pairs to be added to $url as query string
3844 * @param array $options request options. Must include either 'file' or 'filepath'
3845 * @return bool|string true on success or error string on failure
3847 public function download_one($url, $params, $options = array()) {
3848 $options['CURLOPT_HTTPGET'] = 1;
3849 if (!empty($params)) {
3850 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3851 $url .= http_build_query($params, '', '&');
3853 if (!empty($options['filepath']) && empty($options['file'])) {
3854 // open file
3855 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3856 $this->errno = 100;
3857 return get_string('cannotwritefile', 'error', $options['filepath']);
3859 $filepath = $options['filepath'];
3861 unset($options['filepath']);
3862 $result = $this->request($url, $options);
3863 if (isset($filepath)) {
3864 fclose($options['file']);
3865 if ($result !== true) {
3866 unlink($filepath);
3869 return $result;
3873 * HTTP PUT method
3875 * @param string $url
3876 * @param array $params
3877 * @param array $options
3878 * @return bool
3880 public function put($url, $params = array(), $options = array()) {
3881 $file = '';
3882 $fp = false;
3883 if (isset($params['file'])) {
3884 $file = $params['file'];
3885 if (is_file($file)) {
3886 $fp = fopen($file, 'r');
3887 $size = filesize($file);
3888 $options['CURLOPT_PUT'] = 1;
3889 $options['CURLOPT_INFILESIZE'] = $size;
3890 $options['CURLOPT_INFILE'] = $fp;
3891 } else {
3892 return null;
3894 if (!isset($this->options['CURLOPT_USERPWD'])) {
3895 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3897 } else {
3898 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3899 $options['CURLOPT_POSTFIELDS'] = $params;
3902 $ret = $this->request($url, $options);
3903 if ($fp !== false) {
3904 fclose($fp);
3906 return $ret;
3910 * HTTP DELETE method
3912 * @param string $url
3913 * @param array $param
3914 * @param array $options
3915 * @return bool
3917 public function delete($url, $param = array(), $options = array()) {
3918 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3919 if (!isset($options['CURLOPT_USERPWD'])) {
3920 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3922 $ret = $this->request($url, $options);
3923 return $ret;
3927 * HTTP TRACE method
3929 * @param string $url
3930 * @param array $options
3931 * @return bool
3933 public function trace($url, $options = array()) {
3934 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3935 $ret = $this->request($url, $options);
3936 return $ret;
3940 * HTTP OPTIONS method
3942 * @param string $url
3943 * @param array $options
3944 * @return bool
3946 public function options($url, $options = array()) {
3947 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3948 $ret = $this->request($url, $options);
3949 return $ret;
3953 * Get curl information
3955 * @return string
3957 public function get_info() {
3958 return $this->info;
3962 * Get curl error code
3964 * @return int
3966 public function get_errno() {
3967 return $this->errno;
3971 * When using a proxy, an additional HTTP response code may appear at
3972 * the start of the header. For example, when using https over a proxy
3973 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3974 * also possible and some may come with their own headers.
3976 * If using the return value containing all headers, this function can be
3977 * called to remove unwanted doubles.
3979 * Note that it is not possible to distinguish this situation from valid
3980 * data unless you know the actual response part (below the headers)
3981 * will not be included in this string, or else will not 'look like' HTTP
3982 * headers. As a result it is not safe to call this function for general
3983 * data.
3985 * @param string $input Input HTTP response
3986 * @return string HTTP response with additional headers stripped if any
3988 public static function strip_double_headers($input) {
3989 // I have tried to make this regular expression as specific as possible
3990 // to avoid any case where it does weird stuff if you happen to put
3991 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3992 // also make it faster because it can abandon regex processing as soon
3993 // as it hits something that doesn't look like an http header. The
3994 // header definition is taken from RFC 822, except I didn't support
3995 // folding which is never used in practice.
3996 $crlf = "\r\n";
3997 return preg_replace(
3998 // HTTP version and status code (ignore value of code).
3999 '~^HTTP/1\..*' . $crlf .
4000 // Header name: character between 33 and 126 decimal, except colon.
4001 // Colon. Header value: any character except \r and \n. CRLF.
4002 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
4003 // Headers are terminated by another CRLF (blank line).
4004 $crlf .
4005 // Second HTTP status code, this time must be 200.
4006 '(HTTP/1.[01] 200 )~', '$1', $input);
4011 * This class is used by cURL class, use case:
4013 * <code>
4014 * $CFG->repositorycacheexpire = 120;
4015 * $CFG->curlcache = 120;
4017 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
4018 * $ret = $c->get('http://www.google.com');
4019 * </code>
4021 * @package core_files
4022 * @copyright Dongsheng Cai <dongsheng@moodle.com>
4023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4025 class curl_cache {
4026 /** @var string Path to cache directory */
4027 public $dir = '';
4030 * Constructor
4032 * @global stdClass $CFG
4033 * @param string $module which module is using curl_cache
4035 public function __construct($module = 'repository') {
4036 global $CFG;
4037 if (!empty($module)) {
4038 $this->dir = $CFG->cachedir.'/'.$module.'/';
4039 } else {
4040 $this->dir = $CFG->cachedir.'/misc/';
4042 if (!file_exists($this->dir)) {
4043 mkdir($this->dir, $CFG->directorypermissions, true);
4045 if ($module == 'repository') {
4046 if (empty($CFG->repositorycacheexpire)) {
4047 $CFG->repositorycacheexpire = 120;
4049 $this->ttl = $CFG->repositorycacheexpire;
4050 } else {
4051 if (empty($CFG->curlcache)) {
4052 $CFG->curlcache = 120;
4054 $this->ttl = $CFG->curlcache;
4059 * Get cached value
4061 * @global stdClass $CFG
4062 * @global stdClass $USER
4063 * @param mixed $param
4064 * @return bool|string
4066 public function get($param) {
4067 global $CFG, $USER;
4068 $this->cleanup($this->ttl);
4069 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4070 if(file_exists($this->dir.$filename)) {
4071 $lasttime = filemtime($this->dir.$filename);
4072 if (time()-$lasttime > $this->ttl) {
4073 return false;
4074 } else {
4075 $fp = fopen($this->dir.$filename, 'r');
4076 $size = filesize($this->dir.$filename);
4077 $content = fread($fp, $size);
4078 return unserialize($content);
4081 return false;
4085 * Set cache value
4087 * @global object $CFG
4088 * @global object $USER
4089 * @param mixed $param
4090 * @param mixed $val
4092 public function set($param, $val) {
4093 global $CFG, $USER;
4094 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4095 $fp = fopen($this->dir.$filename, 'w');
4096 fwrite($fp, serialize($val));
4097 fclose($fp);
4098 @chmod($this->dir.$filename, $CFG->filepermissions);
4102 * Remove cache files
4104 * @param int $expire The number of seconds before expiry
4106 public function cleanup($expire) {
4107 if ($dir = opendir($this->dir)) {
4108 while (false !== ($file = readdir($dir))) {
4109 if(!is_dir($file) && $file != '.' && $file != '..') {
4110 $lasttime = @filemtime($this->dir.$file);
4111 if (time() - $lasttime > $expire) {
4112 @unlink($this->dir.$file);
4116 closedir($dir);
4120 * delete current user's cache file
4122 * @global object $CFG
4123 * @global object $USER
4125 public function refresh() {
4126 global $CFG, $USER;
4127 if ($dir = opendir($this->dir)) {
4128 while (false !== ($file = readdir($dir))) {
4129 if (!is_dir($file) && $file != '.' && $file != '..') {
4130 if (strpos($file, 'u'.$USER->id.'_') !== false) {
4131 @unlink($this->dir.$file);
4140 * This function delegates file serving to individual plugins
4142 * @param string $relativepath
4143 * @param bool $forcedownload
4144 * @param null|string $preview the preview mode, defaults to serving the original file
4145 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4146 * offline (e.g. mobile app).
4147 * @param bool $embed Whether this file will be served embed into an iframe.
4148 * @todo MDL-31088 file serving improments
4150 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4151 global $DB, $CFG, $USER;
4152 // relative path must start with '/'
4153 if (!$relativepath) {
4154 print_error('invalidargorconf');
4155 } else if ($relativepath[0] != '/') {
4156 print_error('pathdoesnotstartslash');
4159 // extract relative path components
4160 $args = explode('/', ltrim($relativepath, '/'));
4162 if (count($args) < 3) { // always at least context, component and filearea
4163 print_error('invalidarguments');
4166 $contextid = (int)array_shift($args);
4167 $component = clean_param(array_shift($args), PARAM_COMPONENT);
4168 $filearea = clean_param(array_shift($args), PARAM_AREA);
4170 list($context, $course, $cm) = get_context_info_array($contextid);
4172 $fs = get_file_storage();
4174 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4176 // ========================================================================================================================
4177 if ($component === 'blog') {
4178 // Blog file serving
4179 if ($context->contextlevel != CONTEXT_SYSTEM) {
4180 send_file_not_found();
4182 if ($filearea !== 'attachment' and $filearea !== 'post') {
4183 send_file_not_found();
4186 if (empty($CFG->enableblogs)) {
4187 print_error('siteblogdisable', 'blog');
4190 $entryid = (int)array_shift($args);
4191 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4192 send_file_not_found();
4194 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4195 require_login();
4196 if (isguestuser()) {
4197 print_error('noguest');
4199 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4200 if ($USER->id != $entry->userid) {
4201 send_file_not_found();
4206 if ($entry->publishstate === 'public') {
4207 if ($CFG->forcelogin) {
4208 require_login();
4211 } else if ($entry->publishstate === 'site') {
4212 require_login();
4213 //ok
4214 } else if ($entry->publishstate === 'draft') {
4215 require_login();
4216 if ($USER->id != $entry->userid) {
4217 send_file_not_found();
4221 $filename = array_pop($args);
4222 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4224 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4225 send_file_not_found();
4228 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4230 // ========================================================================================================================
4231 } else if ($component === 'grade') {
4233 require_once($CFG->libdir . '/grade/constants.php');
4235 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4236 // Global gradebook files
4237 if ($CFG->forcelogin) {
4238 require_login();
4241 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4243 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4244 send_file_not_found();
4247 \core\session\manager::write_close(); // Unlock session during file serving.
4248 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4250 } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4251 if ($context->contextlevel != CONTEXT_MODULE) {
4252 send_file_not_found();
4255 require_login($course, false);
4257 $gradeid = (int) array_shift($args);
4258 $filename = array_pop($args);
4259 if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4260 $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4261 } else {
4262 $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4265 if (!$grade) {
4266 send_file_not_found();
4269 $iscurrentuser = $USER->id == $grade->userid;
4271 if (!$iscurrentuser) {
4272 $coursecontext = context_course::instance($course->id);
4273 if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4274 send_file_not_found();
4278 $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4280 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4281 send_file_not_found();
4284 \core\session\manager::write_close(); // Unlock session during file serving.
4285 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4286 } else {
4287 send_file_not_found();
4290 // ========================================================================================================================
4291 } else if ($component === 'tag') {
4292 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4294 // All tag descriptions are going to be public but we still need to respect forcelogin
4295 if ($CFG->forcelogin) {
4296 require_login();
4299 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4301 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4302 send_file_not_found();
4305 \core\session\manager::write_close(); // Unlock session during file serving.
4306 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4308 } else {
4309 send_file_not_found();
4311 // ========================================================================================================================
4312 } else if ($component === 'badges') {
4313 require_once($CFG->libdir . '/badgeslib.php');
4315 $badgeid = (int)array_shift($args);
4316 $badge = new badge($badgeid);
4317 $filename = array_pop($args);
4319 if ($filearea === 'badgeimage') {
4320 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4321 send_file_not_found();
4323 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4324 send_file_not_found();
4327 \core\session\manager::write_close();
4328 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4329 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4330 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4331 send_file_not_found();
4334 \core\session\manager::write_close();
4335 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4337 // ========================================================================================================================
4338 } else if ($component === 'calendar') {
4339 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4341 // All events here are public the one requirement is that we respect forcelogin
4342 if ($CFG->forcelogin) {
4343 require_login();
4346 // Get the event if from the args array
4347 $eventid = array_shift($args);
4349 // Load the event from the database
4350 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4351 send_file_not_found();
4354 // Get the file and serve if successful
4355 $filename = array_pop($args);
4356 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4357 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4358 send_file_not_found();
4361 \core\session\manager::write_close(); // Unlock session during file serving.
4362 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4364 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4366 // Must be logged in, if they are not then they obviously can't be this user
4367 require_login();
4369 // Don't want guests here, potentially saves a DB call
4370 if (isguestuser()) {
4371 send_file_not_found();
4374 // Get the event if from the args array
4375 $eventid = array_shift($args);
4377 // Load the event from the database - user id must match
4378 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4379 send_file_not_found();
4382 // Get the file and serve if successful
4383 $filename = array_pop($args);
4384 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4385 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4386 send_file_not_found();
4389 \core\session\manager::write_close(); // Unlock session during file serving.
4390 send_stored_file($file, 0, 0, true, $sendfileoptions);
4392 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4394 // Respect forcelogin and require login unless this is the site.... it probably
4395 // should NEVER be the site
4396 if ($CFG->forcelogin || $course->id != SITEID) {
4397 require_login($course);
4400 // Must be able to at least view the course. This does not apply to the front page.
4401 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4402 //TODO: hmm, do we really want to block guests here?
4403 send_file_not_found();
4406 // Get the event id
4407 $eventid = array_shift($args);
4409 // Load the event from the database we need to check whether it is
4410 // a) valid course event
4411 // b) a group event
4412 // Group events use the course context (there is no group context)
4413 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4414 send_file_not_found();
4417 // If its a group event require either membership of view all groups capability
4418 if ($event->eventtype === 'group') {
4419 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4420 send_file_not_found();
4422 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4423 // Ok. Please note that the event type 'site' still uses a course context.
4424 } else {
4425 // Some other type.
4426 send_file_not_found();
4429 // If we get this far we can serve the file
4430 $filename = array_pop($args);
4431 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4432 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4433 send_file_not_found();
4436 \core\session\manager::write_close(); // Unlock session during file serving.
4437 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4439 } else {
4440 send_file_not_found();
4443 // ========================================================================================================================
4444 } else if ($component === 'user') {
4445 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4446 if (count($args) == 1) {
4447 $themename = theme_config::DEFAULT_THEME;
4448 $filename = array_shift($args);
4449 } else {
4450 $themename = array_shift($args);
4451 $filename = array_shift($args);
4454 // fix file name automatically
4455 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4456 $filename = 'f1';
4459 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4460 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4461 // protect images if login required and not logged in;
4462 // also if login is required for profile images and is not logged in or guest
4463 // do not use require_login() because it is expensive and not suitable here anyway
4464 $theme = theme_config::load($themename);
4465 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4468 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4469 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4470 if ($filename === 'f3') {
4471 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4472 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4473 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4478 if (!$file) {
4479 // bad reference - try to prevent future retries as hard as possible!
4480 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4481 if ($user->picture > 0) {
4482 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4485 // no redirect here because it is not cached
4486 $theme = theme_config::load($themename);
4487 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4488 send_file($imagefile, basename($imagefile), 60*60*24*14);
4491 $options = $sendfileoptions;
4492 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4493 // Profile images should be cache-able by both browsers and proxies according
4494 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4495 $options['cacheability'] = 'public';
4497 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4499 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4500 require_login();
4502 if (isguestuser()) {
4503 send_file_not_found();
4506 if ($USER->id !== $context->instanceid) {
4507 send_file_not_found();
4510 $filename = array_pop($args);
4511 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4512 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4513 send_file_not_found();
4516 \core\session\manager::write_close(); // Unlock session during file serving.
4517 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4519 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4521 if ($CFG->forcelogin) {
4522 require_login();
4525 $userid = $context->instanceid;
4527 if ($USER->id == $userid) {
4528 // always can access own
4530 } else if (!empty($CFG->forceloginforprofiles)) {
4531 require_login();
4533 if (isguestuser()) {
4534 send_file_not_found();
4537 // we allow access to site profile of all course contacts (usually teachers)
4538 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4539 send_file_not_found();
4542 $canview = false;
4543 if (has_capability('moodle/user:viewdetails', $context)) {
4544 $canview = true;
4545 } else {
4546 $courses = enrol_get_my_courses();
4549 while (!$canview && count($courses) > 0) {
4550 $course = array_shift($courses);
4551 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4552 $canview = true;
4557 $filename = array_pop($args);
4558 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4559 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4560 send_file_not_found();
4563 \core\session\manager::write_close(); // Unlock session during file serving.
4564 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4566 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4567 $userid = (int)array_shift($args);
4568 $usercontext = context_user::instance($userid);
4570 if ($CFG->forcelogin) {
4571 require_login();
4574 if (!empty($CFG->forceloginforprofiles)) {
4575 require_login();
4576 if (isguestuser()) {
4577 print_error('noguest');
4580 //TODO: review this logic of user profile access prevention
4581 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4582 print_error('usernotavailable');
4584 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4585 print_error('cannotviewprofile');
4587 if (!is_enrolled($context, $userid)) {
4588 print_error('notenrolledprofile');
4590 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4591 print_error('groupnotamember');
4595 $filename = array_pop($args);
4596 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4597 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4598 send_file_not_found();
4601 \core\session\manager::write_close(); // Unlock session during file serving.
4602 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4604 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4605 require_login();
4607 if (isguestuser()) {
4608 send_file_not_found();
4610 $userid = $context->instanceid;
4612 if ($USER->id != $userid) {
4613 send_file_not_found();
4616 $filename = array_pop($args);
4617 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4618 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4619 send_file_not_found();
4622 \core\session\manager::write_close(); // Unlock session during file serving.
4623 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4625 } else {
4626 send_file_not_found();
4629 // ========================================================================================================================
4630 } else if ($component === 'coursecat') {
4631 if ($context->contextlevel != CONTEXT_COURSECAT) {
4632 send_file_not_found();
4635 if ($filearea === 'description') {
4636 if ($CFG->forcelogin) {
4637 // no login necessary - unless login forced everywhere
4638 require_login();
4641 // Check if user can view this category.
4642 if (!core_course_category::get($context->instanceid, IGNORE_MISSING)) {
4643 send_file_not_found();
4646 $filename = array_pop($args);
4647 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4648 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4649 send_file_not_found();
4652 \core\session\manager::write_close(); // Unlock session during file serving.
4653 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4654 } else {
4655 send_file_not_found();
4658 // ========================================================================================================================
4659 } else if ($component === 'course') {
4660 if ($context->contextlevel != CONTEXT_COURSE) {
4661 send_file_not_found();
4664 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4665 if ($CFG->forcelogin) {
4666 require_login();
4669 $filename = array_pop($args);
4670 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4671 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4672 send_file_not_found();
4675 \core\session\manager::write_close(); // Unlock session during file serving.
4676 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4678 } else if ($filearea === 'section') {
4679 if ($CFG->forcelogin) {
4680 require_login($course);
4681 } else if ($course->id != SITEID) {
4682 require_login($course);
4685 $sectionid = (int)array_shift($args);
4687 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4688 send_file_not_found();
4691 $filename = array_pop($args);
4692 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4693 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4694 send_file_not_found();
4697 \core\session\manager::write_close(); // Unlock session during file serving.
4698 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4700 } else {
4701 send_file_not_found();
4704 } else if ($component === 'cohort') {
4706 $cohortid = (int)array_shift($args);
4707 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4708 $cohortcontext = context::instance_by_id($cohort->contextid);
4710 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4711 if ($context->id != $cohort->contextid &&
4712 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4713 send_file_not_found();
4716 // User is able to access cohort if they have view cap on cohort level or
4717 // the cohort is visible and they have view cap on course level.
4718 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4719 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4721 if ($filearea === 'description' && $canview) {
4722 $filename = array_pop($args);
4723 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4724 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4725 && !$file->is_directory()) {
4726 \core\session\manager::write_close(); // Unlock session during file serving.
4727 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4731 send_file_not_found();
4733 } else if ($component === 'group') {
4734 if ($context->contextlevel != CONTEXT_COURSE) {
4735 send_file_not_found();
4738 require_course_login($course, true, null, false);
4740 $groupid = (int)array_shift($args);
4742 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4743 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4744 // do not allow access to separate group info if not member or teacher
4745 send_file_not_found();
4748 if ($filearea === 'description') {
4750 require_login($course);
4752 $filename = array_pop($args);
4753 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4754 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4755 send_file_not_found();
4758 \core\session\manager::write_close(); // Unlock session during file serving.
4759 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4761 } else if ($filearea === 'icon') {
4762 $filename = array_pop($args);
4764 if ($filename !== 'f1' and $filename !== 'f2') {
4765 send_file_not_found();
4767 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4768 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4769 send_file_not_found();
4773 \core\session\manager::write_close(); // Unlock session during file serving.
4774 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4776 } else {
4777 send_file_not_found();
4780 } else if ($component === 'grouping') {
4781 if ($context->contextlevel != CONTEXT_COURSE) {
4782 send_file_not_found();
4785 require_login($course);
4787 $groupingid = (int)array_shift($args);
4789 // note: everybody has access to grouping desc images for now
4790 if ($filearea === 'description') {
4792 $filename = array_pop($args);
4793 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4794 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4795 send_file_not_found();
4798 \core\session\manager::write_close(); // Unlock session during file serving.
4799 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4801 } else {
4802 send_file_not_found();
4805 // ========================================================================================================================
4806 } else if ($component === 'backup') {
4807 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4808 require_login($course);
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', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4814 send_file_not_found();
4817 \core\session\manager::write_close(); // Unlock session during file serving.
4818 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4820 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4821 require_login($course);
4822 require_capability('moodle/backup:downloadfile', $context);
4824 $sectionid = (int)array_shift($args);
4826 $filename = array_pop($args);
4827 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4828 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4829 send_file_not_found();
4832 \core\session\manager::write_close();
4833 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4835 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4836 require_login($course, false, $cm);
4837 require_capability('moodle/backup:downloadfile', $context);
4839 $filename = array_pop($args);
4840 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4841 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4842 send_file_not_found();
4845 \core\session\manager::write_close();
4846 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4848 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4849 // Backup files that were generated by the automated backup systems.
4851 require_login($course);
4852 require_capability('moodle/backup:downloadfile', $context);
4853 require_capability('moodle/restore:userinfo', $context);
4855 $filename = array_pop($args);
4856 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4857 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4858 send_file_not_found();
4861 \core\session\manager::write_close(); // Unlock session during file serving.
4862 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4864 } else {
4865 send_file_not_found();
4868 // ========================================================================================================================
4869 } else if ($component === 'question') {
4870 require_once($CFG->libdir . '/questionlib.php');
4871 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4872 send_file_not_found();
4874 // ========================================================================================================================
4875 } else if ($component === 'grading') {
4876 if ($filearea === 'description') {
4877 // files embedded into the form definition description
4879 if ($context->contextlevel == CONTEXT_SYSTEM) {
4880 require_login();
4882 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4883 require_login($course, false, $cm);
4885 } else {
4886 send_file_not_found();
4889 $formid = (int)array_shift($args);
4891 $sql = "SELECT ga.id
4892 FROM {grading_areas} ga
4893 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4894 WHERE gd.id = ? AND ga.contextid = ?";
4895 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4897 if (!$areaid) {
4898 send_file_not_found();
4901 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4903 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4904 send_file_not_found();
4907 \core\session\manager::write_close(); // Unlock session during file serving.
4908 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4911 // ========================================================================================================================
4912 } else if (strpos($component, 'mod_') === 0) {
4913 $modname = substr($component, 4);
4914 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4915 send_file_not_found();
4917 require_once("$CFG->dirroot/mod/$modname/lib.php");
4919 if ($context->contextlevel == CONTEXT_MODULE) {
4920 if ($cm->modname !== $modname) {
4921 // somebody tries to gain illegal access, cm type must match the component!
4922 send_file_not_found();
4926 if ($filearea === 'intro') {
4927 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4928 send_file_not_found();
4931 // Require login to the course first (without login to the module).
4932 require_course_login($course, true);
4934 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4935 $cminfo = cm_info::create($cm);
4936 if (!$cminfo->uservisible) {
4937 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
4938 // Module intro is not visible on the course page and module is not available, show access error.
4939 require_course_login($course, true, $cminfo);
4943 // all users may access it
4944 $filename = array_pop($args);
4945 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4946 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4947 send_file_not_found();
4950 // finally send the file
4951 send_stored_file($file, null, 0, false, $sendfileoptions);
4954 $filefunction = $component.'_pluginfile';
4955 $filefunctionold = $modname.'_pluginfile';
4956 if (function_exists($filefunction)) {
4957 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4958 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4959 } else if (function_exists($filefunctionold)) {
4960 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4961 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4964 send_file_not_found();
4966 // ========================================================================================================================
4967 } else if (strpos($component, 'block_') === 0) {
4968 $blockname = substr($component, 6);
4969 // note: no more class methods in blocks please, that is ....
4970 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4971 send_file_not_found();
4973 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4975 if ($context->contextlevel == CONTEXT_BLOCK) {
4976 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4977 if ($birecord->blockname !== $blockname) {
4978 // somebody tries to gain illegal access, cm type must match the component!
4979 send_file_not_found();
4982 if ($context->get_course_context(false)) {
4983 // If block is in course context, then check if user has capability to access course.
4984 require_course_login($course);
4985 } else if ($CFG->forcelogin) {
4986 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4987 require_login();
4990 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4991 // User can't access file, if block is hidden or doesn't have block:view capability
4992 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4993 send_file_not_found();
4995 } else {
4996 $birecord = null;
4999 $filefunction = $component.'_pluginfile';
5000 if (function_exists($filefunction)) {
5001 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5002 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5005 send_file_not_found();
5007 // ========================================================================================================================
5008 } else if (strpos($component, '_') === false) {
5009 // all core subsystems have to be specified above, no more guessing here!
5010 send_file_not_found();
5012 } else {
5013 // try to serve general plugin file in arbitrary context
5014 $dir = core_component::get_component_directory($component);
5015 if (!file_exists("$dir/lib.php")) {
5016 send_file_not_found();
5018 include_once("$dir/lib.php");
5020 $filefunction = $component.'_pluginfile';
5021 if (function_exists($filefunction)) {
5022 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5023 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5026 send_file_not_found();