MDL-61937 datafield: Add privacy implementation for all datafield
[moodle.git] / lib / filelib.php
blob53f07db0c908132f9d4270e24f0b4f3e10c55341
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 draft area itemid for a given element.
763 * @category files
764 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
765 * @return int the itemid, or 0 if there is not one yet.
767 function file_get_submitted_draft_itemid($elname) {
768 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
769 if (!isset($_REQUEST[$elname])) {
770 return 0;
772 if (is_array($_REQUEST[$elname])) {
773 $param = optional_param_array($elname, 0, PARAM_INT);
774 if (!empty($param['itemid'])) {
775 $param = $param['itemid'];
776 } else {
777 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
778 return false;
781 } else {
782 $param = optional_param($elname, 0, PARAM_INT);
785 if ($param) {
786 require_sesskey();
789 return $param;
793 * Restore the original source field from draft files
795 * Do not use this function because it makes field files.source inconsistent
796 * for draft area files. This function will be deprecated in 2.6
798 * @param stored_file $storedfile This only works with draft files
799 * @return stored_file
801 function file_restore_source_field_from_draft_file($storedfile) {
802 $source = @unserialize($storedfile->get_source());
803 if (!empty($source)) {
804 if (is_object($source)) {
805 $restoredsource = $source->source;
806 $storedfile->set_source($restoredsource);
807 } else {
808 throw new moodle_exception('invalidsourcefield', 'error');
811 return $storedfile;
815 * Removes those files from the user drafts filearea which are not referenced in the editor text.
817 * @param stdClass $editor The online text editor element from the submitted form data.
819 function file_remove_editor_orphaned_files($editor) {
820 global $CFG, $USER;
822 // Find those draft files included in the text, and generate their hashes.
823 $context = context_user::instance($USER->id);
824 $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
825 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
826 preg_match_all($pattern, $editor['text'], $matches);
827 $usedfilehashes = [];
828 foreach ($matches[1] as $matchedfilename) {
829 $matchedfilename = urldecode($matchedfilename);
830 $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
831 $matchedfilename);
834 // Now, compare the hashes of all draft files, and remove those which don't match used files.
835 $fs = get_file_storage();
836 $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
837 foreach ($files as $file) {
838 $tmphash = $file->get_pathnamehash();
839 if (!in_array($tmphash, $usedfilehashes)) {
840 $file->delete();
846 * Saves files from a draft file area to a real one (merging the list of files).
847 * Can rewrite URLs in some content at the same time if desired.
849 * @category files
850 * @global stdClass $USER
851 * @param int $draftitemid the id of the draft area to use. Normally obtained
852 * from file_get_submitted_draft_itemid('elementname') or similar.
853 * @param int $contextid This parameter and the next two identify the file area to save to.
854 * @param string $component
855 * @param string $filearea indentifies the file area.
856 * @param int $itemid helps identifies the file area.
857 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
858 * @param string $text some html content that needs to have embedded links rewritten
859 * to the @@PLUGINFILE@@ form for saving in the database.
860 * @param bool $forcehttps force https urls.
861 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
863 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
864 global $USER;
866 $usercontext = context_user::instance($USER->id);
867 $fs = get_file_storage();
869 $options = (array)$options;
870 if (!isset($options['subdirs'])) {
871 $options['subdirs'] = false;
873 if (!isset($options['maxfiles'])) {
874 $options['maxfiles'] = -1; // unlimited
876 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
877 $options['maxbytes'] = 0; // unlimited
879 if (!isset($options['areamaxbytes'])) {
880 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
882 $allowreferences = true;
883 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
884 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
885 // this is not exactly right. BUT there are many places in code where filemanager options
886 // are not passed to file_save_draft_area_files()
887 $allowreferences = false;
890 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
891 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
892 // anything at all in the next area.
893 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
894 return null;
897 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
898 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
900 // One file in filearea means it is empty (it has only top-level directory '.').
901 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
902 // we have to merge old and new files - we want to keep file ids for files that were not changed
903 // we change time modified for all new and changed files, we keep time created as is
905 $newhashes = array();
906 $filecount = 0;
907 $context = context::instance_by_id($contextid, MUST_EXIST);
908 foreach ($draftfiles as $file) {
909 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
910 continue;
912 if (!$allowreferences && $file->is_external_file()) {
913 continue;
915 if (!$file->is_directory()) {
916 // Check to see if this file was uploaded by someone who can ignore the file size limits.
917 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
918 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
919 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
920 // Oversized file.
921 continue;
923 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
924 // more files - should not get here at all
925 continue;
927 $filecount++;
929 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
930 $newhashes[$newhash] = $file;
933 // Loop through oldfiles and decide which we need to delete and which to update.
934 // After this cycle the array $newhashes will only contain the files that need to be added.
935 foreach ($oldfiles as $oldfile) {
936 $oldhash = $oldfile->get_pathnamehash();
937 if (!isset($newhashes[$oldhash])) {
938 // delete files not needed any more - deleted by user
939 $oldfile->delete();
940 continue;
943 $newfile = $newhashes[$oldhash];
944 // Now we know that we have $oldfile and $newfile for the same path.
945 // Let's check if we can update this file or we need to delete and create.
946 if ($newfile->is_directory()) {
947 // Directories are always ok to just update.
948 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
949 // File has the 'original' - we need to update the file (it may even have not been changed at all).
950 $original = file_storage::unpack_reference($source->original);
951 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
952 // Very odd, original points to another file. Delete and create file.
953 $oldfile->delete();
954 continue;
956 } else {
957 // The same file name but absence of 'original' means that file was deteled and uploaded again.
958 // By deleting and creating new file we properly manage all existing references.
959 $oldfile->delete();
960 continue;
963 // status changed, we delete old file, and create a new one
964 if ($oldfile->get_status() != $newfile->get_status()) {
965 // file was changed, use updated with new timemodified data
966 $oldfile->delete();
967 // This file will be added later
968 continue;
971 // Updated author
972 if ($oldfile->get_author() != $newfile->get_author()) {
973 $oldfile->set_author($newfile->get_author());
975 // Updated license
976 if ($oldfile->get_license() != $newfile->get_license()) {
977 $oldfile->set_license($newfile->get_license());
980 // Updated file source
981 // Field files.source for draftarea files contains serialised object with source and original information.
982 // We only store the source part of it for non-draft file area.
983 $newsource = $newfile->get_source();
984 if ($source = @unserialize($newfile->get_source())) {
985 $newsource = $source->source;
987 if ($oldfile->get_source() !== $newsource) {
988 $oldfile->set_source($newsource);
991 // Updated sort order
992 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
993 $oldfile->set_sortorder($newfile->get_sortorder());
996 // Update file timemodified
997 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
998 $oldfile->set_timemodified($newfile->get_timemodified());
1001 // Replaced file content
1002 if (!$oldfile->is_directory() &&
1003 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1004 $oldfile->get_filesize() != $newfile->get_filesize() ||
1005 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1006 $oldfile->get_userid() != $newfile->get_userid())) {
1007 $oldfile->replace_file_with($newfile);
1010 // unchanged file or directory - we keep it as is
1011 unset($newhashes[$oldhash]);
1014 // Add fresh file or the file which has changed status
1015 // the size and subdirectory tests are extra safety only, the UI should prevent it
1016 foreach ($newhashes as $file) {
1017 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1018 if ($source = @unserialize($file->get_source())) {
1019 // Field files.source for draftarea files contains serialised object with source and original information.
1020 // We only store the source part of it for non-draft file area.
1021 $file_record['source'] = $source->source;
1024 if ($file->is_external_file()) {
1025 $repoid = $file->get_repository_id();
1026 if (!empty($repoid)) {
1027 $context = context::instance_by_id($contextid, MUST_EXIST);
1028 $repo = repository::get_repository_by_id($repoid, $context);
1029 if (!empty($options)) {
1030 $repo->options = $options;
1032 $file_record['repositoryid'] = $repoid;
1033 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1034 // to the file store. E.g. transfer ownership of the file to a system account etc.
1035 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1037 $file_record['reference'] = $reference;
1041 $fs->create_file_from_storedfile($file_record, $file);
1045 // note: do not purge the draft area - we clean up areas later in cron,
1046 // the reason is that user might press submit twice and they would loose the files,
1047 // also sometimes we might want to use hacks that save files into two different areas
1049 if (is_null($text)) {
1050 return null;
1051 } else {
1052 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1057 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1058 * ready to be saved in the database. Normally, this is done automatically by
1059 * {@link file_save_draft_area_files()}.
1061 * @category files
1062 * @param string $text the content to process.
1063 * @param int $draftitemid the draft file area the content was using.
1064 * @param bool $forcehttps whether the content contains https URLs. Default false.
1065 * @return string the processed content.
1067 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1068 global $CFG, $USER;
1070 $usercontext = context_user::instance($USER->id);
1072 $wwwroot = $CFG->wwwroot;
1073 if ($forcehttps) {
1074 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1077 // relink embedded files if text submitted - no absolute links allowed in database!
1078 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1080 if (strpos($text, 'draftfile.php?file=') !== false) {
1081 $matches = array();
1082 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1083 if ($matches) {
1084 foreach ($matches[0] as $match) {
1085 $replace = str_ireplace('%2F', '/', $match);
1086 $text = str_replace($match, $replace, $text);
1089 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1092 return $text;
1096 * Set file sort order
1098 * @global moodle_database $DB
1099 * @param int $contextid the context id
1100 * @param string $component file component
1101 * @param string $filearea file area.
1102 * @param int $itemid itemid.
1103 * @param string $filepath file path.
1104 * @param string $filename file name.
1105 * @param int $sortorder the sort order of file.
1106 * @return bool
1108 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1109 global $DB;
1110 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1111 if ($file_record = $DB->get_record('files', $conditions)) {
1112 $sortorder = (int)$sortorder;
1113 $file_record->sortorder = $sortorder;
1114 $DB->update_record('files', $file_record);
1115 return true;
1117 return false;
1121 * reset file sort order number to 0
1122 * @global moodle_database $DB
1123 * @param int $contextid the context id
1124 * @param string $component
1125 * @param string $filearea file area.
1126 * @param int|bool $itemid itemid.
1127 * @return bool
1129 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1130 global $DB;
1132 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1133 if ($itemid !== false) {
1134 $conditions['itemid'] = $itemid;
1137 $file_records = $DB->get_records('files', $conditions);
1138 foreach ($file_records as $file_record) {
1139 $file_record->sortorder = 0;
1140 $DB->update_record('files', $file_record);
1142 return true;
1146 * Returns description of upload error
1148 * @param int $errorcode found in $_FILES['filename.ext']['error']
1149 * @return string error description string, '' if ok
1151 function file_get_upload_error($errorcode) {
1153 switch ($errorcode) {
1154 case 0: // UPLOAD_ERR_OK - no error
1155 $errmessage = '';
1156 break;
1158 case 1: // UPLOAD_ERR_INI_SIZE
1159 $errmessage = get_string('uploadserverlimit');
1160 break;
1162 case 2: // UPLOAD_ERR_FORM_SIZE
1163 $errmessage = get_string('uploadformlimit');
1164 break;
1166 case 3: // UPLOAD_ERR_PARTIAL
1167 $errmessage = get_string('uploadpartialfile');
1168 break;
1170 case 4: // UPLOAD_ERR_NO_FILE
1171 $errmessage = get_string('uploadnofilefound');
1172 break;
1174 // Note: there is no error with a value of 5
1176 case 6: // UPLOAD_ERR_NO_TMP_DIR
1177 $errmessage = get_string('uploadnotempdir');
1178 break;
1180 case 7: // UPLOAD_ERR_CANT_WRITE
1181 $errmessage = get_string('uploadcantwrite');
1182 break;
1184 case 8: // UPLOAD_ERR_EXTENSION
1185 $errmessage = get_string('uploadextension');
1186 break;
1188 default:
1189 $errmessage = get_string('uploadproblem');
1192 return $errmessage;
1196 * Recursive function formating an array in POST parameter
1197 * @param array $arraydata - the array that we are going to format and add into &$data array
1198 * @param string $currentdata - a row of the final postdata array at instant T
1199 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1200 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1202 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1203 foreach ($arraydata as $k=>$v) {
1204 $newcurrentdata = $currentdata;
1205 if (is_array($v)) { //the value is an array, call the function recursively
1206 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1207 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1208 } else { //add the POST parameter to the $data array
1209 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1215 * Transform a PHP array into POST parameter
1216 * (see the recursive function format_array_postdata_for_curlcall)
1217 * @param array $postdata
1218 * @return array containing all POST parameters (1 row = 1 POST parameter)
1220 function format_postdata_for_curlcall($postdata) {
1221 $data = array();
1222 foreach ($postdata as $k=>$v) {
1223 if (is_array($v)) {
1224 $currentdata = urlencode($k);
1225 format_array_postdata_for_curlcall($v, $currentdata, $data);
1226 } else {
1227 $data[] = urlencode($k).'='.urlencode($v);
1230 $convertedpostdata = implode('&', $data);
1231 return $convertedpostdata;
1235 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1236 * Due to security concerns only downloads from http(s) sources are supported.
1238 * @category files
1239 * @param string $url file url starting with http(s)://
1240 * @param array $headers http headers, null if none. If set, should be an
1241 * associative array of header name => value pairs.
1242 * @param array $postdata array means use POST request with given parameters
1243 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1244 * (if false, just returns content)
1245 * @param int $timeout timeout for complete download process including all file transfer
1246 * (default 5 minutes)
1247 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1248 * usually happens if the remote server is completely down (default 20 seconds);
1249 * may not work when using proxy
1250 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1251 * Only use this when already in a trusted location.
1252 * @param string $tofile store the downloaded content to file instead of returning it.
1253 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1254 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1255 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1256 * if file downloaded into $tofile successfully or the file content as a string.
1258 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1259 global $CFG;
1261 // Only http and https links supported.
1262 if (!preg_match('|^https?://|i', $url)) {
1263 if ($fullresponse) {
1264 $response = new stdClass();
1265 $response->status = 0;
1266 $response->headers = array();
1267 $response->response_code = 'Invalid protocol specified in url';
1268 $response->results = '';
1269 $response->error = 'Invalid protocol specified in url';
1270 return $response;
1271 } else {
1272 return false;
1276 $options = array();
1278 $headers2 = array();
1279 if (is_array($headers)) {
1280 foreach ($headers as $key => $value) {
1281 if (is_numeric($key)) {
1282 $headers2[] = $value;
1283 } else {
1284 $headers2[] = "$key: $value";
1289 if ($skipcertverify) {
1290 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1291 } else {
1292 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1295 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1297 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1298 $options['CURLOPT_MAXREDIRS'] = 5;
1300 // Use POST if requested.
1301 if (is_array($postdata)) {
1302 $postdata = format_postdata_for_curlcall($postdata);
1303 } else if (empty($postdata)) {
1304 $postdata = null;
1307 // Optionally attempt to get more correct timeout by fetching the file size.
1308 if (!isset($CFG->curltimeoutkbitrate)) {
1309 // Use very slow rate of 56kbps as a timeout speed when not set.
1310 $bitrate = 56;
1311 } else {
1312 $bitrate = $CFG->curltimeoutkbitrate;
1314 if ($calctimeout and !isset($postdata)) {
1315 $curl = new curl();
1316 $curl->setHeader($headers2);
1318 $curl->head($url, $postdata, $options);
1320 $info = $curl->get_info();
1321 $error_no = $curl->get_errno();
1322 if (!$error_no && $info['download_content_length'] > 0) {
1323 // No curl errors - adjust for large files only - take max timeout.
1324 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1328 $curl = new curl();
1329 $curl->setHeader($headers2);
1331 $options['CURLOPT_RETURNTRANSFER'] = true;
1332 $options['CURLOPT_NOBODY'] = false;
1333 $options['CURLOPT_TIMEOUT'] = $timeout;
1335 if ($tofile) {
1336 $fh = fopen($tofile, 'w');
1337 if (!$fh) {
1338 if ($fullresponse) {
1339 $response = new stdClass();
1340 $response->status = 0;
1341 $response->headers = array();
1342 $response->response_code = 'Can not write to file';
1343 $response->results = false;
1344 $response->error = 'Can not write to file';
1345 return $response;
1346 } else {
1347 return false;
1350 $options['CURLOPT_FILE'] = $fh;
1353 if (isset($postdata)) {
1354 $content = $curl->post($url, $postdata, $options);
1355 } else {
1356 $content = $curl->get($url, null, $options);
1359 if ($tofile) {
1360 fclose($fh);
1361 @chmod($tofile, $CFG->filepermissions);
1365 // Try to detect encoding problems.
1366 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1367 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1368 $result = curl_exec($ch);
1372 $info = $curl->get_info();
1373 $error_no = $curl->get_errno();
1374 $rawheaders = $curl->get_raw_response();
1376 if ($error_no) {
1377 $error = $content;
1378 if (!$fullresponse) {
1379 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1380 return false;
1383 $response = new stdClass();
1384 if ($error_no == 28) {
1385 $response->status = '-100'; // Mimic snoopy.
1386 } else {
1387 $response->status = '0';
1389 $response->headers = array();
1390 $response->response_code = $error;
1391 $response->results = false;
1392 $response->error = $error;
1393 return $response;
1396 if ($tofile) {
1397 $content = true;
1400 if (empty($info['http_code'])) {
1401 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1402 $response = new stdClass();
1403 $response->status = '0';
1404 $response->headers = array();
1405 $response->response_code = 'Unknown cURL error';
1406 $response->results = false; // do NOT change this, we really want to ignore the result!
1407 $response->error = 'Unknown cURL error';
1409 } else {
1410 $response = new stdClass();
1411 $response->status = (string)$info['http_code'];
1412 $response->headers = $rawheaders;
1413 $response->results = $content;
1414 $response->error = '';
1416 // There might be multiple headers on redirect, find the status of the last one.
1417 $firstline = true;
1418 foreach ($rawheaders as $line) {
1419 if ($firstline) {
1420 $response->response_code = $line;
1421 $firstline = false;
1423 if (trim($line, "\r\n") === '') {
1424 $firstline = true;
1429 if ($fullresponse) {
1430 return $response;
1433 if ($info['http_code'] != 200) {
1434 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1435 return false;
1437 return $response->results;
1441 * Returns a list of information about file types based on extensions.
1443 * The following elements expected in value array for each extension:
1444 * 'type' - mimetype
1445 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1446 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1447 * also files with bigger sizes under names
1448 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1449 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1450 * commonly used in moodle the following groups:
1451 * - web_image - image that can be included as <img> in HTML
1452 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1453 * - video - file that can be imported as video in text editor
1454 * - audio - file that can be imported as audio in text editor
1455 * - archive - we can extract files from this archive
1456 * - spreadsheet - used for portfolio format
1457 * - document - used for portfolio format
1458 * - presentation - used for portfolio format
1459 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1460 * human-readable description for this filetype;
1461 * Function {@link get_mimetype_description()} first looks at the presence of string for
1462 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1463 * attribute, if not found returns the value of 'type';
1464 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1465 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1466 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1468 * @category files
1469 * @return array List of information about file types based on extensions.
1470 * Associative array of extension (lower-case) to associative array
1471 * from 'element name' to data. Current element names are 'type' and 'icon'.
1472 * Unknown types should use the 'xxx' entry which includes defaults.
1474 function &get_mimetypes_array() {
1475 // Get types from the core_filetypes function, which includes caching.
1476 return core_filetypes::get_types();
1480 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1482 * This function retrieves a file's MIME type for a file that will be sent to the user.
1483 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1484 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1485 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1487 * @param string $filename The file's filename.
1488 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1490 function get_mimetype_for_sending($filename = '') {
1491 // Guess the file's MIME type using mimeinfo.
1492 $mimetype = mimeinfo('type', $filename);
1494 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1495 if (!$mimetype || $mimetype === 'document/unknown') {
1496 $mimetype = 'application/octet-stream';
1499 return $mimetype;
1503 * Obtains information about a filetype based on its extension. Will
1504 * use a default if no information is present about that particular
1505 * extension.
1507 * @category files
1508 * @param string $element Desired information (usually 'icon'
1509 * for icon filename or 'type' for MIME type. Can also be
1510 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1511 * @param string $filename Filename we're looking up
1512 * @return string Requested piece of information from array
1514 function mimeinfo($element, $filename) {
1515 global $CFG;
1516 $mimeinfo = & get_mimetypes_array();
1517 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1519 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1520 if (empty($filetype)) {
1521 $filetype = 'xxx'; // file without extension
1523 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1524 $iconsize = max(array(16, (int)$iconsizematch[1]));
1525 $filenames = array($mimeinfo['xxx']['icon']);
1526 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1527 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1529 // find the file with the closest size, first search for specific icon then for default icon
1530 foreach ($filenames as $filename) {
1531 foreach ($iconpostfixes as $size => $postfix) {
1532 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1533 if ($iconsize >= $size &&
1534 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1535 return $filename.$postfix;
1539 } else if (isset($mimeinfo[$filetype][$element])) {
1540 return $mimeinfo[$filetype][$element];
1541 } else if (isset($mimeinfo['xxx'][$element])) {
1542 return $mimeinfo['xxx'][$element]; // By default
1543 } else {
1544 return null;
1549 * Obtains information about a filetype based on the MIME type rather than
1550 * the other way around.
1552 * @category files
1553 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1554 * @param string $mimetype MIME type we're looking up
1555 * @return string Requested piece of information from array
1557 function mimeinfo_from_type($element, $mimetype) {
1558 /* array of cached mimetype->extension associations */
1559 static $cached = array();
1560 $mimeinfo = & get_mimetypes_array();
1562 if (!array_key_exists($mimetype, $cached)) {
1563 $cached[$mimetype] = null;
1564 foreach($mimeinfo as $filetype => $values) {
1565 if ($values['type'] == $mimetype) {
1566 if ($cached[$mimetype] === null) {
1567 $cached[$mimetype] = '.'.$filetype;
1569 if (!empty($values['defaulticon'])) {
1570 $cached[$mimetype] = '.'.$filetype;
1571 break;
1575 if (empty($cached[$mimetype])) {
1576 $cached[$mimetype] = '.xxx';
1579 if ($element === 'extension') {
1580 return $cached[$mimetype];
1581 } else {
1582 return mimeinfo($element, $cached[$mimetype]);
1587 * Return the relative icon path for a given file
1589 * Usage:
1590 * <code>
1591 * // $file - instance of stored_file or file_info
1592 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1593 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1594 * </code>
1595 * or
1596 * <code>
1597 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1598 * </code>
1600 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1601 * and $file->mimetype are expected)
1602 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1603 * @return string
1605 function file_file_icon($file, $size = null) {
1606 if (!is_object($file)) {
1607 $file = (object)$file;
1609 if (isset($file->filename)) {
1610 $filename = $file->filename;
1611 } else if (method_exists($file, 'get_filename')) {
1612 $filename = $file->get_filename();
1613 } else if (method_exists($file, 'get_visible_name')) {
1614 $filename = $file->get_visible_name();
1615 } else {
1616 $filename = '';
1618 if (isset($file->mimetype)) {
1619 $mimetype = $file->mimetype;
1620 } else if (method_exists($file, 'get_mimetype')) {
1621 $mimetype = $file->get_mimetype();
1622 } else {
1623 $mimetype = '';
1625 $mimetypes = &get_mimetypes_array();
1626 if ($filename) {
1627 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1628 if ($extension && !empty($mimetypes[$extension])) {
1629 // if file name has known extension, return icon for this extension
1630 return file_extension_icon($filename, $size);
1633 return file_mimetype_icon($mimetype, $size);
1637 * Return the relative icon path for a folder image
1639 * Usage:
1640 * <code>
1641 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1642 * echo html_writer::empty_tag('img', array('src' => $icon));
1643 * </code>
1644 * or
1645 * <code>
1646 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1647 * </code>
1649 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1650 * @return string
1652 function file_folder_icon($iconsize = null) {
1653 global $CFG;
1654 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1655 static $cached = array();
1656 $iconsize = max(array(16, (int)$iconsize));
1657 if (!array_key_exists($iconsize, $cached)) {
1658 foreach ($iconpostfixes as $size => $postfix) {
1659 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1660 if ($iconsize >= $size &&
1661 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1662 $cached[$iconsize] = 'f/folder'.$postfix;
1663 break;
1667 return $cached[$iconsize];
1671 * Returns the relative icon path for a given mime type
1673 * This function should be used in conjunction with $OUTPUT->image_url to produce
1674 * a return the full path to an icon.
1676 * <code>
1677 * $mimetype = 'image/jpg';
1678 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1679 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1680 * </code>
1682 * @category files
1683 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1684 * to conform with that.
1685 * @param string $mimetype The mimetype to fetch an icon for
1686 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1687 * @return string The relative path to the icon
1689 function file_mimetype_icon($mimetype, $size = NULL) {
1690 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1694 * Returns the relative icon path for a given file name
1696 * This function should be used in conjunction with $OUTPUT->image_url to produce
1697 * a return the full path to an icon.
1699 * <code>
1700 * $filename = '.jpg';
1701 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1702 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1703 * </code>
1705 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1706 * to conform with that.
1707 * @todo MDL-31074 Implement $size
1708 * @category files
1709 * @param string $filename The filename to get the icon for
1710 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1711 * @return string
1713 function file_extension_icon($filename, $size = NULL) {
1714 return 'f/'.mimeinfo('icon'.$size, $filename);
1718 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1719 * mimetypes.php language file.
1721 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1722 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1723 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1724 * @param bool $capitalise If true, capitalises first character of result
1725 * @return string Text description
1727 function get_mimetype_description($obj, $capitalise=false) {
1728 $filename = $mimetype = '';
1729 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1730 // this is an instance of stored_file
1731 $mimetype = $obj->get_mimetype();
1732 $filename = $obj->get_filename();
1733 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1734 // this is an instance of file_info
1735 $mimetype = $obj->get_mimetype();
1736 $filename = $obj->get_visible_name();
1737 } else if (is_array($obj) || is_object ($obj)) {
1738 $obj = (array)$obj;
1739 if (!empty($obj['filename'])) {
1740 $filename = $obj['filename'];
1742 if (!empty($obj['mimetype'])) {
1743 $mimetype = $obj['mimetype'];
1745 } else {
1746 $mimetype = $obj;
1748 $mimetypefromext = mimeinfo('type', $filename);
1749 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1750 // if file has a known extension, overwrite the specified mimetype
1751 $mimetype = $mimetypefromext;
1753 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1754 if (empty($extension)) {
1755 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1756 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1757 } else {
1758 $mimetypestr = mimeinfo('string', $filename);
1760 $chunks = explode('/', $mimetype, 2);
1761 $chunks[] = '';
1762 $attr = array(
1763 'mimetype' => $mimetype,
1764 'ext' => $extension,
1765 'mimetype1' => $chunks[0],
1766 'mimetype2' => $chunks[1],
1768 $a = array();
1769 foreach ($attr as $key => $value) {
1770 $a[$key] = $value;
1771 $a[strtoupper($key)] = strtoupper($value);
1772 $a[ucfirst($key)] = ucfirst($value);
1775 // MIME types may include + symbol but this is not permitted in string ids.
1776 $safemimetype = str_replace('+', '_', $mimetype);
1777 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1778 $customdescription = mimeinfo('customdescription', $filename);
1779 if ($customdescription) {
1780 // Call format_string on the custom description so that multilang
1781 // filter can be used (if enabled on system context). We use system
1782 // context because it is possible that the page context might not have
1783 // been defined yet.
1784 $result = format_string($customdescription, true,
1785 array('context' => context_system::instance()));
1786 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1787 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1788 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1789 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1790 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1791 $result = get_string('default', 'mimetypes', (object)$a);
1792 } else {
1793 $result = $mimetype;
1795 if ($capitalise) {
1796 $result=ucfirst($result);
1798 return $result;
1802 * Returns array of elements of type $element in type group(s)
1804 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1805 * @param string|array $groups one group or array of groups/extensions/mimetypes
1806 * @return array
1808 function file_get_typegroup($element, $groups) {
1809 static $cached = array();
1810 if (!is_array($groups)) {
1811 $groups = array($groups);
1813 if (!array_key_exists($element, $cached)) {
1814 $cached[$element] = array();
1816 $result = array();
1817 foreach ($groups as $group) {
1818 if (!array_key_exists($group, $cached[$element])) {
1819 // retrieive and cache all elements of type $element for group $group
1820 $mimeinfo = & get_mimetypes_array();
1821 $cached[$element][$group] = array();
1822 foreach ($mimeinfo as $extension => $value) {
1823 $value['extension'] = '.'.$extension;
1824 if (empty($value[$element])) {
1825 continue;
1827 if (($group === '.'.$extension || $group === $value['type'] ||
1828 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1829 !in_array($value[$element], $cached[$element][$group])) {
1830 $cached[$element][$group][] = $value[$element];
1834 $result = array_merge($result, $cached[$element][$group]);
1836 return array_values(array_unique($result));
1840 * Checks if file with name $filename has one of the extensions in groups $groups
1842 * @see get_mimetypes_array()
1843 * @param string $filename name of the file to check
1844 * @param string|array $groups one group or array of groups to check
1845 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1846 * file mimetype is in mimetypes in groups $groups
1847 * @return bool
1849 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1850 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1851 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1852 return true;
1854 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1858 * Checks if mimetype $mimetype belongs to one of the groups $groups
1860 * @see get_mimetypes_array()
1861 * @param string $mimetype
1862 * @param string|array $groups one group or array of groups to check
1863 * @return bool
1865 function file_mimetype_in_typegroup($mimetype, $groups) {
1866 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1870 * Requested file is not found or not accessible, does not return, terminates script
1872 * @global stdClass $CFG
1873 * @global stdClass $COURSE
1875 function send_file_not_found() {
1876 global $CFG, $COURSE;
1878 // Allow cross-origin requests only for Web Services.
1879 // This allow to receive requests done by Web Workers or webapps in different domains.
1880 if (WS_SERVER) {
1881 header('Access-Control-Allow-Origin: *');
1884 send_header_404();
1885 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1888 * Helper function to send correct 404 for server.
1890 function send_header_404() {
1891 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1892 header("Status: 404 Not Found");
1893 } else {
1894 header('HTTP/1.0 404 not found');
1899 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1900 * platforms). This wrapper uses readfile for small files and custom code for
1901 * large ones.
1903 * @param string $path Path to file
1904 * @param int $filesize Size of file (if left out, will get it automatically)
1905 * @return int|bool Size read (will always be $filesize) or false if failed
1907 function readfile_allow_large($path, $filesize = -1) {
1908 // Automatically get size if not specified.
1909 if ($filesize === -1) {
1910 $filesize = filesize($path);
1912 if ($filesize <= 2147483647) {
1913 // If the file is up to 2^31 - 1, send it normally using readfile.
1914 return readfile($path);
1915 } else {
1916 // For large files, read and output in 64KB chunks.
1917 $handle = fopen($path, 'r');
1918 if ($handle === false) {
1919 return false;
1921 $left = $filesize;
1922 while ($left > 0) {
1923 $size = min($left, 65536);
1924 $buffer = fread($handle, $size);
1925 if ($buffer === false) {
1926 return false;
1928 echo $buffer;
1929 $left -= $size;
1931 return $filesize;
1936 * Enhanced readfile() with optional acceleration.
1937 * @param string|stored_file $file
1938 * @param string $mimetype
1939 * @param bool $accelerate
1940 * @return void
1942 function readfile_accel($file, $mimetype, $accelerate) {
1943 global $CFG;
1945 if ($mimetype === 'text/plain') {
1946 // there is no encoding specified in text files, we need something consistent
1947 header('Content-Type: text/plain; charset=utf-8');
1948 } else {
1949 header('Content-Type: '.$mimetype);
1952 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1953 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1955 if (is_object($file)) {
1956 header('Etag: "' . $file->get_contenthash() . '"');
1957 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1958 header('HTTP/1.1 304 Not Modified');
1959 return;
1963 // if etag present for stored file rely on it exclusively
1964 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1965 // get unixtime of request header; clip extra junk off first
1966 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1967 if ($since && $since >= $lastmodified) {
1968 header('HTTP/1.1 304 Not Modified');
1969 return;
1973 if ($accelerate and !empty($CFG->xsendfile)) {
1974 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1975 header('Accept-Ranges: bytes');
1976 } else {
1977 header('Accept-Ranges: none');
1980 if (is_object($file)) {
1981 $fs = get_file_storage();
1982 if ($fs->xsendfile($file->get_contenthash())) {
1983 return;
1986 } else {
1987 require_once("$CFG->libdir/xsendfilelib.php");
1988 if (xsendfile($file)) {
1989 return;
1994 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1996 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1998 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1999 header('Accept-Ranges: bytes');
2001 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2002 // byteserving stuff - for acrobat reader and download accelerators
2003 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2004 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2005 $ranges = false;
2006 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2007 foreach ($ranges as $key=>$value) {
2008 if ($ranges[$key][1] == '') {
2009 //suffix case
2010 $ranges[$key][1] = $filesize - $ranges[$key][2];
2011 $ranges[$key][2] = $filesize - 1;
2012 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2013 //fix range length
2014 $ranges[$key][2] = $filesize - 1;
2016 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2017 //invalid byte-range ==> ignore header
2018 $ranges = false;
2019 break;
2021 //prepare multipart header
2022 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2023 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2025 } else {
2026 $ranges = false;
2028 if ($ranges) {
2029 if (is_object($file)) {
2030 $handle = $file->get_content_file_handle();
2031 } else {
2032 $handle = fopen($file, 'rb');
2034 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2037 } else {
2038 // Do not byteserve
2039 header('Accept-Ranges: none');
2042 header('Content-Length: '.$filesize);
2044 if ($filesize > 10000000) {
2045 // for large files try to flush and close all buffers to conserve memory
2046 while(@ob_get_level()) {
2047 if (!@ob_end_flush()) {
2048 break;
2053 // send the whole file content
2054 if (is_object($file)) {
2055 $file->readfile();
2056 } else {
2057 readfile_allow_large($file, $filesize);
2062 * Similar to readfile_accel() but designed for strings.
2063 * @param string $string
2064 * @param string $mimetype
2065 * @param bool $accelerate
2066 * @return void
2068 function readstring_accel($string, $mimetype, $accelerate) {
2069 global $CFG;
2071 if ($mimetype === 'text/plain') {
2072 // there is no encoding specified in text files, we need something consistent
2073 header('Content-Type: text/plain; charset=utf-8');
2074 } else {
2075 header('Content-Type: '.$mimetype);
2077 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2078 header('Accept-Ranges: none');
2080 if ($accelerate and !empty($CFG->xsendfile)) {
2081 $fs = get_file_storage();
2082 if ($fs->xsendfile(sha1($string))) {
2083 return;
2087 header('Content-Length: '.strlen($string));
2088 echo $string;
2092 * Handles the sending of temporary file to user, download is forced.
2093 * File is deleted after abort or successful sending, does not return, script terminated
2095 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2096 * @param string $filename proposed file name when saving file
2097 * @param bool $pathisstring If the path is string
2099 function send_temp_file($path, $filename, $pathisstring=false) {
2100 global $CFG;
2102 // Guess the file's MIME type.
2103 $mimetype = get_mimetype_for_sending($filename);
2105 // close session - not needed anymore
2106 \core\session\manager::write_close();
2108 if (!$pathisstring) {
2109 if (!file_exists($path)) {
2110 send_header_404();
2111 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2113 // executed after normal finish or abort
2114 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2117 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2118 if (core_useragent::is_ie()) {
2119 $filename = urlencode($filename);
2122 header('Content-Disposition: attachment; filename="'.$filename.'"');
2123 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2124 header('Cache-Control: private, max-age=10, no-transform');
2125 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2126 header('Pragma: ');
2127 } else { //normal http - prevent caching at all cost
2128 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2129 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2130 header('Pragma: no-cache');
2133 // send the contents - we can not accelerate this because the file will be deleted asap
2134 if ($pathisstring) {
2135 readstring_accel($path, $mimetype, false);
2136 } else {
2137 readfile_accel($path, $mimetype, false);
2138 @unlink($path);
2141 die; //no more chars to output
2145 * Internal callback function used by send_temp_file()
2147 * @param string $path
2149 function send_temp_file_finished($path) {
2150 if (file_exists($path)) {
2151 @unlink($path);
2156 * Serve content which is not meant to be cached.
2158 * This is only intended to be used for volatile public files, for instance
2159 * when development is enabled, or when caching is not required on a public resource.
2161 * @param string $content Raw content.
2162 * @param string $filename The file name.
2163 * @return void
2165 function send_content_uncached($content, $filename) {
2166 $mimetype = mimeinfo('type', $filename);
2167 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2169 header('Content-Disposition: inline; filename="' . $filename . '"');
2170 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2171 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2172 header('Pragma: ');
2173 header('Accept-Ranges: none');
2174 header('Content-Type: ' . $mimetype . $charset);
2175 header('Content-Length: ' . strlen($content));
2177 echo $content;
2178 die();
2182 * Safely save content to a certain path.
2184 * This function tries hard to be atomic by first copying the content
2185 * to a separate file, and then moving the file across. It also prevents
2186 * the user to abort a request to prevent half-safed files.
2188 * This function is intended to be used when saving some content to cache like
2189 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2191 * @param string $content The file content.
2192 * @param string $destination The absolute path of the final file.
2193 * @return void
2195 function file_safe_save_content($content, $destination) {
2196 global $CFG;
2198 clearstatcache();
2199 if (!file_exists(dirname($destination))) {
2200 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2203 // Prevent serving of incomplete file from concurrent request,
2204 // the rename() should be more atomic than fwrite().
2205 ignore_user_abort(true);
2206 if ($fp = fopen($destination . '.tmp', 'xb')) {
2207 fwrite($fp, $content);
2208 fclose($fp);
2209 rename($destination . '.tmp', $destination);
2210 @chmod($destination, $CFG->filepermissions);
2211 @unlink($destination . '.tmp'); // Just in case anything fails.
2213 ignore_user_abort(false);
2214 if (connection_aborted()) {
2215 die();
2220 * Handles the sending of file data to the user's browser, including support for
2221 * byteranges etc.
2223 * @category files
2224 * @param string|stored_file $path Path of file on disk (including real filename),
2225 * or actual content of file as string,
2226 * or stored_file object
2227 * @param string $filename Filename to send
2228 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2229 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2230 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2231 * Forced to false when $path is a stored_file object.
2232 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2233 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2234 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2235 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2236 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2237 * and should not be reopened.
2238 * @param array $options An array of options, currently accepts:
2239 * - (string) cacheability: public, or private.
2240 * - (string|null) immutable
2241 * @return null script execution stopped unless $dontdie is true
2243 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2244 $dontdie=false, array $options = array()) {
2245 global $CFG, $COURSE;
2247 if ($dontdie) {
2248 ignore_user_abort(true);
2251 if ($lifetime === 'default' or is_null($lifetime)) {
2252 $lifetime = $CFG->filelifetime;
2255 if (is_object($path)) {
2256 $pathisstring = false;
2259 \core\session\manager::write_close(); // Unlock session during file serving.
2261 // Use given MIME type if specified, otherwise guess it.
2262 if (!$mimetype || $mimetype === 'document/unknown') {
2263 $mimetype = get_mimetype_for_sending($filename);
2266 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2267 if (core_useragent::is_ie()) {
2268 $filename = rawurlencode($filename);
2271 if ($forcedownload) {
2272 header('Content-Disposition: attachment; filename="'.$filename.'"');
2273 } else if ($mimetype !== 'application/x-shockwave-flash') {
2274 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2275 // as an upload and enforces security that may prevent the file from being loaded.
2277 header('Content-Disposition: inline; filename="'.$filename.'"');
2280 if ($lifetime > 0) {
2281 $immutable = '';
2282 if (!empty($options['immutable'])) {
2283 $immutable = ', immutable';
2284 // Overwrite lifetime accordingly:
2285 // 90 days only - based on Moodle point release cadence being every 3 months.
2286 $lifetimemin = 60 * 60 * 24 * 90;
2287 $lifetime = max($lifetime, $lifetimemin);
2289 $cacheability = ' public,';
2290 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2291 // This file must be cache-able by both browsers and proxies.
2292 $cacheability = ' public,';
2293 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2294 // This file must be cache-able only by browsers.
2295 $cacheability = ' private,';
2296 } else if (isloggedin() and !isguestuser()) {
2297 // By default, under the conditions above, this file must be cache-able only by browsers.
2298 $cacheability = ' private,';
2300 $nobyteserving = false;
2301 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2302 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2303 header('Pragma: ');
2305 } else { // Do not cache files in proxies and browsers
2306 $nobyteserving = true;
2307 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2308 header('Cache-Control: private, max-age=10, no-transform');
2309 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2310 header('Pragma: ');
2311 } else { //normal http - prevent caching at all cost
2312 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2313 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2314 header('Pragma: no-cache');
2318 if (empty($filter)) {
2319 // send the contents
2320 if ($pathisstring) {
2321 readstring_accel($path, $mimetype, !$dontdie);
2322 } else {
2323 readfile_accel($path, $mimetype, !$dontdie);
2326 } else {
2327 // Try to put the file through filters
2328 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2329 $options = new stdClass();
2330 $options->noclean = true;
2331 $options->nocache = true; // temporary workaround for MDL-5136
2332 if (is_object($path)) {
2333 $text = $path->get_content();
2334 } else if ($pathisstring) {
2335 $text = $path;
2336 } else {
2337 $text = implode('', file($path));
2339 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2341 readstring_accel($output, $mimetype, false);
2343 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2344 // only filter text if filter all files is selected
2345 $options = new stdClass();
2346 $options->newlines = false;
2347 $options->noclean = true;
2348 if (is_object($path)) {
2349 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2350 } else if ($pathisstring) {
2351 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2352 } else {
2353 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2355 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2357 readstring_accel($output, $mimetype, false);
2359 } else {
2360 // send the contents
2361 if ($pathisstring) {
2362 readstring_accel($path, $mimetype, !$dontdie);
2363 } else {
2364 readfile_accel($path, $mimetype, !$dontdie);
2368 if ($dontdie) {
2369 return;
2371 die; //no more chars to output!!!
2375 * Handles the sending of file data to the user's browser, including support for
2376 * byteranges etc.
2378 * The $options parameter supports the following keys:
2379 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2380 * (string|null) filename - overrides the implicit filename
2381 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2382 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2383 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2384 * and should not be reopened
2385 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2386 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2387 * defaults to "public".
2388 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2389 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2391 * @category files
2392 * @param stored_file $stored_file local file object
2393 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2394 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2395 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2396 * @param array $options additional options affecting the file serving
2397 * @return null script execution stopped unless $options['dontdie'] is true
2399 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2400 global $CFG, $COURSE;
2402 if (empty($options['filename'])) {
2403 $filename = null;
2404 } else {
2405 $filename = $options['filename'];
2408 if (empty($options['dontdie'])) {
2409 $dontdie = false;
2410 } else {
2411 $dontdie = true;
2414 if ($lifetime === 'default' or is_null($lifetime)) {
2415 $lifetime = $CFG->filelifetime;
2418 if (!empty($options['preview'])) {
2419 // replace the file with its preview
2420 $fs = get_file_storage();
2421 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2422 if (!$preview_file) {
2423 // unable to create a preview of the file, send its default mime icon instead
2424 if ($options['preview'] === 'tinyicon') {
2425 $size = 24;
2426 } else if ($options['preview'] === 'thumb') {
2427 $size = 90;
2428 } else {
2429 $size = 256;
2431 $fileicon = file_file_icon($stored_file, $size);
2432 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2433 } else {
2434 // preview images have fixed cache lifetime and they ignore forced download
2435 // (they are generated by GD and therefore they are considered reasonably safe).
2436 $stored_file = $preview_file;
2437 $lifetime = DAYSECS;
2438 $filter = 0;
2439 $forcedownload = false;
2443 // handle external resource
2444 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2445 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2446 die;
2449 if (!$stored_file or $stored_file->is_directory()) {
2450 // nothing to serve
2451 if ($dontdie) {
2452 return;
2454 die;
2457 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2459 // Use given MIME type if specified.
2460 $mimetype = $stored_file->get_mimetype();
2462 // Allow cross-origin requests only for Web Services.
2463 // This allow to receive requests done by Web Workers or webapps in different domains.
2464 if (WS_SERVER) {
2465 header('Access-Control-Allow-Origin: *');
2468 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2472 * Recursively delete the file or folder with path $location. That is,
2473 * if it is a file delete it. If it is a folder, delete all its content
2474 * then delete it. If $location does not exist to start, that is not
2475 * considered an error.
2477 * @param string $location the path to remove.
2478 * @return bool
2480 function fulldelete($location) {
2481 if (empty($location)) {
2482 // extra safety against wrong param
2483 return false;
2485 if (is_dir($location)) {
2486 if (!$currdir = opendir($location)) {
2487 return false;
2489 while (false !== ($file = readdir($currdir))) {
2490 if ($file <> ".." && $file <> ".") {
2491 $fullfile = $location."/".$file;
2492 if (is_dir($fullfile)) {
2493 if (!fulldelete($fullfile)) {
2494 return false;
2496 } else {
2497 if (!unlink($fullfile)) {
2498 return false;
2503 closedir($currdir);
2504 if (! rmdir($location)) {
2505 return false;
2508 } else if (file_exists($location)) {
2509 if (!unlink($location)) {
2510 return false;
2513 return true;
2517 * Send requested byterange of file.
2519 * @param resource $handle A file handle
2520 * @param string $mimetype The mimetype for the output
2521 * @param array $ranges An array of ranges to send
2522 * @param string $filesize The size of the content if only one range is used
2524 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2525 // better turn off any kind of compression and buffering
2526 ini_set('zlib.output_compression', 'Off');
2528 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2529 if ($handle === false) {
2530 die;
2532 if (count($ranges) == 1) { //only one range requested
2533 $length = $ranges[0][2] - $ranges[0][1] + 1;
2534 header('HTTP/1.1 206 Partial content');
2535 header('Content-Length: '.$length);
2536 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2537 header('Content-Type: '.$mimetype);
2539 while(@ob_get_level()) {
2540 if (!@ob_end_flush()) {
2541 break;
2545 fseek($handle, $ranges[0][1]);
2546 while (!feof($handle) && $length > 0) {
2547 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2548 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2549 echo $buffer;
2550 flush();
2551 $length -= strlen($buffer);
2553 fclose($handle);
2554 die;
2555 } else { // multiple ranges requested - not tested much
2556 $totallength = 0;
2557 foreach($ranges as $range) {
2558 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2560 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2561 header('HTTP/1.1 206 Partial content');
2562 header('Content-Length: '.$totallength);
2563 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2565 while(@ob_get_level()) {
2566 if (!@ob_end_flush()) {
2567 break;
2571 foreach($ranges as $range) {
2572 $length = $range[2] - $range[1] + 1;
2573 echo $range[0];
2574 fseek($handle, $range[1]);
2575 while (!feof($handle) && $length > 0) {
2576 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2577 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2578 echo $buffer;
2579 flush();
2580 $length -= strlen($buffer);
2583 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2584 fclose($handle);
2585 die;
2590 * Tells whether the filename is executable.
2592 * @link http://php.net/manual/en/function.is-executable.php
2593 * @link https://bugs.php.net/bug.php?id=41062
2594 * @param string $filename Path to the file.
2595 * @return bool True if the filename exists and is executable; otherwise, false.
2597 function file_is_executable($filename) {
2598 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2599 if (is_executable($filename)) {
2600 return true;
2601 } else {
2602 $fileext = strrchr($filename, '.');
2603 // If we have an extension we can check if it is listed as executable.
2604 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2605 $winpathext = strtolower(getenv('PATHEXT'));
2606 $winpathexts = explode(';', $winpathext);
2608 return in_array(strtolower($fileext), $winpathexts);
2611 return false;
2613 } else {
2614 return is_executable($filename);
2619 * Overwrite an existing file in a draft area.
2621 * @param stored_file $newfile the new file with the new content and meta-data
2622 * @param stored_file $existingfile the file that will be overwritten
2623 * @throws moodle_exception
2624 * @since Moodle 3.2
2626 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2627 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2628 throw new coding_exception('The file to overwrite is not in a draft area.');
2631 $fs = get_file_storage();
2632 // Remember original file source field.
2633 $source = @unserialize($existingfile->get_source());
2634 // Remember the original sortorder.
2635 $sortorder = $existingfile->get_sortorder();
2636 if ($newfile->is_external_file()) {
2637 // New file is a reference. Check that existing file does not have any other files referencing to it
2638 if (isset($source->original) && $fs->search_references_count($source->original)) {
2639 throw new moodle_exception('errordoublereference', 'repository');
2643 // Delete existing file to release filename.
2644 $newfilerecord = array(
2645 'contextid' => $existingfile->get_contextid(),
2646 'component' => 'user',
2647 'filearea' => 'draft',
2648 'itemid' => $existingfile->get_itemid(),
2649 'timemodified' => time()
2651 $existingfile->delete();
2653 // Create new file.
2654 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2655 // Preserve original file location (stored in source field) for handling references.
2656 if (isset($source->original)) {
2657 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2658 $newfilesource = new stdClass();
2660 $newfilesource->original = $source->original;
2661 $newfile->set_source(serialize($newfilesource));
2663 $newfile->set_sortorder($sortorder);
2667 * Add files from a draft area into a final area.
2669 * Most of the time you do not want to use this. It is intended to be used
2670 * by asynchronous services which cannot direcly manipulate a final
2671 * area through a draft area. Instead they add files to a new draft
2672 * area and merge that new draft into the final area when ready.
2674 * @param int $draftitemid the id of the draft area to use.
2675 * @param int $contextid this parameter and the next two identify the file area to save to.
2676 * @param string $component component name
2677 * @param string $filearea indentifies the file area
2678 * @param int $itemid identifies the item id or false for all items in the file area
2679 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2680 * @see file_save_draft_area_files
2681 * @since Moodle 3.2
2683 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2684 array $options = null) {
2685 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2686 $finaldraftid = 0;
2687 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2688 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2689 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2693 * Merge files from two draftarea areas.
2695 * This does not handle conflict resolution, files in the destination area which appear
2696 * to be more recent will be kept disregarding the intended ones.
2698 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2699 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2700 * @throws coding_exception
2701 * @since Moodle 3.2
2703 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2704 global $USER;
2706 $fs = get_file_storage();
2707 $contextid = context_user::instance($USER->id)->id;
2709 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2710 throw new coding_exception('Nothing to merge or area does not belong to current user');
2713 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2715 // Get hashes of the files to merge.
2716 $newhashes = array();
2717 foreach ($filestomerge as $filetomerge) {
2718 $filepath = $filetomerge->get_filepath();
2719 $filename = $filetomerge->get_filename();
2721 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2722 $newhashes[$newhash] = $filetomerge;
2725 // Calculate wich files must be added.
2726 foreach ($currentfiles as $file) {
2727 $filehash = $file->get_pathnamehash();
2728 // One file to be merged already exists.
2729 if (isset($newhashes[$filehash])) {
2730 $updatedfile = $newhashes[$filehash];
2732 // Avoid race conditions.
2733 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2734 // The existing file is more recent, do not copy the suposedly "new" one.
2735 unset($newhashes[$filehash]);
2736 continue;
2738 // Update existing file (not only content, meta-data too).
2739 file_overwrite_existing_draftfile($updatedfile, $file);
2740 unset($newhashes[$filehash]);
2744 foreach ($newhashes as $newfile) {
2745 $newfilerecord = array(
2746 'contextid' => $contextid,
2747 'component' => 'user',
2748 'filearea' => 'draft',
2749 'itemid' => $mergeintodraftid,
2750 'timemodified' => time()
2753 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2758 * RESTful cURL class
2760 * This is a wrapper class for curl, it is quite easy to use:
2761 * <code>
2762 * $c = new curl;
2763 * // enable cache
2764 * $c = new curl(array('cache'=>true));
2765 * // enable cookie
2766 * $c = new curl(array('cookie'=>true));
2767 * // enable proxy
2768 * $c = new curl(array('proxy'=>true));
2770 * // HTTP GET Method
2771 * $html = $c->get('http://example.com');
2772 * // HTTP POST Method
2773 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2774 * // HTTP PUT Method
2775 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2776 * </code>
2778 * @package core_files
2779 * @category files
2780 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2781 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2783 class curl {
2784 /** @var bool Caches http request contents */
2785 public $cache = false;
2786 /** @var bool Uses proxy, null means automatic based on URL */
2787 public $proxy = null;
2788 /** @var string library version */
2789 public $version = '0.4 dev';
2790 /** @var array http's response */
2791 public $response = array();
2792 /** @var array Raw response headers, needed for BC in download_file_content(). */
2793 public $rawresponse = array();
2794 /** @var array http header */
2795 public $header = array();
2796 /** @var string cURL information */
2797 public $info;
2798 /** @var string error */
2799 public $error;
2800 /** @var int error code */
2801 public $errno;
2802 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2803 public $emulateredirects = null;
2805 /** @var array cURL options */
2806 private $options;
2808 /** @var string Proxy host */
2809 private $proxy_host = '';
2810 /** @var string Proxy auth */
2811 private $proxy_auth = '';
2812 /** @var string Proxy type */
2813 private $proxy_type = '';
2814 /** @var bool Debug mode on */
2815 private $debug = false;
2816 /** @var bool|string Path to cookie file */
2817 private $cookie = false;
2818 /** @var bool tracks multiple headers in response - redirect detection */
2819 private $responsefinished = false;
2820 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2821 private $securityhelper;
2822 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2823 private $ignoresecurity;
2824 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
2825 private static $mockresponses = [];
2828 * Curl constructor.
2830 * Allowed settings are:
2831 * proxy: (bool) use proxy server, null means autodetect non-local from url
2832 * debug: (bool) use debug output
2833 * cookie: (string) path to cookie file, false if none
2834 * cache: (bool) use cache
2835 * module_cache: (string) type of cache
2836 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
2837 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
2839 * @param array $settings
2841 public function __construct($settings = array()) {
2842 global $CFG;
2843 if (!function_exists('curl_init')) {
2844 $this->error = 'cURL module must be enabled!';
2845 trigger_error($this->error, E_USER_ERROR);
2846 return false;
2849 // All settings of this class should be init here.
2850 $this->resetopt();
2851 if (!empty($settings['debug'])) {
2852 $this->debug = true;
2854 if (!empty($settings['cookie'])) {
2855 if($settings['cookie'] === true) {
2856 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2857 } else {
2858 $this->cookie = $settings['cookie'];
2861 if (!empty($settings['cache'])) {
2862 if (class_exists('curl_cache')) {
2863 if (!empty($settings['module_cache'])) {
2864 $this->cache = new curl_cache($settings['module_cache']);
2865 } else {
2866 $this->cache = new curl_cache('misc');
2870 if (!empty($CFG->proxyhost)) {
2871 if (empty($CFG->proxyport)) {
2872 $this->proxy_host = $CFG->proxyhost;
2873 } else {
2874 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2876 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2877 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2878 $this->setopt(array(
2879 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2880 'proxyuserpwd'=>$this->proxy_auth));
2882 if (!empty($CFG->proxytype)) {
2883 if ($CFG->proxytype == 'SOCKS5') {
2884 $this->proxy_type = CURLPROXY_SOCKS5;
2885 } else {
2886 $this->proxy_type = CURLPROXY_HTTP;
2887 $this->setopt(array('httpproxytunnel'=>false));
2889 $this->setopt(array('proxytype'=>$this->proxy_type));
2892 if (isset($settings['proxy'])) {
2893 $this->proxy = $settings['proxy'];
2895 } else {
2896 $this->proxy = false;
2899 if (!isset($this->emulateredirects)) {
2900 $this->emulateredirects = ini_get('open_basedir');
2903 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
2904 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
2905 $this->set_security($settings['securityhelper']);
2906 } else {
2907 $this->set_security(new \core\files\curl_security_helper());
2909 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
2913 * Resets the CURL options that have already been set
2915 public function resetopt() {
2916 $this->options = array();
2917 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2918 // True to include the header in the output
2919 $this->options['CURLOPT_HEADER'] = 0;
2920 // True to Exclude the body from the output
2921 $this->options['CURLOPT_NOBODY'] = 0;
2922 // Redirect ny default.
2923 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2924 $this->options['CURLOPT_MAXREDIRS'] = 10;
2925 $this->options['CURLOPT_ENCODING'] = '';
2926 // TRUE to return the transfer as a string of the return
2927 // value of curl_exec() instead of outputting it out directly.
2928 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2929 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2930 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2931 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2933 if ($cacert = self::get_cacert()) {
2934 $this->options['CURLOPT_CAINFO'] = $cacert;
2939 * Get the location of ca certificates.
2940 * @return string absolute file path or empty if default used
2942 public static function get_cacert() {
2943 global $CFG;
2945 // Bundle in dataroot always wins.
2946 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2947 return realpath("$CFG->dataroot/moodleorgca.crt");
2950 // Next comes the default from php.ini
2951 $cacert = ini_get('curl.cainfo');
2952 if (!empty($cacert) and is_readable($cacert)) {
2953 return realpath($cacert);
2956 // Windows PHP does not have any certs, we need to use something.
2957 if ($CFG->ostype === 'WINDOWS') {
2958 if (is_readable("$CFG->libdir/cacert.pem")) {
2959 return realpath("$CFG->libdir/cacert.pem");
2963 // Use default, this should work fine on all properly configured *nix systems.
2964 return null;
2968 * Reset Cookie
2970 public function resetcookie() {
2971 if (!empty($this->cookie)) {
2972 if (is_file($this->cookie)) {
2973 $fp = fopen($this->cookie, 'w');
2974 if (!empty($fp)) {
2975 fwrite($fp, '');
2976 fclose($fp);
2983 * Set curl options.
2985 * Do not use the curl constants to define the options, pass a string
2986 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2987 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2989 * @param array $options If array is null, this function will reset the options to default value.
2990 * @return void
2991 * @throws coding_exception If an option uses constant value instead of option name.
2993 public function setopt($options = array()) {
2994 if (is_array($options)) {
2995 foreach ($options as $name => $val) {
2996 if (!is_string($name)) {
2997 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2999 if (stripos($name, 'CURLOPT_') === false) {
3000 $name = strtoupper('CURLOPT_'.$name);
3001 } else {
3002 $name = strtoupper($name);
3004 $this->options[$name] = $val;
3010 * Reset http method
3012 public function cleanopt() {
3013 unset($this->options['CURLOPT_HTTPGET']);
3014 unset($this->options['CURLOPT_POST']);
3015 unset($this->options['CURLOPT_POSTFIELDS']);
3016 unset($this->options['CURLOPT_PUT']);
3017 unset($this->options['CURLOPT_INFILE']);
3018 unset($this->options['CURLOPT_INFILESIZE']);
3019 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3020 unset($this->options['CURLOPT_FILE']);
3024 * Resets the HTTP Request headers (to prepare for the new request)
3026 public function resetHeader() {
3027 $this->header = array();
3031 * Set HTTP Request Header
3033 * @param array $header
3035 public function setHeader($header) {
3036 if (is_array($header)) {
3037 foreach ($header as $v) {
3038 $this->setHeader($v);
3040 } else {
3041 // Remove newlines, they are not allowed in headers.
3042 $newvalue = preg_replace('/[\r\n]/', '', $header);
3043 if (!in_array($newvalue, $this->header)) {
3044 $this->header[] = $newvalue;
3050 * Get HTTP Response Headers
3051 * @return array of arrays
3053 public function getResponse() {
3054 return $this->response;
3058 * Get raw HTTP Response Headers
3059 * @return array of strings
3061 public function get_raw_response() {
3062 return $this->rawresponse;
3066 * private callback function
3067 * Formatting HTTP Response Header
3069 * We only keep the last headers returned. For example during a redirect the
3070 * redirect headers will not appear in {@link self::getResponse()}, if you need
3071 * to use those headers, refer to {@link self::get_raw_response()}.
3073 * @param resource $ch Apparently not used
3074 * @param string $header
3075 * @return int The strlen of the header
3077 private function formatHeader($ch, $header) {
3078 $this->rawresponse[] = $header;
3080 if (trim($header, "\r\n") === '') {
3081 // This must be the last header.
3082 $this->responsefinished = true;
3085 if (strlen($header) > 2) {
3086 if ($this->responsefinished) {
3087 // We still have headers after the supposedly last header, we must be
3088 // in a redirect so let's empty the response to keep the last headers.
3089 $this->responsefinished = false;
3090 $this->response = array();
3092 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3093 $key = rtrim($parts[0], ':');
3094 $value = isset($parts[1]) ? $parts[1] : null;
3095 if (!empty($this->response[$key])) {
3096 if (is_array($this->response[$key])) {
3097 $this->response[$key][] = $value;
3098 } else {
3099 $tmp = $this->response[$key];
3100 $this->response[$key] = array();
3101 $this->response[$key][] = $tmp;
3102 $this->response[$key][] = $value;
3105 } else {
3106 $this->response[$key] = $value;
3109 return strlen($header);
3113 * Set options for individual curl instance
3115 * @param resource $curl A curl handle
3116 * @param array $options
3117 * @return resource The curl handle
3119 private function apply_opt($curl, $options) {
3120 // Clean up
3121 $this->cleanopt();
3122 // set cookie
3123 if (!empty($this->cookie) || !empty($options['cookie'])) {
3124 $this->setopt(array('cookiejar'=>$this->cookie,
3125 'cookiefile'=>$this->cookie
3129 // Bypass proxy if required.
3130 if ($this->proxy === null) {
3131 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3132 $proxy = false;
3133 } else {
3134 $proxy = true;
3136 } else {
3137 $proxy = (bool)$this->proxy;
3140 // Set proxy.
3141 if ($proxy) {
3142 $options['CURLOPT_PROXY'] = $this->proxy_host;
3143 } else {
3144 unset($this->options['CURLOPT_PROXY']);
3147 $this->setopt($options);
3149 // Reset before set options.
3150 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3152 // Setting the User-Agent based on options provided.
3153 $useragent = '';
3155 if (!empty($options['CURLOPT_USERAGENT'])) {
3156 $useragent = $options['CURLOPT_USERAGENT'];
3157 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3158 $useragent = $this->options['CURLOPT_USERAGENT'];
3159 } else {
3160 $useragent = 'MoodleBot/1.0';
3163 // Set headers.
3164 if (empty($this->header)) {
3165 $this->setHeader(array(
3166 'User-Agent: ' . $useragent,
3167 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3168 'Connection: keep-alive'
3170 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3171 // Remove old User-Agent if one existed.
3172 // We have to partial search since we don't know what the original User-Agent is.
3173 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3174 $key = array_keys($match)[0];
3175 unset($this->header[$key]);
3177 $this->setHeader(array('User-Agent: ' . $useragent));
3179 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3181 if ($this->debug) {
3182 echo '<h1>Options</h1>';
3183 var_dump($this->options);
3184 echo '<h1>Header</h1>';
3185 var_dump($this->header);
3188 // Do not allow infinite redirects.
3189 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3190 $this->options['CURLOPT_MAXREDIRS'] = 0;
3191 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3192 $this->options['CURLOPT_MAXREDIRS'] = 100;
3193 } else {
3194 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3197 // Make sure we always know if redirects expected.
3198 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3199 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3202 // Limit the protocols to HTTP and HTTPS.
3203 if (defined('CURLOPT_PROTOCOLS')) {
3204 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3205 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3208 // Set options.
3209 foreach($this->options as $name => $val) {
3210 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3211 // The redirects are emulated elsewhere.
3212 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3213 continue;
3215 $name = constant($name);
3216 curl_setopt($curl, $name, $val);
3219 return $curl;
3223 * Download multiple files in parallel
3225 * Calls {@link multi()} with specific download headers
3227 * <code>
3228 * $c = new curl();
3229 * $file1 = fopen('a', 'wb');
3230 * $file2 = fopen('b', 'wb');
3231 * $c->download(array(
3232 * array('url'=>'http://localhost/', 'file'=>$file1),
3233 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3234 * ));
3235 * fclose($file1);
3236 * fclose($file2);
3237 * </code>
3239 * or
3241 * <code>
3242 * $c = new curl();
3243 * $c->download(array(
3244 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3245 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3246 * ));
3247 * </code>
3249 * @param array $requests An array of files to request {
3250 * url => url to download the file [required]
3251 * file => file handler, or
3252 * filepath => file path
3254 * If 'file' and 'filepath' parameters are both specified in one request, the
3255 * open file handle in the 'file' parameter will take precedence and 'filepath'
3256 * will be ignored.
3258 * @param array $options An array of options to set
3259 * @return array An array of results
3261 public function download($requests, $options = array()) {
3262 $options['RETURNTRANSFER'] = false;
3263 return $this->multi($requests, $options);
3267 * Returns the current curl security helper.
3269 * @return \core\files\curl_security_helper instance.
3271 public function get_security() {
3272 return $this->securityhelper;
3276 * Sets the curl security helper.
3278 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3279 * @return bool true if the security helper could be set, false otherwise.
3281 public function set_security($securityobject) {
3282 if ($securityobject instanceof \core\files\curl_security_helper) {
3283 $this->securityhelper = $securityobject;
3284 return true;
3286 return false;
3290 * Multi HTTP Requests
3291 * This function could run multi-requests in parallel.
3293 * @param array $requests An array of files to request
3294 * @param array $options An array of options to set
3295 * @return array An array of results
3297 protected function multi($requests, $options = array()) {
3298 $count = count($requests);
3299 $handles = array();
3300 $results = array();
3301 $main = curl_multi_init();
3302 for ($i = 0; $i < $count; $i++) {
3303 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3304 // open file
3305 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3306 $requests[$i]['auto-handle'] = true;
3308 foreach($requests[$i] as $n=>$v) {
3309 $options[$n] = $v;
3311 $handles[$i] = curl_init($requests[$i]['url']);
3312 $this->apply_opt($handles[$i], $options);
3313 curl_multi_add_handle($main, $handles[$i]);
3315 $running = 0;
3316 do {
3317 curl_multi_exec($main, $running);
3318 } while($running > 0);
3319 for ($i = 0; $i < $count; $i++) {
3320 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3321 $results[] = true;
3322 } else {
3323 $results[] = curl_multi_getcontent($handles[$i]);
3325 curl_multi_remove_handle($main, $handles[$i]);
3327 curl_multi_close($main);
3329 for ($i = 0; $i < $count; $i++) {
3330 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3331 // close file handler if file is opened in this function
3332 fclose($requests[$i]['file']);
3335 return $results;
3339 * Helper function to reset the request state vars.
3341 * @return void.
3343 protected function reset_request_state_vars() {
3344 $this->info = array();
3345 $this->error = '';
3346 $this->errno = 0;
3347 $this->response = array();
3348 $this->rawresponse = array();
3349 $this->responsefinished = false;
3353 * For use only in unit tests - we can pre-set the next curl response.
3354 * This is useful for unit testing APIs that call external systems.
3355 * @param string $response
3357 public static function mock_response($response) {
3358 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3359 array_push(self::$mockresponses, $response);
3360 } else {
3361 throw new coding_excpetion('mock_response function is only available for unit tests.');
3366 * Single HTTP Request
3368 * @param string $url The URL to request
3369 * @param array $options
3370 * @return bool
3372 protected function request($url, $options = array()) {
3373 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3374 $this->reset_request_state_vars();
3376 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3377 if ($mockresponse = array_pop(self::$mockresponses)) {
3378 $this->info = [ 'http_code' => 200 ];
3379 return $mockresponse;
3383 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3384 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3385 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3386 $this->error = $this->securityhelper->get_blocked_url_string();
3387 return $this->error;
3390 // Set the URL as a curl option.
3391 $this->setopt(array('CURLOPT_URL' => $url));
3393 // Create curl instance.
3394 $curl = curl_init();
3396 $this->apply_opt($curl, $options);
3397 if ($this->cache && $ret = $this->cache->get($this->options)) {
3398 return $ret;
3401 $ret = curl_exec($curl);
3402 $this->info = curl_getinfo($curl);
3403 $this->error = curl_error($curl);
3404 $this->errno = curl_errno($curl);
3405 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3407 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3408 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3409 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3410 $this->reset_request_state_vars();
3411 $this->error = $this->securityhelper->get_blocked_url_string();
3412 curl_close($curl);
3413 return $this->error;
3416 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3417 $redirects = 0;
3419 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3421 if ($this->info['http_code'] == 301) {
3422 // Moved Permanently - repeat the same request on new URL.
3424 } else if ($this->info['http_code'] == 302) {
3425 // Found - the standard redirect - repeat the same request on new URL.
3427 } else if ($this->info['http_code'] == 303) {
3428 // 303 See Other - repeat only if GET, do not bother with POSTs.
3429 if (empty($this->options['CURLOPT_HTTPGET'])) {
3430 break;
3433 } else if ($this->info['http_code'] == 307) {
3434 // Temporary Redirect - must repeat using the same request type.
3436 } else if ($this->info['http_code'] == 308) {
3437 // Permanent Redirect - must repeat using the same request type.
3439 } else {
3440 // Some other http code means do not retry!
3441 break;
3444 $redirects++;
3446 $redirecturl = null;
3447 if (isset($this->info['redirect_url'])) {
3448 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3449 $redirecturl = $this->info['redirect_url'];
3452 if (!$redirecturl) {
3453 foreach ($this->response as $k => $v) {
3454 if (strtolower($k) === 'location') {
3455 $redirecturl = $v;
3456 break;
3459 if (preg_match('|^https?://|i', $redirecturl)) {
3460 // Great, this is the correct location format!
3462 } else if ($redirecturl) {
3463 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3464 if (strpos($redirecturl, '/') === 0) {
3465 // Relative to server root - just guess.
3466 $pos = strpos('/', $current, 8);
3467 if ($pos === false) {
3468 $redirecturl = $current.$redirecturl;
3469 } else {
3470 $redirecturl = substr($current, 0, $pos).$redirecturl;
3472 } else {
3473 // Relative to current script.
3474 $redirecturl = dirname($current).'/'.$redirecturl;
3479 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3480 $ret = curl_exec($curl);
3482 $this->info = curl_getinfo($curl);
3483 $this->error = curl_error($curl);
3484 $this->errno = curl_errno($curl);
3486 $this->info['redirect_count'] = $redirects;
3488 if ($this->info['http_code'] === 200) {
3489 // Finally this is what we wanted.
3490 break;
3492 if ($this->errno != CURLE_OK) {
3493 // Something wrong is going on.
3494 break;
3497 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3498 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3499 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3503 if ($this->cache) {
3504 $this->cache->set($this->options, $ret);
3507 if ($this->debug) {
3508 echo '<h1>Return Data</h1>';
3509 var_dump($ret);
3510 echo '<h1>Info</h1>';
3511 var_dump($this->info);
3512 echo '<h1>Error</h1>';
3513 var_dump($this->error);
3516 curl_close($curl);
3518 if (empty($this->error)) {
3519 return $ret;
3520 } else {
3521 return $this->error;
3522 // exception is not ajax friendly
3523 //throw new moodle_exception($this->error, 'curl');
3528 * HTTP HEAD method
3530 * @see request()
3532 * @param string $url
3533 * @param array $options
3534 * @return bool
3536 public function head($url, $options = array()) {
3537 $options['CURLOPT_HTTPGET'] = 0;
3538 $options['CURLOPT_HEADER'] = 1;
3539 $options['CURLOPT_NOBODY'] = 1;
3540 return $this->request($url, $options);
3544 * HTTP PATCH method
3546 * @param string $url
3547 * @param array|string $params
3548 * @param array $options
3549 * @return bool
3551 public function patch($url, $params = '', $options = array()) {
3552 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3553 if (is_array($params)) {
3554 $this->_tmp_file_post_params = array();
3555 foreach ($params as $key => $value) {
3556 if ($value instanceof stored_file) {
3557 $value->add_to_curl_request($this, $key);
3558 } else {
3559 $this->_tmp_file_post_params[$key] = $value;
3562 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3563 unset($this->_tmp_file_post_params);
3564 } else {
3565 // The variable $params is the raw post data.
3566 $options['CURLOPT_POSTFIELDS'] = $params;
3568 return $this->request($url, $options);
3572 * HTTP POST method
3574 * @param string $url
3575 * @param array|string $params
3576 * @param array $options
3577 * @return bool
3579 public function post($url, $params = '', $options = array()) {
3580 $options['CURLOPT_POST'] = 1;
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 // $params is the raw post data
3594 $options['CURLOPT_POSTFIELDS'] = $params;
3596 return $this->request($url, $options);
3600 * HTTP GET method
3602 * @param string $url
3603 * @param array $params
3604 * @param array $options
3605 * @return bool
3607 public function get($url, $params = array(), $options = array()) {
3608 $options['CURLOPT_HTTPGET'] = 1;
3610 if (!empty($params)) {
3611 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3612 $url .= http_build_query($params, '', '&');
3614 return $this->request($url, $options);
3618 * Downloads one file and writes it to the specified file handler
3620 * <code>
3621 * $c = new curl();
3622 * $file = fopen('savepath', 'w');
3623 * $result = $c->download_one('http://localhost/', null,
3624 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3625 * fclose($file);
3626 * $download_info = $c->get_info();
3627 * if ($result === true) {
3628 * // file downloaded successfully
3629 * } else {
3630 * $error_text = $result;
3631 * $error_code = $c->get_errno();
3633 * </code>
3635 * <code>
3636 * $c = new curl();
3637 * $result = $c->download_one('http://localhost/', null,
3638 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3639 * // ... see above, no need to close handle and remove file if unsuccessful
3640 * </code>
3642 * @param string $url
3643 * @param array|null $params key-value pairs to be added to $url as query string
3644 * @param array $options request options. Must include either 'file' or 'filepath'
3645 * @return bool|string true on success or error string on failure
3647 public function download_one($url, $params, $options = array()) {
3648 $options['CURLOPT_HTTPGET'] = 1;
3649 if (!empty($params)) {
3650 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3651 $url .= http_build_query($params, '', '&');
3653 if (!empty($options['filepath']) && empty($options['file'])) {
3654 // open file
3655 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3656 $this->errno = 100;
3657 return get_string('cannotwritefile', 'error', $options['filepath']);
3659 $filepath = $options['filepath'];
3661 unset($options['filepath']);
3662 $result = $this->request($url, $options);
3663 if (isset($filepath)) {
3664 fclose($options['file']);
3665 if ($result !== true) {
3666 unlink($filepath);
3669 return $result;
3673 * HTTP PUT method
3675 * @param string $url
3676 * @param array $params
3677 * @param array $options
3678 * @return bool
3680 public function put($url, $params = array(), $options = array()) {
3681 $file = '';
3682 $fp = false;
3683 if (isset($params['file'])) {
3684 $file = $params['file'];
3685 if (is_file($file)) {
3686 $fp = fopen($file, 'r');
3687 $size = filesize($file);
3688 $options['CURLOPT_PUT'] = 1;
3689 $options['CURLOPT_INFILESIZE'] = $size;
3690 $options['CURLOPT_INFILE'] = $fp;
3691 } else {
3692 return null;
3694 if (!isset($this->options['CURLOPT_USERPWD'])) {
3695 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3697 } else {
3698 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3699 $options['CURLOPT_POSTFIELDS'] = $params;
3702 $ret = $this->request($url, $options);
3703 if ($fp !== false) {
3704 fclose($fp);
3706 return $ret;
3710 * HTTP DELETE method
3712 * @param string $url
3713 * @param array $param
3714 * @param array $options
3715 * @return bool
3717 public function delete($url, $param = array(), $options = array()) {
3718 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3719 if (!isset($options['CURLOPT_USERPWD'])) {
3720 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3722 $ret = $this->request($url, $options);
3723 return $ret;
3727 * HTTP TRACE method
3729 * @param string $url
3730 * @param array $options
3731 * @return bool
3733 public function trace($url, $options = array()) {
3734 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3735 $ret = $this->request($url, $options);
3736 return $ret;
3740 * HTTP OPTIONS method
3742 * @param string $url
3743 * @param array $options
3744 * @return bool
3746 public function options($url, $options = array()) {
3747 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3748 $ret = $this->request($url, $options);
3749 return $ret;
3753 * Get curl information
3755 * @return string
3757 public function get_info() {
3758 return $this->info;
3762 * Get curl error code
3764 * @return int
3766 public function get_errno() {
3767 return $this->errno;
3771 * When using a proxy, an additional HTTP response code may appear at
3772 * the start of the header. For example, when using https over a proxy
3773 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3774 * also possible and some may come with their own headers.
3776 * If using the return value containing all headers, this function can be
3777 * called to remove unwanted doubles.
3779 * Note that it is not possible to distinguish this situation from valid
3780 * data unless you know the actual response part (below the headers)
3781 * will not be included in this string, or else will not 'look like' HTTP
3782 * headers. As a result it is not safe to call this function for general
3783 * data.
3785 * @param string $input Input HTTP response
3786 * @return string HTTP response with additional headers stripped if any
3788 public static function strip_double_headers($input) {
3789 // I have tried to make this regular expression as specific as possible
3790 // to avoid any case where it does weird stuff if you happen to put
3791 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3792 // also make it faster because it can abandon regex processing as soon
3793 // as it hits something that doesn't look like an http header. The
3794 // header definition is taken from RFC 822, except I didn't support
3795 // folding which is never used in practice.
3796 $crlf = "\r\n";
3797 return preg_replace(
3798 // HTTP version and status code (ignore value of code).
3799 '~^HTTP/1\..*' . $crlf .
3800 // Header name: character between 33 and 126 decimal, except colon.
3801 // Colon. Header value: any character except \r and \n. CRLF.
3802 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3803 // Headers are terminated by another CRLF (blank line).
3804 $crlf .
3805 // Second HTTP status code, this time must be 200.
3806 '(HTTP/1.[01] 200 )~', '$1', $input);
3811 * This class is used by cURL class, use case:
3813 * <code>
3814 * $CFG->repositorycacheexpire = 120;
3815 * $CFG->curlcache = 120;
3817 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3818 * $ret = $c->get('http://www.google.com');
3819 * </code>
3821 * @package core_files
3822 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3825 class curl_cache {
3826 /** @var string Path to cache directory */
3827 public $dir = '';
3830 * Constructor
3832 * @global stdClass $CFG
3833 * @param string $module which module is using curl_cache
3835 public function __construct($module = 'repository') {
3836 global $CFG;
3837 if (!empty($module)) {
3838 $this->dir = $CFG->cachedir.'/'.$module.'/';
3839 } else {
3840 $this->dir = $CFG->cachedir.'/misc/';
3842 if (!file_exists($this->dir)) {
3843 mkdir($this->dir, $CFG->directorypermissions, true);
3845 if ($module == 'repository') {
3846 if (empty($CFG->repositorycacheexpire)) {
3847 $CFG->repositorycacheexpire = 120;
3849 $this->ttl = $CFG->repositorycacheexpire;
3850 } else {
3851 if (empty($CFG->curlcache)) {
3852 $CFG->curlcache = 120;
3854 $this->ttl = $CFG->curlcache;
3859 * Get cached value
3861 * @global stdClass $CFG
3862 * @global stdClass $USER
3863 * @param mixed $param
3864 * @return bool|string
3866 public function get($param) {
3867 global $CFG, $USER;
3868 $this->cleanup($this->ttl);
3869 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3870 if(file_exists($this->dir.$filename)) {
3871 $lasttime = filemtime($this->dir.$filename);
3872 if (time()-$lasttime > $this->ttl) {
3873 return false;
3874 } else {
3875 $fp = fopen($this->dir.$filename, 'r');
3876 $size = filesize($this->dir.$filename);
3877 $content = fread($fp, $size);
3878 return unserialize($content);
3881 return false;
3885 * Set cache value
3887 * @global object $CFG
3888 * @global object $USER
3889 * @param mixed $param
3890 * @param mixed $val
3892 public function set($param, $val) {
3893 global $CFG, $USER;
3894 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3895 $fp = fopen($this->dir.$filename, 'w');
3896 fwrite($fp, serialize($val));
3897 fclose($fp);
3898 @chmod($this->dir.$filename, $CFG->filepermissions);
3902 * Remove cache files
3904 * @param int $expire The number of seconds before expiry
3906 public function cleanup($expire) {
3907 if ($dir = opendir($this->dir)) {
3908 while (false !== ($file = readdir($dir))) {
3909 if(!is_dir($file) && $file != '.' && $file != '..') {
3910 $lasttime = @filemtime($this->dir.$file);
3911 if (time() - $lasttime > $expire) {
3912 @unlink($this->dir.$file);
3916 closedir($dir);
3920 * delete current user's cache file
3922 * @global object $CFG
3923 * @global object $USER
3925 public function refresh() {
3926 global $CFG, $USER;
3927 if ($dir = opendir($this->dir)) {
3928 while (false !== ($file = readdir($dir))) {
3929 if (!is_dir($file) && $file != '.' && $file != '..') {
3930 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3931 @unlink($this->dir.$file);
3940 * This function delegates file serving to individual plugins
3942 * @param string $relativepath
3943 * @param bool $forcedownload
3944 * @param null|string $preview the preview mode, defaults to serving the original file
3945 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
3946 * offline (e.g. mobile app).
3947 * @param bool $embed Whether this file will be served embed into an iframe.
3948 * @todo MDL-31088 file serving improments
3950 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
3951 global $DB, $CFG, $USER;
3952 // relative path must start with '/'
3953 if (!$relativepath) {
3954 print_error('invalidargorconf');
3955 } else if ($relativepath[0] != '/') {
3956 print_error('pathdoesnotstartslash');
3959 // extract relative path components
3960 $args = explode('/', ltrim($relativepath, '/'));
3962 if (count($args) < 3) { // always at least context, component and filearea
3963 print_error('invalidarguments');
3966 $contextid = (int)array_shift($args);
3967 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3968 $filearea = clean_param(array_shift($args), PARAM_AREA);
3970 list($context, $course, $cm) = get_context_info_array($contextid);
3972 $fs = get_file_storage();
3974 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
3976 // ========================================================================================================================
3977 if ($component === 'blog') {
3978 // Blog file serving
3979 if ($context->contextlevel != CONTEXT_SYSTEM) {
3980 send_file_not_found();
3982 if ($filearea !== 'attachment' and $filearea !== 'post') {
3983 send_file_not_found();
3986 if (empty($CFG->enableblogs)) {
3987 print_error('siteblogdisable', 'blog');
3990 $entryid = (int)array_shift($args);
3991 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3992 send_file_not_found();
3994 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3995 require_login();
3996 if (isguestuser()) {
3997 print_error('noguest');
3999 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4000 if ($USER->id != $entry->userid) {
4001 send_file_not_found();
4006 if ($entry->publishstate === 'public') {
4007 if ($CFG->forcelogin) {
4008 require_login();
4011 } else if ($entry->publishstate === 'site') {
4012 require_login();
4013 //ok
4014 } else if ($entry->publishstate === 'draft') {
4015 require_login();
4016 if ($USER->id != $entry->userid) {
4017 send_file_not_found();
4021 $filename = array_pop($args);
4022 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4024 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4025 send_file_not_found();
4028 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4030 // ========================================================================================================================
4031 } else if ($component === 'grade') {
4032 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4033 // Global gradebook files
4034 if ($CFG->forcelogin) {
4035 require_login();
4038 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4040 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4041 send_file_not_found();
4044 \core\session\manager::write_close(); // Unlock session during file serving.
4045 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4047 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
4048 //TODO: nobody implemented this yet in grade edit form!!
4049 send_file_not_found();
4051 if ($CFG->forcelogin || $course->id != SITEID) {
4052 require_login($course);
4055 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4057 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4058 send_file_not_found();
4061 \core\session\manager::write_close(); // Unlock session during file serving.
4062 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4063 } else {
4064 send_file_not_found();
4067 // ========================================================================================================================
4068 } else if ($component === 'tag') {
4069 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4071 // All tag descriptions are going to be public but we still need to respect forcelogin
4072 if ($CFG->forcelogin) {
4073 require_login();
4076 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4078 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4079 send_file_not_found();
4082 \core\session\manager::write_close(); // Unlock session during file serving.
4083 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4085 } else {
4086 send_file_not_found();
4088 // ========================================================================================================================
4089 } else if ($component === 'badges') {
4090 require_once($CFG->libdir . '/badgeslib.php');
4092 $badgeid = (int)array_shift($args);
4093 $badge = new badge($badgeid);
4094 $filename = array_pop($args);
4096 if ($filearea === 'badgeimage') {
4097 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4098 send_file_not_found();
4100 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4101 send_file_not_found();
4104 \core\session\manager::write_close();
4105 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4106 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4107 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4108 send_file_not_found();
4111 \core\session\manager::write_close();
4112 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4114 // ========================================================================================================================
4115 } else if ($component === 'calendar') {
4116 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4118 // All events here are public the one requirement is that we respect forcelogin
4119 if ($CFG->forcelogin) {
4120 require_login();
4123 // Get the event if from the args array
4124 $eventid = array_shift($args);
4126 // Load the event from the database
4127 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4128 send_file_not_found();
4131 // Get the file and serve if successful
4132 $filename = array_pop($args);
4133 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4134 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4135 send_file_not_found();
4138 \core\session\manager::write_close(); // Unlock session during file serving.
4139 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4141 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4143 // Must be logged in, if they are not then they obviously can't be this user
4144 require_login();
4146 // Don't want guests here, potentially saves a DB call
4147 if (isguestuser()) {
4148 send_file_not_found();
4151 // Get the event if from the args array
4152 $eventid = array_shift($args);
4154 // Load the event from the database - user id must match
4155 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
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, 0, 0, true, $sendfileoptions);
4169 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4171 // Respect forcelogin and require login unless this is the site.... it probably
4172 // should NEVER be the site
4173 if ($CFG->forcelogin || $course->id != SITEID) {
4174 require_login($course);
4177 // Must be able to at least view the course. This does not apply to the front page.
4178 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4179 //TODO: hmm, do we really want to block guests here?
4180 send_file_not_found();
4183 // Get the event id
4184 $eventid = array_shift($args);
4186 // Load the event from the database we need to check whether it is
4187 // a) valid course event
4188 // b) a group event
4189 // Group events use the course context (there is no group context)
4190 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4191 send_file_not_found();
4194 // If its a group event require either membership of view all groups capability
4195 if ($event->eventtype === 'group') {
4196 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4197 send_file_not_found();
4199 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4200 // Ok. Please note that the event type 'site' still uses a course context.
4201 } else {
4202 // Some other type.
4203 send_file_not_found();
4206 // If we get this far we can serve the file
4207 $filename = array_pop($args);
4208 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4209 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4210 send_file_not_found();
4213 \core\session\manager::write_close(); // Unlock session during file serving.
4214 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4216 } else {
4217 send_file_not_found();
4220 // ========================================================================================================================
4221 } else if ($component === 'user') {
4222 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4223 if (count($args) == 1) {
4224 $themename = theme_config::DEFAULT_THEME;
4225 $filename = array_shift($args);
4226 } else {
4227 $themename = array_shift($args);
4228 $filename = array_shift($args);
4231 // fix file name automatically
4232 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4233 $filename = 'f1';
4236 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4237 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4238 // protect images if login required and not logged in;
4239 // also if login is required for profile images and is not logged in or guest
4240 // do not use require_login() because it is expensive and not suitable here anyway
4241 $theme = theme_config::load($themename);
4242 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4245 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4246 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4247 if ($filename === 'f3') {
4248 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4249 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4250 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4255 if (!$file) {
4256 // bad reference - try to prevent future retries as hard as possible!
4257 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4258 if ($user->picture > 0) {
4259 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4262 // no redirect here because it is not cached
4263 $theme = theme_config::load($themename);
4264 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4265 send_file($imagefile, basename($imagefile), 60*60*24*14);
4268 $options = $sendfileoptions;
4269 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4270 // Profile images should be cache-able by both browsers and proxies according
4271 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4272 $options['cacheability'] = 'public';
4274 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4276 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4277 require_login();
4279 if (isguestuser()) {
4280 send_file_not_found();
4283 if ($USER->id !== $context->instanceid) {
4284 send_file_not_found();
4287 $filename = array_pop($args);
4288 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4289 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4290 send_file_not_found();
4293 \core\session\manager::write_close(); // Unlock session during file serving.
4294 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4296 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4298 if ($CFG->forcelogin) {
4299 require_login();
4302 $userid = $context->instanceid;
4304 if ($USER->id == $userid) {
4305 // always can access own
4307 } else if (!empty($CFG->forceloginforprofiles)) {
4308 require_login();
4310 if (isguestuser()) {
4311 send_file_not_found();
4314 // we allow access to site profile of all course contacts (usually teachers)
4315 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4316 send_file_not_found();
4319 $canview = false;
4320 if (has_capability('moodle/user:viewdetails', $context)) {
4321 $canview = true;
4322 } else {
4323 $courses = enrol_get_my_courses();
4326 while (!$canview && count($courses) > 0) {
4327 $course = array_shift($courses);
4328 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4329 $canview = true;
4334 $filename = array_pop($args);
4335 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4336 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4337 send_file_not_found();
4340 \core\session\manager::write_close(); // Unlock session during file serving.
4341 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4343 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4344 $userid = (int)array_shift($args);
4345 $usercontext = context_user::instance($userid);
4347 if ($CFG->forcelogin) {
4348 require_login();
4351 if (!empty($CFG->forceloginforprofiles)) {
4352 require_login();
4353 if (isguestuser()) {
4354 print_error('noguest');
4357 //TODO: review this logic of user profile access prevention
4358 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4359 print_error('usernotavailable');
4361 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4362 print_error('cannotviewprofile');
4364 if (!is_enrolled($context, $userid)) {
4365 print_error('notenrolledprofile');
4367 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4368 print_error('groupnotamember');
4372 $filename = array_pop($args);
4373 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4374 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4375 send_file_not_found();
4378 \core\session\manager::write_close(); // Unlock session during file serving.
4379 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4381 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4382 require_login();
4384 if (isguestuser()) {
4385 send_file_not_found();
4387 $userid = $context->instanceid;
4389 if ($USER->id != $userid) {
4390 send_file_not_found();
4393 $filename = array_pop($args);
4394 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4395 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4396 send_file_not_found();
4399 \core\session\manager::write_close(); // Unlock session during file serving.
4400 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4402 } else {
4403 send_file_not_found();
4406 // ========================================================================================================================
4407 } else if ($component === 'coursecat') {
4408 if ($context->contextlevel != CONTEXT_COURSECAT) {
4409 send_file_not_found();
4412 if ($filearea === 'description') {
4413 if ($CFG->forcelogin) {
4414 // no login necessary - unless login forced everywhere
4415 require_login();
4418 // Check if user can view this category.
4419 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4420 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid));
4421 if (!$coursecatvisible) {
4422 send_file_not_found();
4426 $filename = array_pop($args);
4427 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4428 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4429 send_file_not_found();
4432 \core\session\manager::write_close(); // Unlock session during file serving.
4433 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4434 } else {
4435 send_file_not_found();
4438 // ========================================================================================================================
4439 } else if ($component === 'course') {
4440 if ($context->contextlevel != CONTEXT_COURSE) {
4441 send_file_not_found();
4444 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4445 if ($CFG->forcelogin) {
4446 require_login();
4449 $filename = array_pop($args);
4450 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4451 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4452 send_file_not_found();
4455 \core\session\manager::write_close(); // Unlock session during file serving.
4456 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4458 } else if ($filearea === 'section') {
4459 if ($CFG->forcelogin) {
4460 require_login($course);
4461 } else if ($course->id != SITEID) {
4462 require_login($course);
4465 $sectionid = (int)array_shift($args);
4467 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4468 send_file_not_found();
4471 $filename = array_pop($args);
4472 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4473 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4474 send_file_not_found();
4477 \core\session\manager::write_close(); // Unlock session during file serving.
4478 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4480 } else {
4481 send_file_not_found();
4484 } else if ($component === 'cohort') {
4486 $cohortid = (int)array_shift($args);
4487 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4488 $cohortcontext = context::instance_by_id($cohort->contextid);
4490 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4491 if ($context->id != $cohort->contextid &&
4492 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4493 send_file_not_found();
4496 // User is able to access cohort if they have view cap on cohort level or
4497 // the cohort is visible and they have view cap on course level.
4498 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4499 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4501 if ($filearea === 'description' && $canview) {
4502 $filename = array_pop($args);
4503 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4504 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4505 && !$file->is_directory()) {
4506 \core\session\manager::write_close(); // Unlock session during file serving.
4507 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4511 send_file_not_found();
4513 } else if ($component === 'group') {
4514 if ($context->contextlevel != CONTEXT_COURSE) {
4515 send_file_not_found();
4518 require_course_login($course, true, null, false);
4520 $groupid = (int)array_shift($args);
4522 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4523 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4524 // do not allow access to separate group info if not member or teacher
4525 send_file_not_found();
4528 if ($filearea === 'description') {
4530 require_login($course);
4532 $filename = array_pop($args);
4533 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4534 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4535 send_file_not_found();
4538 \core\session\manager::write_close(); // Unlock session during file serving.
4539 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4541 } else if ($filearea === 'icon') {
4542 $filename = array_pop($args);
4544 if ($filename !== 'f1' and $filename !== 'f2') {
4545 send_file_not_found();
4547 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4548 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4549 send_file_not_found();
4553 \core\session\manager::write_close(); // Unlock session during file serving.
4554 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4556 } else {
4557 send_file_not_found();
4560 } else if ($component === 'grouping') {
4561 if ($context->contextlevel != CONTEXT_COURSE) {
4562 send_file_not_found();
4565 require_login($course);
4567 $groupingid = (int)array_shift($args);
4569 // note: everybody has access to grouping desc images for now
4570 if ($filearea === 'description') {
4572 $filename = array_pop($args);
4573 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4574 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4575 send_file_not_found();
4578 \core\session\manager::write_close(); // Unlock session during file serving.
4579 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4581 } else {
4582 send_file_not_found();
4585 // ========================================================================================================================
4586 } else if ($component === 'backup') {
4587 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4588 require_login($course);
4589 require_capability('moodle/backup:downloadfile', $context);
4591 $filename = array_pop($args);
4592 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4593 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4594 send_file_not_found();
4597 \core\session\manager::write_close(); // Unlock session during file serving.
4598 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4600 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4601 require_login($course);
4602 require_capability('moodle/backup:downloadfile', $context);
4604 $sectionid = (int)array_shift($args);
4606 $filename = array_pop($args);
4607 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4608 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4609 send_file_not_found();
4612 \core\session\manager::write_close();
4613 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4615 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4616 require_login($course, false, $cm);
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', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4622 send_file_not_found();
4625 \core\session\manager::write_close();
4626 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4628 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4629 // Backup files that were generated by the automated backup systems.
4631 require_login($course);
4632 require_capability('moodle/backup:downloadfile', $context);
4633 require_capability('moodle/restore:userinfo', $context);
4635 $filename = array_pop($args);
4636 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4637 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4638 send_file_not_found();
4641 \core\session\manager::write_close(); // Unlock session during file serving.
4642 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4644 } else {
4645 send_file_not_found();
4648 // ========================================================================================================================
4649 } else if ($component === 'question') {
4650 require_once($CFG->libdir . '/questionlib.php');
4651 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4652 send_file_not_found();
4654 // ========================================================================================================================
4655 } else if ($component === 'grading') {
4656 if ($filearea === 'description') {
4657 // files embedded into the form definition description
4659 if ($context->contextlevel == CONTEXT_SYSTEM) {
4660 require_login();
4662 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4663 require_login($course, false, $cm);
4665 } else {
4666 send_file_not_found();
4669 $formid = (int)array_shift($args);
4671 $sql = "SELECT ga.id
4672 FROM {grading_areas} ga
4673 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4674 WHERE gd.id = ? AND ga.contextid = ?";
4675 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4677 if (!$areaid) {
4678 send_file_not_found();
4681 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4683 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4684 send_file_not_found();
4687 \core\session\manager::write_close(); // Unlock session during file serving.
4688 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4691 // ========================================================================================================================
4692 } else if (strpos($component, 'mod_') === 0) {
4693 $modname = substr($component, 4);
4694 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4695 send_file_not_found();
4697 require_once("$CFG->dirroot/mod/$modname/lib.php");
4699 if ($context->contextlevel == CONTEXT_MODULE) {
4700 if ($cm->modname !== $modname) {
4701 // somebody tries to gain illegal access, cm type must match the component!
4702 send_file_not_found();
4706 if ($filearea === 'intro') {
4707 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4708 send_file_not_found();
4711 // Require login to the course first (without login to the module).
4712 require_course_login($course, true);
4714 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4715 $cminfo = cm_info::create($cm);
4716 if (!$cminfo->uservisible) {
4717 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
4718 // Module intro is not visible on the course page and module is not available, show access error.
4719 require_course_login($course, true, $cminfo);
4723 // all users may access it
4724 $filename = array_pop($args);
4725 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4726 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4727 send_file_not_found();
4730 // finally send the file
4731 send_stored_file($file, null, 0, false, $sendfileoptions);
4734 $filefunction = $component.'_pluginfile';
4735 $filefunctionold = $modname.'_pluginfile';
4736 if (function_exists($filefunction)) {
4737 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4738 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4739 } else if (function_exists($filefunctionold)) {
4740 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4741 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4744 send_file_not_found();
4746 // ========================================================================================================================
4747 } else if (strpos($component, 'block_') === 0) {
4748 $blockname = substr($component, 6);
4749 // note: no more class methods in blocks please, that is ....
4750 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4751 send_file_not_found();
4753 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4755 if ($context->contextlevel == CONTEXT_BLOCK) {
4756 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4757 if ($birecord->blockname !== $blockname) {
4758 // somebody tries to gain illegal access, cm type must match the component!
4759 send_file_not_found();
4762 if ($context->get_course_context(false)) {
4763 // If block is in course context, then check if user has capability to access course.
4764 require_course_login($course);
4765 } else if ($CFG->forcelogin) {
4766 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4767 require_login();
4770 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4771 // User can't access file, if block is hidden or doesn't have block:view capability
4772 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4773 send_file_not_found();
4775 } else {
4776 $birecord = null;
4779 $filefunction = $component.'_pluginfile';
4780 if (function_exists($filefunction)) {
4781 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4782 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4785 send_file_not_found();
4787 // ========================================================================================================================
4788 } else if (strpos($component, '_') === false) {
4789 // all core subsystems have to be specified above, no more guessing here!
4790 send_file_not_found();
4792 } else {
4793 // try to serve general plugin file in arbitrary context
4794 $dir = core_component::get_component_directory($component);
4795 if (!file_exists("$dir/lib.php")) {
4796 send_file_not_found();
4798 include_once("$dir/lib.php");
4800 $filefunction = $component.'_pluginfile';
4801 if (function_exists($filefunction)) {
4802 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4803 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4806 send_file_not_found();