Merge branch 'MDL-61960-master' of git://github.com/farhan6318/moodle
[moodle.git] / lib / filelib.php
blob2d189a3963aecc00285e6ce1d4e4c064b6e97287
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 * @category files
459 * @global stdClass $CFG
460 * @param string $text The content that may contain ULRs in need of rewriting.
461 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
462 * @param int $contextid This parameter and the next two identify the file area to use.
463 * @param string $component
464 * @param string $filearea helps identify the file area.
465 * @param int $itemid helps identify the file area.
466 * @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function.
467 * @return string the processed text.
469 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
470 global $CFG;
472 $options = (array)$options;
473 if (!isset($options['forcehttps'])) {
474 $options['forcehttps'] = false;
477 if (!$CFG->slasharguments) {
478 $file = $file . '?file=';
481 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
483 if ($itemid !== null) {
484 $baseurl .= "$itemid/";
487 if ($options['forcehttps']) {
488 $baseurl = str_replace('http://', 'https://', $baseurl);
491 if (!empty($options['reverse'])) {
492 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
493 } else {
494 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
499 * Returns information about files in a draft area.
501 * @global stdClass $CFG
502 * @global stdClass $USER
503 * @param int $draftitemid the draft area item id.
504 * @param string $filepath path to the directory from which the information have to be retrieved.
505 * @return array with the following entries:
506 * 'filecount' => number of files in the draft area.
507 * 'filesize' => total size of the files in the draft area.
508 * 'foldercount' => number of folders in the draft area.
509 * 'filesize_without_references' => total size of the area excluding file references.
510 * (more information will be added as needed).
512 function file_get_draft_area_info($draftitemid, $filepath = '/') {
513 global $USER;
515 $usercontext = context_user::instance($USER->id);
516 return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
520 * Returns information about files in an area.
522 * @param int $contextid context id
523 * @param string $component component
524 * @param string $filearea file area name
525 * @param int $itemid item id or all files if not specified
526 * @param string $filepath path to the directory from which the information have to be retrieved.
527 * @return array with the following entries:
528 * 'filecount' => number of files in the area.
529 * 'filesize' => total size of the files in the area.
530 * 'foldercount' => number of folders in the area.
531 * 'filesize_without_references' => total size of the area excluding file references.
532 * @since Moodle 3.4
534 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
536 $fs = get_file_storage();
538 $results = array(
539 'filecount' => 0,
540 'foldercount' => 0,
541 'filesize' => 0,
542 'filesize_without_references' => 0
545 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
547 foreach ($draftfiles as $file) {
548 if ($file->is_directory()) {
549 $results['foldercount'] += 1;
550 } else {
551 $results['filecount'] += 1;
554 $filesize = $file->get_filesize();
555 $results['filesize'] += $filesize;
556 if (!$file->is_external_file()) {
557 $results['filesize_without_references'] += $filesize;
561 return $results;
565 * Returns whether a draft area has exceeded/will exceed its size limit.
567 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
569 * @param int $draftitemid the draft area item id.
570 * @param int $areamaxbytes the maximum size allowed in this draft area.
571 * @param int $newfilesize the size that would be added to the current area.
572 * @param bool $includereferences true to include the size of the references in the area size.
573 * @return bool true if the area will/has exceeded its limit.
574 * @since Moodle 2.4
576 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
577 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
578 $draftinfo = file_get_draft_area_info($draftitemid);
579 $areasize = $draftinfo['filesize_without_references'];
580 if ($includereferences) {
581 $areasize = $draftinfo['filesize'];
583 if ($areasize + $newfilesize > $areamaxbytes) {
584 return true;
587 return false;
591 * Get used space of files
592 * @global moodle_database $DB
593 * @global stdClass $USER
594 * @return int total bytes
596 function file_get_user_used_space() {
597 global $DB, $USER;
599 $usercontext = context_user::instance($USER->id);
600 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
601 JOIN (SELECT contenthash, filename, MAX(id) AS id
602 FROM {files}
603 WHERE contextid = ? AND component = ? AND filearea != ?
604 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
605 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
606 $record = $DB->get_record_sql($sql, $params);
607 return (int)$record->totalbytes;
611 * Convert any string to a valid filepath
612 * @todo review this function
613 * @param string $str
614 * @return string path
616 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
617 if ($str == '/' or empty($str)) {
618 return '/';
619 } else {
620 return '/'.trim($str, '/').'/';
625 * Generate a folder tree of draft area of current USER recursively
627 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
628 * @param int $draftitemid
629 * @param string $filepath
630 * @param mixed $data
632 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
633 global $USER, $OUTPUT, $CFG;
634 $data->children = array();
635 $context = context_user::instance($USER->id);
636 $fs = get_file_storage();
637 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
638 foreach ($files as $file) {
639 if ($file->is_directory()) {
640 $item = new stdClass();
641 $item->sortorder = $file->get_sortorder();
642 $item->filepath = $file->get_filepath();
644 $foldername = explode('/', trim($item->filepath, '/'));
645 $item->fullname = trim(array_pop($foldername), '/');
647 $item->id = uniqid();
648 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
649 $data->children[] = $item;
650 } else {
651 continue;
658 * Listing all files (including folders) in current path (draft area)
659 * used by file manager
660 * @param int $draftitemid
661 * @param string $filepath
662 * @return stdClass
664 function file_get_drafarea_files($draftitemid, $filepath = '/') {
665 global $USER, $OUTPUT, $CFG;
667 $context = context_user::instance($USER->id);
668 $fs = get_file_storage();
670 $data = new stdClass();
671 $data->path = array();
672 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
674 // will be used to build breadcrumb
675 $trail = '/';
676 if ($filepath !== '/') {
677 $filepath = file_correct_filepath($filepath);
678 $parts = explode('/', $filepath);
679 foreach ($parts as $part) {
680 if ($part != '' && $part != null) {
681 $trail .= ($part.'/');
682 $data->path[] = array('name'=>$part, 'path'=>$trail);
687 $list = array();
688 $maxlength = 12;
689 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
690 foreach ($files as $file) {
691 $item = new stdClass();
692 $item->filename = $file->get_filename();
693 $item->filepath = $file->get_filepath();
694 $item->fullname = trim($item->filename, '/');
695 $filesize = $file->get_filesize();
696 $item->size = $filesize ? $filesize : null;
697 $item->filesize = $filesize ? display_size($filesize) : '';
699 $item->sortorder = $file->get_sortorder();
700 $item->author = $file->get_author();
701 $item->license = $file->get_license();
702 $item->datemodified = $file->get_timemodified();
703 $item->datecreated = $file->get_timecreated();
704 $item->isref = $file->is_external_file();
705 if ($item->isref && $file->get_status() == 666) {
706 $item->originalmissing = true;
708 // find the file this draft file was created from and count all references in local
709 // system pointing to that file
710 $source = @unserialize($file->get_source());
711 if (isset($source->original)) {
712 $item->refcount = $fs->search_references_count($source->original);
715 if ($file->is_directory()) {
716 $item->filesize = 0;
717 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
718 $item->type = 'folder';
719 $foldername = explode('/', trim($item->filepath, '/'));
720 $item->fullname = trim(array_pop($foldername), '/');
721 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
722 } else {
723 // do NOT use file browser here!
724 $item->mimetype = get_mimetype_description($file);
725 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
726 $item->type = 'zip';
727 } else {
728 $item->type = 'file';
730 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
731 $item->url = $itemurl->out();
732 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
733 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
735 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
736 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
737 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
738 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
739 // used by the widget to display a warning about the problem files.
740 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
741 $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
742 if ($item->status == 0) {
743 if ($imageinfo = $file->get_imageinfo()) {
744 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
745 'oid' => $file->get_timemodified()));
746 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
747 $item->image_width = $imageinfo['width'];
748 $item->image_height = $imageinfo['height'];
752 $list[] = $item;
755 $data->itemid = $draftitemid;
756 $data->list = $list;
757 return $data;
761 * Returns all of the files in the draftarea.
763 * @param int $draftitemid The draft item ID
764 * @param string $filepath path for the uploaded files.
765 * @return array An array of files associated with this draft item id.
767 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
768 $files = [];
769 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
770 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
772 if (!empty($draftfiles)) {
773 foreach ($draftfiles->list as $draftfile) {
774 if ($draftfile->type == 'file') {
775 $files[] = $draftfile;
779 if (isset($draftfiles->children)) {
780 foreach ($draftfiles->children as $draftfile) {
781 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
785 return $files;
789 * Returns draft area itemid for a given element.
791 * @category files
792 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
793 * @return int the itemid, or 0 if there is not one yet.
795 function file_get_submitted_draft_itemid($elname) {
796 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
797 if (!isset($_REQUEST[$elname])) {
798 return 0;
800 if (is_array($_REQUEST[$elname])) {
801 $param = optional_param_array($elname, 0, PARAM_INT);
802 if (!empty($param['itemid'])) {
803 $param = $param['itemid'];
804 } else {
805 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
806 return false;
809 } else {
810 $param = optional_param($elname, 0, PARAM_INT);
813 if ($param) {
814 require_sesskey();
817 return $param;
821 * Restore the original source field from draft files
823 * Do not use this function because it makes field files.source inconsistent
824 * for draft area files. This function will be deprecated in 2.6
826 * @param stored_file $storedfile This only works with draft files
827 * @return stored_file
829 function file_restore_source_field_from_draft_file($storedfile) {
830 $source = @unserialize($storedfile->get_source());
831 if (!empty($source)) {
832 if (is_object($source)) {
833 $restoredsource = $source->source;
834 $storedfile->set_source($restoredsource);
835 } else {
836 throw new moodle_exception('invalidsourcefield', 'error');
839 return $storedfile;
843 * Removes those files from the user drafts filearea which are not referenced in the editor text.
845 * @param stdClass $editor The online text editor element from the submitted form data.
847 function file_remove_editor_orphaned_files($editor) {
848 global $CFG, $USER;
850 // Find those draft files included in the text, and generate their hashes.
851 $context = context_user::instance($USER->id);
852 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
853 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
854 preg_match_all($pattern, $editor['text'], $matches);
855 $usedfilehashes = [];
856 foreach ($matches[1] as $matchedfilename) {
857 $matchedfilename = urldecode($matchedfilename);
858 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
859 $matchedfilename);
862 // Now, compare the hashes of all draft files, and remove those which don't match used files.
863 $fs = get_file_storage();
864 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
865 foreach ($files as $file) {
866 $tmphash = $file->get_pathnamehash();
867 if (!in_array($tmphash, $usedfilehashes)) {
868 $file->delete();
874 * Saves files from a draft file area to a real one (merging the list of files).
875 * Can rewrite URLs in some content at the same time if desired.
877 * @category files
878 * @global stdClass $USER
879 * @param int $draftitemid the id of the draft area to use. Normally obtained
880 * from file_get_submitted_draft_itemid('elementname') or similar.
881 * @param int $contextid This parameter and the next two identify the file area to save to.
882 * @param string $component
883 * @param string $filearea indentifies the file area.
884 * @param int $itemid helps identifies the file area.
885 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
886 * @param string $text some html content that needs to have embedded links rewritten
887 * to the @@PLUGINFILE@@ form for saving in the database.
888 * @param bool $forcehttps force https urls.
889 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
891 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
892 global $USER;
894 $usercontext = context_user::instance($USER->id);
895 $fs = get_file_storage();
897 $options = (array)$options;
898 if (!isset($options['subdirs'])) {
899 $options['subdirs'] = false;
901 if (!isset($options['maxfiles'])) {
902 $options['maxfiles'] = -1; // unlimited
904 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
905 $options['maxbytes'] = 0; // unlimited
907 if (!isset($options['areamaxbytes'])) {
908 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
910 $allowreferences = true;
911 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
912 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
913 // this is not exactly right. BUT there are many places in code where filemanager options
914 // are not passed to file_save_draft_area_files()
915 $allowreferences = false;
918 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
919 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
920 // anything at all in the next area.
921 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
922 return null;
925 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
926 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
928 // One file in filearea means it is empty (it has only top-level directory '.').
929 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
930 // we have to merge old and new files - we want to keep file ids for files that were not changed
931 // we change time modified for all new and changed files, we keep time created as is
933 $newhashes = array();
934 $filecount = 0;
935 $context = context::instance_by_id($contextid, MUST_EXIST);
936 foreach ($draftfiles as $file) {
937 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
938 continue;
940 if (!$allowreferences && $file->is_external_file()) {
941 continue;
943 if (!$file->is_directory()) {
944 // Check to see if this file was uploaded by someone who can ignore the file size limits.
945 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
946 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
947 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
948 // Oversized file.
949 continue;
951 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
952 // more files - should not get here at all
953 continue;
955 $filecount++;
957 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
958 $newhashes[$newhash] = $file;
961 // Loop through oldfiles and decide which we need to delete and which to update.
962 // After this cycle the array $newhashes will only contain the files that need to be added.
963 foreach ($oldfiles as $oldfile) {
964 $oldhash = $oldfile->get_pathnamehash();
965 if (!isset($newhashes[$oldhash])) {
966 // delete files not needed any more - deleted by user
967 $oldfile->delete();
968 continue;
971 $newfile = $newhashes[$oldhash];
972 // Now we know that we have $oldfile and $newfile for the same path.
973 // Let's check if we can update this file or we need to delete and create.
974 if ($newfile->is_directory()) {
975 // Directories are always ok to just update.
976 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
977 // File has the 'original' - we need to update the file (it may even have not been changed at all).
978 $original = file_storage::unpack_reference($source->original);
979 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
980 // Very odd, original points to another file. Delete and create file.
981 $oldfile->delete();
982 continue;
984 } else {
985 // The same file name but absence of 'original' means that file was deteled and uploaded again.
986 // By deleting and creating new file we properly manage all existing references.
987 $oldfile->delete();
988 continue;
991 // status changed, we delete old file, and create a new one
992 if ($oldfile->get_status() != $newfile->get_status()) {
993 // file was changed, use updated with new timemodified data
994 $oldfile->delete();
995 // This file will be added later
996 continue;
999 // Updated author
1000 if ($oldfile->get_author() != $newfile->get_author()) {
1001 $oldfile->set_author($newfile->get_author());
1003 // Updated license
1004 if ($oldfile->get_license() != $newfile->get_license()) {
1005 $oldfile->set_license($newfile->get_license());
1008 // Updated file source
1009 // Field files.source for draftarea files contains serialised object with source and original information.
1010 // We only store the source part of it for non-draft file area.
1011 $newsource = $newfile->get_source();
1012 if ($source = @unserialize($newfile->get_source())) {
1013 $newsource = $source->source;
1015 if ($oldfile->get_source() !== $newsource) {
1016 $oldfile->set_source($newsource);
1019 // Updated sort order
1020 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1021 $oldfile->set_sortorder($newfile->get_sortorder());
1024 // Update file timemodified
1025 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1026 $oldfile->set_timemodified($newfile->get_timemodified());
1029 // Replaced file content
1030 if (!$oldfile->is_directory() &&
1031 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1032 $oldfile->get_filesize() != $newfile->get_filesize() ||
1033 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1034 $oldfile->get_userid() != $newfile->get_userid())) {
1035 $oldfile->replace_file_with($newfile);
1038 // unchanged file or directory - we keep it as is
1039 unset($newhashes[$oldhash]);
1042 // Add fresh file or the file which has changed status
1043 // the size and subdirectory tests are extra safety only, the UI should prevent it
1044 foreach ($newhashes as $file) {
1045 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1046 if ($source = @unserialize($file->get_source())) {
1047 // Field files.source for draftarea files contains serialised object with source and original information.
1048 // We only store the source part of it for non-draft file area.
1049 $file_record['source'] = $source->source;
1052 if ($file->is_external_file()) {
1053 $repoid = $file->get_repository_id();
1054 if (!empty($repoid)) {
1055 $context = context::instance_by_id($contextid, MUST_EXIST);
1056 $repo = repository::get_repository_by_id($repoid, $context);
1057 if (!empty($options)) {
1058 $repo->options = $options;
1060 $file_record['repositoryid'] = $repoid;
1061 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1062 // to the file store. E.g. transfer ownership of the file to a system account etc.
1063 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1065 $file_record['reference'] = $reference;
1069 $fs->create_file_from_storedfile($file_record, $file);
1073 // note: do not purge the draft area - we clean up areas later in cron,
1074 // the reason is that user might press submit twice and they would loose the files,
1075 // also sometimes we might want to use hacks that save files into two different areas
1077 if (is_null($text)) {
1078 return null;
1079 } else {
1080 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1085 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1086 * ready to be saved in the database. Normally, this is done automatically by
1087 * {@link file_save_draft_area_files()}.
1089 * @category files
1090 * @param string $text the content to process.
1091 * @param int $draftitemid the draft file area the content was using.
1092 * @param bool $forcehttps whether the content contains https URLs. Default false.
1093 * @return string the processed content.
1095 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1096 global $CFG, $USER;
1098 $usercontext = context_user::instance($USER->id);
1100 $wwwroot = $CFG->wwwroot;
1101 if ($forcehttps) {
1102 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1105 // relink embedded files if text submitted - no absolute links allowed in database!
1106 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1108 if (strpos($text, 'draftfile.php?file=') !== false) {
1109 $matches = array();
1110 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1111 if ($matches) {
1112 foreach ($matches[0] as $match) {
1113 $replace = str_ireplace('%2F', '/', $match);
1114 $text = str_replace($match, $replace, $text);
1117 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1120 return $text;
1124 * Set file sort order
1126 * @global moodle_database $DB
1127 * @param int $contextid the context id
1128 * @param string $component file component
1129 * @param string $filearea file area.
1130 * @param int $itemid itemid.
1131 * @param string $filepath file path.
1132 * @param string $filename file name.
1133 * @param int $sortorder the sort order of file.
1134 * @return bool
1136 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1137 global $DB;
1138 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1139 if ($file_record = $DB->get_record('files', $conditions)) {
1140 $sortorder = (int)$sortorder;
1141 $file_record->sortorder = $sortorder;
1142 $DB->update_record('files', $file_record);
1143 return true;
1145 return false;
1149 * reset file sort order number to 0
1150 * @global moodle_database $DB
1151 * @param int $contextid the context id
1152 * @param string $component
1153 * @param string $filearea file area.
1154 * @param int|bool $itemid itemid.
1155 * @return bool
1157 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1158 global $DB;
1160 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1161 if ($itemid !== false) {
1162 $conditions['itemid'] = $itemid;
1165 $file_records = $DB->get_records('files', $conditions);
1166 foreach ($file_records as $file_record) {
1167 $file_record->sortorder = 0;
1168 $DB->update_record('files', $file_record);
1170 return true;
1174 * Returns description of upload error
1176 * @param int $errorcode found in $_FILES['filename.ext']['error']
1177 * @return string error description string, '' if ok
1179 function file_get_upload_error($errorcode) {
1181 switch ($errorcode) {
1182 case 0: // UPLOAD_ERR_OK - no error
1183 $errmessage = '';
1184 break;
1186 case 1: // UPLOAD_ERR_INI_SIZE
1187 $errmessage = get_string('uploadserverlimit');
1188 break;
1190 case 2: // UPLOAD_ERR_FORM_SIZE
1191 $errmessage = get_string('uploadformlimit');
1192 break;
1194 case 3: // UPLOAD_ERR_PARTIAL
1195 $errmessage = get_string('uploadpartialfile');
1196 break;
1198 case 4: // UPLOAD_ERR_NO_FILE
1199 $errmessage = get_string('uploadnofilefound');
1200 break;
1202 // Note: there is no error with a value of 5
1204 case 6: // UPLOAD_ERR_NO_TMP_DIR
1205 $errmessage = get_string('uploadnotempdir');
1206 break;
1208 case 7: // UPLOAD_ERR_CANT_WRITE
1209 $errmessage = get_string('uploadcantwrite');
1210 break;
1212 case 8: // UPLOAD_ERR_EXTENSION
1213 $errmessage = get_string('uploadextension');
1214 break;
1216 default:
1217 $errmessage = get_string('uploadproblem');
1220 return $errmessage;
1224 * Recursive function formating an array in POST parameter
1225 * @param array $arraydata - the array that we are going to format and add into &$data array
1226 * @param string $currentdata - a row of the final postdata array at instant T
1227 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1228 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1230 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1231 foreach ($arraydata as $k=>$v) {
1232 $newcurrentdata = $currentdata;
1233 if (is_array($v)) { //the value is an array, call the function recursively
1234 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1235 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1236 } else { //add the POST parameter to the $data array
1237 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1243 * Transform a PHP array into POST parameter
1244 * (see the recursive function format_array_postdata_for_curlcall)
1245 * @param array $postdata
1246 * @return array containing all POST parameters (1 row = 1 POST parameter)
1248 function format_postdata_for_curlcall($postdata) {
1249 $data = array();
1250 foreach ($postdata as $k=>$v) {
1251 if (is_array($v)) {
1252 $currentdata = urlencode($k);
1253 format_array_postdata_for_curlcall($v, $currentdata, $data);
1254 } else {
1255 $data[] = urlencode($k).'='.urlencode($v);
1258 $convertedpostdata = implode('&', $data);
1259 return $convertedpostdata;
1263 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1264 * Due to security concerns only downloads from http(s) sources are supported.
1266 * @category files
1267 * @param string $url file url starting with http(s)://
1268 * @param array $headers http headers, null if none. If set, should be an
1269 * associative array of header name => value pairs.
1270 * @param array $postdata array means use POST request with given parameters
1271 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1272 * (if false, just returns content)
1273 * @param int $timeout timeout for complete download process including all file transfer
1274 * (default 5 minutes)
1275 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1276 * usually happens if the remote server is completely down (default 20 seconds);
1277 * may not work when using proxy
1278 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1279 * Only use this when already in a trusted location.
1280 * @param string $tofile store the downloaded content to file instead of returning it.
1281 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1282 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1283 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1284 * if file downloaded into $tofile successfully or the file content as a string.
1286 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1287 global $CFG;
1289 // Only http and https links supported.
1290 if (!preg_match('|^https?://|i', $url)) {
1291 if ($fullresponse) {
1292 $response = new stdClass();
1293 $response->status = 0;
1294 $response->headers = array();
1295 $response->response_code = 'Invalid protocol specified in url';
1296 $response->results = '';
1297 $response->error = 'Invalid protocol specified in url';
1298 return $response;
1299 } else {
1300 return false;
1304 $options = array();
1306 $headers2 = array();
1307 if (is_array($headers)) {
1308 foreach ($headers as $key => $value) {
1309 if (is_numeric($key)) {
1310 $headers2[] = $value;
1311 } else {
1312 $headers2[] = "$key: $value";
1317 if ($skipcertverify) {
1318 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1319 } else {
1320 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1323 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1325 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1326 $options['CURLOPT_MAXREDIRS'] = 5;
1328 // Use POST if requested.
1329 if (is_array($postdata)) {
1330 $postdata = format_postdata_for_curlcall($postdata);
1331 } else if (empty($postdata)) {
1332 $postdata = null;
1335 // Optionally attempt to get more correct timeout by fetching the file size.
1336 if (!isset($CFG->curltimeoutkbitrate)) {
1337 // Use very slow rate of 56kbps as a timeout speed when not set.
1338 $bitrate = 56;
1339 } else {
1340 $bitrate = $CFG->curltimeoutkbitrate;
1342 if ($calctimeout and !isset($postdata)) {
1343 $curl = new curl();
1344 $curl->setHeader($headers2);
1346 $curl->head($url, $postdata, $options);
1348 $info = $curl->get_info();
1349 $error_no = $curl->get_errno();
1350 if (!$error_no && $info['download_content_length'] > 0) {
1351 // No curl errors - adjust for large files only - take max timeout.
1352 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1356 $curl = new curl();
1357 $curl->setHeader($headers2);
1359 $options['CURLOPT_RETURNTRANSFER'] = true;
1360 $options['CURLOPT_NOBODY'] = false;
1361 $options['CURLOPT_TIMEOUT'] = $timeout;
1363 if ($tofile) {
1364 $fh = fopen($tofile, 'w');
1365 if (!$fh) {
1366 if ($fullresponse) {
1367 $response = new stdClass();
1368 $response->status = 0;
1369 $response->headers = array();
1370 $response->response_code = 'Can not write to file';
1371 $response->results = false;
1372 $response->error = 'Can not write to file';
1373 return $response;
1374 } else {
1375 return false;
1378 $options['CURLOPT_FILE'] = $fh;
1381 if (isset($postdata)) {
1382 $content = $curl->post($url, $postdata, $options);
1383 } else {
1384 $content = $curl->get($url, null, $options);
1387 if ($tofile) {
1388 fclose($fh);
1389 @chmod($tofile, $CFG->filepermissions);
1393 // Try to detect encoding problems.
1394 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1395 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1396 $result = curl_exec($ch);
1400 $info = $curl->get_info();
1401 $error_no = $curl->get_errno();
1402 $rawheaders = $curl->get_raw_response();
1404 if ($error_no) {
1405 $error = $content;
1406 if (!$fullresponse) {
1407 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1408 return false;
1411 $response = new stdClass();
1412 if ($error_no == 28) {
1413 $response->status = '-100'; // Mimic snoopy.
1414 } else {
1415 $response->status = '0';
1417 $response->headers = array();
1418 $response->response_code = $error;
1419 $response->results = false;
1420 $response->error = $error;
1421 return $response;
1424 if ($tofile) {
1425 $content = true;
1428 if (empty($info['http_code'])) {
1429 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1430 $response = new stdClass();
1431 $response->status = '0';
1432 $response->headers = array();
1433 $response->response_code = 'Unknown cURL error';
1434 $response->results = false; // do NOT change this, we really want to ignore the result!
1435 $response->error = 'Unknown cURL error';
1437 } else {
1438 $response = new stdClass();
1439 $response->status = (string)$info['http_code'];
1440 $response->headers = $rawheaders;
1441 $response->results = $content;
1442 $response->error = '';
1444 // There might be multiple headers on redirect, find the status of the last one.
1445 $firstline = true;
1446 foreach ($rawheaders as $line) {
1447 if ($firstline) {
1448 $response->response_code = $line;
1449 $firstline = false;
1451 if (trim($line, "\r\n") === '') {
1452 $firstline = true;
1457 if ($fullresponse) {
1458 return $response;
1461 if ($info['http_code'] != 200) {
1462 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1463 return false;
1465 return $response->results;
1469 * Returns a list of information about file types based on extensions.
1471 * The following elements expected in value array for each extension:
1472 * 'type' - mimetype
1473 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1474 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1475 * also files with bigger sizes under names
1476 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1477 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1478 * commonly used in moodle the following groups:
1479 * - web_image - image that can be included as <img> in HTML
1480 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1481 * - video - file that can be imported as video in text editor
1482 * - audio - file that can be imported as audio in text editor
1483 * - archive - we can extract files from this archive
1484 * - spreadsheet - used for portfolio format
1485 * - document - used for portfolio format
1486 * - presentation - used for portfolio format
1487 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1488 * human-readable description for this filetype;
1489 * Function {@link get_mimetype_description()} first looks at the presence of string for
1490 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1491 * attribute, if not found returns the value of 'type';
1492 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1493 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1494 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1496 * @category files
1497 * @return array List of information about file types based on extensions.
1498 * Associative array of extension (lower-case) to associative array
1499 * from 'element name' to data. Current element names are 'type' and 'icon'.
1500 * Unknown types should use the 'xxx' entry which includes defaults.
1502 function &get_mimetypes_array() {
1503 // Get types from the core_filetypes function, which includes caching.
1504 return core_filetypes::get_types();
1508 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1510 * This function retrieves a file's MIME type for a file that will be sent to the user.
1511 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1512 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1513 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1515 * @param string $filename The file's filename.
1516 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1518 function get_mimetype_for_sending($filename = '') {
1519 // Guess the file's MIME type using mimeinfo.
1520 $mimetype = mimeinfo('type', $filename);
1522 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1523 if (!$mimetype || $mimetype === 'document/unknown') {
1524 $mimetype = 'application/octet-stream';
1527 return $mimetype;
1531 * Obtains information about a filetype based on its extension. Will
1532 * use a default if no information is present about that particular
1533 * extension.
1535 * @category files
1536 * @param string $element Desired information (usually 'icon'
1537 * for icon filename or 'type' for MIME type. Can also be
1538 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1539 * @param string $filename Filename we're looking up
1540 * @return string Requested piece of information from array
1542 function mimeinfo($element, $filename) {
1543 global $CFG;
1544 $mimeinfo = & get_mimetypes_array();
1545 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1547 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1548 if (empty($filetype)) {
1549 $filetype = 'xxx'; // file without extension
1551 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1552 $iconsize = max(array(16, (int)$iconsizematch[1]));
1553 $filenames = array($mimeinfo['xxx']['icon']);
1554 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1555 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1557 // find the file with the closest size, first search for specific icon then for default icon
1558 foreach ($filenames as $filename) {
1559 foreach ($iconpostfixes as $size => $postfix) {
1560 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1561 if ($iconsize >= $size &&
1562 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1563 return $filename.$postfix;
1567 } else if (isset($mimeinfo[$filetype][$element])) {
1568 return $mimeinfo[$filetype][$element];
1569 } else if (isset($mimeinfo['xxx'][$element])) {
1570 return $mimeinfo['xxx'][$element]; // By default
1571 } else {
1572 return null;
1577 * Obtains information about a filetype based on the MIME type rather than
1578 * the other way around.
1580 * @category files
1581 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1582 * @param string $mimetype MIME type we're looking up
1583 * @return string Requested piece of information from array
1585 function mimeinfo_from_type($element, $mimetype) {
1586 /* array of cached mimetype->extension associations */
1587 static $cached = array();
1588 $mimeinfo = & get_mimetypes_array();
1590 if (!array_key_exists($mimetype, $cached)) {
1591 $cached[$mimetype] = null;
1592 foreach($mimeinfo as $filetype => $values) {
1593 if ($values['type'] == $mimetype) {
1594 if ($cached[$mimetype] === null) {
1595 $cached[$mimetype] = '.'.$filetype;
1597 if (!empty($values['defaulticon'])) {
1598 $cached[$mimetype] = '.'.$filetype;
1599 break;
1603 if (empty($cached[$mimetype])) {
1604 $cached[$mimetype] = '.xxx';
1607 if ($element === 'extension') {
1608 return $cached[$mimetype];
1609 } else {
1610 return mimeinfo($element, $cached[$mimetype]);
1615 * Return the relative icon path for a given file
1617 * Usage:
1618 * <code>
1619 * // $file - instance of stored_file or file_info
1620 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1621 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1622 * </code>
1623 * or
1624 * <code>
1625 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1626 * </code>
1628 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1629 * and $file->mimetype are expected)
1630 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1631 * @return string
1633 function file_file_icon($file, $size = null) {
1634 if (!is_object($file)) {
1635 $file = (object)$file;
1637 if (isset($file->filename)) {
1638 $filename = $file->filename;
1639 } else if (method_exists($file, 'get_filename')) {
1640 $filename = $file->get_filename();
1641 } else if (method_exists($file, 'get_visible_name')) {
1642 $filename = $file->get_visible_name();
1643 } else {
1644 $filename = '';
1646 if (isset($file->mimetype)) {
1647 $mimetype = $file->mimetype;
1648 } else if (method_exists($file, 'get_mimetype')) {
1649 $mimetype = $file->get_mimetype();
1650 } else {
1651 $mimetype = '';
1653 $mimetypes = &get_mimetypes_array();
1654 if ($filename) {
1655 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1656 if ($extension && !empty($mimetypes[$extension])) {
1657 // if file name has known extension, return icon for this extension
1658 return file_extension_icon($filename, $size);
1661 return file_mimetype_icon($mimetype, $size);
1665 * Return the relative icon path for a folder image
1667 * Usage:
1668 * <code>
1669 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1670 * echo html_writer::empty_tag('img', array('src' => $icon));
1671 * </code>
1672 * or
1673 * <code>
1674 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1675 * </code>
1677 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1678 * @return string
1680 function file_folder_icon($iconsize = null) {
1681 global $CFG;
1682 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1683 static $cached = array();
1684 $iconsize = max(array(16, (int)$iconsize));
1685 if (!array_key_exists($iconsize, $cached)) {
1686 foreach ($iconpostfixes as $size => $postfix) {
1687 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1688 if ($iconsize >= $size &&
1689 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1690 $cached[$iconsize] = 'f/folder'.$postfix;
1691 break;
1695 return $cached[$iconsize];
1699 * Returns the relative icon path for a given mime type
1701 * This function should be used in conjunction with $OUTPUT->image_url to produce
1702 * a return the full path to an icon.
1704 * <code>
1705 * $mimetype = 'image/jpg';
1706 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1707 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1708 * </code>
1710 * @category files
1711 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1712 * to conform with that.
1713 * @param string $mimetype The mimetype to fetch an icon for
1714 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1715 * @return string The relative path to the icon
1717 function file_mimetype_icon($mimetype, $size = NULL) {
1718 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1722 * Returns the relative icon path for a given file name
1724 * This function should be used in conjunction with $OUTPUT->image_url to produce
1725 * a return the full path to an icon.
1727 * <code>
1728 * $filename = '.jpg';
1729 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1730 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1731 * </code>
1733 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1734 * to conform with that.
1735 * @todo MDL-31074 Implement $size
1736 * @category files
1737 * @param string $filename The filename to get the icon for
1738 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1739 * @return string
1741 function file_extension_icon($filename, $size = NULL) {
1742 return 'f/'.mimeinfo('icon'.$size, $filename);
1746 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1747 * mimetypes.php language file.
1749 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1750 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1751 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1752 * @param bool $capitalise If true, capitalises first character of result
1753 * @return string Text description
1755 function get_mimetype_description($obj, $capitalise=false) {
1756 $filename = $mimetype = '';
1757 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1758 // this is an instance of stored_file
1759 $mimetype = $obj->get_mimetype();
1760 $filename = $obj->get_filename();
1761 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1762 // this is an instance of file_info
1763 $mimetype = $obj->get_mimetype();
1764 $filename = $obj->get_visible_name();
1765 } else if (is_array($obj) || is_object ($obj)) {
1766 $obj = (array)$obj;
1767 if (!empty($obj['filename'])) {
1768 $filename = $obj['filename'];
1770 if (!empty($obj['mimetype'])) {
1771 $mimetype = $obj['mimetype'];
1773 } else {
1774 $mimetype = $obj;
1776 $mimetypefromext = mimeinfo('type', $filename);
1777 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1778 // if file has a known extension, overwrite the specified mimetype
1779 $mimetype = $mimetypefromext;
1781 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1782 if (empty($extension)) {
1783 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1784 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1785 } else {
1786 $mimetypestr = mimeinfo('string', $filename);
1788 $chunks = explode('/', $mimetype, 2);
1789 $chunks[] = '';
1790 $attr = array(
1791 'mimetype' => $mimetype,
1792 'ext' => $extension,
1793 'mimetype1' => $chunks[0],
1794 'mimetype2' => $chunks[1],
1796 $a = array();
1797 foreach ($attr as $key => $value) {
1798 $a[$key] = $value;
1799 $a[strtoupper($key)] = strtoupper($value);
1800 $a[ucfirst($key)] = ucfirst($value);
1803 // MIME types may include + symbol but this is not permitted in string ids.
1804 $safemimetype = str_replace('+', '_', $mimetype);
1805 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1806 $customdescription = mimeinfo('customdescription', $filename);
1807 if ($customdescription) {
1808 // Call format_string on the custom description so that multilang
1809 // filter can be used (if enabled on system context). We use system
1810 // context because it is possible that the page context might not have
1811 // been defined yet.
1812 $result = format_string($customdescription, true,
1813 array('context' => context_system::instance()));
1814 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1815 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1816 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1817 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1818 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1819 $result = get_string('default', 'mimetypes', (object)$a);
1820 } else {
1821 $result = $mimetype;
1823 if ($capitalise) {
1824 $result=ucfirst($result);
1826 return $result;
1830 * Returns array of elements of type $element in type group(s)
1832 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1833 * @param string|array $groups one group or array of groups/extensions/mimetypes
1834 * @return array
1836 function file_get_typegroup($element, $groups) {
1837 static $cached = array();
1838 if (!is_array($groups)) {
1839 $groups = array($groups);
1841 if (!array_key_exists($element, $cached)) {
1842 $cached[$element] = array();
1844 $result = array();
1845 foreach ($groups as $group) {
1846 if (!array_key_exists($group, $cached[$element])) {
1847 // retrieive and cache all elements of type $element for group $group
1848 $mimeinfo = & get_mimetypes_array();
1849 $cached[$element][$group] = array();
1850 foreach ($mimeinfo as $extension => $value) {
1851 $value['extension'] = '.'.$extension;
1852 if (empty($value[$element])) {
1853 continue;
1855 if (($group === '.'.$extension || $group === $value['type'] ||
1856 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1857 !in_array($value[$element], $cached[$element][$group])) {
1858 $cached[$element][$group][] = $value[$element];
1862 $result = array_merge($result, $cached[$element][$group]);
1864 return array_values(array_unique($result));
1868 * Checks if file with name $filename has one of the extensions in groups $groups
1870 * @see get_mimetypes_array()
1871 * @param string $filename name of the file to check
1872 * @param string|array $groups one group or array of groups to check
1873 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1874 * file mimetype is in mimetypes in groups $groups
1875 * @return bool
1877 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1878 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1879 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1880 return true;
1882 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1886 * Checks if mimetype $mimetype belongs to one of the groups $groups
1888 * @see get_mimetypes_array()
1889 * @param string $mimetype
1890 * @param string|array $groups one group or array of groups to check
1891 * @return bool
1893 function file_mimetype_in_typegroup($mimetype, $groups) {
1894 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1898 * Requested file is not found or not accessible, does not return, terminates script
1900 * @global stdClass $CFG
1901 * @global stdClass $COURSE
1903 function send_file_not_found() {
1904 global $CFG, $COURSE;
1906 // Allow cross-origin requests only for Web Services.
1907 // This allow to receive requests done by Web Workers or webapps in different domains.
1908 if (WS_SERVER) {
1909 header('Access-Control-Allow-Origin: *');
1912 send_header_404();
1913 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1916 * Helper function to send correct 404 for server.
1918 function send_header_404() {
1919 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1920 header("Status: 404 Not Found");
1921 } else {
1922 header('HTTP/1.0 404 not found');
1927 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1928 * platforms). This wrapper uses readfile for small files and custom code for
1929 * large ones.
1931 * @param string $path Path to file
1932 * @param int $filesize Size of file (if left out, will get it automatically)
1933 * @return int|bool Size read (will always be $filesize) or false if failed
1935 function readfile_allow_large($path, $filesize = -1) {
1936 // Automatically get size if not specified.
1937 if ($filesize === -1) {
1938 $filesize = filesize($path);
1940 if ($filesize <= 2147483647) {
1941 // If the file is up to 2^31 - 1, send it normally using readfile.
1942 return readfile($path);
1943 } else {
1944 // For large files, read and output in 64KB chunks.
1945 $handle = fopen($path, 'r');
1946 if ($handle === false) {
1947 return false;
1949 $left = $filesize;
1950 while ($left > 0) {
1951 $size = min($left, 65536);
1952 $buffer = fread($handle, $size);
1953 if ($buffer === false) {
1954 return false;
1956 echo $buffer;
1957 $left -= $size;
1959 return $filesize;
1964 * Enhanced readfile() with optional acceleration.
1965 * @param string|stored_file $file
1966 * @param string $mimetype
1967 * @param bool $accelerate
1968 * @return void
1970 function readfile_accel($file, $mimetype, $accelerate) {
1971 global $CFG;
1973 if ($mimetype === 'text/plain') {
1974 // there is no encoding specified in text files, we need something consistent
1975 header('Content-Type: text/plain; charset=utf-8');
1976 } else {
1977 header('Content-Type: '.$mimetype);
1980 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1981 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1983 if (is_object($file)) {
1984 header('Etag: "' . $file->get_contenthash() . '"');
1985 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1986 header('HTTP/1.1 304 Not Modified');
1987 return;
1991 // if etag present for stored file rely on it exclusively
1992 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1993 // get unixtime of request header; clip extra junk off first
1994 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1995 if ($since && $since >= $lastmodified) {
1996 header('HTTP/1.1 304 Not Modified');
1997 return;
2001 if ($accelerate and !empty($CFG->xsendfile)) {
2002 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2003 header('Accept-Ranges: bytes');
2004 } else {
2005 header('Accept-Ranges: none');
2008 if (is_object($file)) {
2009 $fs = get_file_storage();
2010 if ($fs->xsendfile($file->get_contenthash())) {
2011 return;
2014 } else {
2015 require_once("$CFG->libdir/xsendfilelib.php");
2016 if (xsendfile($file)) {
2017 return;
2022 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2024 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2026 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2027 header('Accept-Ranges: bytes');
2029 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2030 // byteserving stuff - for acrobat reader and download accelerators
2031 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2032 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2033 $ranges = false;
2034 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2035 foreach ($ranges as $key=>$value) {
2036 if ($ranges[$key][1] == '') {
2037 //suffix case
2038 $ranges[$key][1] = $filesize - $ranges[$key][2];
2039 $ranges[$key][2] = $filesize - 1;
2040 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2041 //fix range length
2042 $ranges[$key][2] = $filesize - 1;
2044 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2045 //invalid byte-range ==> ignore header
2046 $ranges = false;
2047 break;
2049 //prepare multipart header
2050 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2051 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2053 } else {
2054 $ranges = false;
2056 if ($ranges) {
2057 if (is_object($file)) {
2058 $handle = $file->get_content_file_handle();
2059 } else {
2060 $handle = fopen($file, 'rb');
2062 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2065 } else {
2066 // Do not byteserve
2067 header('Accept-Ranges: none');
2070 header('Content-Length: '.$filesize);
2072 if ($filesize > 10000000) {
2073 // for large files try to flush and close all buffers to conserve memory
2074 while(@ob_get_level()) {
2075 if (!@ob_end_flush()) {
2076 break;
2081 // send the whole file content
2082 if (is_object($file)) {
2083 $file->readfile();
2084 } else {
2085 readfile_allow_large($file, $filesize);
2090 * Similar to readfile_accel() but designed for strings.
2091 * @param string $string
2092 * @param string $mimetype
2093 * @param bool $accelerate
2094 * @return void
2096 function readstring_accel($string, $mimetype, $accelerate) {
2097 global $CFG;
2099 if ($mimetype === 'text/plain') {
2100 // there is no encoding specified in text files, we need something consistent
2101 header('Content-Type: text/plain; charset=utf-8');
2102 } else {
2103 header('Content-Type: '.$mimetype);
2105 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2106 header('Accept-Ranges: none');
2108 if ($accelerate and !empty($CFG->xsendfile)) {
2109 $fs = get_file_storage();
2110 if ($fs->xsendfile(sha1($string))) {
2111 return;
2115 header('Content-Length: '.strlen($string));
2116 echo $string;
2120 * Handles the sending of temporary file to user, download is forced.
2121 * File is deleted after abort or successful sending, does not return, script terminated
2123 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2124 * @param string $filename proposed file name when saving file
2125 * @param bool $pathisstring If the path is string
2127 function send_temp_file($path, $filename, $pathisstring=false) {
2128 global $CFG;
2130 // Guess the file's MIME type.
2131 $mimetype = get_mimetype_for_sending($filename);
2133 // close session - not needed anymore
2134 \core\session\manager::write_close();
2136 if (!$pathisstring) {
2137 if (!file_exists($path)) {
2138 send_header_404();
2139 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2141 // executed after normal finish or abort
2142 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2145 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2146 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2147 $filename = urlencode($filename);
2150 header('Content-Disposition: attachment; filename="'.$filename.'"');
2151 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2152 header('Cache-Control: private, max-age=10, no-transform');
2153 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2154 header('Pragma: ');
2155 } else { //normal http - prevent caching at all cost
2156 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2157 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2158 header('Pragma: no-cache');
2161 // send the contents - we can not accelerate this because the file will be deleted asap
2162 if ($pathisstring) {
2163 readstring_accel($path, $mimetype, false);
2164 } else {
2165 readfile_accel($path, $mimetype, false);
2166 @unlink($path);
2169 die; //no more chars to output
2173 * Internal callback function used by send_temp_file()
2175 * @param string $path
2177 function send_temp_file_finished($path) {
2178 if (file_exists($path)) {
2179 @unlink($path);
2184 * Serve content which is not meant to be cached.
2186 * This is only intended to be used for volatile public files, for instance
2187 * when development is enabled, or when caching is not required on a public resource.
2189 * @param string $content Raw content.
2190 * @param string $filename The file name.
2191 * @return void
2193 function send_content_uncached($content, $filename) {
2194 $mimetype = mimeinfo('type', $filename);
2195 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2197 header('Content-Disposition: inline; filename="' . $filename . '"');
2198 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2199 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2200 header('Pragma: ');
2201 header('Accept-Ranges: none');
2202 header('Content-Type: ' . $mimetype . $charset);
2203 header('Content-Length: ' . strlen($content));
2205 echo $content;
2206 die();
2210 * Safely save content to a certain path.
2212 * This function tries hard to be atomic by first copying the content
2213 * to a separate file, and then moving the file across. It also prevents
2214 * the user to abort a request to prevent half-safed files.
2216 * This function is intended to be used when saving some content to cache like
2217 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2219 * @param string $content The file content.
2220 * @param string $destination The absolute path of the final file.
2221 * @return void
2223 function file_safe_save_content($content, $destination) {
2224 global $CFG;
2226 clearstatcache();
2227 if (!file_exists(dirname($destination))) {
2228 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2231 // Prevent serving of incomplete file from concurrent request,
2232 // the rename() should be more atomic than fwrite().
2233 ignore_user_abort(true);
2234 if ($fp = fopen($destination . '.tmp', 'xb')) {
2235 fwrite($fp, $content);
2236 fclose($fp);
2237 rename($destination . '.tmp', $destination);
2238 @chmod($destination, $CFG->filepermissions);
2239 @unlink($destination . '.tmp'); // Just in case anything fails.
2241 ignore_user_abort(false);
2242 if (connection_aborted()) {
2243 die();
2248 * Handles the sending of file data to the user's browser, including support for
2249 * byteranges etc.
2251 * @category files
2252 * @param string|stored_file $path Path of file on disk (including real filename),
2253 * or actual content of file as string,
2254 * or stored_file object
2255 * @param string $filename Filename to send
2256 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2257 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2258 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2259 * Forced to false when $path is a stored_file object.
2260 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2261 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2262 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2263 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2264 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2265 * and should not be reopened.
2266 * @param array $options An array of options, currently accepts:
2267 * - (string) cacheability: public, or private.
2268 * - (string|null) immutable
2269 * @return null script execution stopped unless $dontdie is true
2271 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2272 $dontdie=false, array $options = array()) {
2273 global $CFG, $COURSE;
2275 if ($dontdie) {
2276 ignore_user_abort(true);
2279 if ($lifetime === 'default' or is_null($lifetime)) {
2280 $lifetime = $CFG->filelifetime;
2283 if (is_object($path)) {
2284 $pathisstring = false;
2287 \core\session\manager::write_close(); // Unlock session during file serving.
2289 // Use given MIME type if specified, otherwise guess it.
2290 if (!$mimetype || $mimetype === 'document/unknown') {
2291 $mimetype = get_mimetype_for_sending($filename);
2294 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2295 if (core_useragent::is_ie() || core_useragent::is_edge()) {
2296 $filename = rawurlencode($filename);
2299 if ($forcedownload) {
2300 header('Content-Disposition: attachment; filename="'.$filename.'"');
2301 } else if ($mimetype !== 'application/x-shockwave-flash') {
2302 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2303 // as an upload and enforces security that may prevent the file from being loaded.
2305 header('Content-Disposition: inline; filename="'.$filename.'"');
2308 if ($lifetime > 0) {
2309 $immutable = '';
2310 if (!empty($options['immutable'])) {
2311 $immutable = ', immutable';
2312 // Overwrite lifetime accordingly:
2313 // 90 days only - based on Moodle point release cadence being every 3 months.
2314 $lifetimemin = 60 * 60 * 24 * 90;
2315 $lifetime = max($lifetime, $lifetimemin);
2317 $cacheability = ' public,';
2318 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2319 // This file must be cache-able by both browsers and proxies.
2320 $cacheability = ' public,';
2321 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2322 // This file must be cache-able only by browsers.
2323 $cacheability = ' private,';
2324 } else if (isloggedin() and !isguestuser()) {
2325 // By default, under the conditions above, this file must be cache-able only by browsers.
2326 $cacheability = ' private,';
2328 $nobyteserving = false;
2329 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2330 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2331 header('Pragma: ');
2333 } else { // Do not cache files in proxies and browsers
2334 $nobyteserving = true;
2335 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2336 header('Cache-Control: private, max-age=10, no-transform');
2337 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2338 header('Pragma: ');
2339 } else { //normal http - prevent caching at all cost
2340 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2341 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2342 header('Pragma: no-cache');
2346 if (empty($filter)) {
2347 // send the contents
2348 if ($pathisstring) {
2349 readstring_accel($path, $mimetype, !$dontdie);
2350 } else {
2351 readfile_accel($path, $mimetype, !$dontdie);
2354 } else {
2355 // Try to put the file through filters
2356 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2357 $options = new stdClass();
2358 $options->noclean = true;
2359 $options->nocache = true; // temporary workaround for MDL-5136
2360 if (is_object($path)) {
2361 $text = $path->get_content();
2362 } else if ($pathisstring) {
2363 $text = $path;
2364 } else {
2365 $text = implode('', file($path));
2367 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2369 readstring_accel($output, $mimetype, false);
2371 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2372 // only filter text if filter all files is selected
2373 $options = new stdClass();
2374 $options->newlines = false;
2375 $options->noclean = true;
2376 if (is_object($path)) {
2377 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2378 } else if ($pathisstring) {
2379 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2380 } else {
2381 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2383 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2385 readstring_accel($output, $mimetype, false);
2387 } else {
2388 // send the contents
2389 if ($pathisstring) {
2390 readstring_accel($path, $mimetype, !$dontdie);
2391 } else {
2392 readfile_accel($path, $mimetype, !$dontdie);
2396 if ($dontdie) {
2397 return;
2399 die; //no more chars to output!!!
2403 * Handles the sending of file data to the user's browser, including support for
2404 * byteranges etc.
2406 * The $options parameter supports the following keys:
2407 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2408 * (string|null) filename - overrides the implicit filename
2409 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2410 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2411 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2412 * and should not be reopened
2413 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2414 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2415 * defaults to "public".
2416 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2417 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2419 * @category files
2420 * @param stored_file $stored_file local file object
2421 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2422 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2423 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2424 * @param array $options additional options affecting the file serving
2425 * @return null script execution stopped unless $options['dontdie'] is true
2427 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2428 global $CFG, $COURSE;
2430 if (empty($options['filename'])) {
2431 $filename = null;
2432 } else {
2433 $filename = $options['filename'];
2436 if (empty($options['dontdie'])) {
2437 $dontdie = false;
2438 } else {
2439 $dontdie = true;
2442 if ($lifetime === 'default' or is_null($lifetime)) {
2443 $lifetime = $CFG->filelifetime;
2446 if (!empty($options['preview'])) {
2447 // replace the file with its preview
2448 $fs = get_file_storage();
2449 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2450 if (!$preview_file) {
2451 // unable to create a preview of the file, send its default mime icon instead
2452 if ($options['preview'] === 'tinyicon') {
2453 $size = 24;
2454 } else if ($options['preview'] === 'thumb') {
2455 $size = 90;
2456 } else {
2457 $size = 256;
2459 $fileicon = file_file_icon($stored_file, $size);
2460 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2461 } else {
2462 // preview images have fixed cache lifetime and they ignore forced download
2463 // (they are generated by GD and therefore they are considered reasonably safe).
2464 $stored_file = $preview_file;
2465 $lifetime = DAYSECS;
2466 $filter = 0;
2467 $forcedownload = false;
2471 // handle external resource
2472 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2473 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2474 die;
2477 if (!$stored_file or $stored_file->is_directory()) {
2478 // nothing to serve
2479 if ($dontdie) {
2480 return;
2482 die;
2485 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2487 // Use given MIME type if specified.
2488 $mimetype = $stored_file->get_mimetype();
2490 // Allow cross-origin requests only for Web Services.
2491 // This allow to receive requests done by Web Workers or webapps in different domains.
2492 if (WS_SERVER) {
2493 header('Access-Control-Allow-Origin: *');
2496 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2500 * Recursively delete the file or folder with path $location. That is,
2501 * if it is a file delete it. If it is a folder, delete all its content
2502 * then delete it. If $location does not exist to start, that is not
2503 * considered an error.
2505 * @param string $location the path to remove.
2506 * @return bool
2508 function fulldelete($location) {
2509 if (empty($location)) {
2510 // extra safety against wrong param
2511 return false;
2513 if (is_dir($location)) {
2514 if (!$currdir = opendir($location)) {
2515 return false;
2517 while (false !== ($file = readdir($currdir))) {
2518 if ($file <> ".." && $file <> ".") {
2519 $fullfile = $location."/".$file;
2520 if (is_dir($fullfile)) {
2521 if (!fulldelete($fullfile)) {
2522 return false;
2524 } else {
2525 if (!unlink($fullfile)) {
2526 return false;
2531 closedir($currdir);
2532 if (! rmdir($location)) {
2533 return false;
2536 } else if (file_exists($location)) {
2537 if (!unlink($location)) {
2538 return false;
2541 return true;
2545 * Send requested byterange of file.
2547 * @param resource $handle A file handle
2548 * @param string $mimetype The mimetype for the output
2549 * @param array $ranges An array of ranges to send
2550 * @param string $filesize The size of the content if only one range is used
2552 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2553 // better turn off any kind of compression and buffering
2554 ini_set('zlib.output_compression', 'Off');
2556 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2557 if ($handle === false) {
2558 die;
2560 if (count($ranges) == 1) { //only one range requested
2561 $length = $ranges[0][2] - $ranges[0][1] + 1;
2562 header('HTTP/1.1 206 Partial content');
2563 header('Content-Length: '.$length);
2564 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2565 header('Content-Type: '.$mimetype);
2567 while(@ob_get_level()) {
2568 if (!@ob_end_flush()) {
2569 break;
2573 fseek($handle, $ranges[0][1]);
2574 while (!feof($handle) && $length > 0) {
2575 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2576 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2577 echo $buffer;
2578 flush();
2579 $length -= strlen($buffer);
2581 fclose($handle);
2582 die;
2583 } else { // multiple ranges requested - not tested much
2584 $totallength = 0;
2585 foreach($ranges as $range) {
2586 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2588 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2589 header('HTTP/1.1 206 Partial content');
2590 header('Content-Length: '.$totallength);
2591 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2593 while(@ob_get_level()) {
2594 if (!@ob_end_flush()) {
2595 break;
2599 foreach($ranges as $range) {
2600 $length = $range[2] - $range[1] + 1;
2601 echo $range[0];
2602 fseek($handle, $range[1]);
2603 while (!feof($handle) && $length > 0) {
2604 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2605 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2606 echo $buffer;
2607 flush();
2608 $length -= strlen($buffer);
2611 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2612 fclose($handle);
2613 die;
2618 * Tells whether the filename is executable.
2620 * @link http://php.net/manual/en/function.is-executable.php
2621 * @link https://bugs.php.net/bug.php?id=41062
2622 * @param string $filename Path to the file.
2623 * @return bool True if the filename exists and is executable; otherwise, false.
2625 function file_is_executable($filename) {
2626 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2627 if (is_executable($filename)) {
2628 return true;
2629 } else {
2630 $fileext = strrchr($filename, '.');
2631 // If we have an extension we can check if it is listed as executable.
2632 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2633 $winpathext = strtolower(getenv('PATHEXT'));
2634 $winpathexts = explode(';', $winpathext);
2636 return in_array(strtolower($fileext), $winpathexts);
2639 return false;
2641 } else {
2642 return is_executable($filename);
2647 * Overwrite an existing file in a draft area.
2649 * @param stored_file $newfile the new file with the new content and meta-data
2650 * @param stored_file $existingfile the file that will be overwritten
2651 * @throws moodle_exception
2652 * @since Moodle 3.2
2654 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2655 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2656 throw new coding_exception('The file to overwrite is not in a draft area.');
2659 $fs = get_file_storage();
2660 // Remember original file source field.
2661 $source = @unserialize($existingfile->get_source());
2662 // Remember the original sortorder.
2663 $sortorder = $existingfile->get_sortorder();
2664 if ($newfile->is_external_file()) {
2665 // New file is a reference. Check that existing file does not have any other files referencing to it
2666 if (isset($source->original) && $fs->search_references_count($source->original)) {
2667 throw new moodle_exception('errordoublereference', 'repository');
2671 // Delete existing file to release filename.
2672 $newfilerecord = array(
2673 'contextid' => $existingfile->get_contextid(),
2674 'component' => 'user',
2675 'filearea' => 'draft',
2676 'itemid' => $existingfile->get_itemid(),
2677 'timemodified' => time()
2679 $existingfile->delete();
2681 // Create new file.
2682 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2683 // Preserve original file location (stored in source field) for handling references.
2684 if (isset($source->original)) {
2685 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2686 $newfilesource = new stdClass();
2688 $newfilesource->original = $source->original;
2689 $newfile->set_source(serialize($newfilesource));
2691 $newfile->set_sortorder($sortorder);
2695 * Add files from a draft area into a final area.
2697 * Most of the time you do not want to use this. It is intended to be used
2698 * by asynchronous services which cannot direcly manipulate a final
2699 * area through a draft area. Instead they add files to a new draft
2700 * area and merge that new draft into the final area when ready.
2702 * @param int $draftitemid the id of the draft area to use.
2703 * @param int $contextid this parameter and the next two identify the file area to save to.
2704 * @param string $component component name
2705 * @param string $filearea indentifies the file area
2706 * @param int $itemid identifies the item id or false for all items in the file area
2707 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2708 * @see file_save_draft_area_files
2709 * @since Moodle 3.2
2711 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2712 array $options = null) {
2713 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2714 $finaldraftid = 0;
2715 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2716 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2717 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2721 * Merge files from two draftarea areas.
2723 * This does not handle conflict resolution, files in the destination area which appear
2724 * to be more recent will be kept disregarding the intended ones.
2726 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2727 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2728 * @throws coding_exception
2729 * @since Moodle 3.2
2731 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2732 global $USER;
2734 $fs = get_file_storage();
2735 $contextid = context_user::instance($USER->id)->id;
2737 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2738 throw new coding_exception('Nothing to merge or area does not belong to current user');
2741 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2743 // Get hashes of the files to merge.
2744 $newhashes = array();
2745 foreach ($filestomerge as $filetomerge) {
2746 $filepath = $filetomerge->get_filepath();
2747 $filename = $filetomerge->get_filename();
2749 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2750 $newhashes[$newhash] = $filetomerge;
2753 // Calculate wich files must be added.
2754 foreach ($currentfiles as $file) {
2755 $filehash = $file->get_pathnamehash();
2756 // One file to be merged already exists.
2757 if (isset($newhashes[$filehash])) {
2758 $updatedfile = $newhashes[$filehash];
2760 // Avoid race conditions.
2761 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2762 // The existing file is more recent, do not copy the suposedly "new" one.
2763 unset($newhashes[$filehash]);
2764 continue;
2766 // Update existing file (not only content, meta-data too).
2767 file_overwrite_existing_draftfile($updatedfile, $file);
2768 unset($newhashes[$filehash]);
2772 foreach ($newhashes as $newfile) {
2773 $newfilerecord = array(
2774 'contextid' => $contextid,
2775 'component' => 'user',
2776 'filearea' => 'draft',
2777 'itemid' => $mergeintodraftid,
2778 'timemodified' => time()
2781 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2786 * RESTful cURL class
2788 * This is a wrapper class for curl, it is quite easy to use:
2789 * <code>
2790 * $c = new curl;
2791 * // enable cache
2792 * $c = new curl(array('cache'=>true));
2793 * // enable cookie
2794 * $c = new curl(array('cookie'=>true));
2795 * // enable proxy
2796 * $c = new curl(array('proxy'=>true));
2798 * // HTTP GET Method
2799 * $html = $c->get('http://example.com');
2800 * // HTTP POST Method
2801 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2802 * // HTTP PUT Method
2803 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2804 * </code>
2806 * @package core_files
2807 * @category files
2808 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2809 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2811 class curl {
2812 /** @var bool Caches http request contents */
2813 public $cache = false;
2814 /** @var bool Uses proxy, null means automatic based on URL */
2815 public $proxy = null;
2816 /** @var string library version */
2817 public $version = '0.4 dev';
2818 /** @var array http's response */
2819 public $response = array();
2820 /** @var array Raw response headers, needed for BC in download_file_content(). */
2821 public $rawresponse = array();
2822 /** @var array http header */
2823 public $header = array();
2824 /** @var string cURL information */
2825 public $info;
2826 /** @var string error */
2827 public $error;
2828 /** @var int error code */
2829 public $errno;
2830 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2831 public $emulateredirects = null;
2833 /** @var array cURL options */
2834 private $options;
2836 /** @var string Proxy host */
2837 private $proxy_host = '';
2838 /** @var string Proxy auth */
2839 private $proxy_auth = '';
2840 /** @var string Proxy type */
2841 private $proxy_type = '';
2842 /** @var bool Debug mode on */
2843 private $debug = false;
2844 /** @var bool|string Path to cookie file */
2845 private $cookie = false;
2846 /** @var bool tracks multiple headers in response - redirect detection */
2847 private $responsefinished = false;
2848 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2849 private $securityhelper;
2850 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2851 private $ignoresecurity;
2852 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
2853 private static $mockresponses = [];
2856 * Curl constructor.
2858 * Allowed settings are:
2859 * proxy: (bool) use proxy server, null means autodetect non-local from url
2860 * debug: (bool) use debug output
2861 * cookie: (string) path to cookie file, false if none
2862 * cache: (bool) use cache
2863 * module_cache: (string) type of cache
2864 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
2865 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
2867 * @param array $settings
2869 public function __construct($settings = array()) {
2870 global $CFG;
2871 if (!function_exists('curl_init')) {
2872 $this->error = 'cURL module must be enabled!';
2873 trigger_error($this->error, E_USER_ERROR);
2874 return false;
2877 // All settings of this class should be init here.
2878 $this->resetopt();
2879 if (!empty($settings['debug'])) {
2880 $this->debug = true;
2882 if (!empty($settings['cookie'])) {
2883 if($settings['cookie'] === true) {
2884 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2885 } else {
2886 $this->cookie = $settings['cookie'];
2889 if (!empty($settings['cache'])) {
2890 if (class_exists('curl_cache')) {
2891 if (!empty($settings['module_cache'])) {
2892 $this->cache = new curl_cache($settings['module_cache']);
2893 } else {
2894 $this->cache = new curl_cache('misc');
2898 if (!empty($CFG->proxyhost)) {
2899 if (empty($CFG->proxyport)) {
2900 $this->proxy_host = $CFG->proxyhost;
2901 } else {
2902 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2904 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2905 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2906 $this->setopt(array(
2907 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2908 'proxyuserpwd'=>$this->proxy_auth));
2910 if (!empty($CFG->proxytype)) {
2911 if ($CFG->proxytype == 'SOCKS5') {
2912 $this->proxy_type = CURLPROXY_SOCKS5;
2913 } else {
2914 $this->proxy_type = CURLPROXY_HTTP;
2915 $this->setopt(array('httpproxytunnel'=>false));
2917 $this->setopt(array('proxytype'=>$this->proxy_type));
2920 if (isset($settings['proxy'])) {
2921 $this->proxy = $settings['proxy'];
2923 } else {
2924 $this->proxy = false;
2927 if (!isset($this->emulateredirects)) {
2928 $this->emulateredirects = ini_get('open_basedir');
2931 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
2932 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
2933 $this->set_security($settings['securityhelper']);
2934 } else {
2935 $this->set_security(new \core\files\curl_security_helper());
2937 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
2941 * Resets the CURL options that have already been set
2943 public function resetopt() {
2944 $this->options = array();
2945 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2946 // True to include the header in the output
2947 $this->options['CURLOPT_HEADER'] = 0;
2948 // True to Exclude the body from the output
2949 $this->options['CURLOPT_NOBODY'] = 0;
2950 // Redirect ny default.
2951 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2952 $this->options['CURLOPT_MAXREDIRS'] = 10;
2953 $this->options['CURLOPT_ENCODING'] = '';
2954 // TRUE to return the transfer as a string of the return
2955 // value of curl_exec() instead of outputting it out directly.
2956 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2957 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2958 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2959 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2961 if ($cacert = self::get_cacert()) {
2962 $this->options['CURLOPT_CAINFO'] = $cacert;
2967 * Get the location of ca certificates.
2968 * @return string absolute file path or empty if default used
2970 public static function get_cacert() {
2971 global $CFG;
2973 // Bundle in dataroot always wins.
2974 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2975 return realpath("$CFG->dataroot/moodleorgca.crt");
2978 // Next comes the default from php.ini
2979 $cacert = ini_get('curl.cainfo');
2980 if (!empty($cacert) and is_readable($cacert)) {
2981 return realpath($cacert);
2984 // Windows PHP does not have any certs, we need to use something.
2985 if ($CFG->ostype === 'WINDOWS') {
2986 if (is_readable("$CFG->libdir/cacert.pem")) {
2987 return realpath("$CFG->libdir/cacert.pem");
2991 // Use default, this should work fine on all properly configured *nix systems.
2992 return null;
2996 * Reset Cookie
2998 public function resetcookie() {
2999 if (!empty($this->cookie)) {
3000 if (is_file($this->cookie)) {
3001 $fp = fopen($this->cookie, 'w');
3002 if (!empty($fp)) {
3003 fwrite($fp, '');
3004 fclose($fp);
3011 * Set curl options.
3013 * Do not use the curl constants to define the options, pass a string
3014 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3015 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3017 * @param array $options If array is null, this function will reset the options to default value.
3018 * @return void
3019 * @throws coding_exception If an option uses constant value instead of option name.
3021 public function setopt($options = array()) {
3022 if (is_array($options)) {
3023 foreach ($options as $name => $val) {
3024 if (!is_string($name)) {
3025 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3027 if (stripos($name, 'CURLOPT_') === false) {
3028 $name = strtoupper('CURLOPT_'.$name);
3029 } else {
3030 $name = strtoupper($name);
3032 $this->options[$name] = $val;
3038 * Reset http method
3040 public function cleanopt() {
3041 unset($this->options['CURLOPT_HTTPGET']);
3042 unset($this->options['CURLOPT_POST']);
3043 unset($this->options['CURLOPT_POSTFIELDS']);
3044 unset($this->options['CURLOPT_PUT']);
3045 unset($this->options['CURLOPT_INFILE']);
3046 unset($this->options['CURLOPT_INFILESIZE']);
3047 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3048 unset($this->options['CURLOPT_FILE']);
3052 * Resets the HTTP Request headers (to prepare for the new request)
3054 public function resetHeader() {
3055 $this->header = array();
3059 * Set HTTP Request Header
3061 * @param array $header
3063 public function setHeader($header) {
3064 if (is_array($header)) {
3065 foreach ($header as $v) {
3066 $this->setHeader($v);
3068 } else {
3069 // Remove newlines, they are not allowed in headers.
3070 $newvalue = preg_replace('/[\r\n]/', '', $header);
3071 if (!in_array($newvalue, $this->header)) {
3072 $this->header[] = $newvalue;
3078 * Get HTTP Response Headers
3079 * @return array of arrays
3081 public function getResponse() {
3082 return $this->response;
3086 * Get raw HTTP Response Headers
3087 * @return array of strings
3089 public function get_raw_response() {
3090 return $this->rawresponse;
3094 * private callback function
3095 * Formatting HTTP Response Header
3097 * We only keep the last headers returned. For example during a redirect the
3098 * redirect headers will not appear in {@link self::getResponse()}, if you need
3099 * to use those headers, refer to {@link self::get_raw_response()}.
3101 * @param resource $ch Apparently not used
3102 * @param string $header
3103 * @return int The strlen of the header
3105 private function formatHeader($ch, $header) {
3106 $this->rawresponse[] = $header;
3108 if (trim($header, "\r\n") === '') {
3109 // This must be the last header.
3110 $this->responsefinished = true;
3113 if (strlen($header) > 2) {
3114 if ($this->responsefinished) {
3115 // We still have headers after the supposedly last header, we must be
3116 // in a redirect so let's empty the response to keep the last headers.
3117 $this->responsefinished = false;
3118 $this->response = array();
3120 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3121 $key = rtrim($parts[0], ':');
3122 $value = isset($parts[1]) ? $parts[1] : null;
3123 if (!empty($this->response[$key])) {
3124 if (is_array($this->response[$key])) {
3125 $this->response[$key][] = $value;
3126 } else {
3127 $tmp = $this->response[$key];
3128 $this->response[$key] = array();
3129 $this->response[$key][] = $tmp;
3130 $this->response[$key][] = $value;
3133 } else {
3134 $this->response[$key] = $value;
3137 return strlen($header);
3141 * Set options for individual curl instance
3143 * @param resource $curl A curl handle
3144 * @param array $options
3145 * @return resource The curl handle
3147 private function apply_opt($curl, $options) {
3148 // Clean up
3149 $this->cleanopt();
3150 // set cookie
3151 if (!empty($this->cookie) || !empty($options['cookie'])) {
3152 $this->setopt(array('cookiejar'=>$this->cookie,
3153 'cookiefile'=>$this->cookie
3157 // Bypass proxy if required.
3158 if ($this->proxy === null) {
3159 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3160 $proxy = false;
3161 } else {
3162 $proxy = true;
3164 } else {
3165 $proxy = (bool)$this->proxy;
3168 // Set proxy.
3169 if ($proxy) {
3170 $options['CURLOPT_PROXY'] = $this->proxy_host;
3171 } else {
3172 unset($this->options['CURLOPT_PROXY']);
3175 $this->setopt($options);
3177 // Reset before set options.
3178 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3180 // Setting the User-Agent based on options provided.
3181 $useragent = '';
3183 if (!empty($options['CURLOPT_USERAGENT'])) {
3184 $useragent = $options['CURLOPT_USERAGENT'];
3185 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3186 $useragent = $this->options['CURLOPT_USERAGENT'];
3187 } else {
3188 $useragent = 'MoodleBot/1.0';
3191 // Set headers.
3192 if (empty($this->header)) {
3193 $this->setHeader(array(
3194 'User-Agent: ' . $useragent,
3195 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3196 'Connection: keep-alive'
3198 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3199 // Remove old User-Agent if one existed.
3200 // We have to partial search since we don't know what the original User-Agent is.
3201 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3202 $key = array_keys($match)[0];
3203 unset($this->header[$key]);
3205 $this->setHeader(array('User-Agent: ' . $useragent));
3207 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3209 if ($this->debug) {
3210 echo '<h1>Options</h1>';
3211 var_dump($this->options);
3212 echo '<h1>Header</h1>';
3213 var_dump($this->header);
3216 // Do not allow infinite redirects.
3217 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3218 $this->options['CURLOPT_MAXREDIRS'] = 0;
3219 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3220 $this->options['CURLOPT_MAXREDIRS'] = 100;
3221 } else {
3222 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3225 // Make sure we always know if redirects expected.
3226 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3227 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3230 // Limit the protocols to HTTP and HTTPS.
3231 if (defined('CURLOPT_PROTOCOLS')) {
3232 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3233 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3236 // Set options.
3237 foreach($this->options as $name => $val) {
3238 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3239 // The redirects are emulated elsewhere.
3240 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3241 continue;
3243 $name = constant($name);
3244 curl_setopt($curl, $name, $val);
3247 return $curl;
3251 * Download multiple files in parallel
3253 * Calls {@link multi()} with specific download headers
3255 * <code>
3256 * $c = new curl();
3257 * $file1 = fopen('a', 'wb');
3258 * $file2 = fopen('b', 'wb');
3259 * $c->download(array(
3260 * array('url'=>'http://localhost/', 'file'=>$file1),
3261 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3262 * ));
3263 * fclose($file1);
3264 * fclose($file2);
3265 * </code>
3267 * or
3269 * <code>
3270 * $c = new curl();
3271 * $c->download(array(
3272 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3273 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3274 * ));
3275 * </code>
3277 * @param array $requests An array of files to request {
3278 * url => url to download the file [required]
3279 * file => file handler, or
3280 * filepath => file path
3282 * If 'file' and 'filepath' parameters are both specified in one request, the
3283 * open file handle in the 'file' parameter will take precedence and 'filepath'
3284 * will be ignored.
3286 * @param array $options An array of options to set
3287 * @return array An array of results
3289 public function download($requests, $options = array()) {
3290 $options['RETURNTRANSFER'] = false;
3291 return $this->multi($requests, $options);
3295 * Returns the current curl security helper.
3297 * @return \core\files\curl_security_helper instance.
3299 public function get_security() {
3300 return $this->securityhelper;
3304 * Sets the curl security helper.
3306 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3307 * @return bool true if the security helper could be set, false otherwise.
3309 public function set_security($securityobject) {
3310 if ($securityobject instanceof \core\files\curl_security_helper) {
3311 $this->securityhelper = $securityobject;
3312 return true;
3314 return false;
3318 * Multi HTTP Requests
3319 * This function could run multi-requests in parallel.
3321 * @param array $requests An array of files to request
3322 * @param array $options An array of options to set
3323 * @return array An array of results
3325 protected function multi($requests, $options = array()) {
3326 $count = count($requests);
3327 $handles = array();
3328 $results = array();
3329 $main = curl_multi_init();
3330 for ($i = 0; $i < $count; $i++) {
3331 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3332 // open file
3333 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3334 $requests[$i]['auto-handle'] = true;
3336 foreach($requests[$i] as $n=>$v) {
3337 $options[$n] = $v;
3339 $handles[$i] = curl_init($requests[$i]['url']);
3340 $this->apply_opt($handles[$i], $options);
3341 curl_multi_add_handle($main, $handles[$i]);
3343 $running = 0;
3344 do {
3345 curl_multi_exec($main, $running);
3346 } while($running > 0);
3347 for ($i = 0; $i < $count; $i++) {
3348 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3349 $results[] = true;
3350 } else {
3351 $results[] = curl_multi_getcontent($handles[$i]);
3353 curl_multi_remove_handle($main, $handles[$i]);
3355 curl_multi_close($main);
3357 for ($i = 0; $i < $count; $i++) {
3358 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3359 // close file handler if file is opened in this function
3360 fclose($requests[$i]['file']);
3363 return $results;
3367 * Helper function to reset the request state vars.
3369 * @return void.
3371 protected function reset_request_state_vars() {
3372 $this->info = array();
3373 $this->error = '';
3374 $this->errno = 0;
3375 $this->response = array();
3376 $this->rawresponse = array();
3377 $this->responsefinished = false;
3381 * For use only in unit tests - we can pre-set the next curl response.
3382 * This is useful for unit testing APIs that call external systems.
3383 * @param string $response
3385 public static function mock_response($response) {
3386 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3387 array_push(self::$mockresponses, $response);
3388 } else {
3389 throw new coding_excpetion('mock_response function is only available for unit tests.');
3394 * Single HTTP Request
3396 * @param string $url The URL to request
3397 * @param array $options
3398 * @return bool
3400 protected function request($url, $options = array()) {
3401 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3402 $this->reset_request_state_vars();
3404 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3405 if ($mockresponse = array_pop(self::$mockresponses)) {
3406 $this->info = [ 'http_code' => 200 ];
3407 return $mockresponse;
3411 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3412 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3413 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3414 $this->error = $this->securityhelper->get_blocked_url_string();
3415 return $this->error;
3418 // Set the URL as a curl option.
3419 $this->setopt(array('CURLOPT_URL' => $url));
3421 // Create curl instance.
3422 $curl = curl_init();
3424 $this->apply_opt($curl, $options);
3425 if ($this->cache && $ret = $this->cache->get($this->options)) {
3426 return $ret;
3429 $ret = curl_exec($curl);
3430 $this->info = curl_getinfo($curl);
3431 $this->error = curl_error($curl);
3432 $this->errno = curl_errno($curl);
3433 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3435 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3436 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3437 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3438 $this->reset_request_state_vars();
3439 $this->error = $this->securityhelper->get_blocked_url_string();
3440 curl_close($curl);
3441 return $this->error;
3444 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3445 $redirects = 0;
3447 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3449 if ($this->info['http_code'] == 301) {
3450 // Moved Permanently - repeat the same request on new URL.
3452 } else if ($this->info['http_code'] == 302) {
3453 // Found - the standard redirect - repeat the same request on new URL.
3455 } else if ($this->info['http_code'] == 303) {
3456 // 303 See Other - repeat only if GET, do not bother with POSTs.
3457 if (empty($this->options['CURLOPT_HTTPGET'])) {
3458 break;
3461 } else if ($this->info['http_code'] == 307) {
3462 // Temporary Redirect - must repeat using the same request type.
3464 } else if ($this->info['http_code'] == 308) {
3465 // Permanent Redirect - must repeat using the same request type.
3467 } else {
3468 // Some other http code means do not retry!
3469 break;
3472 $redirects++;
3474 $redirecturl = null;
3475 if (isset($this->info['redirect_url'])) {
3476 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3477 $redirecturl = $this->info['redirect_url'];
3480 if (!$redirecturl) {
3481 foreach ($this->response as $k => $v) {
3482 if (strtolower($k) === 'location') {
3483 $redirecturl = $v;
3484 break;
3487 if (preg_match('|^https?://|i', $redirecturl)) {
3488 // Great, this is the correct location format!
3490 } else if ($redirecturl) {
3491 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3492 if (strpos($redirecturl, '/') === 0) {
3493 // Relative to server root - just guess.
3494 $pos = strpos('/', $current, 8);
3495 if ($pos === false) {
3496 $redirecturl = $current.$redirecturl;
3497 } else {
3498 $redirecturl = substr($current, 0, $pos).$redirecturl;
3500 } else {
3501 // Relative to current script.
3502 $redirecturl = dirname($current).'/'.$redirecturl;
3507 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3508 $ret = curl_exec($curl);
3510 $this->info = curl_getinfo($curl);
3511 $this->error = curl_error($curl);
3512 $this->errno = curl_errno($curl);
3514 $this->info['redirect_count'] = $redirects;
3516 if ($this->info['http_code'] === 200) {
3517 // Finally this is what we wanted.
3518 break;
3520 if ($this->errno != CURLE_OK) {
3521 // Something wrong is going on.
3522 break;
3525 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3526 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3527 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3531 if ($this->cache) {
3532 $this->cache->set($this->options, $ret);
3535 if ($this->debug) {
3536 echo '<h1>Return Data</h1>';
3537 var_dump($ret);
3538 echo '<h1>Info</h1>';
3539 var_dump($this->info);
3540 echo '<h1>Error</h1>';
3541 var_dump($this->error);
3544 curl_close($curl);
3546 if (empty($this->error)) {
3547 return $ret;
3548 } else {
3549 return $this->error;
3550 // exception is not ajax friendly
3551 //throw new moodle_exception($this->error, 'curl');
3556 * HTTP HEAD method
3558 * @see request()
3560 * @param string $url
3561 * @param array $options
3562 * @return bool
3564 public function head($url, $options = array()) {
3565 $options['CURLOPT_HTTPGET'] = 0;
3566 $options['CURLOPT_HEADER'] = 1;
3567 $options['CURLOPT_NOBODY'] = 1;
3568 return $this->request($url, $options);
3572 * HTTP PATCH method
3574 * @param string $url
3575 * @param array|string $params
3576 * @param array $options
3577 * @return bool
3579 public function patch($url, $params = '', $options = array()) {
3580 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3581 if (is_array($params)) {
3582 $this->_tmp_file_post_params = array();
3583 foreach ($params as $key => $value) {
3584 if ($value instanceof stored_file) {
3585 $value->add_to_curl_request($this, $key);
3586 } else {
3587 $this->_tmp_file_post_params[$key] = $value;
3590 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3591 unset($this->_tmp_file_post_params);
3592 } else {
3593 // The variable $params is the raw post data.
3594 $options['CURLOPT_POSTFIELDS'] = $params;
3596 return $this->request($url, $options);
3600 * HTTP POST method
3602 * @param string $url
3603 * @param array|string $params
3604 * @param array $options
3605 * @return bool
3607 public function post($url, $params = '', $options = array()) {
3608 $options['CURLOPT_POST'] = 1;
3609 if (is_array($params)) {
3610 $this->_tmp_file_post_params = array();
3611 foreach ($params as $key => $value) {
3612 if ($value instanceof stored_file) {
3613 $value->add_to_curl_request($this, $key);
3614 } else {
3615 $this->_tmp_file_post_params[$key] = $value;
3618 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3619 unset($this->_tmp_file_post_params);
3620 } else {
3621 // $params is the raw post data
3622 $options['CURLOPT_POSTFIELDS'] = $params;
3624 return $this->request($url, $options);
3628 * HTTP GET method
3630 * @param string $url
3631 * @param array $params
3632 * @param array $options
3633 * @return bool
3635 public function get($url, $params = array(), $options = array()) {
3636 $options['CURLOPT_HTTPGET'] = 1;
3638 if (!empty($params)) {
3639 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3640 $url .= http_build_query($params, '', '&');
3642 return $this->request($url, $options);
3646 * Downloads one file and writes it to the specified file handler
3648 * <code>
3649 * $c = new curl();
3650 * $file = fopen('savepath', 'w');
3651 * $result = $c->download_one('http://localhost/', null,
3652 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3653 * fclose($file);
3654 * $download_info = $c->get_info();
3655 * if ($result === true) {
3656 * // file downloaded successfully
3657 * } else {
3658 * $error_text = $result;
3659 * $error_code = $c->get_errno();
3661 * </code>
3663 * <code>
3664 * $c = new curl();
3665 * $result = $c->download_one('http://localhost/', null,
3666 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3667 * // ... see above, no need to close handle and remove file if unsuccessful
3668 * </code>
3670 * @param string $url
3671 * @param array|null $params key-value pairs to be added to $url as query string
3672 * @param array $options request options. Must include either 'file' or 'filepath'
3673 * @return bool|string true on success or error string on failure
3675 public function download_one($url, $params, $options = array()) {
3676 $options['CURLOPT_HTTPGET'] = 1;
3677 if (!empty($params)) {
3678 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3679 $url .= http_build_query($params, '', '&');
3681 if (!empty($options['filepath']) && empty($options['file'])) {
3682 // open file
3683 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3684 $this->errno = 100;
3685 return get_string('cannotwritefile', 'error', $options['filepath']);
3687 $filepath = $options['filepath'];
3689 unset($options['filepath']);
3690 $result = $this->request($url, $options);
3691 if (isset($filepath)) {
3692 fclose($options['file']);
3693 if ($result !== true) {
3694 unlink($filepath);
3697 return $result;
3701 * HTTP PUT method
3703 * @param string $url
3704 * @param array $params
3705 * @param array $options
3706 * @return bool
3708 public function put($url, $params = array(), $options = array()) {
3709 $file = '';
3710 $fp = false;
3711 if (isset($params['file'])) {
3712 $file = $params['file'];
3713 if (is_file($file)) {
3714 $fp = fopen($file, 'r');
3715 $size = filesize($file);
3716 $options['CURLOPT_PUT'] = 1;
3717 $options['CURLOPT_INFILESIZE'] = $size;
3718 $options['CURLOPT_INFILE'] = $fp;
3719 } else {
3720 return null;
3722 if (!isset($this->options['CURLOPT_USERPWD'])) {
3723 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3725 } else {
3726 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3727 $options['CURLOPT_POSTFIELDS'] = $params;
3730 $ret = $this->request($url, $options);
3731 if ($fp !== false) {
3732 fclose($fp);
3734 return $ret;
3738 * HTTP DELETE method
3740 * @param string $url
3741 * @param array $param
3742 * @param array $options
3743 * @return bool
3745 public function delete($url, $param = array(), $options = array()) {
3746 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3747 if (!isset($options['CURLOPT_USERPWD'])) {
3748 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3750 $ret = $this->request($url, $options);
3751 return $ret;
3755 * HTTP TRACE method
3757 * @param string $url
3758 * @param array $options
3759 * @return bool
3761 public function trace($url, $options = array()) {
3762 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3763 $ret = $this->request($url, $options);
3764 return $ret;
3768 * HTTP OPTIONS method
3770 * @param string $url
3771 * @param array $options
3772 * @return bool
3774 public function options($url, $options = array()) {
3775 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3776 $ret = $this->request($url, $options);
3777 return $ret;
3781 * Get curl information
3783 * @return string
3785 public function get_info() {
3786 return $this->info;
3790 * Get curl error code
3792 * @return int
3794 public function get_errno() {
3795 return $this->errno;
3799 * When using a proxy, an additional HTTP response code may appear at
3800 * the start of the header. For example, when using https over a proxy
3801 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3802 * also possible and some may come with their own headers.
3804 * If using the return value containing all headers, this function can be
3805 * called to remove unwanted doubles.
3807 * Note that it is not possible to distinguish this situation from valid
3808 * data unless you know the actual response part (below the headers)
3809 * will not be included in this string, or else will not 'look like' HTTP
3810 * headers. As a result it is not safe to call this function for general
3811 * data.
3813 * @param string $input Input HTTP response
3814 * @return string HTTP response with additional headers stripped if any
3816 public static function strip_double_headers($input) {
3817 // I have tried to make this regular expression as specific as possible
3818 // to avoid any case where it does weird stuff if you happen to put
3819 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3820 // also make it faster because it can abandon regex processing as soon
3821 // as it hits something that doesn't look like an http header. The
3822 // header definition is taken from RFC 822, except I didn't support
3823 // folding which is never used in practice.
3824 $crlf = "\r\n";
3825 return preg_replace(
3826 // HTTP version and status code (ignore value of code).
3827 '~^HTTP/1\..*' . $crlf .
3828 // Header name: character between 33 and 126 decimal, except colon.
3829 // Colon. Header value: any character except \r and \n. CRLF.
3830 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3831 // Headers are terminated by another CRLF (blank line).
3832 $crlf .
3833 // Second HTTP status code, this time must be 200.
3834 '(HTTP/1.[01] 200 )~', '$1', $input);
3839 * This class is used by cURL class, use case:
3841 * <code>
3842 * $CFG->repositorycacheexpire = 120;
3843 * $CFG->curlcache = 120;
3845 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3846 * $ret = $c->get('http://www.google.com');
3847 * </code>
3849 * @package core_files
3850 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3851 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3853 class curl_cache {
3854 /** @var string Path to cache directory */
3855 public $dir = '';
3858 * Constructor
3860 * @global stdClass $CFG
3861 * @param string $module which module is using curl_cache
3863 public function __construct($module = 'repository') {
3864 global $CFG;
3865 if (!empty($module)) {
3866 $this->dir = $CFG->cachedir.'/'.$module.'/';
3867 } else {
3868 $this->dir = $CFG->cachedir.'/misc/';
3870 if (!file_exists($this->dir)) {
3871 mkdir($this->dir, $CFG->directorypermissions, true);
3873 if ($module == 'repository') {
3874 if (empty($CFG->repositorycacheexpire)) {
3875 $CFG->repositorycacheexpire = 120;
3877 $this->ttl = $CFG->repositorycacheexpire;
3878 } else {
3879 if (empty($CFG->curlcache)) {
3880 $CFG->curlcache = 120;
3882 $this->ttl = $CFG->curlcache;
3887 * Get cached value
3889 * @global stdClass $CFG
3890 * @global stdClass $USER
3891 * @param mixed $param
3892 * @return bool|string
3894 public function get($param) {
3895 global $CFG, $USER;
3896 $this->cleanup($this->ttl);
3897 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3898 if(file_exists($this->dir.$filename)) {
3899 $lasttime = filemtime($this->dir.$filename);
3900 if (time()-$lasttime > $this->ttl) {
3901 return false;
3902 } else {
3903 $fp = fopen($this->dir.$filename, 'r');
3904 $size = filesize($this->dir.$filename);
3905 $content = fread($fp, $size);
3906 return unserialize($content);
3909 return false;
3913 * Set cache value
3915 * @global object $CFG
3916 * @global object $USER
3917 * @param mixed $param
3918 * @param mixed $val
3920 public function set($param, $val) {
3921 global $CFG, $USER;
3922 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3923 $fp = fopen($this->dir.$filename, 'w');
3924 fwrite($fp, serialize($val));
3925 fclose($fp);
3926 @chmod($this->dir.$filename, $CFG->filepermissions);
3930 * Remove cache files
3932 * @param int $expire The number of seconds before expiry
3934 public function cleanup($expire) {
3935 if ($dir = opendir($this->dir)) {
3936 while (false !== ($file = readdir($dir))) {
3937 if(!is_dir($file) && $file != '.' && $file != '..') {
3938 $lasttime = @filemtime($this->dir.$file);
3939 if (time() - $lasttime > $expire) {
3940 @unlink($this->dir.$file);
3944 closedir($dir);
3948 * delete current user's cache file
3950 * @global object $CFG
3951 * @global object $USER
3953 public function refresh() {
3954 global $CFG, $USER;
3955 if ($dir = opendir($this->dir)) {
3956 while (false !== ($file = readdir($dir))) {
3957 if (!is_dir($file) && $file != '.' && $file != '..') {
3958 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3959 @unlink($this->dir.$file);
3968 * This function delegates file serving to individual plugins
3970 * @param string $relativepath
3971 * @param bool $forcedownload
3972 * @param null|string $preview the preview mode, defaults to serving the original file
3973 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
3974 * offline (e.g. mobile app).
3975 * @param bool $embed Whether this file will be served embed into an iframe.
3976 * @todo MDL-31088 file serving improments
3978 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
3979 global $DB, $CFG, $USER;
3980 // relative path must start with '/'
3981 if (!$relativepath) {
3982 print_error('invalidargorconf');
3983 } else if ($relativepath[0] != '/') {
3984 print_error('pathdoesnotstartslash');
3987 // extract relative path components
3988 $args = explode('/', ltrim($relativepath, '/'));
3990 if (count($args) < 3) { // always at least context, component and filearea
3991 print_error('invalidarguments');
3994 $contextid = (int)array_shift($args);
3995 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3996 $filearea = clean_param(array_shift($args), PARAM_AREA);
3998 list($context, $course, $cm) = get_context_info_array($contextid);
4000 $fs = get_file_storage();
4002 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4004 // ========================================================================================================================
4005 if ($component === 'blog') {
4006 // Blog file serving
4007 if ($context->contextlevel != CONTEXT_SYSTEM) {
4008 send_file_not_found();
4010 if ($filearea !== 'attachment' and $filearea !== 'post') {
4011 send_file_not_found();
4014 if (empty($CFG->enableblogs)) {
4015 print_error('siteblogdisable', 'blog');
4018 $entryid = (int)array_shift($args);
4019 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4020 send_file_not_found();
4022 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4023 require_login();
4024 if (isguestuser()) {
4025 print_error('noguest');
4027 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4028 if ($USER->id != $entry->userid) {
4029 send_file_not_found();
4034 if ($entry->publishstate === 'public') {
4035 if ($CFG->forcelogin) {
4036 require_login();
4039 } else if ($entry->publishstate === 'site') {
4040 require_login();
4041 //ok
4042 } else if ($entry->publishstate === 'draft') {
4043 require_login();
4044 if ($USER->id != $entry->userid) {
4045 send_file_not_found();
4049 $filename = array_pop($args);
4050 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4052 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4053 send_file_not_found();
4056 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4058 // ========================================================================================================================
4059 } else if ($component === 'grade') {
4060 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4061 // Global gradebook files
4062 if ($CFG->forcelogin) {
4063 require_login();
4066 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4068 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4069 send_file_not_found();
4072 \core\session\manager::write_close(); // Unlock session during file serving.
4073 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4075 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
4076 //TODO: nobody implemented this yet in grade edit form!!
4077 send_file_not_found();
4079 if ($CFG->forcelogin || $course->id != SITEID) {
4080 require_login($course);
4083 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4085 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4086 send_file_not_found();
4089 \core\session\manager::write_close(); // Unlock session during file serving.
4090 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4091 } else {
4092 send_file_not_found();
4095 // ========================================================================================================================
4096 } else if ($component === 'tag') {
4097 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4099 // All tag descriptions are going to be public but we still need to respect forcelogin
4100 if ($CFG->forcelogin) {
4101 require_login();
4104 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4106 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4107 send_file_not_found();
4110 \core\session\manager::write_close(); // Unlock session during file serving.
4111 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4113 } else {
4114 send_file_not_found();
4116 // ========================================================================================================================
4117 } else if ($component === 'badges') {
4118 require_once($CFG->libdir . '/badgeslib.php');
4120 $badgeid = (int)array_shift($args);
4121 $badge = new badge($badgeid);
4122 $filename = array_pop($args);
4124 if ($filearea === 'badgeimage') {
4125 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4126 send_file_not_found();
4128 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4129 send_file_not_found();
4132 \core\session\manager::write_close();
4133 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4134 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4135 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4136 send_file_not_found();
4139 \core\session\manager::write_close();
4140 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4142 // ========================================================================================================================
4143 } else if ($component === 'calendar') {
4144 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4146 // All events here are public the one requirement is that we respect forcelogin
4147 if ($CFG->forcelogin) {
4148 require_login();
4151 // Get the event if from the args array
4152 $eventid = array_shift($args);
4154 // Load the event from the database
4155 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4156 send_file_not_found();
4159 // Get the file and serve if successful
4160 $filename = array_pop($args);
4161 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4162 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4163 send_file_not_found();
4166 \core\session\manager::write_close(); // Unlock session during file serving.
4167 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4169 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4171 // Must be logged in, if they are not then they obviously can't be this user
4172 require_login();
4174 // Don't want guests here, potentially saves a DB call
4175 if (isguestuser()) {
4176 send_file_not_found();
4179 // Get the event if from the args array
4180 $eventid = array_shift($args);
4182 // Load the event from the database - user id must match
4183 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4184 send_file_not_found();
4187 // Get the file and serve if successful
4188 $filename = array_pop($args);
4189 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4190 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4191 send_file_not_found();
4194 \core\session\manager::write_close(); // Unlock session during file serving.
4195 send_stored_file($file, 0, 0, true, $sendfileoptions);
4197 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4199 // Respect forcelogin and require login unless this is the site.... it probably
4200 // should NEVER be the site
4201 if ($CFG->forcelogin || $course->id != SITEID) {
4202 require_login($course);
4205 // Must be able to at least view the course. This does not apply to the front page.
4206 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4207 //TODO: hmm, do we really want to block guests here?
4208 send_file_not_found();
4211 // Get the event id
4212 $eventid = array_shift($args);
4214 // Load the event from the database we need to check whether it is
4215 // a) valid course event
4216 // b) a group event
4217 // Group events use the course context (there is no group context)
4218 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4219 send_file_not_found();
4222 // If its a group event require either membership of view all groups capability
4223 if ($event->eventtype === 'group') {
4224 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4225 send_file_not_found();
4227 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4228 // Ok. Please note that the event type 'site' still uses a course context.
4229 } else {
4230 // Some other type.
4231 send_file_not_found();
4234 // If we get this far we can serve the file
4235 $filename = array_pop($args);
4236 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4237 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4238 send_file_not_found();
4241 \core\session\manager::write_close(); // Unlock session during file serving.
4242 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4244 } else {
4245 send_file_not_found();
4248 // ========================================================================================================================
4249 } else if ($component === 'user') {
4250 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4251 if (count($args) == 1) {
4252 $themename = theme_config::DEFAULT_THEME;
4253 $filename = array_shift($args);
4254 } else {
4255 $themename = array_shift($args);
4256 $filename = array_shift($args);
4259 // fix file name automatically
4260 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4261 $filename = 'f1';
4264 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4265 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4266 // protect images if login required and not logged in;
4267 // also if login is required for profile images and is not logged in or guest
4268 // do not use require_login() because it is expensive and not suitable here anyway
4269 $theme = theme_config::load($themename);
4270 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4273 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4274 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4275 if ($filename === 'f3') {
4276 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4277 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4278 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4283 if (!$file) {
4284 // bad reference - try to prevent future retries as hard as possible!
4285 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4286 if ($user->picture > 0) {
4287 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4290 // no redirect here because it is not cached
4291 $theme = theme_config::load($themename);
4292 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4293 send_file($imagefile, basename($imagefile), 60*60*24*14);
4296 $options = $sendfileoptions;
4297 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4298 // Profile images should be cache-able by both browsers and proxies according
4299 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4300 $options['cacheability'] = 'public';
4302 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4304 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4305 require_login();
4307 if (isguestuser()) {
4308 send_file_not_found();
4311 if ($USER->id !== $context->instanceid) {
4312 send_file_not_found();
4315 $filename = array_pop($args);
4316 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4317 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4318 send_file_not_found();
4321 \core\session\manager::write_close(); // Unlock session during file serving.
4322 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4324 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4326 if ($CFG->forcelogin) {
4327 require_login();
4330 $userid = $context->instanceid;
4332 if ($USER->id == $userid) {
4333 // always can access own
4335 } else if (!empty($CFG->forceloginforprofiles)) {
4336 require_login();
4338 if (isguestuser()) {
4339 send_file_not_found();
4342 // we allow access to site profile of all course contacts (usually teachers)
4343 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4344 send_file_not_found();
4347 $canview = false;
4348 if (has_capability('moodle/user:viewdetails', $context)) {
4349 $canview = true;
4350 } else {
4351 $courses = enrol_get_my_courses();
4354 while (!$canview && count($courses) > 0) {
4355 $course = array_shift($courses);
4356 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4357 $canview = true;
4362 $filename = array_pop($args);
4363 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4364 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4365 send_file_not_found();
4368 \core\session\manager::write_close(); // Unlock session during file serving.
4369 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4371 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4372 $userid = (int)array_shift($args);
4373 $usercontext = context_user::instance($userid);
4375 if ($CFG->forcelogin) {
4376 require_login();
4379 if (!empty($CFG->forceloginforprofiles)) {
4380 require_login();
4381 if (isguestuser()) {
4382 print_error('noguest');
4385 //TODO: review this logic of user profile access prevention
4386 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4387 print_error('usernotavailable');
4389 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4390 print_error('cannotviewprofile');
4392 if (!is_enrolled($context, $userid)) {
4393 print_error('notenrolledprofile');
4395 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4396 print_error('groupnotamember');
4400 $filename = array_pop($args);
4401 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4402 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4403 send_file_not_found();
4406 \core\session\manager::write_close(); // Unlock session during file serving.
4407 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4409 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4410 require_login();
4412 if (isguestuser()) {
4413 send_file_not_found();
4415 $userid = $context->instanceid;
4417 if ($USER->id != $userid) {
4418 send_file_not_found();
4421 $filename = array_pop($args);
4422 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4423 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4424 send_file_not_found();
4427 \core\session\manager::write_close(); // Unlock session during file serving.
4428 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4430 } else {
4431 send_file_not_found();
4434 // ========================================================================================================================
4435 } else if ($component === 'coursecat') {
4436 if ($context->contextlevel != CONTEXT_COURSECAT) {
4437 send_file_not_found();
4440 if ($filearea === 'description') {
4441 if ($CFG->forcelogin) {
4442 // no login necessary - unless login forced everywhere
4443 require_login();
4446 // Check if user can view this category.
4447 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4448 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid));
4449 if (!$coursecatvisible) {
4450 send_file_not_found();
4454 $filename = array_pop($args);
4455 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4456 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4457 send_file_not_found();
4460 \core\session\manager::write_close(); // Unlock session during file serving.
4461 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4462 } else {
4463 send_file_not_found();
4466 // ========================================================================================================================
4467 } else if ($component === 'course') {
4468 if ($context->contextlevel != CONTEXT_COURSE) {
4469 send_file_not_found();
4472 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4473 if ($CFG->forcelogin) {
4474 require_login();
4477 $filename = array_pop($args);
4478 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4479 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4480 send_file_not_found();
4483 \core\session\manager::write_close(); // Unlock session during file serving.
4484 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4486 } else if ($filearea === 'section') {
4487 if ($CFG->forcelogin) {
4488 require_login($course);
4489 } else if ($course->id != SITEID) {
4490 require_login($course);
4493 $sectionid = (int)array_shift($args);
4495 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4496 send_file_not_found();
4499 $filename = array_pop($args);
4500 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4501 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4502 send_file_not_found();
4505 \core\session\manager::write_close(); // Unlock session during file serving.
4506 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4508 } else {
4509 send_file_not_found();
4512 } else if ($component === 'cohort') {
4514 $cohortid = (int)array_shift($args);
4515 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4516 $cohortcontext = context::instance_by_id($cohort->contextid);
4518 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4519 if ($context->id != $cohort->contextid &&
4520 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4521 send_file_not_found();
4524 // User is able to access cohort if they have view cap on cohort level or
4525 // the cohort is visible and they have view cap on course level.
4526 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4527 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4529 if ($filearea === 'description' && $canview) {
4530 $filename = array_pop($args);
4531 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4532 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4533 && !$file->is_directory()) {
4534 \core\session\manager::write_close(); // Unlock session during file serving.
4535 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4539 send_file_not_found();
4541 } else if ($component === 'group') {
4542 if ($context->contextlevel != CONTEXT_COURSE) {
4543 send_file_not_found();
4546 require_course_login($course, true, null, false);
4548 $groupid = (int)array_shift($args);
4550 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4551 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4552 // do not allow access to separate group info if not member or teacher
4553 send_file_not_found();
4556 if ($filearea === 'description') {
4558 require_login($course);
4560 $filename = array_pop($args);
4561 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4562 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4563 send_file_not_found();
4566 \core\session\manager::write_close(); // Unlock session during file serving.
4567 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4569 } else if ($filearea === 'icon') {
4570 $filename = array_pop($args);
4572 if ($filename !== 'f1' and $filename !== 'f2') {
4573 send_file_not_found();
4575 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4576 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4577 send_file_not_found();
4581 \core\session\manager::write_close(); // Unlock session during file serving.
4582 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4584 } else {
4585 send_file_not_found();
4588 } else if ($component === 'grouping') {
4589 if ($context->contextlevel != CONTEXT_COURSE) {
4590 send_file_not_found();
4593 require_login($course);
4595 $groupingid = (int)array_shift($args);
4597 // note: everybody has access to grouping desc images for now
4598 if ($filearea === 'description') {
4600 $filename = array_pop($args);
4601 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4602 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4603 send_file_not_found();
4606 \core\session\manager::write_close(); // Unlock session during file serving.
4607 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4609 } else {
4610 send_file_not_found();
4613 // ========================================================================================================================
4614 } else if ($component === 'backup') {
4615 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4616 require_login($course);
4617 require_capability('moodle/backup:downloadfile', $context);
4619 $filename = array_pop($args);
4620 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4621 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4622 send_file_not_found();
4625 \core\session\manager::write_close(); // Unlock session during file serving.
4626 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4628 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4629 require_login($course);
4630 require_capability('moodle/backup:downloadfile', $context);
4632 $sectionid = (int)array_shift($args);
4634 $filename = array_pop($args);
4635 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4636 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4637 send_file_not_found();
4640 \core\session\manager::write_close();
4641 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4643 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4644 require_login($course, false, $cm);
4645 require_capability('moodle/backup:downloadfile', $context);
4647 $filename = array_pop($args);
4648 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4649 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4650 send_file_not_found();
4653 \core\session\manager::write_close();
4654 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4656 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4657 // Backup files that were generated by the automated backup systems.
4659 require_login($course);
4660 require_capability('moodle/backup:downloadfile', $context);
4661 require_capability('moodle/restore:userinfo', $context);
4663 $filename = array_pop($args);
4664 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4665 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4666 send_file_not_found();
4669 \core\session\manager::write_close(); // Unlock session during file serving.
4670 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4672 } else {
4673 send_file_not_found();
4676 // ========================================================================================================================
4677 } else if ($component === 'question') {
4678 require_once($CFG->libdir . '/questionlib.php');
4679 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4680 send_file_not_found();
4682 // ========================================================================================================================
4683 } else if ($component === 'grading') {
4684 if ($filearea === 'description') {
4685 // files embedded into the form definition description
4687 if ($context->contextlevel == CONTEXT_SYSTEM) {
4688 require_login();
4690 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4691 require_login($course, false, $cm);
4693 } else {
4694 send_file_not_found();
4697 $formid = (int)array_shift($args);
4699 $sql = "SELECT ga.id
4700 FROM {grading_areas} ga
4701 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4702 WHERE gd.id = ? AND ga.contextid = ?";
4703 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4705 if (!$areaid) {
4706 send_file_not_found();
4709 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4711 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4712 send_file_not_found();
4715 \core\session\manager::write_close(); // Unlock session during file serving.
4716 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4719 // ========================================================================================================================
4720 } else if (strpos($component, 'mod_') === 0) {
4721 $modname = substr($component, 4);
4722 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4723 send_file_not_found();
4725 require_once("$CFG->dirroot/mod/$modname/lib.php");
4727 if ($context->contextlevel == CONTEXT_MODULE) {
4728 if ($cm->modname !== $modname) {
4729 // somebody tries to gain illegal access, cm type must match the component!
4730 send_file_not_found();
4734 if ($filearea === 'intro') {
4735 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4736 send_file_not_found();
4739 // Require login to the course first (without login to the module).
4740 require_course_login($course, true);
4742 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4743 $cminfo = cm_info::create($cm);
4744 if (!$cminfo->uservisible) {
4745 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
4746 // Module intro is not visible on the course page and module is not available, show access error.
4747 require_course_login($course, true, $cminfo);
4751 // all users may access it
4752 $filename = array_pop($args);
4753 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4754 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4755 send_file_not_found();
4758 // finally send the file
4759 send_stored_file($file, null, 0, false, $sendfileoptions);
4762 $filefunction = $component.'_pluginfile';
4763 $filefunctionold = $modname.'_pluginfile';
4764 if (function_exists($filefunction)) {
4765 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4766 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4767 } else if (function_exists($filefunctionold)) {
4768 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4769 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4772 send_file_not_found();
4774 // ========================================================================================================================
4775 } else if (strpos($component, 'block_') === 0) {
4776 $blockname = substr($component, 6);
4777 // note: no more class methods in blocks please, that is ....
4778 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4779 send_file_not_found();
4781 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4783 if ($context->contextlevel == CONTEXT_BLOCK) {
4784 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4785 if ($birecord->blockname !== $blockname) {
4786 // somebody tries to gain illegal access, cm type must match the component!
4787 send_file_not_found();
4790 if ($context->get_course_context(false)) {
4791 // If block is in course context, then check if user has capability to access course.
4792 require_course_login($course);
4793 } else if ($CFG->forcelogin) {
4794 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4795 require_login();
4798 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4799 // User can't access file, if block is hidden or doesn't have block:view capability
4800 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4801 send_file_not_found();
4803 } else {
4804 $birecord = null;
4807 $filefunction = $component.'_pluginfile';
4808 if (function_exists($filefunction)) {
4809 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4810 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4813 send_file_not_found();
4815 // ========================================================================================================================
4816 } else if (strpos($component, '_') === false) {
4817 // all core subsystems have to be specified above, no more guessing here!
4818 send_file_not_found();
4820 } else {
4821 // try to serve general plugin file in arbitrary context
4822 $dir = core_component::get_component_directory($component);
4823 if (!file_exists("$dir/lib.php")) {
4824 send_file_not_found();
4826 include_once("$dir/lib.php");
4828 $filefunction = $component.'_pluginfile';
4829 if (function_exists($filefunction)) {
4830 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4831 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4834 send_file_not_found();