MDL-36754 output: Support token pluginfiles in group pic
[moodle.git] / lib / filelib.php
blob01b360c8430910619335434b3bc3cf2351fab55a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for file handling.
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 /**
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
42 /**
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56 global $CFG;
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
65 if ($forcedownload) {
66 $return .= '?forcedownload=1';
68 } else {
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
71 if ($forcedownload) {
72 $return .= '&amp;forcedownload=1';
76 if ($https) {
77 $return = str_replace('http://', 'https://', $return);
80 return $return;
83 /**
84 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
92 * @return bool
94 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
95 global $DB;
97 if (!isset($itemid)) {
98 // Not initialised yet.
99 return false;
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
114 * displayed.
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
118 * @category files
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id != $context->id) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
161 $contextid = null;
162 $itemid = null;
163 if (!isset($data)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
176 } else {
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
183 } else {
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
195 } else {
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
199 return $data;
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
213 * @category files
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
240 if (!isset($options['removeorphaneddrafts'])) {
241 $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
244 if ($options['trusttext']) {
245 $data->{$field.'trust'} = trusttext_trusted($context);
246 } else {
247 $data->{$field.'trust'} = 0;
250 $editor = $data->{$field.'_editor'};
252 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
253 $data->{$field} = $editor['text'];
254 } else {
255 // Clean the user drafts area of any files not referenced in the editor text.
256 if ($options['removeorphaneddrafts']) {
257 file_remove_editor_orphaned_files($editor);
259 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
261 $data->{$field.'format'} = $editor['format'];
263 return $data;
267 * Saves text and files modified by Editor formslib element
269 * @category files
270 * @param stdClass $data $database entry field
271 * @param string $field name of data field
272 * @param array $options various options
273 * @param stdClass $context context - must already exist
274 * @param string $component
275 * @param string $filearea file area name
276 * @param int $itemid must already exist, usually means data is in db
277 * @return stdClass modified data obejct
279 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
280 $options = (array)$options;
281 if (!isset($options['subdirs'])) {
282 $options['subdirs'] = false;
284 if (is_null($itemid) or is_null($context)) {
285 $itemid = null;
286 $contextid = null;
287 } else {
288 $contextid = $context->id;
291 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
292 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
293 $data->{$field.'_filemanager'} = $draftid_editor;
295 return $data;
299 * Saves files modified by File manager formslib element
301 * @todo MDL-31073 review this function
302 * @category files
303 * @param stdClass $data $database entry field
304 * @param string $field name of data field
305 * @param array $options various options
306 * @param stdClass $context context - must already exist
307 * @param string $component
308 * @param string $filearea file area name
309 * @param int $itemid must already exist, usually means data is in db
310 * @return stdClass modified data obejct
312 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
313 $options = (array)$options;
314 if (!isset($options['subdirs'])) {
315 $options['subdirs'] = false;
317 if (!isset($options['maxfiles'])) {
318 $options['maxfiles'] = -1; // unlimited
320 if (!isset($options['maxbytes'])) {
321 $options['maxbytes'] = 0; // unlimited
324 if (empty($data->{$field.'_filemanager'})) {
325 $data->$field = '';
327 } else {
328 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
329 $fs = get_file_storage();
331 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
332 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
333 } else {
334 $data->$field = '';
338 return $data;
342 * Generate a draft itemid
344 * @category files
345 * @global moodle_database $DB
346 * @global stdClass $USER
347 * @return int a random but available draft itemid that can be used to create a new draft
348 * file area.
350 function file_get_unused_draft_itemid() {
351 global $DB, $USER;
353 if (isguestuser() or !isloggedin()) {
354 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
355 print_error('noguest');
358 $contextid = context_user::instance($USER->id)->id;
360 $fs = get_file_storage();
361 $draftitemid = rand(1, 999999999);
362 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
363 $draftitemid = rand(1, 999999999);
366 return $draftitemid;
370 * Initialise a draft file area from a real one by copying the files. A draft
371 * area will be created if one does not already exist. Normally you should
372 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
374 * @category files
375 * @global stdClass $CFG
376 * @global stdClass $USER
377 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
378 * @param int $contextid This parameter and the next two identify the file area to copy files from.
379 * @param string $component
380 * @param string $filearea helps indentify the file area.
381 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
382 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
383 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
384 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
386 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
387 global $CFG, $USER, $CFG;
389 $options = (array)$options;
390 if (!isset($options['subdirs'])) {
391 $options['subdirs'] = false;
393 if (!isset($options['forcehttps'])) {
394 $options['forcehttps'] = false;
397 $usercontext = context_user::instance($USER->id);
398 $fs = get_file_storage();
400 if (empty($draftitemid)) {
401 // create a new area and copy existing files into
402 $draftitemid = file_get_unused_draft_itemid();
403 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
404 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
405 foreach ($files as $file) {
406 if ($file->is_directory() and $file->get_filepath() === '/') {
407 // we need a way to mark the age of each draft area,
408 // by not copying the root dir we force it to be created automatically with current timestamp
409 continue;
411 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
412 continue;
414 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
415 // XXX: This is a hack for file manager (MDL-28666)
416 // File manager needs to know the original file information before copying
417 // to draft area, so we append these information in mdl_files.source field
418 // {@link file_storage::search_references()}
419 // {@link file_storage::search_references_count()}
420 $sourcefield = $file->get_source();
421 $newsourcefield = new stdClass;
422 $newsourcefield->source = $sourcefield;
423 $original = new stdClass;
424 $original->contextid = $contextid;
425 $original->component = $component;
426 $original->filearea = $filearea;
427 $original->itemid = $itemid;
428 $original->filename = $file->get_filename();
429 $original->filepath = $file->get_filepath();
430 $newsourcefield->original = file_storage::pack_reference($original);
431 $draftfile->set_source(serialize($newsourcefield));
432 // End of file manager hack
435 if (!is_null($text)) {
436 // at this point there should not be any draftfile links yet,
437 // because this is a new text from database that should still contain the @@pluginfile@@ links
438 // this happens when developers forget to post process the text
439 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
441 } else {
442 // nothing to do
445 if (is_null($text)) {
446 return null;
449 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
450 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
454 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
455 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
456 * in the @@PLUGINFILE@@ form.
458 * @param string $text The content that may contain ULRs in need of rewriting.
459 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
460 * @param int $contextid This parameter and the next two identify the file area to use.
461 * @param string $component
462 * @param string $filearea helps identify the file area.
463 * @param int $itemid helps identify the file area.
464 * @param array $options
465 * bool $options.forcehttps Force the user of https
466 * bool $options.reverse Reverse the behaviour of the function
467 * bool $options.includetoken Use a token for authentication
468 * string The processed text.
470 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
471 global $CFG, $USER;
473 $options = (array)$options;
474 if (!isset($options['forcehttps'])) {
475 $options['forcehttps'] = false;
478 $baseurl = "{$CFG->wwwroot}/{$file}";
479 if (!empty($options['includetoken'])) {
480 $token = get_user_key('core_files', $USER->id);
481 $finalfile = basename($file);
482 $tokenfile = "token{$finalfile}";
483 $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
485 if (!$CFG->slasharguments) {
486 $baseurl .= "?token={$token}&file=";
487 } else {
488 $baseurl .= "/{$token}";
492 $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
494 if ($itemid !== null) {
495 $baseurl .= "$itemid/";
498 if ($options['forcehttps']) {
499 $baseurl = str_replace('http://', 'https://', $baseurl);
502 if (!empty($options['reverse'])) {
503 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
504 } else {
505 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
510 * Returns information about files in a draft area.
512 * @global stdClass $CFG
513 * @global stdClass $USER
514 * @param int $draftitemid the draft area item id.
515 * @param string $filepath path to the directory from which the information have to be retrieved.
516 * @return array with the following entries:
517 * 'filecount' => number of files in the draft area.
518 * 'filesize' => total size of the files in the draft area.
519 * 'foldercount' => number of folders in the draft area.
520 * 'filesize_without_references' => total size of the area excluding file references.
521 * (more information will be added as needed).
523 function file_get_draft_area_info($draftitemid, $filepath = '/') {
524 global $USER;
526 $usercontext = context_user::instance($USER->id);
527 return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
531 * Returns information about files in an area.
533 * @param int $contextid context id
534 * @param string $component component
535 * @param string $filearea file area name
536 * @param int $itemid item id or all files if not specified
537 * @param string $filepath path to the directory from which the information have to be retrieved.
538 * @return array with the following entries:
539 * 'filecount' => number of files in the area.
540 * 'filesize' => total size of the files in the area.
541 * 'foldercount' => number of folders in the area.
542 * 'filesize_without_references' => total size of the area excluding file references.
543 * @since Moodle 3.4
545 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
547 $fs = get_file_storage();
549 $results = array(
550 'filecount' => 0,
551 'foldercount' => 0,
552 'filesize' => 0,
553 'filesize_without_references' => 0
556 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
558 foreach ($draftfiles as $file) {
559 if ($file->is_directory()) {
560 $results['foldercount'] += 1;
561 } else {
562 $results['filecount'] += 1;
565 $filesize = $file->get_filesize();
566 $results['filesize'] += $filesize;
567 if (!$file->is_external_file()) {
568 $results['filesize_without_references'] += $filesize;
572 return $results;
576 * Returns whether a draft area has exceeded/will exceed its size limit.
578 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
580 * @param int $draftitemid the draft area item id.
581 * @param int $areamaxbytes the maximum size allowed in this draft area.
582 * @param int $newfilesize the size that would be added to the current area.
583 * @param bool $includereferences true to include the size of the references in the area size.
584 * @return bool true if the area will/has exceeded its limit.
585 * @since Moodle 2.4
587 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
588 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
589 $draftinfo = file_get_draft_area_info($draftitemid);
590 $areasize = $draftinfo['filesize_without_references'];
591 if ($includereferences) {
592 $areasize = $draftinfo['filesize'];
594 if ($areasize + $newfilesize > $areamaxbytes) {
595 return true;
598 return false;
602 * Get used space of files
603 * @global moodle_database $DB
604 * @global stdClass $USER
605 * @return int total bytes
607 function file_get_user_used_space() {
608 global $DB, $USER;
610 $usercontext = context_user::instance($USER->id);
611 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
612 JOIN (SELECT contenthash, filename, MAX(id) AS id
613 FROM {files}
614 WHERE contextid = ? AND component = ? AND filearea != ?
615 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
616 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
617 $record = $DB->get_record_sql($sql, $params);
618 return (int)$record->totalbytes;
622 * Convert any string to a valid filepath
623 * @todo review this function
624 * @param string $str
625 * @return string path
627 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
628 if ($str == '/' or empty($str)) {
629 return '/';
630 } else {
631 return '/'.trim($str, '/').'/';
636 * Generate a folder tree of draft area of current USER recursively
638 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
639 * @param int $draftitemid
640 * @param string $filepath
641 * @param mixed $data
643 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
644 global $USER, $OUTPUT, $CFG;
645 $data->children = array();
646 $context = context_user::instance($USER->id);
647 $fs = get_file_storage();
648 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
649 foreach ($files as $file) {
650 if ($file->is_directory()) {
651 $item = new stdClass();
652 $item->sortorder = $file->get_sortorder();
653 $item->filepath = $file->get_filepath();
655 $foldername = explode('/', trim($item->filepath, '/'));
656 $item->fullname = trim(array_pop($foldername), '/');
658 $item->id = uniqid();
659 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
660 $data->children[] = $item;
661 } else {
662 continue;
669 * Listing all files (including folders) in current path (draft area)
670 * used by file manager
671 * @param int $draftitemid
672 * @param string $filepath
673 * @return stdClass
675 function file_get_drafarea_files($draftitemid, $filepath = '/') {
676 global $USER, $OUTPUT, $CFG;
678 $context = context_user::instance($USER->id);
679 $fs = get_file_storage();
681 $data = new stdClass();
682 $data->path = array();
683 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
685 // will be used to build breadcrumb
686 $trail = '/';
687 if ($filepath !== '/') {
688 $filepath = file_correct_filepath($filepath);
689 $parts = explode('/', $filepath);
690 foreach ($parts as $part) {
691 if ($part != '' && $part != null) {
692 $trail .= ($part.'/');
693 $data->path[] = array('name'=>$part, 'path'=>$trail);
698 $list = array();
699 $maxlength = 12;
700 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
701 foreach ($files as $file) {
702 $item = new stdClass();
703 $item->filename = $file->get_filename();
704 $item->filepath = $file->get_filepath();
705 $item->fullname = trim($item->filename, '/');
706 $filesize = $file->get_filesize();
707 $item->size = $filesize ? $filesize : null;
708 $item->filesize = $filesize ? display_size($filesize) : '';
710 $item->sortorder = $file->get_sortorder();
711 $item->author = $file->get_author();
712 $item->license = $file->get_license();
713 $item->datemodified = $file->get_timemodified();
714 $item->datecreated = $file->get_timecreated();
715 $item->isref = $file->is_external_file();
716 if ($item->isref && $file->get_status() == 666) {
717 $item->originalmissing = true;
719 // find the file this draft file was created from and count all references in local
720 // system pointing to that file
721 $source = @unserialize($file->get_source());
722 if (isset($source->original)) {
723 $item->refcount = $fs->search_references_count($source->original);
726 if ($file->is_directory()) {
727 $item->filesize = 0;
728 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
729 $item->type = 'folder';
730 $foldername = explode('/', trim($item->filepath, '/'));
731 $item->fullname = trim(array_pop($foldername), '/');
732 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
733 } else {
734 // do NOT use file browser here!
735 $item->mimetype = get_mimetype_description($file);
736 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
737 $item->type = 'zip';
738 } else {
739 $item->type = 'file';
741 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
742 $item->url = $itemurl->out();
743 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
744 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
746 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
747 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
748 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
749 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
750 // used by the widget to display a warning about the problem files.
751 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
752 $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
753 if ($item->status == 0) {
754 if ($imageinfo = $file->get_imageinfo()) {
755 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
756 'oid' => $file->get_timemodified()));
757 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
758 $item->image_width = $imageinfo['width'];
759 $item->image_height = $imageinfo['height'];
763 $list[] = $item;
766 $data->itemid = $draftitemid;
767 $data->list = $list;
768 return $data;
772 * Returns all of the files in the draftarea.
774 * @param int $draftitemid The draft item ID
775 * @param string $filepath path for the uploaded files.
776 * @return array An array of files associated with this draft item id.
778 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
779 $files = [];
780 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
781 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
783 if (!empty($draftfiles)) {
784 foreach ($draftfiles->list as $draftfile) {
785 if ($draftfile->type == 'file') {
786 $files[] = $draftfile;
790 if (isset($draftfiles->children)) {
791 foreach ($draftfiles->children as $draftfile) {
792 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
796 return $files;
800 * Returns draft area itemid for a given element.
802 * @category files
803 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
804 * @return int the itemid, or 0 if there is not one yet.
806 function file_get_submitted_draft_itemid($elname) {
807 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
808 if (!isset($_REQUEST[$elname])) {
809 return 0;
811 if (is_array($_REQUEST[$elname])) {
812 $param = optional_param_array($elname, 0, PARAM_INT);
813 if (!empty($param['itemid'])) {
814 $param = $param['itemid'];
815 } else {
816 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
817 return false;
820 } else {
821 $param = optional_param($elname, 0, PARAM_INT);
824 if ($param) {
825 require_sesskey();
828 return $param;
832 * Restore the original source field from draft files
834 * Do not use this function because it makes field files.source inconsistent
835 * for draft area files. This function will be deprecated in 2.6
837 * @param stored_file $storedfile This only works with draft files
838 * @return stored_file
840 function file_restore_source_field_from_draft_file($storedfile) {
841 $source = @unserialize($storedfile->get_source());
842 if (!empty($source)) {
843 if (is_object($source)) {
844 $restoredsource = $source->source;
845 $storedfile->set_source($restoredsource);
846 } else {
847 throw new moodle_exception('invalidsourcefield', 'error');
850 return $storedfile;
854 * Removes those files from the user drafts filearea which are not referenced in the editor text.
856 * @param stdClass $editor The online text editor element from the submitted form data.
858 function file_remove_editor_orphaned_files($editor) {
859 global $CFG, $USER;
861 // Find those draft files included in the text, and generate their hashes.
862 $context = context_user::instance($USER->id);
863 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
864 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
865 preg_match_all($pattern, $editor['text'], $matches);
866 $usedfilehashes = [];
867 foreach ($matches[1] as $matchedfilename) {
868 $matchedfilename = urldecode($matchedfilename);
869 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
870 $matchedfilename);
873 // Now, compare the hashes of all draft files, and remove those which don't match used files.
874 $fs = get_file_storage();
875 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
876 foreach ($files as $file) {
877 $tmphash = $file->get_pathnamehash();
878 if (!in_array($tmphash, $usedfilehashes)) {
879 $file->delete();
885 * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
886 * content from another draft area it's possible for a single textarea to reference multiple draft areas.
888 * @category files
889 * @param int $draftitemid the id of the primary draft area.
890 * @param int $usercontextid the user's context id.
891 * @param string $text some html content that needs to have files copied to the correct draft area.
892 * @param bool $forcehttps force https urls.
894 * @return string $text html content modified with new draft links
896 function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
897 if (is_null($text)) {
898 return null;
901 $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
903 // No draft areas to rewrite.
904 if (empty($urls)) {
905 return $text;
908 foreach ($urls as $url) {
909 // Do not process the "home" draft area.
910 if ($url['itemid'] == $draftitemid) {
911 continue;
914 // Decode the filename.
915 $filename = urldecode($url['filename']);
917 // Copy the file.
918 file_copy_file_to_file_area($url, $filename, $draftitemid);
920 // Rewrite draft area.
921 $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
923 return $text;
927 * Rewrites a file area in arbitrary text.
929 * @param array $file General information about the file.
930 * @param int $newid The new file area itemid.
931 * @param string $text The text to rewrite.
932 * @param bool $forcehttps force https urls.
933 * @return string The rewritten text.
935 function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
936 global $CFG;
938 $wwwroot = $CFG->wwwroot;
939 if ($forcehttps) {
940 $wwwroot = str_replace('http://', 'https://', $wwwroot);
943 $search = [
944 $wwwroot,
945 $file['urlbase'],
946 $file['contextid'],
947 $file['component'],
948 $file['filearea'],
949 $file['itemid'],
950 $file['filename']
952 $replace = [
953 $wwwroot,
954 $file['urlbase'],
955 $file['contextid'],
956 $file['component'],
957 $file['filearea'],
958 $newid,
959 $file['filename']
962 $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
963 return $text;
967 * Copies a file from one file area to another.
969 * @param array $file Information about the file to be copied.
970 * @param string $filename The filename.
971 * @param int $itemid The new file area.
973 function file_copy_file_to_file_area($file, $filename, $itemid) {
974 $fs = get_file_storage();
976 // Load the current file in the old draft area.
977 $fileinfo = array(
978 'component' => $file['component'],
979 'filearea' => $file['filearea'],
980 'itemid' => $file['itemid'],
981 'contextid' => $file['contextid'],
982 'filepath' => '/',
983 'filename' => $filename
985 $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
986 $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
987 $newfileinfo = array(
988 'component' => $file['component'],
989 'filearea' => $file['filearea'],
990 'itemid' => $itemid,
991 'contextid' => $file['contextid'],
992 'filepath' => '/',
993 'filename' => $filename
996 $newcontextid = $newfileinfo['contextid'];
997 $newcomponent = $newfileinfo['component'];
998 $newfilearea = $newfileinfo['filearea'];
999 $newitemid = $newfileinfo['itemid'];
1000 $newfilepath = $newfileinfo['filepath'];
1001 $newfilename = $newfileinfo['filename'];
1003 // Check if the file exists.
1004 if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1005 $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1010 * Saves files from a draft file area to a real one (merging the list of files).
1011 * Can rewrite URLs in some content at the same time if desired.
1013 * @category files
1014 * @global stdClass $USER
1015 * @param int $draftitemid the id of the draft area to use. Normally obtained
1016 * from file_get_submitted_draft_itemid('elementname') or similar.
1017 * @param int $contextid This parameter and the next two identify the file area to save to.
1018 * @param string $component
1019 * @param string $filearea indentifies the file area.
1020 * @param int $itemid helps identifies the file area.
1021 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1022 * @param string $text some html content that needs to have embedded links rewritten
1023 * to the @@PLUGINFILE@@ form for saving in the database.
1024 * @param bool $forcehttps force https urls.
1025 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1027 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1028 global $USER;
1030 $usercontext = context_user::instance($USER->id);
1031 $fs = get_file_storage();
1033 $options = (array)$options;
1034 if (!isset($options['subdirs'])) {
1035 $options['subdirs'] = false;
1037 if (!isset($options['maxfiles'])) {
1038 $options['maxfiles'] = -1; // unlimited
1040 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
1041 $options['maxbytes'] = 0; // unlimited
1043 if (!isset($options['areamaxbytes'])) {
1044 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
1046 $allowreferences = true;
1047 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
1048 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1049 // this is not exactly right. BUT there are many places in code where filemanager options
1050 // are not passed to file_save_draft_area_files()
1051 $allowreferences = false;
1054 // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1055 // areas and need to be copied into the current draft area.
1056 $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
1058 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1059 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1060 // anything at all in the next area.
1061 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1062 return null;
1065 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
1066 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1068 // One file in filearea means it is empty (it has only top-level directory '.').
1069 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
1070 // we have to merge old and new files - we want to keep file ids for files that were not changed
1071 // we change time modified for all new and changed files, we keep time created as is
1073 $newhashes = array();
1074 $filecount = 0;
1075 $context = context::instance_by_id($contextid, MUST_EXIST);
1076 foreach ($draftfiles as $file) {
1077 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1078 continue;
1080 if (!$allowreferences && $file->is_external_file()) {
1081 continue;
1083 if (!$file->is_directory()) {
1084 // Check to see if this file was uploaded by someone who can ignore the file size limits.
1085 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1086 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1087 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1088 // Oversized file.
1089 continue;
1091 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1092 // more files - should not get here at all
1093 continue;
1095 $filecount++;
1097 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1098 $newhashes[$newhash] = $file;
1101 // Loop through oldfiles and decide which we need to delete and which to update.
1102 // After this cycle the array $newhashes will only contain the files that need to be added.
1103 foreach ($oldfiles as $oldfile) {
1104 $oldhash = $oldfile->get_pathnamehash();
1105 if (!isset($newhashes[$oldhash])) {
1106 // delete files not needed any more - deleted by user
1107 $oldfile->delete();
1108 continue;
1111 $newfile = $newhashes[$oldhash];
1112 // Now we know that we have $oldfile and $newfile for the same path.
1113 // Let's check if we can update this file or we need to delete and create.
1114 if ($newfile->is_directory()) {
1115 // Directories are always ok to just update.
1116 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
1117 // File has the 'original' - we need to update the file (it may even have not been changed at all).
1118 $original = file_storage::unpack_reference($source->original);
1119 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
1120 // Very odd, original points to another file. Delete and create file.
1121 $oldfile->delete();
1122 continue;
1124 } else {
1125 // The same file name but absence of 'original' means that file was deteled and uploaded again.
1126 // By deleting and creating new file we properly manage all existing references.
1127 $oldfile->delete();
1128 continue;
1131 // status changed, we delete old file, and create a new one
1132 if ($oldfile->get_status() != $newfile->get_status()) {
1133 // file was changed, use updated with new timemodified data
1134 $oldfile->delete();
1135 // This file will be added later
1136 continue;
1139 // Updated author
1140 if ($oldfile->get_author() != $newfile->get_author()) {
1141 $oldfile->set_author($newfile->get_author());
1143 // Updated license
1144 if ($oldfile->get_license() != $newfile->get_license()) {
1145 $oldfile->set_license($newfile->get_license());
1148 // Updated file source
1149 // Field files.source for draftarea files contains serialised object with source and original information.
1150 // We only store the source part of it for non-draft file area.
1151 $newsource = $newfile->get_source();
1152 if ($source = @unserialize($newfile->get_source())) {
1153 $newsource = $source->source;
1155 if ($oldfile->get_source() !== $newsource) {
1156 $oldfile->set_source($newsource);
1159 // Updated sort order
1160 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1161 $oldfile->set_sortorder($newfile->get_sortorder());
1164 // Update file timemodified
1165 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1166 $oldfile->set_timemodified($newfile->get_timemodified());
1169 // Replaced file content
1170 if (!$oldfile->is_directory() &&
1171 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1172 $oldfile->get_filesize() != $newfile->get_filesize() ||
1173 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1174 $oldfile->get_userid() != $newfile->get_userid())) {
1175 $oldfile->replace_file_with($newfile);
1178 // unchanged file or directory - we keep it as is
1179 unset($newhashes[$oldhash]);
1182 // Add fresh file or the file which has changed status
1183 // the size and subdirectory tests are extra safety only, the UI should prevent it
1184 foreach ($newhashes as $file) {
1185 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1186 if ($source = @unserialize($file->get_source())) {
1187 // Field files.source for draftarea files contains serialised object with source and original information.
1188 // We only store the source part of it for non-draft file area.
1189 $file_record['source'] = $source->source;
1192 if ($file->is_external_file()) {
1193 $repoid = $file->get_repository_id();
1194 if (!empty($repoid)) {
1195 $context = context::instance_by_id($contextid, MUST_EXIST);
1196 $repo = repository::get_repository_by_id($repoid, $context);
1197 if (!empty($options)) {
1198 $repo->options = $options;
1200 $file_record['repositoryid'] = $repoid;
1201 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1202 // to the file store. E.g. transfer ownership of the file to a system account etc.
1203 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1205 $file_record['reference'] = $reference;
1209 $fs->create_file_from_storedfile($file_record, $file);
1213 // note: do not purge the draft area - we clean up areas later in cron,
1214 // the reason is that user might press submit twice and they would loose the files,
1215 // also sometimes we might want to use hacks that save files into two different areas
1217 if (is_null($text)) {
1218 return null;
1219 } else {
1220 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1225 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1226 * ready to be saved in the database. Normally, this is done automatically by
1227 * {@link file_save_draft_area_files()}.
1229 * @category files
1230 * @param string $text the content to process.
1231 * @param int $draftitemid the draft file area the content was using.
1232 * @param bool $forcehttps whether the content contains https URLs. Default false.
1233 * @return string the processed content.
1235 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1236 global $CFG, $USER;
1238 $usercontext = context_user::instance($USER->id);
1240 $wwwroot = $CFG->wwwroot;
1241 if ($forcehttps) {
1242 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1245 // relink embedded files if text submitted - no absolute links allowed in database!
1246 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1248 if (strpos($text, 'draftfile.php?file=') !== false) {
1249 $matches = array();
1250 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1251 if ($matches) {
1252 foreach ($matches[0] as $match) {
1253 $replace = str_ireplace('%2F', '/', $match);
1254 $text = str_replace($match, $replace, $text);
1257 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1260 return $text;
1264 * Set file sort order
1266 * @global moodle_database $DB
1267 * @param int $contextid the context id
1268 * @param string $component file component
1269 * @param string $filearea file area.
1270 * @param int $itemid itemid.
1271 * @param string $filepath file path.
1272 * @param string $filename file name.
1273 * @param int $sortorder the sort order of file.
1274 * @return bool
1276 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1277 global $DB;
1278 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1279 if ($file_record = $DB->get_record('files', $conditions)) {
1280 $sortorder = (int)$sortorder;
1281 $file_record->sortorder = $sortorder;
1282 $DB->update_record('files', $file_record);
1283 return true;
1285 return false;
1289 * reset file sort order number to 0
1290 * @global moodle_database $DB
1291 * @param int $contextid the context id
1292 * @param string $component
1293 * @param string $filearea file area.
1294 * @param int|bool $itemid itemid.
1295 * @return bool
1297 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1298 global $DB;
1300 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1301 if ($itemid !== false) {
1302 $conditions['itemid'] = $itemid;
1305 $file_records = $DB->get_records('files', $conditions);
1306 foreach ($file_records as $file_record) {
1307 $file_record->sortorder = 0;
1308 $DB->update_record('files', $file_record);
1310 return true;
1314 * Returns description of upload error
1316 * @param int $errorcode found in $_FILES['filename.ext']['error']
1317 * @return string error description string, '' if ok
1319 function file_get_upload_error($errorcode) {
1321 switch ($errorcode) {
1322 case 0: // UPLOAD_ERR_OK - no error
1323 $errmessage = '';
1324 break;
1326 case 1: // UPLOAD_ERR_INI_SIZE
1327 $errmessage = get_string('uploadserverlimit');
1328 break;
1330 case 2: // UPLOAD_ERR_FORM_SIZE
1331 $errmessage = get_string('uploadformlimit');
1332 break;
1334 case 3: // UPLOAD_ERR_PARTIAL
1335 $errmessage = get_string('uploadpartialfile');
1336 break;
1338 case 4: // UPLOAD_ERR_NO_FILE
1339 $errmessage = get_string('uploadnofilefound');
1340 break;
1342 // Note: there is no error with a value of 5
1344 case 6: // UPLOAD_ERR_NO_TMP_DIR
1345 $errmessage = get_string('uploadnotempdir');
1346 break;
1348 case 7: // UPLOAD_ERR_CANT_WRITE
1349 $errmessage = get_string('uploadcantwrite');
1350 break;
1352 case 8: // UPLOAD_ERR_EXTENSION
1353 $errmessage = get_string('uploadextension');
1354 break;
1356 default:
1357 $errmessage = get_string('uploadproblem');
1360 return $errmessage;
1364 * Recursive function formating an array in POST parameter
1365 * @param array $arraydata - the array that we are going to format and add into &$data array
1366 * @param string $currentdata - a row of the final postdata array at instant T
1367 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1368 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1370 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1371 foreach ($arraydata as $k=>$v) {
1372 $newcurrentdata = $currentdata;
1373 if (is_array($v)) { //the value is an array, call the function recursively
1374 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1375 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1376 } else { //add the POST parameter to the $data array
1377 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1383 * Transform a PHP array into POST parameter
1384 * (see the recursive function format_array_postdata_for_curlcall)
1385 * @param array $postdata
1386 * @return array containing all POST parameters (1 row = 1 POST parameter)
1388 function format_postdata_for_curlcall($postdata) {
1389 $data = array();
1390 foreach ($postdata as $k=>$v) {
1391 if (is_array($v)) {
1392 $currentdata = urlencode($k);
1393 format_array_postdata_for_curlcall($v, $currentdata, $data);
1394 } else {
1395 $data[] = urlencode($k).'='.urlencode($v);
1398 $convertedpostdata = implode('&', $data);
1399 return $convertedpostdata;
1403 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1404 * Due to security concerns only downloads from http(s) sources are supported.
1406 * @category files
1407 * @param string $url file url starting with http(s)://
1408 * @param array $headers http headers, null if none. If set, should be an
1409 * associative array of header name => value pairs.
1410 * @param array $postdata array means use POST request with given parameters
1411 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1412 * (if false, just returns content)
1413 * @param int $timeout timeout for complete download process including all file transfer
1414 * (default 5 minutes)
1415 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1416 * usually happens if the remote server is completely down (default 20 seconds);
1417 * may not work when using proxy
1418 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1419 * Only use this when already in a trusted location.
1420 * @param string $tofile store the downloaded content to file instead of returning it.
1421 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1422 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1423 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1424 * if file downloaded into $tofile successfully or the file content as a string.
1426 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1427 global $CFG;
1429 // Only http and https links supported.
1430 if (!preg_match('|^https?://|i', $url)) {
1431 if ($fullresponse) {
1432 $response = new stdClass();
1433 $response->status = 0;
1434 $response->headers = array();
1435 $response->response_code = 'Invalid protocol specified in url';
1436 $response->results = '';
1437 $response->error = 'Invalid protocol specified in url';
1438 return $response;
1439 } else {
1440 return false;
1444 $options = array();
1446 $headers2 = array();
1447 if (is_array($headers)) {
1448 foreach ($headers as $key => $value) {
1449 if (is_numeric($key)) {
1450 $headers2[] = $value;
1451 } else {
1452 $headers2[] = "$key: $value";
1457 if ($skipcertverify) {
1458 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1459 } else {
1460 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1463 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1465 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1466 $options['CURLOPT_MAXREDIRS'] = 5;
1468 // Use POST if requested.
1469 if (is_array($postdata)) {
1470 $postdata = format_postdata_for_curlcall($postdata);
1471 } else if (empty($postdata)) {
1472 $postdata = null;
1475 // Optionally attempt to get more correct timeout by fetching the file size.
1476 if (!isset($CFG->curltimeoutkbitrate)) {
1477 // Use very slow rate of 56kbps as a timeout speed when not set.
1478 $bitrate = 56;
1479 } else {
1480 $bitrate = $CFG->curltimeoutkbitrate;
1482 if ($calctimeout and !isset($postdata)) {
1483 $curl = new curl();
1484 $curl->setHeader($headers2);
1486 $curl->head($url, $postdata, $options);
1488 $info = $curl->get_info();
1489 $error_no = $curl->get_errno();
1490 if (!$error_no && $info['download_content_length'] > 0) {
1491 // No curl errors - adjust for large files only - take max timeout.
1492 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1496 $curl = new curl();
1497 $curl->setHeader($headers2);
1499 $options['CURLOPT_RETURNTRANSFER'] = true;
1500 $options['CURLOPT_NOBODY'] = false;
1501 $options['CURLOPT_TIMEOUT'] = $timeout;
1503 if ($tofile) {
1504 $fh = fopen($tofile, 'w');
1505 if (!$fh) {
1506 if ($fullresponse) {
1507 $response = new stdClass();
1508 $response->status = 0;
1509 $response->headers = array();
1510 $response->response_code = 'Can not write to file';
1511 $response->results = false;
1512 $response->error = 'Can not write to file';
1513 return $response;
1514 } else {
1515 return false;
1518 $options['CURLOPT_FILE'] = $fh;
1521 if (isset($postdata)) {
1522 $content = $curl->post($url, $postdata, $options);
1523 } else {
1524 $content = $curl->get($url, null, $options);
1527 if ($tofile) {
1528 fclose($fh);
1529 @chmod($tofile, $CFG->filepermissions);
1533 // Try to detect encoding problems.
1534 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1535 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1536 $result = curl_exec($ch);
1540 $info = $curl->get_info();
1541 $error_no = $curl->get_errno();
1542 $rawheaders = $curl->get_raw_response();
1544 if ($error_no) {
1545 $error = $content;
1546 if (!$fullresponse) {
1547 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1548 return false;
1551 $response = new stdClass();
1552 if ($error_no == 28) {
1553 $response->status = '-100'; // Mimic snoopy.
1554 } else {
1555 $response->status = '0';
1557 $response->headers = array();
1558 $response->response_code = $error;
1559 $response->results = false;
1560 $response->error = $error;
1561 return $response;
1564 if ($tofile) {
1565 $content = true;
1568 if (empty($info['http_code'])) {
1569 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1570 $response = new stdClass();
1571 $response->status = '0';
1572 $response->headers = array();
1573 $response->response_code = 'Unknown cURL error';
1574 $response->results = false; // do NOT change this, we really want to ignore the result!
1575 $response->error = 'Unknown cURL error';
1577 } else {
1578 $response = new stdClass();
1579 $response->status = (string)$info['http_code'];
1580 $response->headers = $rawheaders;
1581 $response->results = $content;
1582 $response->error = '';
1584 // There might be multiple headers on redirect, find the status of the last one.
1585 $firstline = true;
1586 foreach ($rawheaders as $line) {
1587 if ($firstline) {
1588 $response->response_code = $line;
1589 $firstline = false;
1591 if (trim($line, "\r\n") === '') {
1592 $firstline = true;
1597 if ($fullresponse) {
1598 return $response;
1601 if ($info['http_code'] != 200) {
1602 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1603 return false;
1605 return $response->results;
1609 * Returns a list of information about file types based on extensions.
1611 * The following elements expected in value array for each extension:
1612 * 'type' - mimetype
1613 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1614 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1615 * also files with bigger sizes under names
1616 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1617 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1618 * commonly used in moodle the following groups:
1619 * - web_image - image that can be included as <img> in HTML
1620 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1621 * - video - file that can be imported as video in text editor
1622 * - audio - file that can be imported as audio in text editor
1623 * - archive - we can extract files from this archive
1624 * - spreadsheet - used for portfolio format
1625 * - document - used for portfolio format
1626 * - presentation - used for portfolio format
1627 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1628 * human-readable description for this filetype;
1629 * Function {@link get_mimetype_description()} first looks at the presence of string for
1630 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1631 * attribute, if not found returns the value of 'type';
1632 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1633 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1634 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1636 * @category files
1637 * @return array List of information about file types based on extensions.
1638 * Associative array of extension (lower-case) to associative array
1639 * from 'element name' to data. Current element names are 'type' and 'icon'.
1640 * Unknown types should use the 'xxx' entry which includes defaults.
1642 function &get_mimetypes_array() {
1643 // Get types from the core_filetypes function, which includes caching.
1644 return core_filetypes::get_types();
1648 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1650 * This function retrieves a file's MIME type for a file that will be sent to the user.
1651 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1652 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1653 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1655 * @param string $filename The file's filename.
1656 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1658 function get_mimetype_for_sending($filename = '') {
1659 // Guess the file's MIME type using mimeinfo.
1660 $mimetype = mimeinfo('type', $filename);
1662 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1663 if (!$mimetype || $mimetype === 'document/unknown') {
1664 $mimetype = 'application/octet-stream';
1667 return $mimetype;
1671 * Obtains information about a filetype based on its extension. Will
1672 * use a default if no information is present about that particular
1673 * extension.
1675 * @category files
1676 * @param string $element Desired information (usually 'icon'
1677 * for icon filename or 'type' for MIME type. Can also be
1678 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1679 * @param string $filename Filename we're looking up
1680 * @return string Requested piece of information from array
1682 function mimeinfo($element, $filename) {
1683 global $CFG;
1684 $mimeinfo = & get_mimetypes_array();
1685 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1687 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1688 if (empty($filetype)) {
1689 $filetype = 'xxx'; // file without extension
1691 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1692 $iconsize = max(array(16, (int)$iconsizematch[1]));
1693 $filenames = array($mimeinfo['xxx']['icon']);
1694 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1695 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1697 // find the file with the closest size, first search for specific icon then for default icon
1698 foreach ($filenames as $filename) {
1699 foreach ($iconpostfixes as $size => $postfix) {
1700 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1701 if ($iconsize >= $size &&
1702 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1703 return $filename.$postfix;
1707 } else if (isset($mimeinfo[$filetype][$element])) {
1708 return $mimeinfo[$filetype][$element];
1709 } else if (isset($mimeinfo['xxx'][$element])) {
1710 return $mimeinfo['xxx'][$element]; // By default
1711 } else {
1712 return null;
1717 * Obtains information about a filetype based on the MIME type rather than
1718 * the other way around.
1720 * @category files
1721 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1722 * @param string $mimetype MIME type we're looking up
1723 * @return string Requested piece of information from array
1725 function mimeinfo_from_type($element, $mimetype) {
1726 /* array of cached mimetype->extension associations */
1727 static $cached = array();
1728 $mimeinfo = & get_mimetypes_array();
1730 if (!array_key_exists($mimetype, $cached)) {
1731 $cached[$mimetype] = null;
1732 foreach($mimeinfo as $filetype => $values) {
1733 if ($values['type'] == $mimetype) {
1734 if ($cached[$mimetype] === null) {
1735 $cached[$mimetype] = '.'.$filetype;
1737 if (!empty($values['defaulticon'])) {
1738 $cached[$mimetype] = '.'.$filetype;
1739 break;
1743 if (empty($cached[$mimetype])) {
1744 $cached[$mimetype] = '.xxx';
1747 if ($element === 'extension') {
1748 return $cached[$mimetype];
1749 } else {
1750 return mimeinfo($element, $cached[$mimetype]);
1755 * Return the relative icon path for a given file
1757 * Usage:
1758 * <code>
1759 * // $file - instance of stored_file or file_info
1760 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1761 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1762 * </code>
1763 * or
1764 * <code>
1765 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1766 * </code>
1768 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1769 * and $file->mimetype are expected)
1770 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1771 * @return string
1773 function file_file_icon($file, $size = null) {
1774 if (!is_object($file)) {
1775 $file = (object)$file;
1777 if (isset($file->filename)) {
1778 $filename = $file->filename;
1779 } else if (method_exists($file, 'get_filename')) {
1780 $filename = $file->get_filename();
1781 } else if (method_exists($file, 'get_visible_name')) {
1782 $filename = $file->get_visible_name();
1783 } else {
1784 $filename = '';
1786 if (isset($file->mimetype)) {
1787 $mimetype = $file->mimetype;
1788 } else if (method_exists($file, 'get_mimetype')) {
1789 $mimetype = $file->get_mimetype();
1790 } else {
1791 $mimetype = '';
1793 $mimetypes = &get_mimetypes_array();
1794 if ($filename) {
1795 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1796 if ($extension && !empty($mimetypes[$extension])) {
1797 // if file name has known extension, return icon for this extension
1798 return file_extension_icon($filename, $size);
1801 return file_mimetype_icon($mimetype, $size);
1805 * Return the relative icon path for a folder image
1807 * Usage:
1808 * <code>
1809 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1810 * echo html_writer::empty_tag('img', array('src' => $icon));
1811 * </code>
1812 * or
1813 * <code>
1814 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1815 * </code>
1817 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1818 * @return string
1820 function file_folder_icon($iconsize = null) {
1821 global $CFG;
1822 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1823 static $cached = array();
1824 $iconsize = max(array(16, (int)$iconsize));
1825 if (!array_key_exists($iconsize, $cached)) {
1826 foreach ($iconpostfixes as $size => $postfix) {
1827 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1828 if ($iconsize >= $size &&
1829 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1830 $cached[$iconsize] = 'f/folder'.$postfix;
1831 break;
1835 return $cached[$iconsize];
1839 * Returns the relative icon path for a given mime type
1841 * This function should be used in conjunction with $OUTPUT->image_url to produce
1842 * a return the full path to an icon.
1844 * <code>
1845 * $mimetype = 'image/jpg';
1846 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1847 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1848 * </code>
1850 * @category files
1851 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1852 * to conform with that.
1853 * @param string $mimetype The mimetype to fetch an icon for
1854 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1855 * @return string The relative path to the icon
1857 function file_mimetype_icon($mimetype, $size = NULL) {
1858 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1862 * Returns the relative icon path for a given file name
1864 * This function should be used in conjunction with $OUTPUT->image_url to produce
1865 * a return the full path to an icon.
1867 * <code>
1868 * $filename = '.jpg';
1869 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1870 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1871 * </code>
1873 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1874 * to conform with that.
1875 * @todo MDL-31074 Implement $size
1876 * @category files
1877 * @param string $filename The filename to get the icon for
1878 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1879 * @return string
1881 function file_extension_icon($filename, $size = NULL) {
1882 return 'f/'.mimeinfo('icon'.$size, $filename);
1886 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1887 * mimetypes.php language file.
1889 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1890 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1891 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1892 * @param bool $capitalise If true, capitalises first character of result
1893 * @return string Text description
1895 function get_mimetype_description($obj, $capitalise=false) {
1896 $filename = $mimetype = '';
1897 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1898 // this is an instance of stored_file
1899 $mimetype = $obj->get_mimetype();
1900 $filename = $obj->get_filename();
1901 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1902 // this is an instance of file_info
1903 $mimetype = $obj->get_mimetype();
1904 $filename = $obj->get_visible_name();
1905 } else if (is_array($obj) || is_object ($obj)) {
1906 $obj = (array)$obj;
1907 if (!empty($obj['filename'])) {
1908 $filename = $obj['filename'];
1910 if (!empty($obj['mimetype'])) {
1911 $mimetype = $obj['mimetype'];
1913 } else {
1914 $mimetype = $obj;
1916 $mimetypefromext = mimeinfo('type', $filename);
1917 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1918 // if file has a known extension, overwrite the specified mimetype
1919 $mimetype = $mimetypefromext;
1921 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1922 if (empty($extension)) {
1923 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1924 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1925 } else {
1926 $mimetypestr = mimeinfo('string', $filename);
1928 $chunks = explode('/', $mimetype, 2);
1929 $chunks[] = '';
1930 $attr = array(
1931 'mimetype' => $mimetype,
1932 'ext' => $extension,
1933 'mimetype1' => $chunks[0],
1934 'mimetype2' => $chunks[1],
1936 $a = array();
1937 foreach ($attr as $key => $value) {
1938 $a[$key] = $value;
1939 $a[strtoupper($key)] = strtoupper($value);
1940 $a[ucfirst($key)] = ucfirst($value);
1943 // MIME types may include + symbol but this is not permitted in string ids.
1944 $safemimetype = str_replace('+', '_', $mimetype);
1945 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1946 $customdescription = mimeinfo('customdescription', $filename);
1947 if ($customdescription) {
1948 // Call format_string on the custom description so that multilang
1949 // filter can be used (if enabled on system context). We use system
1950 // context because it is possible that the page context might not have
1951 // been defined yet.
1952 $result = format_string($customdescription, true,
1953 array('context' => context_system::instance()));
1954 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1955 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1956 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1957 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1958 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1959 $result = get_string('default', 'mimetypes', (object)$a);
1960 } else {
1961 $result = $mimetype;
1963 if ($capitalise) {
1964 $result=ucfirst($result);
1966 return $result;
1970 * Returns array of elements of type $element in type group(s)
1972 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1973 * @param string|array $groups one group or array of groups/extensions/mimetypes
1974 * @return array
1976 function file_get_typegroup($element, $groups) {
1977 static $cached = array();
1978 if (!is_array($groups)) {
1979 $groups = array($groups);
1981 if (!array_key_exists($element, $cached)) {
1982 $cached[$element] = array();
1984 $result = array();
1985 foreach ($groups as $group) {
1986 if (!array_key_exists($group, $cached[$element])) {
1987 // retrieive and cache all elements of type $element for group $group
1988 $mimeinfo = & get_mimetypes_array();
1989 $cached[$element][$group] = array();
1990 foreach ($mimeinfo as $extension => $value) {
1991 $value['extension'] = '.'.$extension;
1992 if (empty($value[$element])) {
1993 continue;
1995 if (($group === '.'.$extension || $group === $value['type'] ||
1996 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1997 !in_array($value[$element], $cached[$element][$group])) {
1998 $cached[$element][$group][] = $value[$element];
2002 $result = array_merge($result, $cached[$element][$group]);
2004 return array_values(array_unique($result));
2008 * Checks if file with name $filename has one of the extensions in groups $groups
2010 * @see get_mimetypes_array()
2011 * @param string $filename name of the file to check
2012 * @param string|array $groups one group or array of groups to check
2013 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2014 * file mimetype is in mimetypes in groups $groups
2015 * @return bool
2017 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2018 $extension = pathinfo($filename, PATHINFO_EXTENSION);
2019 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2020 return true;
2022 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2026 * Checks if mimetype $mimetype belongs to one of the groups $groups
2028 * @see get_mimetypes_array()
2029 * @param string $mimetype
2030 * @param string|array $groups one group or array of groups to check
2031 * @return bool
2033 function file_mimetype_in_typegroup($mimetype, $groups) {
2034 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2038 * Requested file is not found or not accessible, does not return, terminates script
2040 * @global stdClass $CFG
2041 * @global stdClass $COURSE
2043 function send_file_not_found() {
2044 global $CFG, $COURSE;
2046 // Allow cross-origin requests only for Web Services.
2047 // This allow to receive requests done by Web Workers or webapps in different domains.
2048 if (WS_SERVER) {
2049 header('Access-Control-Allow-Origin: *');
2052 send_header_404();
2053 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
2056 * Helper function to send correct 404 for server.
2058 function send_header_404() {
2059 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2060 header("Status: 404 Not Found");
2061 } else {
2062 header('HTTP/1.0 404 not found');
2067 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2068 * platforms). This wrapper uses readfile for small files and custom code for
2069 * large ones.
2071 * @param string $path Path to file
2072 * @param int $filesize Size of file (if left out, will get it automatically)
2073 * @return int|bool Size read (will always be $filesize) or false if failed
2075 function readfile_allow_large($path, $filesize = -1) {
2076 // Automatically get size if not specified.
2077 if ($filesize === -1) {
2078 $filesize = filesize($path);
2080 if ($filesize <= 2147483647) {
2081 // If the file is up to 2^31 - 1, send it normally using readfile.
2082 return readfile($path);
2083 } else {
2084 // For large files, read and output in 64KB chunks.
2085 $handle = fopen($path, 'r');
2086 if ($handle === false) {
2087 return false;
2089 $left = $filesize;
2090 while ($left > 0) {
2091 $size = min($left, 65536);
2092 $buffer = fread($handle, $size);
2093 if ($buffer === false) {
2094 return false;
2096 echo $buffer;
2097 $left -= $size;
2099 return $filesize;
2104 * Enhanced readfile() with optional acceleration.
2105 * @param string|stored_file $file
2106 * @param string $mimetype
2107 * @param bool $accelerate
2108 * @return void
2110 function readfile_accel($file, $mimetype, $accelerate) {
2111 global $CFG;
2113 if ($mimetype === 'text/plain') {
2114 // there is no encoding specified in text files, we need something consistent
2115 header('Content-Type: text/plain; charset=utf-8');
2116 } else {
2117 header('Content-Type: '.$mimetype);
2120 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2121 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2123 if (is_object($file)) {
2124 header('Etag: "' . $file->get_contenthash() . '"');
2125 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2126 header('HTTP/1.1 304 Not Modified');
2127 return;
2131 // if etag present for stored file rely on it exclusively
2132 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2133 // get unixtime of request header; clip extra junk off first
2134 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2135 if ($since && $since >= $lastmodified) {
2136 header('HTTP/1.1 304 Not Modified');
2137 return;
2141 if ($accelerate and !empty($CFG->xsendfile)) {
2142 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2143 header('Accept-Ranges: bytes');
2144 } else {
2145 header('Accept-Ranges: none');
2148 if (is_object($file)) {
2149 $fs = get_file_storage();
2150 if ($fs->xsendfile($file->get_contenthash())) {
2151 return;
2154 } else {
2155 require_once("$CFG->libdir/xsendfilelib.php");
2156 if (xsendfile($file)) {
2157 return;
2162 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2164 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2166 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2167 header('Accept-Ranges: bytes');
2169 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2170 // byteserving stuff - for acrobat reader and download accelerators
2171 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2172 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2173 $ranges = false;
2174 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2175 foreach ($ranges as $key=>$value) {
2176 if ($ranges[$key][1] == '') {
2177 //suffix case
2178 $ranges[$key][1] = $filesize - $ranges[$key][2];
2179 $ranges[$key][2] = $filesize - 1;
2180 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2181 //fix range length
2182 $ranges[$key][2] = $filesize - 1;
2184 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2185 //invalid byte-range ==> ignore header
2186 $ranges = false;
2187 break;
2189 //prepare multipart header
2190 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2191 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2193 } else {
2194 $ranges = false;
2196 if ($ranges) {
2197 if (is_object($file)) {
2198 $handle = $file->get_content_file_handle();
2199 } else {
2200 $handle = fopen($file, 'rb');
2202 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2205 } else {
2206 // Do not byteserve
2207 header('Accept-Ranges: none');
2210 header('Content-Length: '.$filesize);
2212 if ($filesize > 10000000) {
2213 // for large files try to flush and close all buffers to conserve memory
2214 while(@ob_get_level()) {
2215 if (!@ob_end_flush()) {
2216 break;
2221 // send the whole file content
2222 if (is_object($file)) {
2223 $file->readfile();
2224 } else {
2225 readfile_allow_large($file, $filesize);
2230 * Similar to readfile_accel() but designed for strings.
2231 * @param string $string
2232 * @param string $mimetype
2233 * @param bool $accelerate
2234 * @return void
2236 function readstring_accel($string, $mimetype, $accelerate) {
2237 global $CFG;
2239 if ($mimetype === 'text/plain') {
2240 // there is no encoding specified in text files, we need something consistent
2241 header('Content-Type: text/plain; charset=utf-8');
2242 } else {
2243 header('Content-Type: '.$mimetype);
2245 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2246 header('Accept-Ranges: none');
2248 if ($accelerate and !empty($CFG->xsendfile)) {
2249 $fs = get_file_storage();
2250 if ($fs->xsendfile(sha1($string))) {
2251 return;
2255 header('Content-Length: '.strlen($string));
2256 echo $string;
2260 * Handles the sending of temporary file to user, download is forced.
2261 * File is deleted after abort or successful sending, does not return, script terminated
2263 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2264 * @param string $filename proposed file name when saving file
2265 * @param bool $pathisstring If the path is string
2267 function send_temp_file($path, $filename, $pathisstring=false) {
2268 global $CFG;
2270 // Guess the file's MIME type.
2271 $mimetype = get_mimetype_for_sending($filename);
2273 // close session - not needed anymore
2274 \core\session\manager::write_close();
2276 if (!$pathisstring) {
2277 if (!file_exists($path)) {
2278 send_header_404();
2279 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2281 // executed after normal finish or abort
2282 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2285 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2286 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2287 $filename = urlencode($filename);
2290 header('Content-Disposition: attachment; filename="'.$filename.'"');
2291 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2292 header('Cache-Control: private, max-age=10, no-transform');
2293 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2294 header('Pragma: ');
2295 } else { //normal http - prevent caching at all cost
2296 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2297 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2298 header('Pragma: no-cache');
2301 // send the contents - we can not accelerate this because the file will be deleted asap
2302 if ($pathisstring) {
2303 readstring_accel($path, $mimetype, false);
2304 } else {
2305 readfile_accel($path, $mimetype, false);
2306 @unlink($path);
2309 die; //no more chars to output
2313 * Internal callback function used by send_temp_file()
2315 * @param string $path
2317 function send_temp_file_finished($path) {
2318 if (file_exists($path)) {
2319 @unlink($path);
2324 * Serve content which is not meant to be cached.
2326 * This is only intended to be used for volatile public files, for instance
2327 * when development is enabled, or when caching is not required on a public resource.
2329 * @param string $content Raw content.
2330 * @param string $filename The file name.
2331 * @return void
2333 function send_content_uncached($content, $filename) {
2334 $mimetype = mimeinfo('type', $filename);
2335 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2337 header('Content-Disposition: inline; filename="' . $filename . '"');
2338 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2339 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2340 header('Pragma: ');
2341 header('Accept-Ranges: none');
2342 header('Content-Type: ' . $mimetype . $charset);
2343 header('Content-Length: ' . strlen($content));
2345 echo $content;
2346 die();
2350 * Safely save content to a certain path.
2352 * This function tries hard to be atomic by first copying the content
2353 * to a separate file, and then moving the file across. It also prevents
2354 * the user to abort a request to prevent half-safed files.
2356 * This function is intended to be used when saving some content to cache like
2357 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2359 * @param string $content The file content.
2360 * @param string $destination The absolute path of the final file.
2361 * @return void
2363 function file_safe_save_content($content, $destination) {
2364 global $CFG;
2366 clearstatcache();
2367 if (!file_exists(dirname($destination))) {
2368 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2371 // Prevent serving of incomplete file from concurrent request,
2372 // the rename() should be more atomic than fwrite().
2373 ignore_user_abort(true);
2374 if ($fp = fopen($destination . '.tmp', 'xb')) {
2375 fwrite($fp, $content);
2376 fclose($fp);
2377 rename($destination . '.tmp', $destination);
2378 @chmod($destination, $CFG->filepermissions);
2379 @unlink($destination . '.tmp'); // Just in case anything fails.
2381 ignore_user_abort(false);
2382 if (connection_aborted()) {
2383 die();
2388 * Handles the sending of file data to the user's browser, including support for
2389 * byteranges etc.
2391 * @category files
2392 * @param string|stored_file $path Path of file on disk (including real filename),
2393 * or actual content of file as string,
2394 * or stored_file object
2395 * @param string $filename Filename to send
2396 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2397 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2398 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2399 * Forced to false when $path is a stored_file object.
2400 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2401 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2402 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2403 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2404 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2405 * and should not be reopened.
2406 * @param array $options An array of options, currently accepts:
2407 * - (string) cacheability: public, or private.
2408 * - (string|null) immutable
2409 * @return null script execution stopped unless $dontdie is true
2411 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2412 $dontdie=false, array $options = array()) {
2413 global $CFG, $COURSE;
2415 if ($dontdie) {
2416 ignore_user_abort(true);
2419 if ($lifetime === 'default' or is_null($lifetime)) {
2420 $lifetime = $CFG->filelifetime;
2423 if (is_object($path)) {
2424 $pathisstring = false;
2427 \core\session\manager::write_close(); // Unlock session during file serving.
2429 // Use given MIME type if specified, otherwise guess it.
2430 if (!$mimetype || $mimetype === 'document/unknown') {
2431 $mimetype = get_mimetype_for_sending($filename);
2434 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2435 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2436 $filename = rawurlencode($filename);
2439 if ($forcedownload) {
2440 header('Content-Disposition: attachment; filename="'.$filename.'"');
2441 } else if ($mimetype !== 'application/x-shockwave-flash') {
2442 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2443 // as an upload and enforces security that may prevent the file from being loaded.
2445 header('Content-Disposition: inline; filename="'.$filename.'"');
2448 if ($lifetime > 0) {
2449 $immutable = '';
2450 if (!empty($options['immutable'])) {
2451 $immutable = ', immutable';
2452 // Overwrite lifetime accordingly:
2453 // 90 days only - based on Moodle point release cadence being every 3 months.
2454 $lifetimemin = 60 * 60 * 24 * 90;
2455 $lifetime = max($lifetime, $lifetimemin);
2457 $cacheability = ' public,';
2458 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2459 // This file must be cache-able by both browsers and proxies.
2460 $cacheability = ' public,';
2461 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2462 // This file must be cache-able only by browsers.
2463 $cacheability = ' private,';
2464 } else if (isloggedin() and !isguestuser()) {
2465 // By default, under the conditions above, this file must be cache-able only by browsers.
2466 $cacheability = ' private,';
2468 $nobyteserving = false;
2469 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2470 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2471 header('Pragma: ');
2473 } else { // Do not cache files in proxies and browsers
2474 $nobyteserving = true;
2475 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2476 header('Cache-Control: private, max-age=10, no-transform');
2477 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2478 header('Pragma: ');
2479 } else { //normal http - prevent caching at all cost
2480 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2481 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2482 header('Pragma: no-cache');
2486 if (empty($filter)) {
2487 // send the contents
2488 if ($pathisstring) {
2489 readstring_accel($path, $mimetype, !$dontdie);
2490 } else {
2491 readfile_accel($path, $mimetype, !$dontdie);
2494 } else {
2495 // Try to put the file through filters
2496 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2497 $options = new stdClass();
2498 $options->noclean = true;
2499 $options->nocache = true; // temporary workaround for MDL-5136
2500 if (is_object($path)) {
2501 $text = $path->get_content();
2502 } else if ($pathisstring) {
2503 $text = $path;
2504 } else {
2505 $text = implode('', file($path));
2507 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2509 readstring_accel($output, $mimetype, false);
2511 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2512 // only filter text if filter all files is selected
2513 $options = new stdClass();
2514 $options->newlines = false;
2515 $options->noclean = true;
2516 if (is_object($path)) {
2517 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2518 } else if ($pathisstring) {
2519 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2520 } else {
2521 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2523 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2525 readstring_accel($output, $mimetype, false);
2527 } else {
2528 // send the contents
2529 if ($pathisstring) {
2530 readstring_accel($path, $mimetype, !$dontdie);
2531 } else {
2532 readfile_accel($path, $mimetype, !$dontdie);
2536 if ($dontdie) {
2537 return;
2539 die; //no more chars to output!!!
2543 * Handles the sending of file data to the user's browser, including support for
2544 * byteranges etc.
2546 * The $options parameter supports the following keys:
2547 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2548 * (string|null) filename - overrides the implicit filename
2549 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2550 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2551 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2552 * and should not be reopened
2553 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2554 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2555 * defaults to "public".
2556 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2557 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2559 * @category files
2560 * @param stored_file $stored_file local file object
2561 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2562 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2563 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2564 * @param array $options additional options affecting the file serving
2565 * @return null script execution stopped unless $options['dontdie'] is true
2567 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2568 global $CFG, $COURSE;
2570 if (empty($options['filename'])) {
2571 $filename = null;
2572 } else {
2573 $filename = $options['filename'];
2576 if (empty($options['dontdie'])) {
2577 $dontdie = false;
2578 } else {
2579 $dontdie = true;
2582 if ($lifetime === 'default' or is_null($lifetime)) {
2583 $lifetime = $CFG->filelifetime;
2586 if (!empty($options['preview'])) {
2587 // replace the file with its preview
2588 $fs = get_file_storage();
2589 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2590 if (!$preview_file) {
2591 // unable to create a preview of the file, send its default mime icon instead
2592 if ($options['preview'] === 'tinyicon') {
2593 $size = 24;
2594 } else if ($options['preview'] === 'thumb') {
2595 $size = 90;
2596 } else {
2597 $size = 256;
2599 $fileicon = file_file_icon($stored_file, $size);
2600 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2601 } else {
2602 // preview images have fixed cache lifetime and they ignore forced download
2603 // (they are generated by GD and therefore they are considered reasonably safe).
2604 $stored_file = $preview_file;
2605 $lifetime = DAYSECS;
2606 $filter = 0;
2607 $forcedownload = false;
2611 // handle external resource
2612 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2613 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2614 die;
2617 if (!$stored_file or $stored_file->is_directory()) {
2618 // nothing to serve
2619 if ($dontdie) {
2620 return;
2622 die;
2625 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2627 // Use given MIME type if specified.
2628 $mimetype = $stored_file->get_mimetype();
2630 // Allow cross-origin requests only for Web Services.
2631 // This allow to receive requests done by Web Workers or webapps in different domains.
2632 if (WS_SERVER) {
2633 header('Access-Control-Allow-Origin: *');
2636 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2640 * Recursively delete the file or folder with path $location. That is,
2641 * if it is a file delete it. If it is a folder, delete all its content
2642 * then delete it. If $location does not exist to start, that is not
2643 * considered an error.
2645 * @param string $location the path to remove.
2646 * @return bool
2648 function fulldelete($location) {
2649 if (empty($location)) {
2650 // extra safety against wrong param
2651 return false;
2653 if (is_dir($location)) {
2654 if (!$currdir = opendir($location)) {
2655 return false;
2657 while (false !== ($file = readdir($currdir))) {
2658 if ($file <> ".." && $file <> ".") {
2659 $fullfile = $location."/".$file;
2660 if (is_dir($fullfile)) {
2661 if (!fulldelete($fullfile)) {
2662 return false;
2664 } else {
2665 if (!unlink($fullfile)) {
2666 return false;
2671 closedir($currdir);
2672 if (! rmdir($location)) {
2673 return false;
2676 } else if (file_exists($location)) {
2677 if (!unlink($location)) {
2678 return false;
2681 return true;
2685 * Send requested byterange of file.
2687 * @param resource $handle A file handle
2688 * @param string $mimetype The mimetype for the output
2689 * @param array $ranges An array of ranges to send
2690 * @param string $filesize The size of the content if only one range is used
2692 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2693 // better turn off any kind of compression and buffering
2694 ini_set('zlib.output_compression', 'Off');
2696 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2697 if ($handle === false) {
2698 die;
2700 if (count($ranges) == 1) { //only one range requested
2701 $length = $ranges[0][2] - $ranges[0][1] + 1;
2702 header('HTTP/1.1 206 Partial content');
2703 header('Content-Length: '.$length);
2704 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2705 header('Content-Type: '.$mimetype);
2707 while(@ob_get_level()) {
2708 if (!@ob_end_flush()) {
2709 break;
2713 fseek($handle, $ranges[0][1]);
2714 while (!feof($handle) && $length > 0) {
2715 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2716 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2717 echo $buffer;
2718 flush();
2719 $length -= strlen($buffer);
2721 fclose($handle);
2722 die;
2723 } else { // multiple ranges requested - not tested much
2724 $totallength = 0;
2725 foreach($ranges as $range) {
2726 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2728 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2729 header('HTTP/1.1 206 Partial content');
2730 header('Content-Length: '.$totallength);
2731 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2733 while(@ob_get_level()) {
2734 if (!@ob_end_flush()) {
2735 break;
2739 foreach($ranges as $range) {
2740 $length = $range[2] - $range[1] + 1;
2741 echo $range[0];
2742 fseek($handle, $range[1]);
2743 while (!feof($handle) && $length > 0) {
2744 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2745 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2746 echo $buffer;
2747 flush();
2748 $length -= strlen($buffer);
2751 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2752 fclose($handle);
2753 die;
2758 * Tells whether the filename is executable.
2760 * @link http://php.net/manual/en/function.is-executable.php
2761 * @link https://bugs.php.net/bug.php?id=41062
2762 * @param string $filename Path to the file.
2763 * @return bool True if the filename exists and is executable; otherwise, false.
2765 function file_is_executable($filename) {
2766 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2767 if (is_executable($filename)) {
2768 return true;
2769 } else {
2770 $fileext = strrchr($filename, '.');
2771 // If we have an extension we can check if it is listed as executable.
2772 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2773 $winpathext = strtolower(getenv('PATHEXT'));
2774 $winpathexts = explode(';', $winpathext);
2776 return in_array(strtolower($fileext), $winpathexts);
2779 return false;
2781 } else {
2782 return is_executable($filename);
2787 * Overwrite an existing file in a draft area.
2789 * @param stored_file $newfile the new file with the new content and meta-data
2790 * @param stored_file $existingfile the file that will be overwritten
2791 * @throws moodle_exception
2792 * @since Moodle 3.2
2794 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2795 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2796 throw new coding_exception('The file to overwrite is not in a draft area.');
2799 $fs = get_file_storage();
2800 // Remember original file source field.
2801 $source = @unserialize($existingfile->get_source());
2802 // Remember the original sortorder.
2803 $sortorder = $existingfile->get_sortorder();
2804 if ($newfile->is_external_file()) {
2805 // New file is a reference. Check that existing file does not have any other files referencing to it
2806 if (isset($source->original) && $fs->search_references_count($source->original)) {
2807 throw new moodle_exception('errordoublereference', 'repository');
2811 // Delete existing file to release filename.
2812 $newfilerecord = array(
2813 'contextid' => $existingfile->get_contextid(),
2814 'component' => 'user',
2815 'filearea' => 'draft',
2816 'itemid' => $existingfile->get_itemid(),
2817 'timemodified' => time()
2819 $existingfile->delete();
2821 // Create new file.
2822 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2823 // Preserve original file location (stored in source field) for handling references.
2824 if (isset($source->original)) {
2825 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2826 $newfilesource = new stdClass();
2828 $newfilesource->original = $source->original;
2829 $newfile->set_source(serialize($newfilesource));
2831 $newfile->set_sortorder($sortorder);
2835 * Add files from a draft area into a final area.
2837 * Most of the time you do not want to use this. It is intended to be used
2838 * by asynchronous services which cannot direcly manipulate a final
2839 * area through a draft area. Instead they add files to a new draft
2840 * area and merge that new draft into the final area when ready.
2842 * @param int $draftitemid the id of the draft area to use.
2843 * @param int $contextid this parameter and the next two identify the file area to save to.
2844 * @param string $component component name
2845 * @param string $filearea indentifies the file area
2846 * @param int $itemid identifies the item id or false for all items in the file area
2847 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2848 * @see file_save_draft_area_files
2849 * @since Moodle 3.2
2851 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2852 array $options = null) {
2853 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2854 $finaldraftid = 0;
2855 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2856 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2857 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2861 * Merge files from two draftarea areas.
2863 * This does not handle conflict resolution, files in the destination area which appear
2864 * to be more recent will be kept disregarding the intended ones.
2866 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2867 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2868 * @throws coding_exception
2869 * @since Moodle 3.2
2871 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2872 global $USER;
2874 $fs = get_file_storage();
2875 $contextid = context_user::instance($USER->id)->id;
2877 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2878 throw new coding_exception('Nothing to merge or area does not belong to current user');
2881 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2883 // Get hashes of the files to merge.
2884 $newhashes = array();
2885 foreach ($filestomerge as $filetomerge) {
2886 $filepath = $filetomerge->get_filepath();
2887 $filename = $filetomerge->get_filename();
2889 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2890 $newhashes[$newhash] = $filetomerge;
2893 // Calculate wich files must be added.
2894 foreach ($currentfiles as $file) {
2895 $filehash = $file->get_pathnamehash();
2896 // One file to be merged already exists.
2897 if (isset($newhashes[$filehash])) {
2898 $updatedfile = $newhashes[$filehash];
2900 // Avoid race conditions.
2901 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2902 // The existing file is more recent, do not copy the suposedly "new" one.
2903 unset($newhashes[$filehash]);
2904 continue;
2906 // Update existing file (not only content, meta-data too).
2907 file_overwrite_existing_draftfile($updatedfile, $file);
2908 unset($newhashes[$filehash]);
2912 foreach ($newhashes as $newfile) {
2913 $newfilerecord = array(
2914 'contextid' => $contextid,
2915 'component' => 'user',
2916 'filearea' => 'draft',
2917 'itemid' => $mergeintodraftid,
2918 'timemodified' => time()
2921 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2926 * RESTful cURL class
2928 * This is a wrapper class for curl, it is quite easy to use:
2929 * <code>
2930 * $c = new curl;
2931 * // enable cache
2932 * $c = new curl(array('cache'=>true));
2933 * // enable cookie
2934 * $c = new curl(array('cookie'=>true));
2935 * // enable proxy
2936 * $c = new curl(array('proxy'=>true));
2938 * // HTTP GET Method
2939 * $html = $c->get('http://example.com');
2940 * // HTTP POST Method
2941 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2942 * // HTTP PUT Method
2943 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2944 * </code>
2946 * @package core_files
2947 * @category files
2948 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2949 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2951 class curl {
2952 /** @var bool Caches http request contents */
2953 public $cache = false;
2954 /** @var bool Uses proxy, null means automatic based on URL */
2955 public $proxy = null;
2956 /** @var string library version */
2957 public $version = '0.4 dev';
2958 /** @var array http's response */
2959 public $response = array();
2960 /** @var array Raw response headers, needed for BC in download_file_content(). */
2961 public $rawresponse = array();
2962 /** @var array http header */
2963 public $header = array();
2964 /** @var string cURL information */
2965 public $info;
2966 /** @var string error */
2967 public $error;
2968 /** @var int error code */
2969 public $errno;
2970 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2971 public $emulateredirects = null;
2973 /** @var array cURL options */
2974 private $options;
2976 /** @var string Proxy host */
2977 private $proxy_host = '';
2978 /** @var string Proxy auth */
2979 private $proxy_auth = '';
2980 /** @var string Proxy type */
2981 private $proxy_type = '';
2982 /** @var bool Debug mode on */
2983 private $debug = false;
2984 /** @var bool|string Path to cookie file */
2985 private $cookie = false;
2986 /** @var bool tracks multiple headers in response - redirect detection */
2987 private $responsefinished = false;
2988 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2989 private $securityhelper;
2990 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2991 private $ignoresecurity;
2992 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
2993 private static $mockresponses = [];
2996 * Curl constructor.
2998 * Allowed settings are:
2999 * proxy: (bool) use proxy server, null means autodetect non-local from url
3000 * debug: (bool) use debug output
3001 * cookie: (string) path to cookie file, false if none
3002 * cache: (bool) use cache
3003 * module_cache: (string) type of cache
3004 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3005 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3007 * @param array $settings
3009 public function __construct($settings = array()) {
3010 global $CFG;
3011 if (!function_exists('curl_init')) {
3012 $this->error = 'cURL module must be enabled!';
3013 trigger_error($this->error, E_USER_ERROR);
3014 return false;
3017 // All settings of this class should be init here.
3018 $this->resetopt();
3019 if (!empty($settings['debug'])) {
3020 $this->debug = true;
3022 if (!empty($settings['cookie'])) {
3023 if($settings['cookie'] === true) {
3024 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3025 } else {
3026 $this->cookie = $settings['cookie'];
3029 if (!empty($settings['cache'])) {
3030 if (class_exists('curl_cache')) {
3031 if (!empty($settings['module_cache'])) {
3032 $this->cache = new curl_cache($settings['module_cache']);
3033 } else {
3034 $this->cache = new curl_cache('misc');
3038 if (!empty($CFG->proxyhost)) {
3039 if (empty($CFG->proxyport)) {
3040 $this->proxy_host = $CFG->proxyhost;
3041 } else {
3042 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3044 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3045 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3046 $this->setopt(array(
3047 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3048 'proxyuserpwd'=>$this->proxy_auth));
3050 if (!empty($CFG->proxytype)) {
3051 if ($CFG->proxytype == 'SOCKS5') {
3052 $this->proxy_type = CURLPROXY_SOCKS5;
3053 } else {
3054 $this->proxy_type = CURLPROXY_HTTP;
3055 $this->setopt(array('httpproxytunnel'=>false));
3057 $this->setopt(array('proxytype'=>$this->proxy_type));
3060 if (isset($settings['proxy'])) {
3061 $this->proxy = $settings['proxy'];
3063 } else {
3064 $this->proxy = false;
3067 if (!isset($this->emulateredirects)) {
3068 $this->emulateredirects = ini_get('open_basedir');
3071 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3072 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3073 $this->set_security($settings['securityhelper']);
3074 } else {
3075 $this->set_security(new \core\files\curl_security_helper());
3077 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3081 * Resets the CURL options that have already been set
3083 public function resetopt() {
3084 $this->options = array();
3085 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
3086 // True to include the header in the output
3087 $this->options['CURLOPT_HEADER'] = 0;
3088 // True to Exclude the body from the output
3089 $this->options['CURLOPT_NOBODY'] = 0;
3090 // Redirect ny default.
3091 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
3092 $this->options['CURLOPT_MAXREDIRS'] = 10;
3093 $this->options['CURLOPT_ENCODING'] = '';
3094 // TRUE to return the transfer as a string of the return
3095 // value of curl_exec() instead of outputting it out directly.
3096 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
3097 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
3098 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
3099 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
3101 if ($cacert = self::get_cacert()) {
3102 $this->options['CURLOPT_CAINFO'] = $cacert;
3107 * Get the location of ca certificates.
3108 * @return string absolute file path or empty if default used
3110 public static function get_cacert() {
3111 global $CFG;
3113 // Bundle in dataroot always wins.
3114 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3115 return realpath("$CFG->dataroot/moodleorgca.crt");
3118 // Next comes the default from php.ini
3119 $cacert = ini_get('curl.cainfo');
3120 if (!empty($cacert) and is_readable($cacert)) {
3121 return realpath($cacert);
3124 // Windows PHP does not have any certs, we need to use something.
3125 if ($CFG->ostype === 'WINDOWS') {
3126 if (is_readable("$CFG->libdir/cacert.pem")) {
3127 return realpath("$CFG->libdir/cacert.pem");
3131 // Use default, this should work fine on all properly configured *nix systems.
3132 return null;
3136 * Reset Cookie
3138 public function resetcookie() {
3139 if (!empty($this->cookie)) {
3140 if (is_file($this->cookie)) {
3141 $fp = fopen($this->cookie, 'w');
3142 if (!empty($fp)) {
3143 fwrite($fp, '');
3144 fclose($fp);
3151 * Set curl options.
3153 * Do not use the curl constants to define the options, pass a string
3154 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3155 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3157 * @param array $options If array is null, this function will reset the options to default value.
3158 * @return void
3159 * @throws coding_exception If an option uses constant value instead of option name.
3161 public function setopt($options = array()) {
3162 if (is_array($options)) {
3163 foreach ($options as $name => $val) {
3164 if (!is_string($name)) {
3165 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3167 if (stripos($name, 'CURLOPT_') === false) {
3168 $name = strtoupper('CURLOPT_'.$name);
3169 } else {
3170 $name = strtoupper($name);
3172 $this->options[$name] = $val;
3178 * Reset http method
3180 public function cleanopt() {
3181 unset($this->options['CURLOPT_HTTPGET']);
3182 unset($this->options['CURLOPT_POST']);
3183 unset($this->options['CURLOPT_POSTFIELDS']);
3184 unset($this->options['CURLOPT_PUT']);
3185 unset($this->options['CURLOPT_INFILE']);
3186 unset($this->options['CURLOPT_INFILESIZE']);
3187 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3188 unset($this->options['CURLOPT_FILE']);
3192 * Resets the HTTP Request headers (to prepare for the new request)
3194 public function resetHeader() {
3195 $this->header = array();
3199 * Set HTTP Request Header
3201 * @param array $header
3203 public function setHeader($header) {
3204 if (is_array($header)) {
3205 foreach ($header as $v) {
3206 $this->setHeader($v);
3208 } else {
3209 // Remove newlines, they are not allowed in headers.
3210 $newvalue = preg_replace('/[\r\n]/', '', $header);
3211 if (!in_array($newvalue, $this->header)) {
3212 $this->header[] = $newvalue;
3218 * Get HTTP Response Headers
3219 * @return array of arrays
3221 public function getResponse() {
3222 return $this->response;
3226 * Get raw HTTP Response Headers
3227 * @return array of strings
3229 public function get_raw_response() {
3230 return $this->rawresponse;
3234 * private callback function
3235 * Formatting HTTP Response Header
3237 * We only keep the last headers returned. For example during a redirect the
3238 * redirect headers will not appear in {@link self::getResponse()}, if you need
3239 * to use those headers, refer to {@link self::get_raw_response()}.
3241 * @param resource $ch Apparently not used
3242 * @param string $header
3243 * @return int The strlen of the header
3245 private function formatHeader($ch, $header) {
3246 $this->rawresponse[] = $header;
3248 if (trim($header, "\r\n") === '') {
3249 // This must be the last header.
3250 $this->responsefinished = true;
3253 if (strlen($header) > 2) {
3254 if ($this->responsefinished) {
3255 // We still have headers after the supposedly last header, we must be
3256 // in a redirect so let's empty the response to keep the last headers.
3257 $this->responsefinished = false;
3258 $this->response = array();
3260 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3261 $key = rtrim($parts[0], ':');
3262 $value = isset($parts[1]) ? $parts[1] : null;
3263 if (!empty($this->response[$key])) {
3264 if (is_array($this->response[$key])) {
3265 $this->response[$key][] = $value;
3266 } else {
3267 $tmp = $this->response[$key];
3268 $this->response[$key] = array();
3269 $this->response[$key][] = $tmp;
3270 $this->response[$key][] = $value;
3273 } else {
3274 $this->response[$key] = $value;
3277 return strlen($header);
3281 * Set options for individual curl instance
3283 * @param resource $curl A curl handle
3284 * @param array $options
3285 * @return resource The curl handle
3287 private function apply_opt($curl, $options) {
3288 // Clean up
3289 $this->cleanopt();
3290 // set cookie
3291 if (!empty($this->cookie) || !empty($options['cookie'])) {
3292 $this->setopt(array('cookiejar'=>$this->cookie,
3293 'cookiefile'=>$this->cookie
3297 // Bypass proxy if required.
3298 if ($this->proxy === null) {
3299 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3300 $proxy = false;
3301 } else {
3302 $proxy = true;
3304 } else {
3305 $proxy = (bool)$this->proxy;
3308 // Set proxy.
3309 if ($proxy) {
3310 $options['CURLOPT_PROXY'] = $this->proxy_host;
3311 } else {
3312 unset($this->options['CURLOPT_PROXY']);
3315 $this->setopt($options);
3317 // Reset before set options.
3318 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3320 // Setting the User-Agent based on options provided.
3321 $useragent = '';
3323 if (!empty($options['CURLOPT_USERAGENT'])) {
3324 $useragent = $options['CURLOPT_USERAGENT'];
3325 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3326 $useragent = $this->options['CURLOPT_USERAGENT'];
3327 } else {
3328 $useragent = 'MoodleBot/1.0';
3331 // Set headers.
3332 if (empty($this->header)) {
3333 $this->setHeader(array(
3334 'User-Agent: ' . $useragent,
3335 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3336 'Connection: keep-alive'
3338 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3339 // Remove old User-Agent if one existed.
3340 // We have to partial search since we don't know what the original User-Agent is.
3341 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3342 $key = array_keys($match)[0];
3343 unset($this->header[$key]);
3345 $this->setHeader(array('User-Agent: ' . $useragent));
3347 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3349 if ($this->debug) {
3350 echo '<h1>Options</h1>';
3351 var_dump($this->options);
3352 echo '<h1>Header</h1>';
3353 var_dump($this->header);
3356 // Do not allow infinite redirects.
3357 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3358 $this->options['CURLOPT_MAXREDIRS'] = 0;
3359 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3360 $this->options['CURLOPT_MAXREDIRS'] = 100;
3361 } else {
3362 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3365 // Make sure we always know if redirects expected.
3366 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3367 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3370 // Limit the protocols to HTTP and HTTPS.
3371 if (defined('CURLOPT_PROTOCOLS')) {
3372 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3373 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3376 // Set options.
3377 foreach($this->options as $name => $val) {
3378 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3379 // The redirects are emulated elsewhere.
3380 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3381 continue;
3383 $name = constant($name);
3384 curl_setopt($curl, $name, $val);
3387 return $curl;
3391 * Download multiple files in parallel
3393 * Calls {@link multi()} with specific download headers
3395 * <code>
3396 * $c = new curl();
3397 * $file1 = fopen('a', 'wb');
3398 * $file2 = fopen('b', 'wb');
3399 * $c->download(array(
3400 * array('url'=>'http://localhost/', 'file'=>$file1),
3401 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3402 * ));
3403 * fclose($file1);
3404 * fclose($file2);
3405 * </code>
3407 * or
3409 * <code>
3410 * $c = new curl();
3411 * $c->download(array(
3412 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3413 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3414 * ));
3415 * </code>
3417 * @param array $requests An array of files to request {
3418 * url => url to download the file [required]
3419 * file => file handler, or
3420 * filepath => file path
3422 * If 'file' and 'filepath' parameters are both specified in one request, the
3423 * open file handle in the 'file' parameter will take precedence and 'filepath'
3424 * will be ignored.
3426 * @param array $options An array of options to set
3427 * @return array An array of results
3429 public function download($requests, $options = array()) {
3430 $options['RETURNTRANSFER'] = false;
3431 return $this->multi($requests, $options);
3435 * Returns the current curl security helper.
3437 * @return \core\files\curl_security_helper instance.
3439 public function get_security() {
3440 return $this->securityhelper;
3444 * Sets the curl security helper.
3446 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3447 * @return bool true if the security helper could be set, false otherwise.
3449 public function set_security($securityobject) {
3450 if ($securityobject instanceof \core\files\curl_security_helper) {
3451 $this->securityhelper = $securityobject;
3452 return true;
3454 return false;
3458 * Multi HTTP Requests
3459 * This function could run multi-requests in parallel.
3461 * @param array $requests An array of files to request
3462 * @param array $options An array of options to set
3463 * @return array An array of results
3465 protected function multi($requests, $options = array()) {
3466 $count = count($requests);
3467 $handles = array();
3468 $results = array();
3469 $main = curl_multi_init();
3470 for ($i = 0; $i < $count; $i++) {
3471 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3472 // open file
3473 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3474 $requests[$i]['auto-handle'] = true;
3476 foreach($requests[$i] as $n=>$v) {
3477 $options[$n] = $v;
3479 $handles[$i] = curl_init($requests[$i]['url']);
3480 $this->apply_opt($handles[$i], $options);
3481 curl_multi_add_handle($main, $handles[$i]);
3483 $running = 0;
3484 do {
3485 curl_multi_exec($main, $running);
3486 } while($running > 0);
3487 for ($i = 0; $i < $count; $i++) {
3488 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3489 $results[] = true;
3490 } else {
3491 $results[] = curl_multi_getcontent($handles[$i]);
3493 curl_multi_remove_handle($main, $handles[$i]);
3495 curl_multi_close($main);
3497 for ($i = 0; $i < $count; $i++) {
3498 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3499 // close file handler if file is opened in this function
3500 fclose($requests[$i]['file']);
3503 return $results;
3507 * Helper function to reset the request state vars.
3509 * @return void.
3511 protected function reset_request_state_vars() {
3512 $this->info = array();
3513 $this->error = '';
3514 $this->errno = 0;
3515 $this->response = array();
3516 $this->rawresponse = array();
3517 $this->responsefinished = false;
3521 * For use only in unit tests - we can pre-set the next curl response.
3522 * This is useful for unit testing APIs that call external systems.
3523 * @param string $response
3525 public static function mock_response($response) {
3526 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3527 array_push(self::$mockresponses, $response);
3528 } else {
3529 throw new coding_excpetion('mock_response function is only available for unit tests.');
3534 * Single HTTP Request
3536 * @param string $url The URL to request
3537 * @param array $options
3538 * @return bool
3540 protected function request($url, $options = array()) {
3541 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3542 $this->reset_request_state_vars();
3544 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3545 if ($mockresponse = array_pop(self::$mockresponses)) {
3546 $this->info = [ 'http_code' => 200 ];
3547 return $mockresponse;
3551 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3552 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3553 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3554 $this->error = $this->securityhelper->get_blocked_url_string();
3555 return $this->error;
3558 // Set the URL as a curl option.
3559 $this->setopt(array('CURLOPT_URL' => $url));
3561 // Create curl instance.
3562 $curl = curl_init();
3564 $this->apply_opt($curl, $options);
3565 if ($this->cache && $ret = $this->cache->get($this->options)) {
3566 return $ret;
3569 $ret = curl_exec($curl);
3570 $this->info = curl_getinfo($curl);
3571 $this->error = curl_error($curl);
3572 $this->errno = curl_errno($curl);
3573 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3575 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3576 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3577 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3578 $this->reset_request_state_vars();
3579 $this->error = $this->securityhelper->get_blocked_url_string();
3580 curl_close($curl);
3581 return $this->error;
3584 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3585 $redirects = 0;
3587 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3589 if ($this->info['http_code'] == 301) {
3590 // Moved Permanently - repeat the same request on new URL.
3592 } else if ($this->info['http_code'] == 302) {
3593 // Found - the standard redirect - repeat the same request on new URL.
3595 } else if ($this->info['http_code'] == 303) {
3596 // 303 See Other - repeat only if GET, do not bother with POSTs.
3597 if (empty($this->options['CURLOPT_HTTPGET'])) {
3598 break;
3601 } else if ($this->info['http_code'] == 307) {
3602 // Temporary Redirect - must repeat using the same request type.
3604 } else if ($this->info['http_code'] == 308) {
3605 // Permanent Redirect - must repeat using the same request type.
3607 } else {
3608 // Some other http code means do not retry!
3609 break;
3612 $redirects++;
3614 $redirecturl = null;
3615 if (isset($this->info['redirect_url'])) {
3616 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3617 $redirecturl = $this->info['redirect_url'];
3620 if (!$redirecturl) {
3621 foreach ($this->response as $k => $v) {
3622 if (strtolower($k) === 'location') {
3623 $redirecturl = $v;
3624 break;
3627 if (preg_match('|^https?://|i', $redirecturl)) {
3628 // Great, this is the correct location format!
3630 } else if ($redirecturl) {
3631 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3632 if (strpos($redirecturl, '/') === 0) {
3633 // Relative to server root - just guess.
3634 $pos = strpos('/', $current, 8);
3635 if ($pos === false) {
3636 $redirecturl = $current.$redirecturl;
3637 } else {
3638 $redirecturl = substr($current, 0, $pos).$redirecturl;
3640 } else {
3641 // Relative to current script.
3642 $redirecturl = dirname($current).'/'.$redirecturl;
3647 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3648 $ret = curl_exec($curl);
3650 $this->info = curl_getinfo($curl);
3651 $this->error = curl_error($curl);
3652 $this->errno = curl_errno($curl);
3654 $this->info['redirect_count'] = $redirects;
3656 if ($this->info['http_code'] === 200) {
3657 // Finally this is what we wanted.
3658 break;
3660 if ($this->errno != CURLE_OK) {
3661 // Something wrong is going on.
3662 break;
3665 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3666 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3667 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3671 if ($this->cache) {
3672 $this->cache->set($this->options, $ret);
3675 if ($this->debug) {
3676 echo '<h1>Return Data</h1>';
3677 var_dump($ret);
3678 echo '<h1>Info</h1>';
3679 var_dump($this->info);
3680 echo '<h1>Error</h1>';
3681 var_dump($this->error);
3684 curl_close($curl);
3686 if (empty($this->error)) {
3687 return $ret;
3688 } else {
3689 return $this->error;
3690 // exception is not ajax friendly
3691 //throw new moodle_exception($this->error, 'curl');
3696 * HTTP HEAD method
3698 * @see request()
3700 * @param string $url
3701 * @param array $options
3702 * @return bool
3704 public function head($url, $options = array()) {
3705 $options['CURLOPT_HTTPGET'] = 0;
3706 $options['CURLOPT_HEADER'] = 1;
3707 $options['CURLOPT_NOBODY'] = 1;
3708 return $this->request($url, $options);
3712 * HTTP PATCH method
3714 * @param string $url
3715 * @param array|string $params
3716 * @param array $options
3717 * @return bool
3719 public function patch($url, $params = '', $options = array()) {
3720 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3721 if (is_array($params)) {
3722 $this->_tmp_file_post_params = array();
3723 foreach ($params as $key => $value) {
3724 if ($value instanceof stored_file) {
3725 $value->add_to_curl_request($this, $key);
3726 } else {
3727 $this->_tmp_file_post_params[$key] = $value;
3730 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3731 unset($this->_tmp_file_post_params);
3732 } else {
3733 // The variable $params is the raw post data.
3734 $options['CURLOPT_POSTFIELDS'] = $params;
3736 return $this->request($url, $options);
3740 * HTTP POST method
3742 * @param string $url
3743 * @param array|string $params
3744 * @param array $options
3745 * @return bool
3747 public function post($url, $params = '', $options = array()) {
3748 $options['CURLOPT_POST'] = 1;
3749 if (is_array($params)) {
3750 $this->_tmp_file_post_params = array();
3751 foreach ($params as $key => $value) {
3752 if ($value instanceof stored_file) {
3753 $value->add_to_curl_request($this, $key);
3754 } else {
3755 $this->_tmp_file_post_params[$key] = $value;
3758 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3759 unset($this->_tmp_file_post_params);
3760 } else {
3761 // $params is the raw post data
3762 $options['CURLOPT_POSTFIELDS'] = $params;
3764 return $this->request($url, $options);
3768 * HTTP GET method
3770 * @param string $url
3771 * @param array $params
3772 * @param array $options
3773 * @return bool
3775 public function get($url, $params = array(), $options = array()) {
3776 $options['CURLOPT_HTTPGET'] = 1;
3778 if (!empty($params)) {
3779 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3780 $url .= http_build_query($params, '', '&');
3782 return $this->request($url, $options);
3786 * Downloads one file and writes it to the specified file handler
3788 * <code>
3789 * $c = new curl();
3790 * $file = fopen('savepath', 'w');
3791 * $result = $c->download_one('http://localhost/', null,
3792 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3793 * fclose($file);
3794 * $download_info = $c->get_info();
3795 * if ($result === true) {
3796 * // file downloaded successfully
3797 * } else {
3798 * $error_text = $result;
3799 * $error_code = $c->get_errno();
3801 * </code>
3803 * <code>
3804 * $c = new curl();
3805 * $result = $c->download_one('http://localhost/', null,
3806 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3807 * // ... see above, no need to close handle and remove file if unsuccessful
3808 * </code>
3810 * @param string $url
3811 * @param array|null $params key-value pairs to be added to $url as query string
3812 * @param array $options request options. Must include either 'file' or 'filepath'
3813 * @return bool|string true on success or error string on failure
3815 public function download_one($url, $params, $options = array()) {
3816 $options['CURLOPT_HTTPGET'] = 1;
3817 if (!empty($params)) {
3818 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3819 $url .= http_build_query($params, '', '&');
3821 if (!empty($options['filepath']) && empty($options['file'])) {
3822 // open file
3823 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3824 $this->errno = 100;
3825 return get_string('cannotwritefile', 'error', $options['filepath']);
3827 $filepath = $options['filepath'];
3829 unset($options['filepath']);
3830 $result = $this->request($url, $options);
3831 if (isset($filepath)) {
3832 fclose($options['file']);
3833 if ($result !== true) {
3834 unlink($filepath);
3837 return $result;
3841 * HTTP PUT method
3843 * @param string $url
3844 * @param array $params
3845 * @param array $options
3846 * @return bool
3848 public function put($url, $params = array(), $options = array()) {
3849 $file = '';
3850 $fp = false;
3851 if (isset($params['file'])) {
3852 $file = $params['file'];
3853 if (is_file($file)) {
3854 $fp = fopen($file, 'r');
3855 $size = filesize($file);
3856 $options['CURLOPT_PUT'] = 1;
3857 $options['CURLOPT_INFILESIZE'] = $size;
3858 $options['CURLOPT_INFILE'] = $fp;
3859 } else {
3860 return null;
3862 if (!isset($this->options['CURLOPT_USERPWD'])) {
3863 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3865 } else {
3866 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3867 $options['CURLOPT_POSTFIELDS'] = $params;
3870 $ret = $this->request($url, $options);
3871 if ($fp !== false) {
3872 fclose($fp);
3874 return $ret;
3878 * HTTP DELETE method
3880 * @param string $url
3881 * @param array $param
3882 * @param array $options
3883 * @return bool
3885 public function delete($url, $param = array(), $options = array()) {
3886 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3887 if (!isset($options['CURLOPT_USERPWD'])) {
3888 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3890 $ret = $this->request($url, $options);
3891 return $ret;
3895 * HTTP TRACE method
3897 * @param string $url
3898 * @param array $options
3899 * @return bool
3901 public function trace($url, $options = array()) {
3902 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3903 $ret = $this->request($url, $options);
3904 return $ret;
3908 * HTTP OPTIONS method
3910 * @param string $url
3911 * @param array $options
3912 * @return bool
3914 public function options($url, $options = array()) {
3915 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3916 $ret = $this->request($url, $options);
3917 return $ret;
3921 * Get curl information
3923 * @return string
3925 public function get_info() {
3926 return $this->info;
3930 * Get curl error code
3932 * @return int
3934 public function get_errno() {
3935 return $this->errno;
3939 * When using a proxy, an additional HTTP response code may appear at
3940 * the start of the header. For example, when using https over a proxy
3941 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3942 * also possible and some may come with their own headers.
3944 * If using the return value containing all headers, this function can be
3945 * called to remove unwanted doubles.
3947 * Note that it is not possible to distinguish this situation from valid
3948 * data unless you know the actual response part (below the headers)
3949 * will not be included in this string, or else will not 'look like' HTTP
3950 * headers. As a result it is not safe to call this function for general
3951 * data.
3953 * @param string $input Input HTTP response
3954 * @return string HTTP response with additional headers stripped if any
3956 public static function strip_double_headers($input) {
3957 // I have tried to make this regular expression as specific as possible
3958 // to avoid any case where it does weird stuff if you happen to put
3959 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3960 // also make it faster because it can abandon regex processing as soon
3961 // as it hits something that doesn't look like an http header. The
3962 // header definition is taken from RFC 822, except I didn't support
3963 // folding which is never used in practice.
3964 $crlf = "\r\n";
3965 return preg_replace(
3966 // HTTP version and status code (ignore value of code).
3967 '~^HTTP/1\..*' . $crlf .
3968 // Header name: character between 33 and 126 decimal, except colon.
3969 // Colon. Header value: any character except \r and \n. CRLF.
3970 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3971 // Headers are terminated by another CRLF (blank line).
3972 $crlf .
3973 // Second HTTP status code, this time must be 200.
3974 '(HTTP/1.[01] 200 )~', '$1', $input);
3979 * This class is used by cURL class, use case:
3981 * <code>
3982 * $CFG->repositorycacheexpire = 120;
3983 * $CFG->curlcache = 120;
3985 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3986 * $ret = $c->get('http://www.google.com');
3987 * </code>
3989 * @package core_files
3990 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3991 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3993 class curl_cache {
3994 /** @var string Path to cache directory */
3995 public $dir = '';
3998 * Constructor
4000 * @global stdClass $CFG
4001 * @param string $module which module is using curl_cache
4003 public function __construct($module = 'repository') {
4004 global $CFG;
4005 if (!empty($module)) {
4006 $this->dir = $CFG->cachedir.'/'.$module.'/';
4007 } else {
4008 $this->dir = $CFG->cachedir.'/misc/';
4010 if (!file_exists($this->dir)) {
4011 mkdir($this->dir, $CFG->directorypermissions, true);
4013 if ($module == 'repository') {
4014 if (empty($CFG->repositorycacheexpire)) {
4015 $CFG->repositorycacheexpire = 120;
4017 $this->ttl = $CFG->repositorycacheexpire;
4018 } else {
4019 if (empty($CFG->curlcache)) {
4020 $CFG->curlcache = 120;
4022 $this->ttl = $CFG->curlcache;
4027 * Get cached value
4029 * @global stdClass $CFG
4030 * @global stdClass $USER
4031 * @param mixed $param
4032 * @return bool|string
4034 public function get($param) {
4035 global $CFG, $USER;
4036 $this->cleanup($this->ttl);
4037 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4038 if(file_exists($this->dir.$filename)) {
4039 $lasttime = filemtime($this->dir.$filename);
4040 if (time()-$lasttime > $this->ttl) {
4041 return false;
4042 } else {
4043 $fp = fopen($this->dir.$filename, 'r');
4044 $size = filesize($this->dir.$filename);
4045 $content = fread($fp, $size);
4046 return unserialize($content);
4049 return false;
4053 * Set cache value
4055 * @global object $CFG
4056 * @global object $USER
4057 * @param mixed $param
4058 * @param mixed $val
4060 public function set($param, $val) {
4061 global $CFG, $USER;
4062 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4063 $fp = fopen($this->dir.$filename, 'w');
4064 fwrite($fp, serialize($val));
4065 fclose($fp);
4066 @chmod($this->dir.$filename, $CFG->filepermissions);
4070 * Remove cache files
4072 * @param int $expire The number of seconds before expiry
4074 public function cleanup($expire) {
4075 if ($dir = opendir($this->dir)) {
4076 while (false !== ($file = readdir($dir))) {
4077 if(!is_dir($file) && $file != '.' && $file != '..') {
4078 $lasttime = @filemtime($this->dir.$file);
4079 if (time() - $lasttime > $expire) {
4080 @unlink($this->dir.$file);
4084 closedir($dir);
4088 * delete current user's cache file
4090 * @global object $CFG
4091 * @global object $USER
4093 public function refresh() {
4094 global $CFG, $USER;
4095 if ($dir = opendir($this->dir)) {
4096 while (false !== ($file = readdir($dir))) {
4097 if (!is_dir($file) && $file != '.' && $file != '..') {
4098 if (strpos($file, 'u'.$USER->id.'_') !== false) {
4099 @unlink($this->dir.$file);
4108 * This function delegates file serving to individual plugins
4110 * @param string $relativepath
4111 * @param bool $forcedownload
4112 * @param null|string $preview the preview mode, defaults to serving the original file
4113 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4114 * offline (e.g. mobile app).
4115 * @param bool $embed Whether this file will be served embed into an iframe.
4116 * @todo MDL-31088 file serving improments
4118 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4119 global $DB, $CFG, $USER;
4120 // relative path must start with '/'
4121 if (!$relativepath) {
4122 print_error('invalidargorconf');
4123 } else if ($relativepath[0] != '/') {
4124 print_error('pathdoesnotstartslash');
4127 // extract relative path components
4128 $args = explode('/', ltrim($relativepath, '/'));
4130 if (count($args) < 3) { // always at least context, component and filearea
4131 print_error('invalidarguments');
4134 $contextid = (int)array_shift($args);
4135 $component = clean_param(array_shift($args), PARAM_COMPONENT);
4136 $filearea = clean_param(array_shift($args), PARAM_AREA);
4138 list($context, $course, $cm) = get_context_info_array($contextid);
4140 $fs = get_file_storage();
4142 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4144 // ========================================================================================================================
4145 if ($component === 'blog') {
4146 // Blog file serving
4147 if ($context->contextlevel != CONTEXT_SYSTEM) {
4148 send_file_not_found();
4150 if ($filearea !== 'attachment' and $filearea !== 'post') {
4151 send_file_not_found();
4154 if (empty($CFG->enableblogs)) {
4155 print_error('siteblogdisable', 'blog');
4158 $entryid = (int)array_shift($args);
4159 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4160 send_file_not_found();
4162 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4163 require_login();
4164 if (isguestuser()) {
4165 print_error('noguest');
4167 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4168 if ($USER->id != $entry->userid) {
4169 send_file_not_found();
4174 if ($entry->publishstate === 'public') {
4175 if ($CFG->forcelogin) {
4176 require_login();
4179 } else if ($entry->publishstate === 'site') {
4180 require_login();
4181 //ok
4182 } else if ($entry->publishstate === 'draft') {
4183 require_login();
4184 if ($USER->id != $entry->userid) {
4185 send_file_not_found();
4189 $filename = array_pop($args);
4190 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4192 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4193 send_file_not_found();
4196 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4198 // ========================================================================================================================
4199 } else if ($component === 'grade') {
4200 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4201 // Global gradebook files
4202 if ($CFG->forcelogin) {
4203 require_login();
4206 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4208 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4209 send_file_not_found();
4212 \core\session\manager::write_close(); // Unlock session during file serving.
4213 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4215 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
4216 //TODO: nobody implemented this yet in grade edit form!!
4217 send_file_not_found();
4219 if ($CFG->forcelogin || $course->id != SITEID) {
4220 require_login($course);
4223 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4225 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4226 send_file_not_found();
4229 \core\session\manager::write_close(); // Unlock session during file serving.
4230 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4231 } else {
4232 send_file_not_found();
4235 // ========================================================================================================================
4236 } else if ($component === 'tag') {
4237 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4239 // All tag descriptions are going to be public but we still need to respect forcelogin
4240 if ($CFG->forcelogin) {
4241 require_login();
4244 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4246 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4247 send_file_not_found();
4250 \core\session\manager::write_close(); // Unlock session during file serving.
4251 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4253 } else {
4254 send_file_not_found();
4256 // ========================================================================================================================
4257 } else if ($component === 'badges') {
4258 require_once($CFG->libdir . '/badgeslib.php');
4260 $badgeid = (int)array_shift($args);
4261 $badge = new badge($badgeid);
4262 $filename = array_pop($args);
4264 if ($filearea === 'badgeimage') {
4265 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4266 send_file_not_found();
4268 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4269 send_file_not_found();
4272 \core\session\manager::write_close();
4273 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4274 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4275 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4276 send_file_not_found();
4279 \core\session\manager::write_close();
4280 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4282 // ========================================================================================================================
4283 } else if ($component === 'calendar') {
4284 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4286 // All events here are public the one requirement is that we respect forcelogin
4287 if ($CFG->forcelogin) {
4288 require_login();
4291 // Get the event if from the args array
4292 $eventid = array_shift($args);
4294 // Load the event from the database
4295 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4296 send_file_not_found();
4299 // Get the file and serve if successful
4300 $filename = array_pop($args);
4301 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4302 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4303 send_file_not_found();
4306 \core\session\manager::write_close(); // Unlock session during file serving.
4307 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4309 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4311 // Must be logged in, if they are not then they obviously can't be this user
4312 require_login();
4314 // Don't want guests here, potentially saves a DB call
4315 if (isguestuser()) {
4316 send_file_not_found();
4319 // Get the event if from the args array
4320 $eventid = array_shift($args);
4322 // Load the event from the database - user id must match
4323 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4324 send_file_not_found();
4327 // Get the file and serve if successful
4328 $filename = array_pop($args);
4329 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4330 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4331 send_file_not_found();
4334 \core\session\manager::write_close(); // Unlock session during file serving.
4335 send_stored_file($file, 0, 0, true, $sendfileoptions);
4337 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4339 // Respect forcelogin and require login unless this is the site.... it probably
4340 // should NEVER be the site
4341 if ($CFG->forcelogin || $course->id != SITEID) {
4342 require_login($course);
4345 // Must be able to at least view the course. This does not apply to the front page.
4346 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4347 //TODO: hmm, do we really want to block guests here?
4348 send_file_not_found();
4351 // Get the event id
4352 $eventid = array_shift($args);
4354 // Load the event from the database we need to check whether it is
4355 // a) valid course event
4356 // b) a group event
4357 // Group events use the course context (there is no group context)
4358 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4359 send_file_not_found();
4362 // If its a group event require either membership of view all groups capability
4363 if ($event->eventtype === 'group') {
4364 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4365 send_file_not_found();
4367 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4368 // Ok. Please note that the event type 'site' still uses a course context.
4369 } else {
4370 // Some other type.
4371 send_file_not_found();
4374 // If we get this far we can serve the file
4375 $filename = array_pop($args);
4376 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4377 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4378 send_file_not_found();
4381 \core\session\manager::write_close(); // Unlock session during file serving.
4382 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4384 } else {
4385 send_file_not_found();
4388 // ========================================================================================================================
4389 } else if ($component === 'user') {
4390 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4391 if (count($args) == 1) {
4392 $themename = theme_config::DEFAULT_THEME;
4393 $filename = array_shift($args);
4394 } else {
4395 $themename = array_shift($args);
4396 $filename = array_shift($args);
4399 // fix file name automatically
4400 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4401 $filename = 'f1';
4404 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4405 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4406 // protect images if login required and not logged in;
4407 // also if login is required for profile images and is not logged in or guest
4408 // do not use require_login() because it is expensive and not suitable here anyway
4409 $theme = theme_config::load($themename);
4410 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4413 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4414 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4415 if ($filename === 'f3') {
4416 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4417 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4418 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4423 if (!$file) {
4424 // bad reference - try to prevent future retries as hard as possible!
4425 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4426 if ($user->picture > 0) {
4427 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4430 // no redirect here because it is not cached
4431 $theme = theme_config::load($themename);
4432 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4433 send_file($imagefile, basename($imagefile), 60*60*24*14);
4436 $options = $sendfileoptions;
4437 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4438 // Profile images should be cache-able by both browsers and proxies according
4439 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4440 $options['cacheability'] = 'public';
4442 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4444 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4445 require_login();
4447 if (isguestuser()) {
4448 send_file_not_found();
4451 if ($USER->id !== $context->instanceid) {
4452 send_file_not_found();
4455 $filename = array_pop($args);
4456 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4457 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4458 send_file_not_found();
4461 \core\session\manager::write_close(); // Unlock session during file serving.
4462 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4464 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4466 if ($CFG->forcelogin) {
4467 require_login();
4470 $userid = $context->instanceid;
4472 if ($USER->id == $userid) {
4473 // always can access own
4475 } else if (!empty($CFG->forceloginforprofiles)) {
4476 require_login();
4478 if (isguestuser()) {
4479 send_file_not_found();
4482 // we allow access to site profile of all course contacts (usually teachers)
4483 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4484 send_file_not_found();
4487 $canview = false;
4488 if (has_capability('moodle/user:viewdetails', $context)) {
4489 $canview = true;
4490 } else {
4491 $courses = enrol_get_my_courses();
4494 while (!$canview && count($courses) > 0) {
4495 $course = array_shift($courses);
4496 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4497 $canview = true;
4502 $filename = array_pop($args);
4503 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4504 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4505 send_file_not_found();
4508 \core\session\manager::write_close(); // Unlock session during file serving.
4509 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4511 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4512 $userid = (int)array_shift($args);
4513 $usercontext = context_user::instance($userid);
4515 if ($CFG->forcelogin) {
4516 require_login();
4519 if (!empty($CFG->forceloginforprofiles)) {
4520 require_login();
4521 if (isguestuser()) {
4522 print_error('noguest');
4525 //TODO: review this logic of user profile access prevention
4526 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4527 print_error('usernotavailable');
4529 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4530 print_error('cannotviewprofile');
4532 if (!is_enrolled($context, $userid)) {
4533 print_error('notenrolledprofile');
4535 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4536 print_error('groupnotamember');
4540 $filename = array_pop($args);
4541 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4542 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4543 send_file_not_found();
4546 \core\session\manager::write_close(); // Unlock session during file serving.
4547 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4549 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4550 require_login();
4552 if (isguestuser()) {
4553 send_file_not_found();
4555 $userid = $context->instanceid;
4557 if ($USER->id != $userid) {
4558 send_file_not_found();
4561 $filename = array_pop($args);
4562 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4563 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4564 send_file_not_found();
4567 \core\session\manager::write_close(); // Unlock session during file serving.
4568 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4570 } else {
4571 send_file_not_found();
4574 // ========================================================================================================================
4575 } else if ($component === 'coursecat') {
4576 if ($context->contextlevel != CONTEXT_COURSECAT) {
4577 send_file_not_found();
4580 if ($filearea === 'description') {
4581 if ($CFG->forcelogin) {
4582 // no login necessary - unless login forced everywhere
4583 require_login();
4586 // Check if user can view this category.
4587 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4588 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid));
4589 if (!$coursecatvisible) {
4590 send_file_not_found();
4594 $filename = array_pop($args);
4595 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4596 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4597 send_file_not_found();
4600 \core\session\manager::write_close(); // Unlock session during file serving.
4601 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4602 } else {
4603 send_file_not_found();
4606 // ========================================================================================================================
4607 } else if ($component === 'course') {
4608 if ($context->contextlevel != CONTEXT_COURSE) {
4609 send_file_not_found();
4612 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4613 if ($CFG->forcelogin) {
4614 require_login();
4617 $filename = array_pop($args);
4618 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4619 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4620 send_file_not_found();
4623 \core\session\manager::write_close(); // Unlock session during file serving.
4624 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4626 } else if ($filearea === 'section') {
4627 if ($CFG->forcelogin) {
4628 require_login($course);
4629 } else if ($course->id != SITEID) {
4630 require_login($course);
4633 $sectionid = (int)array_shift($args);
4635 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4636 send_file_not_found();
4639 $filename = array_pop($args);
4640 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4641 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4642 send_file_not_found();
4645 \core\session\manager::write_close(); // Unlock session during file serving.
4646 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4648 } else {
4649 send_file_not_found();
4652 } else if ($component === 'cohort') {
4654 $cohortid = (int)array_shift($args);
4655 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4656 $cohortcontext = context::instance_by_id($cohort->contextid);
4658 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4659 if ($context->id != $cohort->contextid &&
4660 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4661 send_file_not_found();
4664 // User is able to access cohort if they have view cap on cohort level or
4665 // the cohort is visible and they have view cap on course level.
4666 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4667 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4669 if ($filearea === 'description' && $canview) {
4670 $filename = array_pop($args);
4671 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4672 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4673 && !$file->is_directory()) {
4674 \core\session\manager::write_close(); // Unlock session during file serving.
4675 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4679 send_file_not_found();
4681 } else if ($component === 'group') {
4682 if ($context->contextlevel != CONTEXT_COURSE) {
4683 send_file_not_found();
4686 require_course_login($course, true, null, false);
4688 $groupid = (int)array_shift($args);
4690 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4691 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4692 // do not allow access to separate group info if not member or teacher
4693 send_file_not_found();
4696 if ($filearea === 'description') {
4698 require_login($course);
4700 $filename = array_pop($args);
4701 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4702 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4703 send_file_not_found();
4706 \core\session\manager::write_close(); // Unlock session during file serving.
4707 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4709 } else if ($filearea === 'icon') {
4710 $filename = array_pop($args);
4712 if ($filename !== 'f1' and $filename !== 'f2') {
4713 send_file_not_found();
4715 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4716 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4717 send_file_not_found();
4721 \core\session\manager::write_close(); // Unlock session during file serving.
4722 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4724 } else {
4725 send_file_not_found();
4728 } else if ($component === 'grouping') {
4729 if ($context->contextlevel != CONTEXT_COURSE) {
4730 send_file_not_found();
4733 require_login($course);
4735 $groupingid = (int)array_shift($args);
4737 // note: everybody has access to grouping desc images for now
4738 if ($filearea === 'description') {
4740 $filename = array_pop($args);
4741 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4742 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4743 send_file_not_found();
4746 \core\session\manager::write_close(); // Unlock session during file serving.
4747 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4749 } else {
4750 send_file_not_found();
4753 // ========================================================================================================================
4754 } else if ($component === 'backup') {
4755 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4756 require_login($course);
4757 require_capability('moodle/backup:downloadfile', $context);
4759 $filename = array_pop($args);
4760 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4761 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4762 send_file_not_found();
4765 \core\session\manager::write_close(); // Unlock session during file serving.
4766 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4768 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4769 require_login($course);
4770 require_capability('moodle/backup:downloadfile', $context);
4772 $sectionid = (int)array_shift($args);
4774 $filename = array_pop($args);
4775 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4776 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4777 send_file_not_found();
4780 \core\session\manager::write_close();
4781 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4783 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4784 require_login($course, false, $cm);
4785 require_capability('moodle/backup:downloadfile', $context);
4787 $filename = array_pop($args);
4788 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4789 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4790 send_file_not_found();
4793 \core\session\manager::write_close();
4794 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4796 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4797 // Backup files that were generated by the automated backup systems.
4799 require_login($course);
4800 require_capability('moodle/backup:downloadfile', $context);
4801 require_capability('moodle/restore:userinfo', $context);
4803 $filename = array_pop($args);
4804 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4805 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4806 send_file_not_found();
4809 \core\session\manager::write_close(); // Unlock session during file serving.
4810 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4812 } else {
4813 send_file_not_found();
4816 // ========================================================================================================================
4817 } else if ($component === 'question') {
4818 require_once($CFG->libdir . '/questionlib.php');
4819 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4820 send_file_not_found();
4822 // ========================================================================================================================
4823 } else if ($component === 'grading') {
4824 if ($filearea === 'description') {
4825 // files embedded into the form definition description
4827 if ($context->contextlevel == CONTEXT_SYSTEM) {
4828 require_login();
4830 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4831 require_login($course, false, $cm);
4833 } else {
4834 send_file_not_found();
4837 $formid = (int)array_shift($args);
4839 $sql = "SELECT ga.id
4840 FROM {grading_areas} ga
4841 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4842 WHERE gd.id = ? AND ga.contextid = ?";
4843 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4845 if (!$areaid) {
4846 send_file_not_found();
4849 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4851 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4852 send_file_not_found();
4855 \core\session\manager::write_close(); // Unlock session during file serving.
4856 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4859 // ========================================================================================================================
4860 } else if (strpos($component, 'mod_') === 0) {
4861 $modname = substr($component, 4);
4862 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4863 send_file_not_found();
4865 require_once("$CFG->dirroot/mod/$modname/lib.php");
4867 if ($context->contextlevel == CONTEXT_MODULE) {
4868 if ($cm->modname !== $modname) {
4869 // somebody tries to gain illegal access, cm type must match the component!
4870 send_file_not_found();
4874 if ($filearea === 'intro') {
4875 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4876 send_file_not_found();
4879 // Require login to the course first (without login to the module).
4880 require_course_login($course, true);
4882 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4883 $cminfo = cm_info::create($cm);
4884 if (!$cminfo->uservisible) {
4885 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
4886 // Module intro is not visible on the course page and module is not available, show access error.
4887 require_course_login($course, true, $cminfo);
4891 // all users may access it
4892 $filename = array_pop($args);
4893 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4894 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4895 send_file_not_found();
4898 // finally send the file
4899 send_stored_file($file, null, 0, false, $sendfileoptions);
4902 $filefunction = $component.'_pluginfile';
4903 $filefunctionold = $modname.'_pluginfile';
4904 if (function_exists($filefunction)) {
4905 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4906 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4907 } else if (function_exists($filefunctionold)) {
4908 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4909 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4912 send_file_not_found();
4914 // ========================================================================================================================
4915 } else if (strpos($component, 'block_') === 0) {
4916 $blockname = substr($component, 6);
4917 // note: no more class methods in blocks please, that is ....
4918 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4919 send_file_not_found();
4921 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4923 if ($context->contextlevel == CONTEXT_BLOCK) {
4924 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4925 if ($birecord->blockname !== $blockname) {
4926 // somebody tries to gain illegal access, cm type must match the component!
4927 send_file_not_found();
4930 if ($context->get_course_context(false)) {
4931 // If block is in course context, then check if user has capability to access course.
4932 require_course_login($course);
4933 } else if ($CFG->forcelogin) {
4934 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4935 require_login();
4938 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4939 // User can't access file, if block is hidden or doesn't have block:view capability
4940 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4941 send_file_not_found();
4943 } else {
4944 $birecord = null;
4947 $filefunction = $component.'_pluginfile';
4948 if (function_exists($filefunction)) {
4949 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4950 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4953 send_file_not_found();
4955 // ========================================================================================================================
4956 } else if (strpos($component, '_') === false) {
4957 // all core subsystems have to be specified above, no more guessing here!
4958 send_file_not_found();
4960 } else {
4961 // try to serve general plugin file in arbitrary context
4962 $dir = core_component::get_component_directory($component);
4963 if (!file_exists("$dir/lib.php")) {
4964 send_file_not_found();
4966 include_once("$dir/lib.php");
4968 $filefunction = $component.'_pluginfile';
4969 if (function_exists($filefunction)) {
4970 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4971 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4974 send_file_not_found();