MDL-57139 myoverview: fix paging button edge case
[moodle.git] / lib / filelib.php
blobb1dafb9e3a22f4b52b7568d7a1c53a1016a1a9e4
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
241 if ($options['trusttext']) {
242 $data->{$field.'trust'} = trusttext_trusted($context);
243 } else {
244 $data->{$field.'trust'} = 0;
247 $editor = $data->{$field.'_editor'};
249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
250 $data->{$field} = $editor['text'];
251 } else {
252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
254 $data->{$field.'format'} = $editor['format'];
256 return $data;
260 * Saves text and files modified by Editor formslib element
262 * @category files
263 * @param stdClass $data $database entry field
264 * @param string $field name of data field
265 * @param array $options various options
266 * @param stdClass $context context - must already exist
267 * @param string $component
268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
270 * @return stdClass modified data obejct
272 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
277 if (is_null($itemid) or is_null($context)) {
278 $itemid = null;
279 $contextid = null;
280 } else {
281 $contextid = $context->id;
284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
286 $data->{$field.'_filemanager'} = $draftid_editor;
288 return $data;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
295 * @category files
296 * @param stdClass $data $database entry field
297 * @param string $field name of data field
298 * @param array $options various options
299 * @param stdClass $context context - must already exist
300 * @param string $component
301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
303 * @return stdClass modified data obejct
305 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
317 if (empty($data->{$field.'_filemanager'})) {
318 $data->$field = '';
320 } else {
321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
322 $fs = get_file_storage();
324 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
326 } else {
327 $data->$field = '';
331 return $data;
335 * Generate a draft itemid
337 * @category files
338 * @global moodle_database $DB
339 * @global stdClass $USER
340 * @return int a random but available draft itemid that can be used to create a new draft
341 * file area.
343 function file_get_unused_draft_itemid() {
344 global $DB, $USER;
346 if (isguestuser() or !isloggedin()) {
347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
348 print_error('noguest');
351 $contextid = context_user::instance($USER->id)->id;
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
356 $draftitemid = rand(1, 999999999);
359 return $draftitemid;
363 * Initialise a draft file area from a real one by copying the files. A draft
364 * area will be created if one does not already exist. Normally you should
365 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
367 * @category files
368 * @global stdClass $CFG
369 * @global stdClass $USER
370 * @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.
371 * @param int $contextid This parameter and the next two identify the file area to copy files from.
372 * @param string $component
373 * @param string $filearea helps indentify the file area.
374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
379 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
380 global $CFG, $USER, $CFG;
382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
386 if (!isset($options['forcehttps'])) {
387 $options['forcehttps'] = false;
390 $usercontext = context_user::instance($USER->id);
391 $fs = get_file_storage();
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
395 $draftitemid = file_get_unused_draft_itemid();
396 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
397 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
398 foreach ($files as $file) {
399 if ($file->is_directory() and $file->get_filepath() === '/') {
400 // we need a way to mark the age of each draft area,
401 // by not copying the root dir we force it to be created automatically with current timestamp
402 continue;
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
405 continue;
407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
408 // XXX: This is a hack for file manager (MDL-28666)
409 // File manager needs to know the original file information before copying
410 // to draft area, so we append these information in mdl_files.source field
411 // {@link file_storage::search_references()}
412 // {@link file_storage::search_references_count()}
413 $sourcefield = $file->get_source();
414 $newsourcefield = new stdClass;
415 $newsourcefield->source = $sourcefield;
416 $original = new stdClass;
417 $original->contextid = $contextid;
418 $original->component = $component;
419 $original->filearea = $filearea;
420 $original->itemid = $itemid;
421 $original->filename = $file->get_filename();
422 $original->filepath = $file->get_filepath();
423 $newsourcefield->original = file_storage::pack_reference($original);
424 $draftfile->set_source(serialize($newsourcefield));
425 // End of file manager hack
428 if (!is_null($text)) {
429 // at this point there should not be any draftfile links yet,
430 // because this is a new text from database that should still contain the @@pluginfile@@ links
431 // this happens when developers forget to post process the text
432 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
434 } else {
435 // nothing to do
438 if (is_null($text)) {
439 return null;
442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
448 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
449 * in the @@PLUGINFILE@@ form.
451 * @category files
452 * @global stdClass $CFG
453 * @param string $text The content that may contain ULRs in need of rewriting.
454 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
455 * @param int $contextid This parameter and the next two identify the file area to use.
456 * @param string $component
457 * @param string $filearea helps identify the file area.
458 * @param int $itemid helps identify the file area.
459 * @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function.
460 * @return string the processed text.
462 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
463 global $CFG;
465 $options = (array)$options;
466 if (!isset($options['forcehttps'])) {
467 $options['forcehttps'] = false;
470 if (!$CFG->slasharguments) {
471 $file = $file . '?file=';
474 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
476 if ($itemid !== null) {
477 $baseurl .= "$itemid/";
480 if ($options['forcehttps']) {
481 $baseurl = str_replace('http://', 'https://', $baseurl);
484 if (!empty($options['reverse'])) {
485 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
486 } else {
487 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
492 * Returns information about files in a draft area.
494 * @global stdClass $CFG
495 * @global stdClass $USER
496 * @param int $draftitemid the draft area item id.
497 * @param string $filepath path to the directory from which the information have to be retrieved.
498 * @return array with the following entries:
499 * 'filecount' => number of files in the draft area.
500 * 'filesize' => total size of the files in the draft area.
501 * 'foldercount' => number of folders in the draft area.
502 * 'filesize_without_references' => total size of the area excluding file references.
503 * (more information will be added as needed).
505 function file_get_draft_area_info($draftitemid, $filepath = '/') {
506 global $CFG, $USER;
508 $usercontext = context_user::instance($USER->id);
509 $fs = get_file_storage();
511 $results = array(
512 'filecount' => 0,
513 'foldercount' => 0,
514 'filesize' => 0,
515 'filesize_without_references' => 0
518 if ($filepath != '/') {
519 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
520 } else {
521 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
523 foreach ($draftfiles as $file) {
524 if ($file->is_directory()) {
525 $results['foldercount'] += 1;
526 } else {
527 $results['filecount'] += 1;
530 $filesize = $file->get_filesize();
531 $results['filesize'] += $filesize;
532 if (!$file->is_external_file()) {
533 $results['filesize_without_references'] += $filesize;
537 return $results;
541 * Returns whether a draft area has exceeded/will exceed its size limit.
543 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
545 * @param int $draftitemid the draft area item id.
546 * @param int $areamaxbytes the maximum size allowed in this draft area.
547 * @param int $newfilesize the size that would be added to the current area.
548 * @param bool $includereferences true to include the size of the references in the area size.
549 * @return bool true if the area will/has exceeded its limit.
550 * @since Moodle 2.4
552 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
553 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
554 $draftinfo = file_get_draft_area_info($draftitemid);
555 $areasize = $draftinfo['filesize_without_references'];
556 if ($includereferences) {
557 $areasize = $draftinfo['filesize'];
559 if ($areasize + $newfilesize > $areamaxbytes) {
560 return true;
563 return false;
567 * Get used space of files
568 * @global moodle_database $DB
569 * @global stdClass $USER
570 * @return int total bytes
572 function file_get_user_used_space() {
573 global $DB, $USER;
575 $usercontext = context_user::instance($USER->id);
576 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
577 JOIN (SELECT contenthash, filename, MAX(id) AS id
578 FROM {files}
579 WHERE contextid = ? AND component = ? AND filearea != ?
580 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
581 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
582 $record = $DB->get_record_sql($sql, $params);
583 return (int)$record->totalbytes;
587 * Convert any string to a valid filepath
588 * @todo review this function
589 * @param string $str
590 * @return string path
592 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
593 if ($str == '/' or empty($str)) {
594 return '/';
595 } else {
596 return '/'.trim($str, '/').'/';
601 * Generate a folder tree of draft area of current USER recursively
603 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
604 * @param int $draftitemid
605 * @param string $filepath
606 * @param mixed $data
608 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
609 global $USER, $OUTPUT, $CFG;
610 $data->children = array();
611 $context = context_user::instance($USER->id);
612 $fs = get_file_storage();
613 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
614 foreach ($files as $file) {
615 if ($file->is_directory()) {
616 $item = new stdClass();
617 $item->sortorder = $file->get_sortorder();
618 $item->filepath = $file->get_filepath();
620 $foldername = explode('/', trim($item->filepath, '/'));
621 $item->fullname = trim(array_pop($foldername), '/');
623 $item->id = uniqid();
624 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
625 $data->children[] = $item;
626 } else {
627 continue;
634 * Listing all files (including folders) in current path (draft area)
635 * used by file manager
636 * @param int $draftitemid
637 * @param string $filepath
638 * @return stdClass
640 function file_get_drafarea_files($draftitemid, $filepath = '/') {
641 global $USER, $OUTPUT, $CFG;
643 $context = context_user::instance($USER->id);
644 $fs = get_file_storage();
646 $data = new stdClass();
647 $data->path = array();
648 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
650 // will be used to build breadcrumb
651 $trail = '/';
652 if ($filepath !== '/') {
653 $filepath = file_correct_filepath($filepath);
654 $parts = explode('/', $filepath);
655 foreach ($parts as $part) {
656 if ($part != '' && $part != null) {
657 $trail .= ($part.'/');
658 $data->path[] = array('name'=>$part, 'path'=>$trail);
663 $list = array();
664 $maxlength = 12;
665 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
666 foreach ($files as $file) {
667 $item = new stdClass();
668 $item->filename = $file->get_filename();
669 $item->filepath = $file->get_filepath();
670 $item->fullname = trim($item->filename, '/');
671 $filesize = $file->get_filesize();
672 $item->size = $filesize ? $filesize : null;
673 $item->filesize = $filesize ? display_size($filesize) : '';
675 $item->sortorder = $file->get_sortorder();
676 $item->author = $file->get_author();
677 $item->license = $file->get_license();
678 $item->datemodified = $file->get_timemodified();
679 $item->datecreated = $file->get_timecreated();
680 $item->isref = $file->is_external_file();
681 if ($item->isref && $file->get_status() == 666) {
682 $item->originalmissing = true;
684 // find the file this draft file was created from and count all references in local
685 // system pointing to that file
686 $source = @unserialize($file->get_source());
687 if (isset($source->original)) {
688 $item->refcount = $fs->search_references_count($source->original);
691 if ($file->is_directory()) {
692 $item->filesize = 0;
693 $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
694 $item->type = 'folder';
695 $foldername = explode('/', trim($item->filepath, '/'));
696 $item->fullname = trim(array_pop($foldername), '/');
697 $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
698 } else {
699 // do NOT use file browser here!
700 $item->mimetype = get_mimetype_description($file);
701 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
702 $item->type = 'zip';
703 } else {
704 $item->type = 'file';
706 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
707 $item->url = $itemurl->out();
708 $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
709 $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
710 if ($imageinfo = $file->get_imageinfo()) {
711 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
712 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
713 $item->image_width = $imageinfo['width'];
714 $item->image_height = $imageinfo['height'];
717 $list[] = $item;
720 $data->itemid = $draftitemid;
721 $data->list = $list;
722 return $data;
726 * Returns draft area itemid for a given element.
728 * @category files
729 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
730 * @return int the itemid, or 0 if there is not one yet.
732 function file_get_submitted_draft_itemid($elname) {
733 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
734 if (!isset($_REQUEST[$elname])) {
735 return 0;
737 if (is_array($_REQUEST[$elname])) {
738 $param = optional_param_array($elname, 0, PARAM_INT);
739 if (!empty($param['itemid'])) {
740 $param = $param['itemid'];
741 } else {
742 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
743 return false;
746 } else {
747 $param = optional_param($elname, 0, PARAM_INT);
750 if ($param) {
751 require_sesskey();
754 return $param;
758 * Restore the original source field from draft files
760 * Do not use this function because it makes field files.source inconsistent
761 * for draft area files. This function will be deprecated in 2.6
763 * @param stored_file $storedfile This only works with draft files
764 * @return stored_file
766 function file_restore_source_field_from_draft_file($storedfile) {
767 $source = @unserialize($storedfile->get_source());
768 if (!empty($source)) {
769 if (is_object($source)) {
770 $restoredsource = $source->source;
771 $storedfile->set_source($restoredsource);
772 } else {
773 throw new moodle_exception('invalidsourcefield', 'error');
776 return $storedfile;
779 * Saves files from a draft file area to a real one (merging the list of files).
780 * Can rewrite URLs in some content at the same time if desired.
782 * @category files
783 * @global stdClass $USER
784 * @param int $draftitemid the id of the draft area to use. Normally obtained
785 * from file_get_submitted_draft_itemid('elementname') or similar.
786 * @param int $contextid This parameter and the next two identify the file area to save to.
787 * @param string $component
788 * @param string $filearea indentifies the file area.
789 * @param int $itemid helps identifies the file area.
790 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
791 * @param string $text some html content that needs to have embedded links rewritten
792 * to the @@PLUGINFILE@@ form for saving in the database.
793 * @param bool $forcehttps force https urls.
794 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
796 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
797 global $USER;
799 $usercontext = context_user::instance($USER->id);
800 $fs = get_file_storage();
802 $options = (array)$options;
803 if (!isset($options['subdirs'])) {
804 $options['subdirs'] = false;
806 if (!isset($options['maxfiles'])) {
807 $options['maxfiles'] = -1; // unlimited
809 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
810 $options['maxbytes'] = 0; // unlimited
812 if (!isset($options['areamaxbytes'])) {
813 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
815 $allowreferences = true;
816 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
817 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
818 // this is not exactly right. BUT there are many places in code where filemanager options
819 // are not passed to file_save_draft_area_files()
820 $allowreferences = false;
823 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
824 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
825 // anything at all in the next area.
826 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
827 return null;
830 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
831 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
833 // One file in filearea means it is empty (it has only top-level directory '.').
834 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
835 // we have to merge old and new files - we want to keep file ids for files that were not changed
836 // we change time modified for all new and changed files, we keep time created as is
838 $newhashes = array();
839 $filecount = 0;
840 foreach ($draftfiles as $file) {
841 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
842 continue;
844 if (!$allowreferences && $file->is_external_file()) {
845 continue;
847 if (!$file->is_directory()) {
848 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
849 // oversized file - should not get here at all
850 continue;
852 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
853 // more files - should not get here at all
854 continue;
856 $filecount++;
858 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
859 $newhashes[$newhash] = $file;
862 // Loop through oldfiles and decide which we need to delete and which to update.
863 // After this cycle the array $newhashes will only contain the files that need to be added.
864 foreach ($oldfiles as $oldfile) {
865 $oldhash = $oldfile->get_pathnamehash();
866 if (!isset($newhashes[$oldhash])) {
867 // delete files not needed any more - deleted by user
868 $oldfile->delete();
869 continue;
872 $newfile = $newhashes[$oldhash];
873 // Now we know that we have $oldfile and $newfile for the same path.
874 // Let's check if we can update this file or we need to delete and create.
875 if ($newfile->is_directory()) {
876 // Directories are always ok to just update.
877 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
878 // File has the 'original' - we need to update the file (it may even have not been changed at all).
879 $original = file_storage::unpack_reference($source->original);
880 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
881 // Very odd, original points to another file. Delete and create file.
882 $oldfile->delete();
883 continue;
885 } else {
886 // The same file name but absence of 'original' means that file was deteled and uploaded again.
887 // By deleting and creating new file we properly manage all existing references.
888 $oldfile->delete();
889 continue;
892 // status changed, we delete old file, and create a new one
893 if ($oldfile->get_status() != $newfile->get_status()) {
894 // file was changed, use updated with new timemodified data
895 $oldfile->delete();
896 // This file will be added later
897 continue;
900 // Updated author
901 if ($oldfile->get_author() != $newfile->get_author()) {
902 $oldfile->set_author($newfile->get_author());
904 // Updated license
905 if ($oldfile->get_license() != $newfile->get_license()) {
906 $oldfile->set_license($newfile->get_license());
909 // Updated file source
910 // Field files.source for draftarea files contains serialised object with source and original information.
911 // We only store the source part of it for non-draft file area.
912 $newsource = $newfile->get_source();
913 if ($source = @unserialize($newfile->get_source())) {
914 $newsource = $source->source;
916 if ($oldfile->get_source() !== $newsource) {
917 $oldfile->set_source($newsource);
920 // Updated sort order
921 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
922 $oldfile->set_sortorder($newfile->get_sortorder());
925 // Update file timemodified
926 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
927 $oldfile->set_timemodified($newfile->get_timemodified());
930 // Replaced file content
931 if (!$oldfile->is_directory() &&
932 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
933 $oldfile->get_filesize() != $newfile->get_filesize() ||
934 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
935 $oldfile->get_userid() != $newfile->get_userid())) {
936 $oldfile->replace_file_with($newfile);
939 // unchanged file or directory - we keep it as is
940 unset($newhashes[$oldhash]);
943 // Add fresh file or the file which has changed status
944 // the size and subdirectory tests are extra safety only, the UI should prevent it
945 foreach ($newhashes as $file) {
946 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
947 if ($source = @unserialize($file->get_source())) {
948 // Field files.source for draftarea files contains serialised object with source and original information.
949 // We only store the source part of it for non-draft file area.
950 $file_record['source'] = $source->source;
953 if ($file->is_external_file()) {
954 $repoid = $file->get_repository_id();
955 if (!empty($repoid)) {
956 $context = context::instance_by_id($contextid, MUST_EXIST);
957 $repo = repository::get_repository_by_id($repoid, $context);
959 $file_record['repositoryid'] = $repoid;
960 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
961 // to the file store. E.g. transfer ownership of the file to a system account etc.
962 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
964 $file_record['reference'] = $reference;
968 $fs->create_file_from_storedfile($file_record, $file);
972 // note: do not purge the draft area - we clean up areas later in cron,
973 // the reason is that user might press submit twice and they would loose the files,
974 // also sometimes we might want to use hacks that save files into two different areas
976 if (is_null($text)) {
977 return null;
978 } else {
979 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
984 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
985 * ready to be saved in the database. Normally, this is done automatically by
986 * {@link file_save_draft_area_files()}.
988 * @category files
989 * @param string $text the content to process.
990 * @param int $draftitemid the draft file area the content was using.
991 * @param bool $forcehttps whether the content contains https URLs. Default false.
992 * @return string the processed content.
994 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
995 global $CFG, $USER;
997 $usercontext = context_user::instance($USER->id);
999 $wwwroot = $CFG->wwwroot;
1000 if ($forcehttps) {
1001 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1004 // relink embedded files if text submitted - no absolute links allowed in database!
1005 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1007 if (strpos($text, 'draftfile.php?file=') !== false) {
1008 $matches = array();
1009 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1010 if ($matches) {
1011 foreach ($matches[0] as $match) {
1012 $replace = str_ireplace('%2F', '/', $match);
1013 $text = str_replace($match, $replace, $text);
1016 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1019 return $text;
1023 * Set file sort order
1025 * @global moodle_database $DB
1026 * @param int $contextid the context id
1027 * @param string $component file component
1028 * @param string $filearea file area.
1029 * @param int $itemid itemid.
1030 * @param string $filepath file path.
1031 * @param string $filename file name.
1032 * @param int $sortorder the sort order of file.
1033 * @return bool
1035 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1036 global $DB;
1037 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1038 if ($file_record = $DB->get_record('files', $conditions)) {
1039 $sortorder = (int)$sortorder;
1040 $file_record->sortorder = $sortorder;
1041 $DB->update_record('files', $file_record);
1042 return true;
1044 return false;
1048 * reset file sort order number to 0
1049 * @global moodle_database $DB
1050 * @param int $contextid the context id
1051 * @param string $component
1052 * @param string $filearea file area.
1053 * @param int|bool $itemid itemid.
1054 * @return bool
1056 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1057 global $DB;
1059 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1060 if ($itemid !== false) {
1061 $conditions['itemid'] = $itemid;
1064 $file_records = $DB->get_records('files', $conditions);
1065 foreach ($file_records as $file_record) {
1066 $file_record->sortorder = 0;
1067 $DB->update_record('files', $file_record);
1069 return true;
1073 * Returns description of upload error
1075 * @param int $errorcode found in $_FILES['filename.ext']['error']
1076 * @return string error description string, '' if ok
1078 function file_get_upload_error($errorcode) {
1080 switch ($errorcode) {
1081 case 0: // UPLOAD_ERR_OK - no error
1082 $errmessage = '';
1083 break;
1085 case 1: // UPLOAD_ERR_INI_SIZE
1086 $errmessage = get_string('uploadserverlimit');
1087 break;
1089 case 2: // UPLOAD_ERR_FORM_SIZE
1090 $errmessage = get_string('uploadformlimit');
1091 break;
1093 case 3: // UPLOAD_ERR_PARTIAL
1094 $errmessage = get_string('uploadpartialfile');
1095 break;
1097 case 4: // UPLOAD_ERR_NO_FILE
1098 $errmessage = get_string('uploadnofilefound');
1099 break;
1101 // Note: there is no error with a value of 5
1103 case 6: // UPLOAD_ERR_NO_TMP_DIR
1104 $errmessage = get_string('uploadnotempdir');
1105 break;
1107 case 7: // UPLOAD_ERR_CANT_WRITE
1108 $errmessage = get_string('uploadcantwrite');
1109 break;
1111 case 8: // UPLOAD_ERR_EXTENSION
1112 $errmessage = get_string('uploadextension');
1113 break;
1115 default:
1116 $errmessage = get_string('uploadproblem');
1119 return $errmessage;
1123 * Recursive function formating an array in POST parameter
1124 * @param array $arraydata - the array that we are going to format and add into &$data array
1125 * @param string $currentdata - a row of the final postdata array at instant T
1126 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1127 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1129 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1130 foreach ($arraydata as $k=>$v) {
1131 $newcurrentdata = $currentdata;
1132 if (is_array($v)) { //the value is an array, call the function recursively
1133 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1134 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1135 } else { //add the POST parameter to the $data array
1136 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1142 * Transform a PHP array into POST parameter
1143 * (see the recursive function format_array_postdata_for_curlcall)
1144 * @param array $postdata
1145 * @return array containing all POST parameters (1 row = 1 POST parameter)
1147 function format_postdata_for_curlcall($postdata) {
1148 $data = array();
1149 foreach ($postdata as $k=>$v) {
1150 if (is_array($v)) {
1151 $currentdata = urlencode($k);
1152 format_array_postdata_for_curlcall($v, $currentdata, $data);
1153 } else {
1154 $data[] = urlencode($k).'='.urlencode($v);
1157 $convertedpostdata = implode('&', $data);
1158 return $convertedpostdata;
1162 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1163 * Due to security concerns only downloads from http(s) sources are supported.
1165 * @category files
1166 * @param string $url file url starting with http(s)://
1167 * @param array $headers http headers, null if none. If set, should be an
1168 * associative array of header name => value pairs.
1169 * @param array $postdata array means use POST request with given parameters
1170 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1171 * (if false, just returns content)
1172 * @param int $timeout timeout for complete download process including all file transfer
1173 * (default 5 minutes)
1174 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1175 * usually happens if the remote server is completely down (default 20 seconds);
1176 * may not work when using proxy
1177 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1178 * Only use this when already in a trusted location.
1179 * @param string $tofile store the downloaded content to file instead of returning it.
1180 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1181 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1182 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1183 * if file downloaded into $tofile successfully or the file content as a string.
1185 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1186 global $CFG;
1188 // Only http and https links supported.
1189 if (!preg_match('|^https?://|i', $url)) {
1190 if ($fullresponse) {
1191 $response = new stdClass();
1192 $response->status = 0;
1193 $response->headers = array();
1194 $response->response_code = 'Invalid protocol specified in url';
1195 $response->results = '';
1196 $response->error = 'Invalid protocol specified in url';
1197 return $response;
1198 } else {
1199 return false;
1203 $options = array();
1205 $headers2 = array();
1206 if (is_array($headers)) {
1207 foreach ($headers as $key => $value) {
1208 if (is_numeric($key)) {
1209 $headers2[] = $value;
1210 } else {
1211 $headers2[] = "$key: $value";
1216 if ($skipcertverify) {
1217 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1218 } else {
1219 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1222 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1224 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1225 $options['CURLOPT_MAXREDIRS'] = 5;
1227 // Use POST if requested.
1228 if (is_array($postdata)) {
1229 $postdata = format_postdata_for_curlcall($postdata);
1230 } else if (empty($postdata)) {
1231 $postdata = null;
1234 // Optionally attempt to get more correct timeout by fetching the file size.
1235 if (!isset($CFG->curltimeoutkbitrate)) {
1236 // Use very slow rate of 56kbps as a timeout speed when not set.
1237 $bitrate = 56;
1238 } else {
1239 $bitrate = $CFG->curltimeoutkbitrate;
1241 if ($calctimeout and !isset($postdata)) {
1242 $curl = new curl();
1243 $curl->setHeader($headers2);
1245 $curl->head($url, $postdata, $options);
1247 $info = $curl->get_info();
1248 $error_no = $curl->get_errno();
1249 if (!$error_no && $info['download_content_length'] > 0) {
1250 // No curl errors - adjust for large files only - take max timeout.
1251 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1255 $curl = new curl();
1256 $curl->setHeader($headers2);
1258 $options['CURLOPT_RETURNTRANSFER'] = true;
1259 $options['CURLOPT_NOBODY'] = false;
1260 $options['CURLOPT_TIMEOUT'] = $timeout;
1262 if ($tofile) {
1263 $fh = fopen($tofile, 'w');
1264 if (!$fh) {
1265 if ($fullresponse) {
1266 $response = new stdClass();
1267 $response->status = 0;
1268 $response->headers = array();
1269 $response->response_code = 'Can not write to file';
1270 $response->results = false;
1271 $response->error = 'Can not write to file';
1272 return $response;
1273 } else {
1274 return false;
1277 $options['CURLOPT_FILE'] = $fh;
1280 if (isset($postdata)) {
1281 $content = $curl->post($url, $postdata, $options);
1282 } else {
1283 $content = $curl->get($url, null, $options);
1286 if ($tofile) {
1287 fclose($fh);
1288 @chmod($tofile, $CFG->filepermissions);
1292 // Try to detect encoding problems.
1293 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1294 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1295 $result = curl_exec($ch);
1299 $info = $curl->get_info();
1300 $error_no = $curl->get_errno();
1301 $rawheaders = $curl->get_raw_response();
1303 if ($error_no) {
1304 $error = $content;
1305 if (!$fullresponse) {
1306 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1307 return false;
1310 $response = new stdClass();
1311 if ($error_no == 28) {
1312 $response->status = '-100'; // Mimic snoopy.
1313 } else {
1314 $response->status = '0';
1316 $response->headers = array();
1317 $response->response_code = $error;
1318 $response->results = false;
1319 $response->error = $error;
1320 return $response;
1323 if ($tofile) {
1324 $content = true;
1327 if (empty($info['http_code'])) {
1328 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1329 $response = new stdClass();
1330 $response->status = '0';
1331 $response->headers = array();
1332 $response->response_code = 'Unknown cURL error';
1333 $response->results = false; // do NOT change this, we really want to ignore the result!
1334 $response->error = 'Unknown cURL error';
1336 } else {
1337 $response = new stdClass();
1338 $response->status = (string)$info['http_code'];
1339 $response->headers = $rawheaders;
1340 $response->results = $content;
1341 $response->error = '';
1343 // There might be multiple headers on redirect, find the status of the last one.
1344 $firstline = true;
1345 foreach ($rawheaders as $line) {
1346 if ($firstline) {
1347 $response->response_code = $line;
1348 $firstline = false;
1350 if (trim($line, "\r\n") === '') {
1351 $firstline = true;
1356 if ($fullresponse) {
1357 return $response;
1360 if ($info['http_code'] != 200) {
1361 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1362 return false;
1364 return $response->results;
1368 * Returns a list of information about file types based on extensions.
1370 * The following elements expected in value array for each extension:
1371 * 'type' - mimetype
1372 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1373 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1374 * also files with bigger sizes under names
1375 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1376 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1377 * commonly used in moodle the following groups:
1378 * - web_image - image that can be included as <img> in HTML
1379 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1380 * - video - file that can be imported as video in text editor
1381 * - audio - file that can be imported as audio in text editor
1382 * - archive - we can extract files from this archive
1383 * - spreadsheet - used for portfolio format
1384 * - document - used for portfolio format
1385 * - presentation - used for portfolio format
1386 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1387 * human-readable description for this filetype;
1388 * Function {@link get_mimetype_description()} first looks at the presence of string for
1389 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1390 * attribute, if not found returns the value of 'type';
1391 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1392 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1393 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1395 * @category files
1396 * @return array List of information about file types based on extensions.
1397 * Associative array of extension (lower-case) to associative array
1398 * from 'element name' to data. Current element names are 'type' and 'icon'.
1399 * Unknown types should use the 'xxx' entry which includes defaults.
1401 function &get_mimetypes_array() {
1402 // Get types from the core_filetypes function, which includes caching.
1403 return core_filetypes::get_types();
1407 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1409 * This function retrieves a file's MIME type for a file that will be sent to the user.
1410 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1411 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1412 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1414 * @param string $filename The file's filename.
1415 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1417 function get_mimetype_for_sending($filename = '') {
1418 // Guess the file's MIME type using mimeinfo.
1419 $mimetype = mimeinfo('type', $filename);
1421 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1422 if (!$mimetype || $mimetype === 'document/unknown') {
1423 $mimetype = 'application/octet-stream';
1426 return $mimetype;
1430 * Obtains information about a filetype based on its extension. Will
1431 * use a default if no information is present about that particular
1432 * extension.
1434 * @category files
1435 * @param string $element Desired information (usually 'icon'
1436 * for icon filename or 'type' for MIME type. Can also be
1437 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1438 * @param string $filename Filename we're looking up
1439 * @return string Requested piece of information from array
1441 function mimeinfo($element, $filename) {
1442 global $CFG;
1443 $mimeinfo = & get_mimetypes_array();
1444 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1446 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1447 if (empty($filetype)) {
1448 $filetype = 'xxx'; // file without extension
1450 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1451 $iconsize = max(array(16, (int)$iconsizematch[1]));
1452 $filenames = array($mimeinfo['xxx']['icon']);
1453 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1454 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1456 // find the file with the closest size, first search for specific icon then for default icon
1457 foreach ($filenames as $filename) {
1458 foreach ($iconpostfixes as $size => $postfix) {
1459 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1460 if ($iconsize >= $size &&
1461 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1462 return $filename.$postfix;
1466 } else if (isset($mimeinfo[$filetype][$element])) {
1467 return $mimeinfo[$filetype][$element];
1468 } else if (isset($mimeinfo['xxx'][$element])) {
1469 return $mimeinfo['xxx'][$element]; // By default
1470 } else {
1471 return null;
1476 * Obtains information about a filetype based on the MIME type rather than
1477 * the other way around.
1479 * @category files
1480 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1481 * @param string $mimetype MIME type we're looking up
1482 * @return string Requested piece of information from array
1484 function mimeinfo_from_type($element, $mimetype) {
1485 /* array of cached mimetype->extension associations */
1486 static $cached = array();
1487 $mimeinfo = & get_mimetypes_array();
1489 if (!array_key_exists($mimetype, $cached)) {
1490 $cached[$mimetype] = null;
1491 foreach($mimeinfo as $filetype => $values) {
1492 if ($values['type'] == $mimetype) {
1493 if ($cached[$mimetype] === null) {
1494 $cached[$mimetype] = '.'.$filetype;
1496 if (!empty($values['defaulticon'])) {
1497 $cached[$mimetype] = '.'.$filetype;
1498 break;
1502 if (empty($cached[$mimetype])) {
1503 $cached[$mimetype] = '.xxx';
1506 if ($element === 'extension') {
1507 return $cached[$mimetype];
1508 } else {
1509 return mimeinfo($element, $cached[$mimetype]);
1514 * Return the relative icon path for a given file
1516 * Usage:
1517 * <code>
1518 * // $file - instance of stored_file or file_info
1519 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1520 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1521 * </code>
1522 * or
1523 * <code>
1524 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1525 * </code>
1527 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1528 * and $file->mimetype are expected)
1529 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1530 * @return string
1532 function file_file_icon($file, $size = null) {
1533 if (!is_object($file)) {
1534 $file = (object)$file;
1536 if (isset($file->filename)) {
1537 $filename = $file->filename;
1538 } else if (method_exists($file, 'get_filename')) {
1539 $filename = $file->get_filename();
1540 } else if (method_exists($file, 'get_visible_name')) {
1541 $filename = $file->get_visible_name();
1542 } else {
1543 $filename = '';
1545 if (isset($file->mimetype)) {
1546 $mimetype = $file->mimetype;
1547 } else if (method_exists($file, 'get_mimetype')) {
1548 $mimetype = $file->get_mimetype();
1549 } else {
1550 $mimetype = '';
1552 $mimetypes = &get_mimetypes_array();
1553 if ($filename) {
1554 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1555 if ($extension && !empty($mimetypes[$extension])) {
1556 // if file name has known extension, return icon for this extension
1557 return file_extension_icon($filename, $size);
1560 return file_mimetype_icon($mimetype, $size);
1564 * Return the relative icon path for a folder image
1566 * Usage:
1567 * <code>
1568 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1569 * echo html_writer::empty_tag('img', array('src' => $icon));
1570 * </code>
1571 * or
1572 * <code>
1573 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1574 * </code>
1576 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1577 * @return string
1579 function file_folder_icon($iconsize = null) {
1580 global $CFG;
1581 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1582 static $cached = array();
1583 $iconsize = max(array(16, (int)$iconsize));
1584 if (!array_key_exists($iconsize, $cached)) {
1585 foreach ($iconpostfixes as $size => $postfix) {
1586 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1587 if ($iconsize >= $size &&
1588 (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1589 $cached[$iconsize] = 'f/folder'.$postfix;
1590 break;
1594 return $cached[$iconsize];
1598 * Returns the relative icon path for a given mime type
1600 * This function should be used in conjunction with $OUTPUT->image_url to produce
1601 * a return the full path to an icon.
1603 * <code>
1604 * $mimetype = 'image/jpg';
1605 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1606 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1607 * </code>
1609 * @category files
1610 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1611 * to conform with that.
1612 * @param string $mimetype The mimetype to fetch an icon for
1613 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1614 * @return string The relative path to the icon
1616 function file_mimetype_icon($mimetype, $size = NULL) {
1617 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1621 * Returns the relative icon path for a given file name
1623 * This function should be used in conjunction with $OUTPUT->image_url to produce
1624 * a return the full path to an icon.
1626 * <code>
1627 * $filename = '.jpg';
1628 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1629 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1630 * </code>
1632 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1633 * to conform with that.
1634 * @todo MDL-31074 Implement $size
1635 * @category files
1636 * @param string $filename The filename to get the icon for
1637 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1638 * @return string
1640 function file_extension_icon($filename, $size = NULL) {
1641 return 'f/'.mimeinfo('icon'.$size, $filename);
1645 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1646 * mimetypes.php language file.
1648 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1649 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1650 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1651 * @param bool $capitalise If true, capitalises first character of result
1652 * @return string Text description
1654 function get_mimetype_description($obj, $capitalise=false) {
1655 $filename = $mimetype = '';
1656 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1657 // this is an instance of stored_file
1658 $mimetype = $obj->get_mimetype();
1659 $filename = $obj->get_filename();
1660 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1661 // this is an instance of file_info
1662 $mimetype = $obj->get_mimetype();
1663 $filename = $obj->get_visible_name();
1664 } else if (is_array($obj) || is_object ($obj)) {
1665 $obj = (array)$obj;
1666 if (!empty($obj['filename'])) {
1667 $filename = $obj['filename'];
1669 if (!empty($obj['mimetype'])) {
1670 $mimetype = $obj['mimetype'];
1672 } else {
1673 $mimetype = $obj;
1675 $mimetypefromext = mimeinfo('type', $filename);
1676 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1677 // if file has a known extension, overwrite the specified mimetype
1678 $mimetype = $mimetypefromext;
1680 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1681 if (empty($extension)) {
1682 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1683 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1684 } else {
1685 $mimetypestr = mimeinfo('string', $filename);
1687 $chunks = explode('/', $mimetype, 2);
1688 $chunks[] = '';
1689 $attr = array(
1690 'mimetype' => $mimetype,
1691 'ext' => $extension,
1692 'mimetype1' => $chunks[0],
1693 'mimetype2' => $chunks[1],
1695 $a = array();
1696 foreach ($attr as $key => $value) {
1697 $a[$key] = $value;
1698 $a[strtoupper($key)] = strtoupper($value);
1699 $a[ucfirst($key)] = ucfirst($value);
1702 // MIME types may include + symbol but this is not permitted in string ids.
1703 $safemimetype = str_replace('+', '_', $mimetype);
1704 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1705 $customdescription = mimeinfo('customdescription', $filename);
1706 if ($customdescription) {
1707 // Call format_string on the custom description so that multilang
1708 // filter can be used (if enabled on system context). We use system
1709 // context because it is possible that the page context might not have
1710 // been defined yet.
1711 $result = format_string($customdescription, true,
1712 array('context' => context_system::instance()));
1713 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1714 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1715 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1716 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1717 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1718 $result = get_string('default', 'mimetypes', (object)$a);
1719 } else {
1720 $result = $mimetype;
1722 if ($capitalise) {
1723 $result=ucfirst($result);
1725 return $result;
1729 * Returns array of elements of type $element in type group(s)
1731 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1732 * @param string|array $groups one group or array of groups/extensions/mimetypes
1733 * @return array
1735 function file_get_typegroup($element, $groups) {
1736 static $cached = array();
1737 if (!is_array($groups)) {
1738 $groups = array($groups);
1740 if (!array_key_exists($element, $cached)) {
1741 $cached[$element] = array();
1743 $result = array();
1744 foreach ($groups as $group) {
1745 if (!array_key_exists($group, $cached[$element])) {
1746 // retrieive and cache all elements of type $element for group $group
1747 $mimeinfo = & get_mimetypes_array();
1748 $cached[$element][$group] = array();
1749 foreach ($mimeinfo as $extension => $value) {
1750 $value['extension'] = '.'.$extension;
1751 if (empty($value[$element])) {
1752 continue;
1754 if (($group === '.'.$extension || $group === $value['type'] ||
1755 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1756 !in_array($value[$element], $cached[$element][$group])) {
1757 $cached[$element][$group][] = $value[$element];
1761 $result = array_merge($result, $cached[$element][$group]);
1763 return array_values(array_unique($result));
1767 * Checks if file with name $filename has one of the extensions in groups $groups
1769 * @see get_mimetypes_array()
1770 * @param string $filename name of the file to check
1771 * @param string|array $groups one group or array of groups to check
1772 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1773 * file mimetype is in mimetypes in groups $groups
1774 * @return bool
1776 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1777 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1778 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1779 return true;
1781 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1785 * Checks if mimetype $mimetype belongs to one of the groups $groups
1787 * @see get_mimetypes_array()
1788 * @param string $mimetype
1789 * @param string|array $groups one group or array of groups to check
1790 * @return bool
1792 function file_mimetype_in_typegroup($mimetype, $groups) {
1793 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1797 * Requested file is not found or not accessible, does not return, terminates script
1799 * @global stdClass $CFG
1800 * @global stdClass $COURSE
1802 function send_file_not_found() {
1803 global $CFG, $COURSE;
1805 // Allow cross-origin requests only for Web Services.
1806 // This allow to receive requests done by Web Workers or webapps in different domains.
1807 if (WS_SERVER) {
1808 header('Access-Control-Allow-Origin: *');
1811 send_header_404();
1812 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1815 * Helper function to send correct 404 for server.
1817 function send_header_404() {
1818 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1819 header("Status: 404 Not Found");
1820 } else {
1821 header('HTTP/1.0 404 not found');
1826 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1827 * platforms). This wrapper uses readfile for small files and custom code for
1828 * large ones.
1830 * @param string $path Path to file
1831 * @param int $filesize Size of file (if left out, will get it automatically)
1832 * @return int|bool Size read (will always be $filesize) or false if failed
1834 function readfile_allow_large($path, $filesize = -1) {
1835 // Automatically get size if not specified.
1836 if ($filesize === -1) {
1837 $filesize = filesize($path);
1839 if ($filesize <= 2147483647) {
1840 // If the file is up to 2^31 - 1, send it normally using readfile.
1841 return readfile($path);
1842 } else {
1843 // For large files, read and output in 64KB chunks.
1844 $handle = fopen($path, 'r');
1845 if ($handle === false) {
1846 return false;
1848 $left = $filesize;
1849 while ($left > 0) {
1850 $size = min($left, 65536);
1851 $buffer = fread($handle, $size);
1852 if ($buffer === false) {
1853 return false;
1855 echo $buffer;
1856 $left -= $size;
1858 return $filesize;
1863 * Enhanced readfile() with optional acceleration.
1864 * @param string|stored_file $file
1865 * @param string $mimetype
1866 * @param bool $accelerate
1867 * @return void
1869 function readfile_accel($file, $mimetype, $accelerate) {
1870 global $CFG;
1872 if ($mimetype === 'text/plain') {
1873 // there is no encoding specified in text files, we need something consistent
1874 header('Content-Type: text/plain; charset=utf-8');
1875 } else {
1876 header('Content-Type: '.$mimetype);
1879 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1880 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1882 if (is_object($file)) {
1883 header('Etag: "' . $file->get_contenthash() . '"');
1884 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1885 header('HTTP/1.1 304 Not Modified');
1886 return;
1890 // if etag present for stored file rely on it exclusively
1891 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1892 // get unixtime of request header; clip extra junk off first
1893 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1894 if ($since && $since >= $lastmodified) {
1895 header('HTTP/1.1 304 Not Modified');
1896 return;
1900 if ($accelerate and !empty($CFG->xsendfile)) {
1901 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1902 header('Accept-Ranges: bytes');
1903 } else {
1904 header('Accept-Ranges: none');
1907 if (is_object($file)) {
1908 $fs = get_file_storage();
1909 if ($fs->xsendfile($file->get_contenthash())) {
1910 return;
1913 } else {
1914 require_once("$CFG->libdir/xsendfilelib.php");
1915 if (xsendfile($file)) {
1916 return;
1921 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1923 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1925 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1926 header('Accept-Ranges: bytes');
1928 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1929 // byteserving stuff - for acrobat reader and download accelerators
1930 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1931 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1932 $ranges = false;
1933 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1934 foreach ($ranges as $key=>$value) {
1935 if ($ranges[$key][1] == '') {
1936 //suffix case
1937 $ranges[$key][1] = $filesize - $ranges[$key][2];
1938 $ranges[$key][2] = $filesize - 1;
1939 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1940 //fix range length
1941 $ranges[$key][2] = $filesize - 1;
1943 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1944 //invalid byte-range ==> ignore header
1945 $ranges = false;
1946 break;
1948 //prepare multipart header
1949 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1950 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1952 } else {
1953 $ranges = false;
1955 if ($ranges) {
1956 if (is_object($file)) {
1957 $handle = $file->get_content_file_handle();
1958 } else {
1959 $handle = fopen($file, 'rb');
1961 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1964 } else {
1965 // Do not byteserve
1966 header('Accept-Ranges: none');
1969 header('Content-Length: '.$filesize);
1971 if ($filesize > 10000000) {
1972 // for large files try to flush and close all buffers to conserve memory
1973 while(@ob_get_level()) {
1974 if (!@ob_end_flush()) {
1975 break;
1980 // send the whole file content
1981 if (is_object($file)) {
1982 $file->readfile();
1983 } else {
1984 readfile_allow_large($file, $filesize);
1989 * Similar to readfile_accel() but designed for strings.
1990 * @param string $string
1991 * @param string $mimetype
1992 * @param bool $accelerate
1993 * @return void
1995 function readstring_accel($string, $mimetype, $accelerate) {
1996 global $CFG;
1998 if ($mimetype === 'text/plain') {
1999 // there is no encoding specified in text files, we need something consistent
2000 header('Content-Type: text/plain; charset=utf-8');
2001 } else {
2002 header('Content-Type: '.$mimetype);
2004 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2005 header('Accept-Ranges: none');
2007 if ($accelerate and !empty($CFG->xsendfile)) {
2008 $fs = get_file_storage();
2009 if ($fs->xsendfile(sha1($string))) {
2010 return;
2014 header('Content-Length: '.strlen($string));
2015 echo $string;
2019 * Handles the sending of temporary file to user, download is forced.
2020 * File is deleted after abort or successful sending, does not return, script terminated
2022 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2023 * @param string $filename proposed file name when saving file
2024 * @param bool $pathisstring If the path is string
2026 function send_temp_file($path, $filename, $pathisstring=false) {
2027 global $CFG;
2029 // Guess the file's MIME type.
2030 $mimetype = get_mimetype_for_sending($filename);
2032 // close session - not needed anymore
2033 \core\session\manager::write_close();
2035 if (!$pathisstring) {
2036 if (!file_exists($path)) {
2037 send_header_404();
2038 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2040 // executed after normal finish or abort
2041 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2044 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2045 if (core_useragent::is_ie()) {
2046 $filename = urlencode($filename);
2049 header('Content-Disposition: attachment; filename="'.$filename.'"');
2050 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2051 header('Cache-Control: private, max-age=10, no-transform');
2052 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2053 header('Pragma: ');
2054 } else { //normal http - prevent caching at all cost
2055 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2056 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2057 header('Pragma: no-cache');
2060 // send the contents - we can not accelerate this because the file will be deleted asap
2061 if ($pathisstring) {
2062 readstring_accel($path, $mimetype, false);
2063 } else {
2064 readfile_accel($path, $mimetype, false);
2065 @unlink($path);
2068 die; //no more chars to output
2072 * Internal callback function used by send_temp_file()
2074 * @param string $path
2076 function send_temp_file_finished($path) {
2077 if (file_exists($path)) {
2078 @unlink($path);
2083 * Serve content which is not meant to be cached.
2085 * This is only intended to be used for volatile public files, for instance
2086 * when development is enabled, or when caching is not required on a public resource.
2088 * @param string $content Raw content.
2089 * @param string $filename The file name.
2090 * @return void
2092 function send_content_uncached($content, $filename) {
2093 $mimetype = mimeinfo('type', $filename);
2094 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2096 header('Content-Disposition: inline; filename="' . $filename . '"');
2097 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2098 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2099 header('Pragma: ');
2100 header('Accept-Ranges: none');
2101 header('Content-Type: ' . $mimetype . $charset);
2102 header('Content-Length: ' . strlen($content));
2104 echo $content;
2105 die();
2109 * Safely save content to a certain path.
2111 * This function tries hard to be atomic by first copying the content
2112 * to a separate file, and then moving the file across. It also prevents
2113 * the user to abort a request to prevent half-safed files.
2115 * This function is intended to be used when saving some content to cache like
2116 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2118 * @param string $content The file content.
2119 * @param string $destination The absolute path of the final file.
2120 * @return void
2122 function file_safe_save_content($content, $destination) {
2123 global $CFG;
2125 clearstatcache();
2126 if (!file_exists(dirname($destination))) {
2127 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2130 // Prevent serving of incomplete file from concurrent request,
2131 // the rename() should be more atomic than fwrite().
2132 ignore_user_abort(true);
2133 if ($fp = fopen($destination . '.tmp', 'xb')) {
2134 fwrite($fp, $content);
2135 fclose($fp);
2136 rename($destination . '.tmp', $destination);
2137 @chmod($destination, $CFG->filepermissions);
2138 @unlink($destination . '.tmp'); // Just in case anything fails.
2140 ignore_user_abort(false);
2141 if (connection_aborted()) {
2142 die();
2147 * Handles the sending of file data to the user's browser, including support for
2148 * byteranges etc.
2150 * @category files
2151 * @param string|stored_file $path Path of file on disk (including real filename),
2152 * or actual content of file as string,
2153 * or stored_file object
2154 * @param string $filename Filename to send
2155 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2156 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2157 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2158 * Forced to false when $path is a stored_file object.
2159 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2160 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2161 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2162 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2163 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2164 * and should not be reopened.
2165 * @param array $options An array of options, currently accepts:
2166 * - (string) cacheability: public, or private.
2167 * - (string|null) immutable
2168 * @return null script execution stopped unless $dontdie is true
2170 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2171 $dontdie=false, array $options = array()) {
2172 global $CFG, $COURSE;
2174 if ($dontdie) {
2175 ignore_user_abort(true);
2178 if ($lifetime === 'default' or is_null($lifetime)) {
2179 $lifetime = $CFG->filelifetime;
2182 if (is_object($path)) {
2183 $pathisstring = false;
2186 \core\session\manager::write_close(); // Unlock session during file serving.
2188 // Use given MIME type if specified, otherwise guess it.
2189 if (!$mimetype || $mimetype === 'document/unknown') {
2190 $mimetype = get_mimetype_for_sending($filename);
2193 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2194 if (core_useragent::is_ie()) {
2195 $filename = rawurlencode($filename);
2198 if ($forcedownload) {
2199 header('Content-Disposition: attachment; filename="'.$filename.'"');
2200 } else if ($mimetype !== 'application/x-shockwave-flash') {
2201 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2202 // as an upload and enforces security that may prevent the file from being loaded.
2204 header('Content-Disposition: inline; filename="'.$filename.'"');
2207 if ($lifetime > 0) {
2208 $immutable = '';
2209 if (!empty($options['immutable'])) {
2210 $immutable = ', immutable';
2211 // Overwrite lifetime accordingly:
2212 // 90 days only - based on Moodle point release cadence being every 3 months.
2213 $lifetimemin = 60 * 60 * 24 * 90;
2214 $lifetime = max($lifetime, $lifetimemin);
2216 $cacheability = ' public,';
2217 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2218 // This file must be cache-able by both browsers and proxies.
2219 $cacheability = ' public,';
2220 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2221 // This file must be cache-able only by browsers.
2222 $cacheability = ' private,';
2223 } else if (isloggedin() and !isguestuser()) {
2224 // By default, under the conditions above, this file must be cache-able only by browsers.
2225 $cacheability = ' private,';
2227 $nobyteserving = false;
2228 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2229 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2230 header('Pragma: ');
2232 } else { // Do not cache files in proxies and browsers
2233 $nobyteserving = true;
2234 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2235 header('Cache-Control: private, max-age=10, no-transform');
2236 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2237 header('Pragma: ');
2238 } else { //normal http - prevent caching at all cost
2239 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2240 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2241 header('Pragma: no-cache');
2245 if (empty($filter)) {
2246 // send the contents
2247 if ($pathisstring) {
2248 readstring_accel($path, $mimetype, !$dontdie);
2249 } else {
2250 readfile_accel($path, $mimetype, !$dontdie);
2253 } else {
2254 // Try to put the file through filters
2255 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2256 $options = new stdClass();
2257 $options->noclean = true;
2258 $options->nocache = true; // temporary workaround for MDL-5136
2259 if (is_object($path)) {
2260 $text = $path->get_content();
2261 } else if ($pathisstring) {
2262 $text = $path;
2263 } else {
2264 $text = implode('', file($path));
2266 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2268 readstring_accel($output, $mimetype, false);
2270 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2271 // only filter text if filter all files is selected
2272 $options = new stdClass();
2273 $options->newlines = false;
2274 $options->noclean = true;
2275 if (is_object($path)) {
2276 $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2277 } else if ($pathisstring) {
2278 $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2279 } else {
2280 $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2282 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2284 readstring_accel($output, $mimetype, false);
2286 } else {
2287 // send the contents
2288 if ($pathisstring) {
2289 readstring_accel($path, $mimetype, !$dontdie);
2290 } else {
2291 readfile_accel($path, $mimetype, !$dontdie);
2295 if ($dontdie) {
2296 return;
2298 die; //no more chars to output!!!
2302 * Handles the sending of file data to the user's browser, including support for
2303 * byteranges etc.
2305 * The $options parameter supports the following keys:
2306 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2307 * (string|null) filename - overrides the implicit filename
2308 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2309 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2310 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2311 * and should not be reopened
2312 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2313 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2314 * defaults to "public".
2315 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2316 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2318 * @category files
2319 * @param stored_file $stored_file local file object
2320 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2321 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2322 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2323 * @param array $options additional options affecting the file serving
2324 * @return null script execution stopped unless $options['dontdie'] is true
2326 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2327 global $CFG, $COURSE;
2329 if (empty($options['filename'])) {
2330 $filename = null;
2331 } else {
2332 $filename = $options['filename'];
2335 if (empty($options['dontdie'])) {
2336 $dontdie = false;
2337 } else {
2338 $dontdie = true;
2341 if ($lifetime === 'default' or is_null($lifetime)) {
2342 $lifetime = $CFG->filelifetime;
2345 if (!empty($options['preview'])) {
2346 // replace the file with its preview
2347 $fs = get_file_storage();
2348 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2349 if (!$preview_file) {
2350 // unable to create a preview of the file, send its default mime icon instead
2351 if ($options['preview'] === 'tinyicon') {
2352 $size = 24;
2353 } else if ($options['preview'] === 'thumb') {
2354 $size = 90;
2355 } else {
2356 $size = 256;
2358 $fileicon = file_file_icon($stored_file, $size);
2359 send_file($CFG->dirroot.'/pix/'.$fileicon.'.svg', basename($fileicon).'.svg');
2360 } else {
2361 // preview images have fixed cache lifetime and they ignore forced download
2362 // (they are generated by GD and therefore they are considered reasonably safe).
2363 $stored_file = $preview_file;
2364 $lifetime = DAYSECS;
2365 $filter = 0;
2366 $forcedownload = false;
2370 // handle external resource
2371 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2372 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2373 die;
2376 if (!$stored_file or $stored_file->is_directory()) {
2377 // nothing to serve
2378 if ($dontdie) {
2379 return;
2381 die;
2384 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2386 // Use given MIME type if specified.
2387 $mimetype = $stored_file->get_mimetype();
2389 // Allow cross-origin requests only for Web Services.
2390 // This allow to receive requests done by Web Workers or webapps in different domains.
2391 if (WS_SERVER) {
2392 header('Access-Control-Allow-Origin: *');
2395 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2399 * Recursively delete the file or folder with path $location. That is,
2400 * if it is a file delete it. If it is a folder, delete all its content
2401 * then delete it. If $location does not exist to start, that is not
2402 * considered an error.
2404 * @param string $location the path to remove.
2405 * @return bool
2407 function fulldelete($location) {
2408 if (empty($location)) {
2409 // extra safety against wrong param
2410 return false;
2412 if (is_dir($location)) {
2413 if (!$currdir = opendir($location)) {
2414 return false;
2416 while (false !== ($file = readdir($currdir))) {
2417 if ($file <> ".." && $file <> ".") {
2418 $fullfile = $location."/".$file;
2419 if (is_dir($fullfile)) {
2420 if (!fulldelete($fullfile)) {
2421 return false;
2423 } else {
2424 if (!unlink($fullfile)) {
2425 return false;
2430 closedir($currdir);
2431 if (! rmdir($location)) {
2432 return false;
2435 } else if (file_exists($location)) {
2436 if (!unlink($location)) {
2437 return false;
2440 return true;
2444 * Send requested byterange of file.
2446 * @param resource $handle A file handle
2447 * @param string $mimetype The mimetype for the output
2448 * @param array $ranges An array of ranges to send
2449 * @param string $filesize The size of the content if only one range is used
2451 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2452 // better turn off any kind of compression and buffering
2453 ini_set('zlib.output_compression', 'Off');
2455 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2456 if ($handle === false) {
2457 die;
2459 if (count($ranges) == 1) { //only one range requested
2460 $length = $ranges[0][2] - $ranges[0][1] + 1;
2461 header('HTTP/1.1 206 Partial content');
2462 header('Content-Length: '.$length);
2463 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2464 header('Content-Type: '.$mimetype);
2466 while(@ob_get_level()) {
2467 if (!@ob_end_flush()) {
2468 break;
2472 fseek($handle, $ranges[0][1]);
2473 while (!feof($handle) && $length > 0) {
2474 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2475 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2476 echo $buffer;
2477 flush();
2478 $length -= strlen($buffer);
2480 fclose($handle);
2481 die;
2482 } else { // multiple ranges requested - not tested much
2483 $totallength = 0;
2484 foreach($ranges as $range) {
2485 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2487 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2488 header('HTTP/1.1 206 Partial content');
2489 header('Content-Length: '.$totallength);
2490 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2492 while(@ob_get_level()) {
2493 if (!@ob_end_flush()) {
2494 break;
2498 foreach($ranges as $range) {
2499 $length = $range[2] - $range[1] + 1;
2500 echo $range[0];
2501 fseek($handle, $range[1]);
2502 while (!feof($handle) && $length > 0) {
2503 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2504 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2505 echo $buffer;
2506 flush();
2507 $length -= strlen($buffer);
2510 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2511 fclose($handle);
2512 die;
2517 * Tells whether the filename is executable.
2519 * @link http://php.net/manual/en/function.is-executable.php
2520 * @link https://bugs.php.net/bug.php?id=41062
2521 * @param string $filename Path to the file.
2522 * @return bool True if the filename exists and is executable; otherwise, false.
2524 function file_is_executable($filename) {
2525 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2526 if (is_executable($filename)) {
2527 return true;
2528 } else {
2529 $fileext = strrchr($filename, '.');
2530 // If we have an extension we can check if it is listed as executable.
2531 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2532 $winpathext = strtolower(getenv('PATHEXT'));
2533 $winpathexts = explode(';', $winpathext);
2535 return in_array(strtolower($fileext), $winpathexts);
2538 return false;
2540 } else {
2541 return is_executable($filename);
2546 * Overwrite an existing file in a draft area.
2548 * @param stored_file $newfile the new file with the new content and meta-data
2549 * @param stored_file $existingfile the file that will be overwritten
2550 * @throws moodle_exception
2551 * @since Moodle 3.2
2553 function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2554 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2555 throw new coding_exception('The file to overwrite is not in a draft area.');
2558 $fs = get_file_storage();
2559 // Remember original file source field.
2560 $source = @unserialize($existingfile->get_source());
2561 // Remember the original sortorder.
2562 $sortorder = $existingfile->get_sortorder();
2563 if ($newfile->is_external_file()) {
2564 // New file is a reference. Check that existing file does not have any other files referencing to it
2565 if (isset($source->original) && $fs->search_references_count($source->original)) {
2566 throw new moodle_exception('errordoublereference', 'repository');
2570 // Delete existing file to release filename.
2571 $newfilerecord = array(
2572 'contextid' => $existingfile->get_contextid(),
2573 'component' => 'user',
2574 'filearea' => 'draft',
2575 'itemid' => $existingfile->get_itemid(),
2576 'timemodified' => time()
2578 $existingfile->delete();
2580 // Create new file.
2581 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2582 // Preserve original file location (stored in source field) for handling references.
2583 if (isset($source->original)) {
2584 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2585 $newfilesource = new stdClass();
2587 $newfilesource->original = $source->original;
2588 $newfile->set_source(serialize($newfilesource));
2590 $newfile->set_sortorder($sortorder);
2594 * Add files from a draft area into a final area.
2596 * Most of the time you do not want to use this. It is intended to be used
2597 * by asynchronous services which cannot direcly manipulate a final
2598 * area through a draft area. Instead they add files to a new draft
2599 * area and merge that new draft into the final area when ready.
2601 * @param int $draftitemid the id of the draft area to use.
2602 * @param int $contextid this parameter and the next two identify the file area to save to.
2603 * @param string $component component name
2604 * @param string $filearea indentifies the file area
2605 * @param int $itemid identifies the item id or false for all items in the file area
2606 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2607 * @see file_save_draft_area_files
2608 * @since Moodle 3.2
2610 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2611 array $options = null) {
2612 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2613 $finaldraftid = 0;
2614 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2615 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2616 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2620 * Merge files from two draftarea areas.
2622 * This does not handle conflict resolution, files in the destination area which appear
2623 * to be more recent will be kept disregarding the intended ones.
2625 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2626 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2627 * @throws coding_exception
2628 * @since Moodle 3.2
2630 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2631 global $USER;
2633 $fs = get_file_storage();
2634 $contextid = context_user::instance($USER->id)->id;
2636 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2637 throw new coding_exception('Nothing to merge or area does not belong to current user');
2640 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2642 // Get hashes of the files to merge.
2643 $newhashes = array();
2644 foreach ($filestomerge as $filetomerge) {
2645 $filepath = $filetomerge->get_filepath();
2646 $filename = $filetomerge->get_filename();
2648 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2649 $newhashes[$newhash] = $filetomerge;
2652 // Calculate wich files must be added.
2653 foreach ($currentfiles as $file) {
2654 $filehash = $file->get_pathnamehash();
2655 // One file to be merged already exists.
2656 if (isset($newhashes[$filehash])) {
2657 $updatedfile = $newhashes[$filehash];
2659 // Avoid race conditions.
2660 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2661 // The existing file is more recent, do not copy the suposedly "new" one.
2662 unset($newhashes[$filehash]);
2663 continue;
2665 // Update existing file (not only content, meta-data too).
2666 file_overwrite_existing_draftfile($updatedfile, $file);
2667 unset($newhashes[$filehash]);
2671 foreach ($newhashes as $newfile) {
2672 $newfilerecord = array(
2673 'contextid' => $contextid,
2674 'component' => 'user',
2675 'filearea' => 'draft',
2676 'itemid' => $mergeintodraftid,
2677 'timemodified' => time()
2680 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2685 * RESTful cURL class
2687 * This is a wrapper class for curl, it is quite easy to use:
2688 * <code>
2689 * $c = new curl;
2690 * // enable cache
2691 * $c = new curl(array('cache'=>true));
2692 * // enable cookie
2693 * $c = new curl(array('cookie'=>true));
2694 * // enable proxy
2695 * $c = new curl(array('proxy'=>true));
2697 * // HTTP GET Method
2698 * $html = $c->get('http://example.com');
2699 * // HTTP POST Method
2700 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2701 * // HTTP PUT Method
2702 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2703 * </code>
2705 * @package core_files
2706 * @category files
2707 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2708 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2710 class curl {
2711 /** @var bool Caches http request contents */
2712 public $cache = false;
2713 /** @var bool Uses proxy, null means automatic based on URL */
2714 public $proxy = null;
2715 /** @var string library version */
2716 public $version = '0.4 dev';
2717 /** @var array http's response */
2718 public $response = array();
2719 /** @var array Raw response headers, needed for BC in download_file_content(). */
2720 public $rawresponse = array();
2721 /** @var array http header */
2722 public $header = array();
2723 /** @var string cURL information */
2724 public $info;
2725 /** @var string error */
2726 public $error;
2727 /** @var int error code */
2728 public $errno;
2729 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2730 public $emulateredirects = null;
2732 /** @var array cURL options */
2733 private $options;
2735 /** @var string Proxy host */
2736 private $proxy_host = '';
2737 /** @var string Proxy auth */
2738 private $proxy_auth = '';
2739 /** @var string Proxy type */
2740 private $proxy_type = '';
2741 /** @var bool Debug mode on */
2742 private $debug = false;
2743 /** @var bool|string Path to cookie file */
2744 private $cookie = false;
2745 /** @var bool tracks multiple headers in response - redirect detection */
2746 private $responsefinished = false;
2747 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2748 private $securityhelper;
2749 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2750 private $ignoresecurity;
2751 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
2752 private static $mockresponses = [];
2755 * Curl constructor.
2757 * Allowed settings are:
2758 * proxy: (bool) use proxy server, null means autodetect non-local from url
2759 * debug: (bool) use debug output
2760 * cookie: (string) path to cookie file, false if none
2761 * cache: (bool) use cache
2762 * module_cache: (string) type of cache
2763 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
2764 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
2766 * @param array $settings
2768 public function __construct($settings = array()) {
2769 global $CFG;
2770 if (!function_exists('curl_init')) {
2771 $this->error = 'cURL module must be enabled!';
2772 trigger_error($this->error, E_USER_ERROR);
2773 return false;
2776 // All settings of this class should be init here.
2777 $this->resetopt();
2778 if (!empty($settings['debug'])) {
2779 $this->debug = true;
2781 if (!empty($settings['cookie'])) {
2782 if($settings['cookie'] === true) {
2783 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2784 } else {
2785 $this->cookie = $settings['cookie'];
2788 if (!empty($settings['cache'])) {
2789 if (class_exists('curl_cache')) {
2790 if (!empty($settings['module_cache'])) {
2791 $this->cache = new curl_cache($settings['module_cache']);
2792 } else {
2793 $this->cache = new curl_cache('misc');
2797 if (!empty($CFG->proxyhost)) {
2798 if (empty($CFG->proxyport)) {
2799 $this->proxy_host = $CFG->proxyhost;
2800 } else {
2801 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2803 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2804 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2805 $this->setopt(array(
2806 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2807 'proxyuserpwd'=>$this->proxy_auth));
2809 if (!empty($CFG->proxytype)) {
2810 if ($CFG->proxytype == 'SOCKS5') {
2811 $this->proxy_type = CURLPROXY_SOCKS5;
2812 } else {
2813 $this->proxy_type = CURLPROXY_HTTP;
2814 $this->setopt(array('httpproxytunnel'=>false));
2816 $this->setopt(array('proxytype'=>$this->proxy_type));
2819 if (isset($settings['proxy'])) {
2820 $this->proxy = $settings['proxy'];
2822 } else {
2823 $this->proxy = false;
2826 if (!isset($this->emulateredirects)) {
2827 $this->emulateredirects = ini_get('open_basedir');
2830 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
2831 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
2832 $this->set_security($settings['securityhelper']);
2833 } else {
2834 $this->set_security(new \core\files\curl_security_helper());
2836 $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
2840 * Resets the CURL options that have already been set
2842 public function resetopt() {
2843 $this->options = array();
2844 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2845 // True to include the header in the output
2846 $this->options['CURLOPT_HEADER'] = 0;
2847 // True to Exclude the body from the output
2848 $this->options['CURLOPT_NOBODY'] = 0;
2849 // Redirect ny default.
2850 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2851 $this->options['CURLOPT_MAXREDIRS'] = 10;
2852 $this->options['CURLOPT_ENCODING'] = '';
2853 // TRUE to return the transfer as a string of the return
2854 // value of curl_exec() instead of outputting it out directly.
2855 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2856 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2857 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2858 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2860 if ($cacert = self::get_cacert()) {
2861 $this->options['CURLOPT_CAINFO'] = $cacert;
2866 * Get the location of ca certificates.
2867 * @return string absolute file path or empty if default used
2869 public static function get_cacert() {
2870 global $CFG;
2872 // Bundle in dataroot always wins.
2873 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2874 return realpath("$CFG->dataroot/moodleorgca.crt");
2877 // Next comes the default from php.ini
2878 $cacert = ini_get('curl.cainfo');
2879 if (!empty($cacert) and is_readable($cacert)) {
2880 return realpath($cacert);
2883 // Windows PHP does not have any certs, we need to use something.
2884 if ($CFG->ostype === 'WINDOWS') {
2885 if (is_readable("$CFG->libdir/cacert.pem")) {
2886 return realpath("$CFG->libdir/cacert.pem");
2890 // Use default, this should work fine on all properly configured *nix systems.
2891 return null;
2895 * Reset Cookie
2897 public function resetcookie() {
2898 if (!empty($this->cookie)) {
2899 if (is_file($this->cookie)) {
2900 $fp = fopen($this->cookie, 'w');
2901 if (!empty($fp)) {
2902 fwrite($fp, '');
2903 fclose($fp);
2910 * Set curl options.
2912 * Do not use the curl constants to define the options, pass a string
2913 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2914 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2916 * @param array $options If array is null, this function will reset the options to default value.
2917 * @return void
2918 * @throws coding_exception If an option uses constant value instead of option name.
2920 public function setopt($options = array()) {
2921 if (is_array($options)) {
2922 foreach ($options as $name => $val) {
2923 if (!is_string($name)) {
2924 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2926 if (stripos($name, 'CURLOPT_') === false) {
2927 $name = strtoupper('CURLOPT_'.$name);
2928 } else {
2929 $name = strtoupper($name);
2931 $this->options[$name] = $val;
2937 * Reset http method
2939 public function cleanopt() {
2940 unset($this->options['CURLOPT_HTTPGET']);
2941 unset($this->options['CURLOPT_POST']);
2942 unset($this->options['CURLOPT_POSTFIELDS']);
2943 unset($this->options['CURLOPT_PUT']);
2944 unset($this->options['CURLOPT_INFILE']);
2945 unset($this->options['CURLOPT_INFILESIZE']);
2946 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2947 unset($this->options['CURLOPT_FILE']);
2951 * Resets the HTTP Request headers (to prepare for the new request)
2953 public function resetHeader() {
2954 $this->header = array();
2958 * Set HTTP Request Header
2960 * @param array $header
2961 * @param bool $replace If true, will remove any existing headers before appending the new one.
2963 public function setHeader($header) {
2964 if (is_array($header)) {
2965 foreach ($header as $v) {
2966 $this->setHeader($v);
2968 } else {
2969 // Remove newlines, they are not allowed in headers.
2970 $this->header[] = preg_replace('/[\r\n]/', '', $header);
2975 * Get HTTP Response Headers
2976 * @return array of arrays
2978 public function getResponse() {
2979 return $this->response;
2983 * Get raw HTTP Response Headers
2984 * @return array of strings
2986 public function get_raw_response() {
2987 return $this->rawresponse;
2991 * private callback function
2992 * Formatting HTTP Response Header
2994 * We only keep the last headers returned. For example during a redirect the
2995 * redirect headers will not appear in {@link self::getResponse()}, if you need
2996 * to use those headers, refer to {@link self::get_raw_response()}.
2998 * @param resource $ch Apparently not used
2999 * @param string $header
3000 * @return int The strlen of the header
3002 private function formatHeader($ch, $header) {
3003 $this->rawresponse[] = $header;
3005 if (trim($header, "\r\n") === '') {
3006 // This must be the last header.
3007 $this->responsefinished = true;
3010 if (strlen($header) > 2) {
3011 if ($this->responsefinished) {
3012 // We still have headers after the supposedly last header, we must be
3013 // in a redirect so let's empty the response to keep the last headers.
3014 $this->responsefinished = false;
3015 $this->response = array();
3017 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3018 $key = rtrim($parts[0], ':');
3019 $value = isset($parts[1]) ? $parts[1] : null;
3020 if (!empty($this->response[$key])) {
3021 if (is_array($this->response[$key])) {
3022 $this->response[$key][] = $value;
3023 } else {
3024 $tmp = $this->response[$key];
3025 $this->response[$key] = array();
3026 $this->response[$key][] = $tmp;
3027 $this->response[$key][] = $value;
3030 } else {
3031 $this->response[$key] = $value;
3034 return strlen($header);
3038 * Set options for individual curl instance
3040 * @param resource $curl A curl handle
3041 * @param array $options
3042 * @return resource The curl handle
3044 private function apply_opt($curl, $options) {
3045 // Clean up
3046 $this->cleanopt();
3047 // set cookie
3048 if (!empty($this->cookie) || !empty($options['cookie'])) {
3049 $this->setopt(array('cookiejar'=>$this->cookie,
3050 'cookiefile'=>$this->cookie
3054 // Bypass proxy if required.
3055 if ($this->proxy === null) {
3056 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3057 $proxy = false;
3058 } else {
3059 $proxy = true;
3061 } else {
3062 $proxy = (bool)$this->proxy;
3065 // Set proxy.
3066 if ($proxy) {
3067 $options['CURLOPT_PROXY'] = $this->proxy_host;
3068 } else {
3069 unset($this->options['CURLOPT_PROXY']);
3072 $this->setopt($options);
3074 // Reset before set options.
3075 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3077 // Setting the User-Agent based on options provided.
3078 $useragent = '';
3080 if (!empty($options['CURLOPT_USERAGENT'])) {
3081 $useragent = $options['CURLOPT_USERAGENT'];
3082 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3083 $useragent = $this->options['CURLOPT_USERAGENT'];
3084 } else {
3085 $useragent = 'MoodleBot/1.0';
3088 // Set headers.
3089 if (empty($this->header)) {
3090 $this->setHeader(array(
3091 'User-Agent: ' . $useragent,
3092 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3093 'Connection: keep-alive'
3095 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3096 // Remove old User-Agent if one existed.
3097 // We have to partial search since we don't know what the original User-Agent is.
3098 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3099 $key = array_keys($match)[0];
3100 unset($this->header[$key]);
3102 $this->setHeader(array('User-Agent: ' . $useragent));
3104 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3106 if ($this->debug) {
3107 echo '<h1>Options</h1>';
3108 var_dump($this->options);
3109 echo '<h1>Header</h1>';
3110 var_dump($this->header);
3113 // Do not allow infinite redirects.
3114 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3115 $this->options['CURLOPT_MAXREDIRS'] = 0;
3116 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3117 $this->options['CURLOPT_MAXREDIRS'] = 100;
3118 } else {
3119 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3122 // Make sure we always know if redirects expected.
3123 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3124 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3127 // Limit the protocols to HTTP and HTTPS.
3128 if (defined('CURLOPT_PROTOCOLS')) {
3129 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3130 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3133 // Set options.
3134 foreach($this->options as $name => $val) {
3135 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3136 // The redirects are emulated elsewhere.
3137 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3138 continue;
3140 $name = constant($name);
3141 curl_setopt($curl, $name, $val);
3144 return $curl;
3148 * Download multiple files in parallel
3150 * Calls {@link multi()} with specific download headers
3152 * <code>
3153 * $c = new curl();
3154 * $file1 = fopen('a', 'wb');
3155 * $file2 = fopen('b', 'wb');
3156 * $c->download(array(
3157 * array('url'=>'http://localhost/', 'file'=>$file1),
3158 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3159 * ));
3160 * fclose($file1);
3161 * fclose($file2);
3162 * </code>
3164 * or
3166 * <code>
3167 * $c = new curl();
3168 * $c->download(array(
3169 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3170 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3171 * ));
3172 * </code>
3174 * @param array $requests An array of files to request {
3175 * url => url to download the file [required]
3176 * file => file handler, or
3177 * filepath => file path
3179 * If 'file' and 'filepath' parameters are both specified in one request, the
3180 * open file handle in the 'file' parameter will take precedence and 'filepath'
3181 * will be ignored.
3183 * @param array $options An array of options to set
3184 * @return array An array of results
3186 public function download($requests, $options = array()) {
3187 $options['RETURNTRANSFER'] = false;
3188 return $this->multi($requests, $options);
3192 * Returns the current curl security helper.
3194 * @return \core\files\curl_security_helper instance.
3196 public function get_security() {
3197 return $this->securityhelper;
3201 * Sets the curl security helper.
3203 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3204 * @return bool true if the security helper could be set, false otherwise.
3206 public function set_security($securityobject) {
3207 if ($securityobject instanceof \core\files\curl_security_helper) {
3208 $this->securityhelper = $securityobject;
3209 return true;
3211 return false;
3215 * Multi HTTP Requests
3216 * This function could run multi-requests in parallel.
3218 * @param array $requests An array of files to request
3219 * @param array $options An array of options to set
3220 * @return array An array of results
3222 protected function multi($requests, $options = array()) {
3223 $count = count($requests);
3224 $handles = array();
3225 $results = array();
3226 $main = curl_multi_init();
3227 for ($i = 0; $i < $count; $i++) {
3228 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3229 // open file
3230 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3231 $requests[$i]['auto-handle'] = true;
3233 foreach($requests[$i] as $n=>$v) {
3234 $options[$n] = $v;
3236 $handles[$i] = curl_init($requests[$i]['url']);
3237 $this->apply_opt($handles[$i], $options);
3238 curl_multi_add_handle($main, $handles[$i]);
3240 $running = 0;
3241 do {
3242 curl_multi_exec($main, $running);
3243 } while($running > 0);
3244 for ($i = 0; $i < $count; $i++) {
3245 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3246 $results[] = true;
3247 } else {
3248 $results[] = curl_multi_getcontent($handles[$i]);
3250 curl_multi_remove_handle($main, $handles[$i]);
3252 curl_multi_close($main);
3254 for ($i = 0; $i < $count; $i++) {
3255 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3256 // close file handler if file is opened in this function
3257 fclose($requests[$i]['file']);
3260 return $results;
3264 * Helper function to reset the request state vars.
3266 * @return void.
3268 protected function reset_request_state_vars() {
3269 $this->info = array();
3270 $this->error = '';
3271 $this->errno = 0;
3272 $this->response = array();
3273 $this->rawresponse = array();
3274 $this->responsefinished = false;
3278 * For use only in unit tests - we can pre-set the next curl response.
3279 * This is useful for unit testing APIs that call external systems.
3280 * @param string $response
3282 public static function mock_response($response) {
3283 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3284 array_push(self::$mockresponses, $response);
3285 } else {
3286 throw new coding_excpetion('mock_response function is only available for unit tests.');
3291 * Single HTTP Request
3293 * @param string $url The URL to request
3294 * @param array $options
3295 * @return bool
3297 protected function request($url, $options = array()) {
3298 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3299 $this->reset_request_state_vars();
3301 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3302 if ($mockresponse = array_pop(self::$mockresponses)) {
3303 $this->info = [ 'http_code' => 200 ];
3304 return $mockresponse;
3308 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3309 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3310 if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3311 $this->error = $this->securityhelper->get_blocked_url_string();
3312 return $this->error;
3315 // Set the URL as a curl option.
3316 $this->setopt(array('CURLOPT_URL' => $url));
3318 // Create curl instance.
3319 $curl = curl_init();
3321 $this->apply_opt($curl, $options);
3322 if ($this->cache && $ret = $this->cache->get($this->options)) {
3323 return $ret;
3326 $ret = curl_exec($curl);
3327 $this->info = curl_getinfo($curl);
3328 $this->error = curl_error($curl);
3329 $this->errno = curl_errno($curl);
3330 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3332 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3333 if (intval($this->info['redirect_count']) > 0 && !$this->ignoresecurity
3334 && $this->securityhelper->url_is_blocked($this->info['url'])) {
3335 $this->reset_request_state_vars();
3336 $this->error = $this->securityhelper->get_blocked_url_string();
3337 curl_close($curl);
3338 return $this->error;
3341 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3342 $redirects = 0;
3344 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3346 if ($this->info['http_code'] == 301) {
3347 // Moved Permanently - repeat the same request on new URL.
3349 } else if ($this->info['http_code'] == 302) {
3350 // Found - the standard redirect - repeat the same request on new URL.
3352 } else if ($this->info['http_code'] == 303) {
3353 // 303 See Other - repeat only if GET, do not bother with POSTs.
3354 if (empty($this->options['CURLOPT_HTTPGET'])) {
3355 break;
3358 } else if ($this->info['http_code'] == 307) {
3359 // Temporary Redirect - must repeat using the same request type.
3361 } else if ($this->info['http_code'] == 308) {
3362 // Permanent Redirect - must repeat using the same request type.
3364 } else {
3365 // Some other http code means do not retry!
3366 break;
3369 $redirects++;
3371 $redirecturl = null;
3372 if (isset($this->info['redirect_url'])) {
3373 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3374 $redirecturl = $this->info['redirect_url'];
3377 if (!$redirecturl) {
3378 foreach ($this->response as $k => $v) {
3379 if (strtolower($k) === 'location') {
3380 $redirecturl = $v;
3381 break;
3384 if (preg_match('|^https?://|i', $redirecturl)) {
3385 // Great, this is the correct location format!
3387 } else if ($redirecturl) {
3388 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3389 if (strpos($redirecturl, '/') === 0) {
3390 // Relative to server root - just guess.
3391 $pos = strpos('/', $current, 8);
3392 if ($pos === false) {
3393 $redirecturl = $current.$redirecturl;
3394 } else {
3395 $redirecturl = substr($current, 0, $pos).$redirecturl;
3397 } else {
3398 // Relative to current script.
3399 $redirecturl = dirname($current).'/'.$redirecturl;
3404 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3405 $ret = curl_exec($curl);
3407 $this->info = curl_getinfo($curl);
3408 $this->error = curl_error($curl);
3409 $this->errno = curl_errno($curl);
3411 $this->info['redirect_count'] = $redirects;
3413 if ($this->info['http_code'] === 200) {
3414 // Finally this is what we wanted.
3415 break;
3417 if ($this->errno != CURLE_OK) {
3418 // Something wrong is going on.
3419 break;
3422 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3423 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3424 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3428 if ($this->cache) {
3429 $this->cache->set($this->options, $ret);
3432 if ($this->debug) {
3433 echo '<h1>Return Data</h1>';
3434 var_dump($ret);
3435 echo '<h1>Info</h1>';
3436 var_dump($this->info);
3437 echo '<h1>Error</h1>';
3438 var_dump($this->error);
3441 curl_close($curl);
3443 if (empty($this->error)) {
3444 return $ret;
3445 } else {
3446 return $this->error;
3447 // exception is not ajax friendly
3448 //throw new moodle_exception($this->error, 'curl');
3453 * HTTP HEAD method
3455 * @see request()
3457 * @param string $url
3458 * @param array $options
3459 * @return bool
3461 public function head($url, $options = array()) {
3462 $options['CURLOPT_HTTPGET'] = 0;
3463 $options['CURLOPT_HEADER'] = 1;
3464 $options['CURLOPT_NOBODY'] = 1;
3465 return $this->request($url, $options);
3469 * HTTP PATCH method
3471 * @param string $url
3472 * @param array|string $params
3473 * @param array $options
3474 * @return bool
3476 public function patch($url, $params = '', $options = array()) {
3477 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3478 if (is_array($params)) {
3479 $this->_tmp_file_post_params = array();
3480 foreach ($params as $key => $value) {
3481 if ($value instanceof stored_file) {
3482 $value->add_to_curl_request($this, $key);
3483 } else {
3484 $this->_tmp_file_post_params[$key] = $value;
3487 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3488 unset($this->_tmp_file_post_params);
3489 } else {
3490 // The variable $params is the raw post data.
3491 $options['CURLOPT_POSTFIELDS'] = $params;
3493 return $this->request($url, $options);
3497 * HTTP POST method
3499 * @param string $url
3500 * @param array|string $params
3501 * @param array $options
3502 * @return bool
3504 public function post($url, $params = '', $options = array()) {
3505 $options['CURLOPT_POST'] = 1;
3506 if (is_array($params)) {
3507 $this->_tmp_file_post_params = array();
3508 foreach ($params as $key => $value) {
3509 if ($value instanceof stored_file) {
3510 $value->add_to_curl_request($this, $key);
3511 } else {
3512 $this->_tmp_file_post_params[$key] = $value;
3515 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3516 unset($this->_tmp_file_post_params);
3517 } else {
3518 // $params is the raw post data
3519 $options['CURLOPT_POSTFIELDS'] = $params;
3521 return $this->request($url, $options);
3525 * HTTP GET method
3527 * @param string $url
3528 * @param array $params
3529 * @param array $options
3530 * @return bool
3532 public function get($url, $params = array(), $options = array()) {
3533 $options['CURLOPT_HTTPGET'] = 1;
3535 if (!empty($params)) {
3536 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3537 $url .= http_build_query($params, '', '&');
3539 return $this->request($url, $options);
3543 * Downloads one file and writes it to the specified file handler
3545 * <code>
3546 * $c = new curl();
3547 * $file = fopen('savepath', 'w');
3548 * $result = $c->download_one('http://localhost/', null,
3549 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3550 * fclose($file);
3551 * $download_info = $c->get_info();
3552 * if ($result === true) {
3553 * // file downloaded successfully
3554 * } else {
3555 * $error_text = $result;
3556 * $error_code = $c->get_errno();
3558 * </code>
3560 * <code>
3561 * $c = new curl();
3562 * $result = $c->download_one('http://localhost/', null,
3563 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3564 * // ... see above, no need to close handle and remove file if unsuccessful
3565 * </code>
3567 * @param string $url
3568 * @param array|null $params key-value pairs to be added to $url as query string
3569 * @param array $options request options. Must include either 'file' or 'filepath'
3570 * @return bool|string true on success or error string on failure
3572 public function download_one($url, $params, $options = array()) {
3573 $options['CURLOPT_HTTPGET'] = 1;
3574 if (!empty($params)) {
3575 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3576 $url .= http_build_query($params, '', '&');
3578 if (!empty($options['filepath']) && empty($options['file'])) {
3579 // open file
3580 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3581 $this->errno = 100;
3582 return get_string('cannotwritefile', 'error', $options['filepath']);
3584 $filepath = $options['filepath'];
3586 unset($options['filepath']);
3587 $result = $this->request($url, $options);
3588 if (isset($filepath)) {
3589 fclose($options['file']);
3590 if ($result !== true) {
3591 unlink($filepath);
3594 return $result;
3598 * HTTP PUT method
3600 * @param string $url
3601 * @param array $params
3602 * @param array $options
3603 * @return bool
3605 public function put($url, $params = array(), $options = array()) {
3606 $file = '';
3607 $fp = false;
3608 if (isset($params['file'])) {
3609 $file = $params['file'];
3610 if (is_file($file)) {
3611 $fp = fopen($file, 'r');
3612 $size = filesize($file);
3613 $options['CURLOPT_PUT'] = 1;
3614 $options['CURLOPT_INFILESIZE'] = $size;
3615 $options['CURLOPT_INFILE'] = $fp;
3616 } else {
3617 return null;
3619 if (!isset($this->options['CURLOPT_USERPWD'])) {
3620 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3622 } else {
3623 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3624 $options['CURLOPT_POSTFIELDS'] = $params;
3627 $ret = $this->request($url, $options);
3628 if ($fp !== false) {
3629 fclose($fp);
3631 return $ret;
3635 * HTTP DELETE method
3637 * @param string $url
3638 * @param array $param
3639 * @param array $options
3640 * @return bool
3642 public function delete($url, $param = array(), $options = array()) {
3643 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3644 if (!isset($options['CURLOPT_USERPWD'])) {
3645 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3647 $ret = $this->request($url, $options);
3648 return $ret;
3652 * HTTP TRACE method
3654 * @param string $url
3655 * @param array $options
3656 * @return bool
3658 public function trace($url, $options = array()) {
3659 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3660 $ret = $this->request($url, $options);
3661 return $ret;
3665 * HTTP OPTIONS method
3667 * @param string $url
3668 * @param array $options
3669 * @return bool
3671 public function options($url, $options = array()) {
3672 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3673 $ret = $this->request($url, $options);
3674 return $ret;
3678 * Get curl information
3680 * @return string
3682 public function get_info() {
3683 return $this->info;
3687 * Get curl error code
3689 * @return int
3691 public function get_errno() {
3692 return $this->errno;
3696 * When using a proxy, an additional HTTP response code may appear at
3697 * the start of the header. For example, when using https over a proxy
3698 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3699 * also possible and some may come with their own headers.
3701 * If using the return value containing all headers, this function can be
3702 * called to remove unwanted doubles.
3704 * Note that it is not possible to distinguish this situation from valid
3705 * data unless you know the actual response part (below the headers)
3706 * will not be included in this string, or else will not 'look like' HTTP
3707 * headers. As a result it is not safe to call this function for general
3708 * data.
3710 * @param string $input Input HTTP response
3711 * @return string HTTP response with additional headers stripped if any
3713 public static function strip_double_headers($input) {
3714 // I have tried to make this regular expression as specific as possible
3715 // to avoid any case where it does weird stuff if you happen to put
3716 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3717 // also make it faster because it can abandon regex processing as soon
3718 // as it hits something that doesn't look like an http header. The
3719 // header definition is taken from RFC 822, except I didn't support
3720 // folding which is never used in practice.
3721 $crlf = "\r\n";
3722 return preg_replace(
3723 // HTTP version and status code (ignore value of code).
3724 '~^HTTP/1\..*' . $crlf .
3725 // Header name: character between 33 and 126 decimal, except colon.
3726 // Colon. Header value: any character except \r and \n. CRLF.
3727 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3728 // Headers are terminated by another CRLF (blank line).
3729 $crlf .
3730 // Second HTTP status code, this time must be 200.
3731 '(HTTP/1.[01] 200 )~', '$1', $input);
3736 * This class is used by cURL class, use case:
3738 * <code>
3739 * $CFG->repositorycacheexpire = 120;
3740 * $CFG->curlcache = 120;
3742 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3743 * $ret = $c->get('http://www.google.com');
3744 * </code>
3746 * @package core_files
3747 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3748 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3750 class curl_cache {
3751 /** @var string Path to cache directory */
3752 public $dir = '';
3755 * Constructor
3757 * @global stdClass $CFG
3758 * @param string $module which module is using curl_cache
3760 public function __construct($module = 'repository') {
3761 global $CFG;
3762 if (!empty($module)) {
3763 $this->dir = $CFG->cachedir.'/'.$module.'/';
3764 } else {
3765 $this->dir = $CFG->cachedir.'/misc/';
3767 if (!file_exists($this->dir)) {
3768 mkdir($this->dir, $CFG->directorypermissions, true);
3770 if ($module == 'repository') {
3771 if (empty($CFG->repositorycacheexpire)) {
3772 $CFG->repositorycacheexpire = 120;
3774 $this->ttl = $CFG->repositorycacheexpire;
3775 } else {
3776 if (empty($CFG->curlcache)) {
3777 $CFG->curlcache = 120;
3779 $this->ttl = $CFG->curlcache;
3784 * Get cached value
3786 * @global stdClass $CFG
3787 * @global stdClass $USER
3788 * @param mixed $param
3789 * @return bool|string
3791 public function get($param) {
3792 global $CFG, $USER;
3793 $this->cleanup($this->ttl);
3794 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3795 if(file_exists($this->dir.$filename)) {
3796 $lasttime = filemtime($this->dir.$filename);
3797 if (time()-$lasttime > $this->ttl) {
3798 return false;
3799 } else {
3800 $fp = fopen($this->dir.$filename, 'r');
3801 $size = filesize($this->dir.$filename);
3802 $content = fread($fp, $size);
3803 return unserialize($content);
3806 return false;
3810 * Set cache value
3812 * @global object $CFG
3813 * @global object $USER
3814 * @param mixed $param
3815 * @param mixed $val
3817 public function set($param, $val) {
3818 global $CFG, $USER;
3819 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3820 $fp = fopen($this->dir.$filename, 'w');
3821 fwrite($fp, serialize($val));
3822 fclose($fp);
3823 @chmod($this->dir.$filename, $CFG->filepermissions);
3827 * Remove cache files
3829 * @param int $expire The number of seconds before expiry
3831 public function cleanup($expire) {
3832 if ($dir = opendir($this->dir)) {
3833 while (false !== ($file = readdir($dir))) {
3834 if(!is_dir($file) && $file != '.' && $file != '..') {
3835 $lasttime = @filemtime($this->dir.$file);
3836 if (time() - $lasttime > $expire) {
3837 @unlink($this->dir.$file);
3841 closedir($dir);
3845 * delete current user's cache file
3847 * @global object $CFG
3848 * @global object $USER
3850 public function refresh() {
3851 global $CFG, $USER;
3852 if ($dir = opendir($this->dir)) {
3853 while (false !== ($file = readdir($dir))) {
3854 if (!is_dir($file) && $file != '.' && $file != '..') {
3855 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3856 @unlink($this->dir.$file);
3865 * This function delegates file serving to individual plugins
3867 * @param string $relativepath
3868 * @param bool $forcedownload
3869 * @param null|string $preview the preview mode, defaults to serving the original file
3870 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
3871 * offline (e.g. mobile app).
3872 * @todo MDL-31088 file serving improments
3874 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false) {
3875 global $DB, $CFG, $USER;
3876 // relative path must start with '/'
3877 if (!$relativepath) {
3878 print_error('invalidargorconf');
3879 } else if ($relativepath[0] != '/') {
3880 print_error('pathdoesnotstartslash');
3883 // extract relative path components
3884 $args = explode('/', ltrim($relativepath, '/'));
3886 if (count($args) < 3) { // always at least context, component and filearea
3887 print_error('invalidarguments');
3890 $contextid = (int)array_shift($args);
3891 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3892 $filearea = clean_param(array_shift($args), PARAM_AREA);
3894 list($context, $course, $cm) = get_context_info_array($contextid);
3896 $fs = get_file_storage();
3898 $sendfileoptions = ['preview' => $preview, 'offline' => $offline];
3900 // ========================================================================================================================
3901 if ($component === 'blog') {
3902 // Blog file serving
3903 if ($context->contextlevel != CONTEXT_SYSTEM) {
3904 send_file_not_found();
3906 if ($filearea !== 'attachment' and $filearea !== 'post') {
3907 send_file_not_found();
3910 if (empty($CFG->enableblogs)) {
3911 print_error('siteblogdisable', 'blog');
3914 $entryid = (int)array_shift($args);
3915 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3916 send_file_not_found();
3918 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3919 require_login();
3920 if (isguestuser()) {
3921 print_error('noguest');
3923 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3924 if ($USER->id != $entry->userid) {
3925 send_file_not_found();
3930 if ($entry->publishstate === 'public') {
3931 if ($CFG->forcelogin) {
3932 require_login();
3935 } else if ($entry->publishstate === 'site') {
3936 require_login();
3937 //ok
3938 } else if ($entry->publishstate === 'draft') {
3939 require_login();
3940 if ($USER->id != $entry->userid) {
3941 send_file_not_found();
3945 $filename = array_pop($args);
3946 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3948 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3949 send_file_not_found();
3952 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
3954 // ========================================================================================================================
3955 } else if ($component === 'grade') {
3956 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3957 // Global gradebook files
3958 if ($CFG->forcelogin) {
3959 require_login();
3962 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3964 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3965 send_file_not_found();
3968 \core\session\manager::write_close(); // Unlock session during file serving.
3969 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
3971 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3972 //TODO: nobody implemented this yet in grade edit form!!
3973 send_file_not_found();
3975 if ($CFG->forcelogin || $course->id != SITEID) {
3976 require_login($course);
3979 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3981 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3982 send_file_not_found();
3985 \core\session\manager::write_close(); // Unlock session during file serving.
3986 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
3987 } else {
3988 send_file_not_found();
3991 // ========================================================================================================================
3992 } else if ($component === 'tag') {
3993 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3995 // All tag descriptions are going to be public but we still need to respect forcelogin
3996 if ($CFG->forcelogin) {
3997 require_login();
4000 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4002 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4003 send_file_not_found();
4006 \core\session\manager::write_close(); // Unlock session during file serving.
4007 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4009 } else {
4010 send_file_not_found();
4012 // ========================================================================================================================
4013 } else if ($component === 'badges') {
4014 require_once($CFG->libdir . '/badgeslib.php');
4016 $badgeid = (int)array_shift($args);
4017 $badge = new badge($badgeid);
4018 $filename = array_pop($args);
4020 if ($filearea === 'badgeimage') {
4021 if ($filename !== 'f1' && $filename !== 'f2') {
4022 send_file_not_found();
4024 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4025 send_file_not_found();
4028 \core\session\manager::write_close();
4029 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4030 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4031 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4032 send_file_not_found();
4035 \core\session\manager::write_close();
4036 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4038 // ========================================================================================================================
4039 } else if ($component === 'calendar') {
4040 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4042 // All events here are public the one requirement is that we respect forcelogin
4043 if ($CFG->forcelogin) {
4044 require_login();
4047 // Get the event if from the args array
4048 $eventid = array_shift($args);
4050 // Load the event from the database
4051 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4052 send_file_not_found();
4055 // Get the file and serve if successful
4056 $filename = array_pop($args);
4057 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4058 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4059 send_file_not_found();
4062 \core\session\manager::write_close(); // Unlock session during file serving.
4063 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4065 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4067 // Must be logged in, if they are not then they obviously can't be this user
4068 require_login();
4070 // Don't want guests here, potentially saves a DB call
4071 if (isguestuser()) {
4072 send_file_not_found();
4075 // Get the event if from the args array
4076 $eventid = array_shift($args);
4078 // Load the event from the database - user id must match
4079 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4080 send_file_not_found();
4083 // Get the file and serve if successful
4084 $filename = array_pop($args);
4085 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4086 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4087 send_file_not_found();
4090 \core\session\manager::write_close(); // Unlock session during file serving.
4091 send_stored_file($file, 0, 0, true, $sendfileoptions);
4093 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4095 // Respect forcelogin and require login unless this is the site.... it probably
4096 // should NEVER be the site
4097 if ($CFG->forcelogin || $course->id != SITEID) {
4098 require_login($course);
4101 // Must be able to at least view the course. This does not apply to the front page.
4102 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4103 //TODO: hmm, do we really want to block guests here?
4104 send_file_not_found();
4107 // Get the event id
4108 $eventid = array_shift($args);
4110 // Load the event from the database we need to check whether it is
4111 // a) valid course event
4112 // b) a group event
4113 // Group events use the course context (there is no group context)
4114 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4115 send_file_not_found();
4118 // If its a group event require either membership of view all groups capability
4119 if ($event->eventtype === 'group') {
4120 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4121 send_file_not_found();
4123 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4124 // Ok. Please note that the event type 'site' still uses a course context.
4125 } else {
4126 // Some other type.
4127 send_file_not_found();
4130 // If we get this far we can serve the file
4131 $filename = array_pop($args);
4132 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4133 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4134 send_file_not_found();
4137 \core\session\manager::write_close(); // Unlock session during file serving.
4138 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4140 } else {
4141 send_file_not_found();
4144 // ========================================================================================================================
4145 } else if ($component === 'user') {
4146 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4147 if (count($args) == 1) {
4148 $themename = theme_config::DEFAULT_THEME;
4149 $filename = array_shift($args);
4150 } else {
4151 $themename = array_shift($args);
4152 $filename = array_shift($args);
4155 // fix file name automatically
4156 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4157 $filename = 'f1';
4160 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4161 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4162 // protect images if login required and not logged in;
4163 // also if login is required for profile images and is not logged in or guest
4164 // do not use require_login() because it is expensive and not suitable here anyway
4165 $theme = theme_config::load($themename);
4166 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4169 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4170 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4171 if ($filename === 'f3') {
4172 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4173 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4174 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4179 if (!$file) {
4180 // bad reference - try to prevent future retries as hard as possible!
4181 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4182 if ($user->picture > 0) {
4183 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4186 // no redirect here because it is not cached
4187 $theme = theme_config::load($themename);
4188 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4189 send_file($imagefile, basename($imagefile), 60*60*24*14);
4192 $options = $sendfileoptions;
4193 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4194 // Profile images should be cache-able by both browsers and proxies according
4195 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4196 $options['cacheability'] = 'public';
4198 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4200 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4201 require_login();
4203 if (isguestuser()) {
4204 send_file_not_found();
4207 if ($USER->id !== $context->instanceid) {
4208 send_file_not_found();
4211 $filename = array_pop($args);
4212 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4213 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4214 send_file_not_found();
4217 \core\session\manager::write_close(); // Unlock session during file serving.
4218 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4220 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4222 if ($CFG->forcelogin) {
4223 require_login();
4226 $userid = $context->instanceid;
4228 if ($USER->id == $userid) {
4229 // always can access own
4231 } else if (!empty($CFG->forceloginforprofiles)) {
4232 require_login();
4234 if (isguestuser()) {
4235 send_file_not_found();
4238 // we allow access to site profile of all course contacts (usually teachers)
4239 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4240 send_file_not_found();
4243 $canview = false;
4244 if (has_capability('moodle/user:viewdetails', $context)) {
4245 $canview = true;
4246 } else {
4247 $courses = enrol_get_my_courses();
4250 while (!$canview && count($courses) > 0) {
4251 $course = array_shift($courses);
4252 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4253 $canview = true;
4258 $filename = array_pop($args);
4259 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4260 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4261 send_file_not_found();
4264 \core\session\manager::write_close(); // Unlock session during file serving.
4265 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4267 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4268 $userid = (int)array_shift($args);
4269 $usercontext = context_user::instance($userid);
4271 if ($CFG->forcelogin) {
4272 require_login();
4275 if (!empty($CFG->forceloginforprofiles)) {
4276 require_login();
4277 if (isguestuser()) {
4278 print_error('noguest');
4281 //TODO: review this logic of user profile access prevention
4282 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4283 print_error('usernotavailable');
4285 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4286 print_error('cannotviewprofile');
4288 if (!is_enrolled($context, $userid)) {
4289 print_error('notenrolledprofile');
4291 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4292 print_error('groupnotamember');
4296 $filename = array_pop($args);
4297 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4298 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4299 send_file_not_found();
4302 \core\session\manager::write_close(); // Unlock session during file serving.
4303 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4305 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4306 require_login();
4308 if (isguestuser()) {
4309 send_file_not_found();
4311 $userid = $context->instanceid;
4313 if ($USER->id != $userid) {
4314 send_file_not_found();
4317 $filename = array_pop($args);
4318 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4319 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4320 send_file_not_found();
4323 \core\session\manager::write_close(); // Unlock session during file serving.
4324 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4326 } else {
4327 send_file_not_found();
4330 // ========================================================================================================================
4331 } else if ($component === 'coursecat') {
4332 if ($context->contextlevel != CONTEXT_COURSECAT) {
4333 send_file_not_found();
4336 if ($filearea === 'description') {
4337 if ($CFG->forcelogin) {
4338 // no login necessary - unless login forced everywhere
4339 require_login();
4342 // Check if user can view this category.
4343 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4344 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid));
4345 if (!$coursecatvisible) {
4346 send_file_not_found();
4350 $filename = array_pop($args);
4351 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4352 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4353 send_file_not_found();
4356 \core\session\manager::write_close(); // Unlock session during file serving.
4357 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4358 } else {
4359 send_file_not_found();
4362 // ========================================================================================================================
4363 } else if ($component === 'course') {
4364 if ($context->contextlevel != CONTEXT_COURSE) {
4365 send_file_not_found();
4368 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4369 if ($CFG->forcelogin) {
4370 require_login();
4373 $filename = array_pop($args);
4374 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4375 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4376 send_file_not_found();
4379 \core\session\manager::write_close(); // Unlock session during file serving.
4380 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4382 } else if ($filearea === 'section') {
4383 if ($CFG->forcelogin) {
4384 require_login($course);
4385 } else if ($course->id != SITEID) {
4386 require_login($course);
4389 $sectionid = (int)array_shift($args);
4391 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4392 send_file_not_found();
4395 $filename = array_pop($args);
4396 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4397 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4398 send_file_not_found();
4401 \core\session\manager::write_close(); // Unlock session during file serving.
4402 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4404 } else {
4405 send_file_not_found();
4408 } else if ($component === 'cohort') {
4410 $cohortid = (int)array_shift($args);
4411 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4412 $cohortcontext = context::instance_by_id($cohort->contextid);
4414 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4415 if ($context->id != $cohort->contextid &&
4416 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4417 send_file_not_found();
4420 // User is able to access cohort if they have view cap on cohort level or
4421 // the cohort is visible and they have view cap on course level.
4422 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4423 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4425 if ($filearea === 'description' && $canview) {
4426 $filename = array_pop($args);
4427 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4428 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4429 && !$file->is_directory()) {
4430 \core\session\manager::write_close(); // Unlock session during file serving.
4431 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4435 send_file_not_found();
4437 } else if ($component === 'group') {
4438 if ($context->contextlevel != CONTEXT_COURSE) {
4439 send_file_not_found();
4442 require_course_login($course, true, null, false);
4444 $groupid = (int)array_shift($args);
4446 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4447 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4448 // do not allow access to separate group info if not member or teacher
4449 send_file_not_found();
4452 if ($filearea === 'description') {
4454 require_login($course);
4456 $filename = array_pop($args);
4457 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4458 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4459 send_file_not_found();
4462 \core\session\manager::write_close(); // Unlock session during file serving.
4463 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4465 } else if ($filearea === 'icon') {
4466 $filename = array_pop($args);
4468 if ($filename !== 'f1' and $filename !== 'f2') {
4469 send_file_not_found();
4471 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4472 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4473 send_file_not_found();
4477 \core\session\manager::write_close(); // Unlock session during file serving.
4478 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4480 } else {
4481 send_file_not_found();
4484 } else if ($component === 'grouping') {
4485 if ($context->contextlevel != CONTEXT_COURSE) {
4486 send_file_not_found();
4489 require_login($course);
4491 $groupingid = (int)array_shift($args);
4493 // note: everybody has access to grouping desc images for now
4494 if ($filearea === 'description') {
4496 $filename = array_pop($args);
4497 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4498 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4499 send_file_not_found();
4502 \core\session\manager::write_close(); // Unlock session during file serving.
4503 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4505 } else {
4506 send_file_not_found();
4509 // ========================================================================================================================
4510 } else if ($component === 'backup') {
4511 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4512 require_login($course);
4513 require_capability('moodle/backup:downloadfile', $context);
4515 $filename = array_pop($args);
4516 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4517 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4518 send_file_not_found();
4521 \core\session\manager::write_close(); // Unlock session during file serving.
4522 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4524 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4525 require_login($course);
4526 require_capability('moodle/backup:downloadfile', $context);
4528 $sectionid = (int)array_shift($args);
4530 $filename = array_pop($args);
4531 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4532 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4533 send_file_not_found();
4536 \core\session\manager::write_close();
4537 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4539 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4540 require_login($course, false, $cm);
4541 require_capability('moodle/backup:downloadfile', $context);
4543 $filename = array_pop($args);
4544 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4545 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4546 send_file_not_found();
4549 \core\session\manager::write_close();
4550 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4552 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4553 // Backup files that were generated by the automated backup systems.
4555 require_login($course);
4556 require_capability('moodle/site:config', $context);
4558 $filename = array_pop($args);
4559 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4560 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4561 send_file_not_found();
4564 \core\session\manager::write_close(); // Unlock session during file serving.
4565 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4567 } else {
4568 send_file_not_found();
4571 // ========================================================================================================================
4572 } else if ($component === 'question') {
4573 require_once($CFG->libdir . '/questionlib.php');
4574 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4575 send_file_not_found();
4577 // ========================================================================================================================
4578 } else if ($component === 'grading') {
4579 if ($filearea === 'description') {
4580 // files embedded into the form definition description
4582 if ($context->contextlevel == CONTEXT_SYSTEM) {
4583 require_login();
4585 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4586 require_login($course, false, $cm);
4588 } else {
4589 send_file_not_found();
4592 $formid = (int)array_shift($args);
4594 $sql = "SELECT ga.id
4595 FROM {grading_areas} ga
4596 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4597 WHERE gd.id = ? AND ga.contextid = ?";
4598 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4600 if (!$areaid) {
4601 send_file_not_found();
4604 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4606 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4607 send_file_not_found();
4610 \core\session\manager::write_close(); // Unlock session during file serving.
4611 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4614 // ========================================================================================================================
4615 } else if (strpos($component, 'mod_') === 0) {
4616 $modname = substr($component, 4);
4617 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4618 send_file_not_found();
4620 require_once("$CFG->dirroot/mod/$modname/lib.php");
4622 if ($context->contextlevel == CONTEXT_MODULE) {
4623 if ($cm->modname !== $modname) {
4624 // somebody tries to gain illegal access, cm type must match the component!
4625 send_file_not_found();
4629 if ($filearea === 'intro') {
4630 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4631 send_file_not_found();
4633 require_course_login($course, true, $cm);
4635 // all users may access it
4636 $filename = array_pop($args);
4637 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4638 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4639 send_file_not_found();
4642 // finally send the file
4643 send_stored_file($file, null, 0, false, $sendfileoptions);
4646 $filefunction = $component.'_pluginfile';
4647 $filefunctionold = $modname.'_pluginfile';
4648 if (function_exists($filefunction)) {
4649 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4650 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4651 } else if (function_exists($filefunctionold)) {
4652 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4653 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4656 send_file_not_found();
4658 // ========================================================================================================================
4659 } else if (strpos($component, 'block_') === 0) {
4660 $blockname = substr($component, 6);
4661 // note: no more class methods in blocks please, that is ....
4662 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4663 send_file_not_found();
4665 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4667 if ($context->contextlevel == CONTEXT_BLOCK) {
4668 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4669 if ($birecord->blockname !== $blockname) {
4670 // somebody tries to gain illegal access, cm type must match the component!
4671 send_file_not_found();
4674 if ($context->get_course_context(false)) {
4675 // If block is in course context, then check if user has capability to access course.
4676 require_course_login($course);
4677 } else if ($CFG->forcelogin) {
4678 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4679 require_login();
4682 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4683 // User can't access file, if block is hidden or doesn't have block:view capability
4684 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4685 send_file_not_found();
4687 } else {
4688 $birecord = null;
4691 $filefunction = $component.'_pluginfile';
4692 if (function_exists($filefunction)) {
4693 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4694 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4697 send_file_not_found();
4699 // ========================================================================================================================
4700 } else if (strpos($component, '_') === false) {
4701 // all core subsystems have to be specified above, no more guessing here!
4702 send_file_not_found();
4704 } else {
4705 // try to serve general plugin file in arbitrary context
4706 $dir = core_component::get_component_directory($component);
4707 if (!file_exists("$dir/lib.php")) {
4708 send_file_not_found();
4710 include_once("$dir/lib.php");
4712 $filefunction = $component.'_pluginfile';
4713 if (function_exists($filefunction)) {
4714 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4715 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4718 send_file_not_found();