2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Functions for file handling.
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();
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
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");
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) {
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;
66 $return .= '?forcedownload=1';
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
72 $return .= '&forcedownload=1';
77 $return = str_replace('http://', 'https://', $return);
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
94 function file_area_contains_subdirs(context
$context, $component, $filearea, $itemid) {
97 if (!isset($itemid)) {
98 // Not initialised yet.
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
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.
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)) {
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'});
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);
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);
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
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.
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);
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'];
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'];
260 * Saves text and files modified by Editor formslib element
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)) {
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;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
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'})) {
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)
335 * Generate a draft itemid
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
343 function file_get_unused_draft_itemid() {
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);
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');
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
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
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);
438 if (is_null($text)) {
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.
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) {
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);
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 = '/') {
508 $usercontext = context_user
::instance($USER->id
);
509 $fs = get_file_storage();
515 'filesize_without_references' => 0
518 if ($filepath != '/') {
519 $draftfiles = $fs->get_directory_files($usercontext->id
, 'user', 'draft', $draftitemid, $filepath, true, true);
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;
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;
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.
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) {
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() {
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
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
590 * @return string path
592 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
593 if ($str == '/' or empty($str)) {
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
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;
634 * Listing all files (including folders) in current path (draft area)
635 * used by file manager
636 * @param int $draftitemid
637 * @param string $filepath
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
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);
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()) {
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);
699 // do NOT use file browser here!
700 $item->mimetype
= get_mimetype_description($file);
701 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
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);
711 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
712 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
713 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
714 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
715 // used by the widget to display a warning about the problem files.
716 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
717 $item->status
= $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ?
0 : 1;
718 if ($item->status
== 0) {
719 if ($imageinfo = $file->get_imageinfo()) {
720 $item->realthumbnail
= $itemurl->out(false, array('preview' => 'thumb',
721 'oid' => $file->get_timemodified()));
722 $item->realicon
= $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
723 $item->image_width
= $imageinfo['width'];
724 $item->image_height
= $imageinfo['height'];
731 $data->itemid
= $draftitemid;
737 * Returns draft area itemid for a given element.
740 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
741 * @return int the itemid, or 0 if there is not one yet.
743 function file_get_submitted_draft_itemid($elname) {
744 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
745 if (!isset($_REQUEST[$elname])) {
748 if (is_array($_REQUEST[$elname])) {
749 $param = optional_param_array($elname, 0, PARAM_INT
);
750 if (!empty($param['itemid'])) {
751 $param = $param['itemid'];
753 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER
);
758 $param = optional_param($elname, 0, PARAM_INT
);
769 * Restore the original source field from draft files
771 * Do not use this function because it makes field files.source inconsistent
772 * for draft area files. This function will be deprecated in 2.6
774 * @param stored_file $storedfile This only works with draft files
775 * @return stored_file
777 function file_restore_source_field_from_draft_file($storedfile) {
778 $source = @unserialize
($storedfile->get_source());
779 if (!empty($source)) {
780 if (is_object($source)) {
781 $restoredsource = $source->source
;
782 $storedfile->set_source($restoredsource);
784 throw new moodle_exception('invalidsourcefield', 'error');
790 * Saves files from a draft file area to a real one (merging the list of files).
791 * Can rewrite URLs in some content at the same time if desired.
794 * @global stdClass $USER
795 * @param int $draftitemid the id of the draft area to use. Normally obtained
796 * from file_get_submitted_draft_itemid('elementname') or similar.
797 * @param int $contextid This parameter and the next two identify the file area to save to.
798 * @param string $component
799 * @param string $filearea indentifies the file area.
800 * @param int $itemid helps identifies the file area.
801 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
802 * @param string $text some html content that needs to have embedded links rewritten
803 * to the @@PLUGINFILE@@ form for saving in the database.
804 * @param bool $forcehttps force https urls.
805 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
807 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
810 $usercontext = context_user
::instance($USER->id
);
811 $fs = get_file_storage();
813 $options = (array)$options;
814 if (!isset($options['subdirs'])) {
815 $options['subdirs'] = false;
817 if (!isset($options['maxfiles'])) {
818 $options['maxfiles'] = -1; // unlimited
820 if (!isset($options['maxbytes']) ||
$options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
821 $options['maxbytes'] = 0; // unlimited
823 if (!isset($options['areamaxbytes'])) {
824 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED
; // Unlimited.
826 $allowreferences = true;
827 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK
))) {
828 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
829 // this is not exactly right. BUT there are many places in code where filemanager options
830 // are not passed to file_save_draft_area_files()
831 $allowreferences = false;
834 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
835 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
836 // anything at all in the next area.
837 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
841 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id');
842 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
844 // One file in filearea means it is empty (it has only top-level directory '.').
845 if (count($draftfiles) > 1 ||
count($oldfiles) > 1) {
846 // we have to merge old and new files - we want to keep file ids for files that were not changed
847 // we change time modified for all new and changed files, we keep time created as is
849 $newhashes = array();
851 $context = context
::instance_by_id($contextid, MUST_EXIST
);
852 foreach ($draftfiles as $file) {
853 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
856 if (!$allowreferences && $file->is_external_file()) {
859 if (!$file->is_directory()) {
860 // Check to see if this file was uploaded by someone who can ignore the file size limits.
861 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
862 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
863 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
867 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
868 // more files - should not get here at all
873 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
874 $newhashes[$newhash] = $file;
877 // Loop through oldfiles and decide which we need to delete and which to update.
878 // After this cycle the array $newhashes will only contain the files that need to be added.
879 foreach ($oldfiles as $oldfile) {
880 $oldhash = $oldfile->get_pathnamehash();
881 if (!isset($newhashes[$oldhash])) {
882 // delete files not needed any more - deleted by user
887 $newfile = $newhashes[$oldhash];
888 // Now we know that we have $oldfile and $newfile for the same path.
889 // Let's check if we can update this file or we need to delete and create.
890 if ($newfile->is_directory()) {
891 // Directories are always ok to just update.
892 } else if (($source = @unserialize
($newfile->get_source())) && isset($source->original
)) {
893 // File has the 'original' - we need to update the file (it may even have not been changed at all).
894 $original = file_storage
::unpack_reference($source->original
);
895 if ($original['filename'] !== $oldfile->get_filename() ||
$original['filepath'] !== $oldfile->get_filepath()) {
896 // Very odd, original points to another file. Delete and create file.
901 // The same file name but absence of 'original' means that file was deteled and uploaded again.
902 // By deleting and creating new file we properly manage all existing references.
907 // status changed, we delete old file, and create a new one
908 if ($oldfile->get_status() != $newfile->get_status()) {
909 // file was changed, use updated with new timemodified data
911 // This file will be added later
916 if ($oldfile->get_author() != $newfile->get_author()) {
917 $oldfile->set_author($newfile->get_author());
920 if ($oldfile->get_license() != $newfile->get_license()) {
921 $oldfile->set_license($newfile->get_license());
924 // Updated file source
925 // Field files.source for draftarea files contains serialised object with source and original information.
926 // We only store the source part of it for non-draft file area.
927 $newsource = $newfile->get_source();
928 if ($source = @unserialize
($newfile->get_source())) {
929 $newsource = $source->source
;
931 if ($oldfile->get_source() !== $newsource) {
932 $oldfile->set_source($newsource);
935 // Updated sort order
936 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
937 $oldfile->set_sortorder($newfile->get_sortorder());
940 // Update file timemodified
941 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
942 $oldfile->set_timemodified($newfile->get_timemodified());
945 // Replaced file content
946 if (!$oldfile->is_directory() &&
947 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
948 $oldfile->get_filesize() != $newfile->get_filesize() ||
949 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
950 $oldfile->get_userid() != $newfile->get_userid())) {
951 $oldfile->replace_file_with($newfile);
954 // unchanged file or directory - we keep it as is
955 unset($newhashes[$oldhash]);
958 // Add fresh file or the file which has changed status
959 // the size and subdirectory tests are extra safety only, the UI should prevent it
960 foreach ($newhashes as $file) {
961 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
962 if ($source = @unserialize
($file->get_source())) {
963 // Field files.source for draftarea files contains serialised object with source and original information.
964 // We only store the source part of it for non-draft file area.
965 $file_record['source'] = $source->source
;
968 if ($file->is_external_file()) {
969 $repoid = $file->get_repository_id();
970 if (!empty($repoid)) {
971 $context = context
::instance_by_id($contextid, MUST_EXIST
);
972 $repo = repository
::get_repository_by_id($repoid, $context);
973 if (!empty($options)) {
974 $repo->options
= $options;
976 $file_record['repositoryid'] = $repoid;
977 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
978 // to the file store. E.g. transfer ownership of the file to a system account etc.
979 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
981 $file_record['reference'] = $reference;
985 $fs->create_file_from_storedfile($file_record, $file);
989 // note: do not purge the draft area - we clean up areas later in cron,
990 // the reason is that user might press submit twice and they would loose the files,
991 // also sometimes we might want to use hacks that save files into two different areas
993 if (is_null($text)) {
996 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1001 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1002 * ready to be saved in the database. Normally, this is done automatically by
1003 * {@link file_save_draft_area_files()}.
1006 * @param string $text the content to process.
1007 * @param int $draftitemid the draft file area the content was using.
1008 * @param bool $forcehttps whether the content contains https URLs. Default false.
1009 * @return string the processed content.
1011 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1014 $usercontext = context_user
::instance($USER->id
);
1016 $wwwroot = $CFG->wwwroot
;
1018 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1021 // relink embedded files if text submitted - no absolute links allowed in database!
1022 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1024 if (strpos($text, 'draftfile.php?file=') !== false) {
1026 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1028 foreach ($matches[0] as $match) {
1029 $replace = str_ireplace('%2F', '/', $match);
1030 $text = str_replace($match, $replace, $text);
1033 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1040 * Set file sort order
1042 * @global moodle_database $DB
1043 * @param int $contextid the context id
1044 * @param string $component file component
1045 * @param string $filearea file area.
1046 * @param int $itemid itemid.
1047 * @param string $filepath file path.
1048 * @param string $filename file name.
1049 * @param int $sortorder the sort order of file.
1052 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1054 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1055 if ($file_record = $DB->get_record('files', $conditions)) {
1056 $sortorder = (int)$sortorder;
1057 $file_record->sortorder
= $sortorder;
1058 $DB->update_record('files', $file_record);
1065 * reset file sort order number to 0
1066 * @global moodle_database $DB
1067 * @param int $contextid the context id
1068 * @param string $component
1069 * @param string $filearea file area.
1070 * @param int|bool $itemid itemid.
1073 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1076 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1077 if ($itemid !== false) {
1078 $conditions['itemid'] = $itemid;
1081 $file_records = $DB->get_records('files', $conditions);
1082 foreach ($file_records as $file_record) {
1083 $file_record->sortorder
= 0;
1084 $DB->update_record('files', $file_record);
1090 * Returns description of upload error
1092 * @param int $errorcode found in $_FILES['filename.ext']['error']
1093 * @return string error description string, '' if ok
1095 function file_get_upload_error($errorcode) {
1097 switch ($errorcode) {
1098 case 0: // UPLOAD_ERR_OK - no error
1102 case 1: // UPLOAD_ERR_INI_SIZE
1103 $errmessage = get_string('uploadserverlimit');
1106 case 2: // UPLOAD_ERR_FORM_SIZE
1107 $errmessage = get_string('uploadformlimit');
1110 case 3: // UPLOAD_ERR_PARTIAL
1111 $errmessage = get_string('uploadpartialfile');
1114 case 4: // UPLOAD_ERR_NO_FILE
1115 $errmessage = get_string('uploadnofilefound');
1118 // Note: there is no error with a value of 5
1120 case 6: // UPLOAD_ERR_NO_TMP_DIR
1121 $errmessage = get_string('uploadnotempdir');
1124 case 7: // UPLOAD_ERR_CANT_WRITE
1125 $errmessage = get_string('uploadcantwrite');
1128 case 8: // UPLOAD_ERR_EXTENSION
1129 $errmessage = get_string('uploadextension');
1133 $errmessage = get_string('uploadproblem');
1140 * Recursive function formating an array in POST parameter
1141 * @param array $arraydata - the array that we are going to format and add into &$data array
1142 * @param string $currentdata - a row of the final postdata array at instant T
1143 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1144 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1146 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1147 foreach ($arraydata as $k=>$v) {
1148 $newcurrentdata = $currentdata;
1149 if (is_array($v)) { //the value is an array, call the function recursively
1150 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1151 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1152 } else { //add the POST parameter to the $data array
1153 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1159 * Transform a PHP array into POST parameter
1160 * (see the recursive function format_array_postdata_for_curlcall)
1161 * @param array $postdata
1162 * @return array containing all POST parameters (1 row = 1 POST parameter)
1164 function format_postdata_for_curlcall($postdata) {
1166 foreach ($postdata as $k=>$v) {
1168 $currentdata = urlencode($k);
1169 format_array_postdata_for_curlcall($v, $currentdata, $data);
1171 $data[] = urlencode($k).'='.urlencode($v);
1174 $convertedpostdata = implode('&', $data);
1175 return $convertedpostdata;
1179 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1180 * Due to security concerns only downloads from http(s) sources are supported.
1183 * @param string $url file url starting with http(s)://
1184 * @param array $headers http headers, null if none. If set, should be an
1185 * associative array of header name => value pairs.
1186 * @param array $postdata array means use POST request with given parameters
1187 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1188 * (if false, just returns content)
1189 * @param int $timeout timeout for complete download process including all file transfer
1190 * (default 5 minutes)
1191 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1192 * usually happens if the remote server is completely down (default 20 seconds);
1193 * may not work when using proxy
1194 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1195 * Only use this when already in a trusted location.
1196 * @param string $tofile store the downloaded content to file instead of returning it.
1197 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1198 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1199 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1200 * if file downloaded into $tofile successfully or the file content as a string.
1202 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1205 // Only http and https links supported.
1206 if (!preg_match('|^https?://|i', $url)) {
1207 if ($fullresponse) {
1208 $response = new stdClass();
1209 $response->status
= 0;
1210 $response->headers
= array();
1211 $response->response_code
= 'Invalid protocol specified in url';
1212 $response->results
= '';
1213 $response->error
= 'Invalid protocol specified in url';
1222 $headers2 = array();
1223 if (is_array($headers)) {
1224 foreach ($headers as $key => $value) {
1225 if (is_numeric($key)) {
1226 $headers2[] = $value;
1228 $headers2[] = "$key: $value";
1233 if ($skipcertverify) {
1234 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1236 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1239 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1241 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1242 $options['CURLOPT_MAXREDIRS'] = 5;
1244 // Use POST if requested.
1245 if (is_array($postdata)) {
1246 $postdata = format_postdata_for_curlcall($postdata);
1247 } else if (empty($postdata)) {
1251 // Optionally attempt to get more correct timeout by fetching the file size.
1252 if (!isset($CFG->curltimeoutkbitrate
)) {
1253 // Use very slow rate of 56kbps as a timeout speed when not set.
1256 $bitrate = $CFG->curltimeoutkbitrate
;
1258 if ($calctimeout and !isset($postdata)) {
1260 $curl->setHeader($headers2);
1262 $curl->head($url, $postdata, $options);
1264 $info = $curl->get_info();
1265 $error_no = $curl->get_errno();
1266 if (!$error_no && $info['download_content_length'] > 0) {
1267 // No curl errors - adjust for large files only - take max timeout.
1268 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1273 $curl->setHeader($headers2);
1275 $options['CURLOPT_RETURNTRANSFER'] = true;
1276 $options['CURLOPT_NOBODY'] = false;
1277 $options['CURLOPT_TIMEOUT'] = $timeout;
1280 $fh = fopen($tofile, 'w');
1282 if ($fullresponse) {
1283 $response = new stdClass();
1284 $response->status
= 0;
1285 $response->headers
= array();
1286 $response->response_code
= 'Can not write to file';
1287 $response->results
= false;
1288 $response->error
= 'Can not write to file';
1294 $options['CURLOPT_FILE'] = $fh;
1297 if (isset($postdata)) {
1298 $content = $curl->post($url, $postdata, $options);
1300 $content = $curl->get($url, null, $options);
1305 @chmod
($tofile, $CFG->filepermissions
);
1309 // Try to detect encoding problems.
1310 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1311 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1312 $result = curl_exec($ch);
1316 $info = $curl->get_info();
1317 $error_no = $curl->get_errno();
1318 $rawheaders = $curl->get_raw_response();
1322 if (!$fullresponse) {
1323 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
1327 $response = new stdClass();
1328 if ($error_no == 28) {
1329 $response->status
= '-100'; // Mimic snoopy.
1331 $response->status
= '0';
1333 $response->headers
= array();
1334 $response->response_code
= $error;
1335 $response->results
= false;
1336 $response->error
= $error;
1344 if (empty($info['http_code'])) {
1345 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1346 $response = new stdClass();
1347 $response->status
= '0';
1348 $response->headers
= array();
1349 $response->response_code
= 'Unknown cURL error';
1350 $response->results
= false; // do NOT change this, we really want to ignore the result!
1351 $response->error
= 'Unknown cURL error';
1354 $response = new stdClass();
1355 $response->status
= (string)$info['http_code'];
1356 $response->headers
= $rawheaders;
1357 $response->results
= $content;
1358 $response->error
= '';
1360 // There might be multiple headers on redirect, find the status of the last one.
1362 foreach ($rawheaders as $line) {
1364 $response->response_code
= $line;
1367 if (trim($line, "\r\n") === '') {
1373 if ($fullresponse) {
1377 if ($info['http_code'] != 200) {
1378 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
1381 return $response->results
;
1385 * Returns a list of information about file types based on extensions.
1387 * The following elements expected in value array for each extension:
1389 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1390 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1391 * also files with bigger sizes under names
1392 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1393 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1394 * commonly used in moodle the following groups:
1395 * - web_image - image that can be included as <img> in HTML
1396 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1397 * - video - file that can be imported as video in text editor
1398 * - audio - file that can be imported as audio in text editor
1399 * - archive - we can extract files from this archive
1400 * - spreadsheet - used for portfolio format
1401 * - document - used for portfolio format
1402 * - presentation - used for portfolio format
1403 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1404 * human-readable description for this filetype;
1405 * Function {@link get_mimetype_description()} first looks at the presence of string for
1406 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1407 * attribute, if not found returns the value of 'type';
1408 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1409 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1410 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1413 * @return array List of information about file types based on extensions.
1414 * Associative array of extension (lower-case) to associative array
1415 * from 'element name' to data. Current element names are 'type' and 'icon'.
1416 * Unknown types should use the 'xxx' entry which includes defaults.
1418 function &get_mimetypes_array() {
1419 // Get types from the core_filetypes function, which includes caching.
1420 return core_filetypes
::get_types();
1424 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1426 * This function retrieves a file's MIME type for a file that will be sent to the user.
1427 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1428 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1429 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1431 * @param string $filename The file's filename.
1432 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1434 function get_mimetype_for_sending($filename = '') {
1435 // Guess the file's MIME type using mimeinfo.
1436 $mimetype = mimeinfo('type', $filename);
1438 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1439 if (!$mimetype ||
$mimetype === 'document/unknown') {
1440 $mimetype = 'application/octet-stream';
1447 * Obtains information about a filetype based on its extension. Will
1448 * use a default if no information is present about that particular
1452 * @param string $element Desired information (usually 'icon'
1453 * for icon filename or 'type' for MIME type. Can also be
1454 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1455 * @param string $filename Filename we're looking up
1456 * @return string Requested piece of information from array
1458 function mimeinfo($element, $filename) {
1460 $mimeinfo = & get_mimetypes_array();
1461 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1463 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1464 if (empty($filetype)) {
1465 $filetype = 'xxx'; // file without extension
1467 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1468 $iconsize = max(array(16, (int)$iconsizematch[1]));
1469 $filenames = array($mimeinfo['xxx']['icon']);
1470 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1471 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1473 // find the file with the closest size, first search for specific icon then for default icon
1474 foreach ($filenames as $filename) {
1475 foreach ($iconpostfixes as $size => $postfix) {
1476 $fullname = $CFG->dirroot
.'/pix/f/'.$filename.$postfix;
1477 if ($iconsize >= $size &&
1478 (file_exists($fullname.'.svg') ||
file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1479 return $filename.$postfix;
1483 } else if (isset($mimeinfo[$filetype][$element])) {
1484 return $mimeinfo[$filetype][$element];
1485 } else if (isset($mimeinfo['xxx'][$element])) {
1486 return $mimeinfo['xxx'][$element]; // By default
1493 * Obtains information about a filetype based on the MIME type rather than
1494 * the other way around.
1497 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1498 * @param string $mimetype MIME type we're looking up
1499 * @return string Requested piece of information from array
1501 function mimeinfo_from_type($element, $mimetype) {
1502 /* array of cached mimetype->extension associations */
1503 static $cached = array();
1504 $mimeinfo = & get_mimetypes_array();
1506 if (!array_key_exists($mimetype, $cached)) {
1507 $cached[$mimetype] = null;
1508 foreach($mimeinfo as $filetype => $values) {
1509 if ($values['type'] == $mimetype) {
1510 if ($cached[$mimetype] === null) {
1511 $cached[$mimetype] = '.'.$filetype;
1513 if (!empty($values['defaulticon'])) {
1514 $cached[$mimetype] = '.'.$filetype;
1519 if (empty($cached[$mimetype])) {
1520 $cached[$mimetype] = '.xxx';
1523 if ($element === 'extension') {
1524 return $cached[$mimetype];
1526 return mimeinfo($element, $cached[$mimetype]);
1531 * Return the relative icon path for a given file
1535 * // $file - instance of stored_file or file_info
1536 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1537 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1541 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1544 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1545 * and $file->mimetype are expected)
1546 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1549 function file_file_icon($file, $size = null) {
1550 if (!is_object($file)) {
1551 $file = (object)$file;
1553 if (isset($file->filename
)) {
1554 $filename = $file->filename
;
1555 } else if (method_exists($file, 'get_filename')) {
1556 $filename = $file->get_filename();
1557 } else if (method_exists($file, 'get_visible_name')) {
1558 $filename = $file->get_visible_name();
1562 if (isset($file->mimetype
)) {
1563 $mimetype = $file->mimetype
;
1564 } else if (method_exists($file, 'get_mimetype')) {
1565 $mimetype = $file->get_mimetype();
1569 $mimetypes = &get_mimetypes_array();
1571 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1572 if ($extension && !empty($mimetypes[$extension])) {
1573 // if file name has known extension, return icon for this extension
1574 return file_extension_icon($filename, $size);
1577 return file_mimetype_icon($mimetype, $size);
1581 * Return the relative icon path for a folder image
1585 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1586 * echo html_writer::empty_tag('img', array('src' => $icon));
1590 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1593 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1596 function file_folder_icon($iconsize = null) {
1598 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1599 static $cached = array();
1600 $iconsize = max(array(16, (int)$iconsize));
1601 if (!array_key_exists($iconsize, $cached)) {
1602 foreach ($iconpostfixes as $size => $postfix) {
1603 $fullname = $CFG->dirroot
.'/pix/f/folder'.$postfix;
1604 if ($iconsize >= $size &&
1605 (file_exists($fullname.'.svg') ||
file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1606 $cached[$iconsize] = 'f/folder'.$postfix;
1611 return $cached[$iconsize];
1615 * Returns the relative icon path for a given mime type
1617 * This function should be used in conjunction with $OUTPUT->image_url to produce
1618 * a return the full path to an icon.
1621 * $mimetype = 'image/jpg';
1622 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1623 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1627 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1628 * to conform with that.
1629 * @param string $mimetype The mimetype to fetch an icon for
1630 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1631 * @return string The relative path to the icon
1633 function file_mimetype_icon($mimetype, $size = NULL) {
1634 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1638 * Returns the relative icon path for a given file name
1640 * This function should be used in conjunction with $OUTPUT->image_url to produce
1641 * a return the full path to an icon.
1644 * $filename = '.jpg';
1645 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1646 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1649 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1650 * to conform with that.
1651 * @todo MDL-31074 Implement $size
1653 * @param string $filename The filename to get the icon for
1654 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1657 function file_extension_icon($filename, $size = NULL) {
1658 return 'f/'.mimeinfo('icon'.$size, $filename);
1662 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1663 * mimetypes.php language file.
1665 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1666 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1667 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1668 * @param bool $capitalise If true, capitalises first character of result
1669 * @return string Text description
1671 function get_mimetype_description($obj, $capitalise=false) {
1672 $filename = $mimetype = '';
1673 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1674 // this is an instance of stored_file
1675 $mimetype = $obj->get_mimetype();
1676 $filename = $obj->get_filename();
1677 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1678 // this is an instance of file_info
1679 $mimetype = $obj->get_mimetype();
1680 $filename = $obj->get_visible_name();
1681 } else if (is_array($obj) ||
is_object ($obj)) {
1683 if (!empty($obj['filename'])) {
1684 $filename = $obj['filename'];
1686 if (!empty($obj['mimetype'])) {
1687 $mimetype = $obj['mimetype'];
1692 $mimetypefromext = mimeinfo('type', $filename);
1693 if (empty($mimetype) ||
$mimetypefromext !== 'document/unknown') {
1694 // if file has a known extension, overwrite the specified mimetype
1695 $mimetype = $mimetypefromext;
1697 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1698 if (empty($extension)) {
1699 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1700 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1702 $mimetypestr = mimeinfo('string', $filename);
1704 $chunks = explode('/', $mimetype, 2);
1707 'mimetype' => $mimetype,
1708 'ext' => $extension,
1709 'mimetype1' => $chunks[0],
1710 'mimetype2' => $chunks[1],
1713 foreach ($attr as $key => $value) {
1715 $a[strtoupper($key)] = strtoupper($value);
1716 $a[ucfirst($key)] = ucfirst($value);
1719 // MIME types may include + symbol but this is not permitted in string ids.
1720 $safemimetype = str_replace('+', '_', $mimetype);
1721 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1722 $customdescription = mimeinfo('customdescription', $filename);
1723 if ($customdescription) {
1724 // Call format_string on the custom description so that multilang
1725 // filter can be used (if enabled on system context). We use system
1726 // context because it is possible that the page context might not have
1727 // been defined yet.
1728 $result = format_string($customdescription, true,
1729 array('context' => context_system
::instance()));
1730 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1731 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1732 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1733 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1734 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1735 $result = get_string('default', 'mimetypes', (object)$a);
1737 $result = $mimetype;
1740 $result=ucfirst($result);
1746 * Returns array of elements of type $element in type group(s)
1748 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1749 * @param string|array $groups one group or array of groups/extensions/mimetypes
1752 function file_get_typegroup($element, $groups) {
1753 static $cached = array();
1754 if (!is_array($groups)) {
1755 $groups = array($groups);
1757 if (!array_key_exists($element, $cached)) {
1758 $cached[$element] = array();
1761 foreach ($groups as $group) {
1762 if (!array_key_exists($group, $cached[$element])) {
1763 // retrieive and cache all elements of type $element for group $group
1764 $mimeinfo = & get_mimetypes_array();
1765 $cached[$element][$group] = array();
1766 foreach ($mimeinfo as $extension => $value) {
1767 $value['extension'] = '.'.$extension;
1768 if (empty($value[$element])) {
1771 if (($group === '.'.$extension ||
$group === $value['type'] ||
1772 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1773 !in_array($value[$element], $cached[$element][$group])) {
1774 $cached[$element][$group][] = $value[$element];
1778 $result = array_merge($result, $cached[$element][$group]);
1780 return array_values(array_unique($result));
1784 * Checks if file with name $filename has one of the extensions in groups $groups
1786 * @see get_mimetypes_array()
1787 * @param string $filename name of the file to check
1788 * @param string|array $groups one group or array of groups to check
1789 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1790 * file mimetype is in mimetypes in groups $groups
1793 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1794 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
1795 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1798 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1802 * Checks if mimetype $mimetype belongs to one of the groups $groups
1804 * @see get_mimetypes_array()
1805 * @param string $mimetype
1806 * @param string|array $groups one group or array of groups to check
1809 function file_mimetype_in_typegroup($mimetype, $groups) {
1810 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1814 * Requested file is not found or not accessible, does not return, terminates script
1816 * @global stdClass $CFG
1817 * @global stdClass $COURSE
1819 function send_file_not_found() {
1820 global $CFG, $COURSE;
1822 // Allow cross-origin requests only for Web Services.
1823 // This allow to receive requests done by Web Workers or webapps in different domains.
1825 header('Access-Control-Allow-Origin: *');
1829 print_error('filenotfound', 'error', $CFG->wwwroot
.'/course/view.php?id='.$COURSE->id
); //this is not displayed on IIS??
1832 * Helper function to send correct 404 for server.
1834 function send_header_404() {
1835 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1836 header("Status: 404 Not Found");
1838 header('HTTP/1.0 404 not found');
1843 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1844 * platforms). This wrapper uses readfile for small files and custom code for
1847 * @param string $path Path to file
1848 * @param int $filesize Size of file (if left out, will get it automatically)
1849 * @return int|bool Size read (will always be $filesize) or false if failed
1851 function readfile_allow_large($path, $filesize = -1) {
1852 // Automatically get size if not specified.
1853 if ($filesize === -1) {
1854 $filesize = filesize($path);
1856 if ($filesize <= 2147483647) {
1857 // If the file is up to 2^31 - 1, send it normally using readfile.
1858 return readfile($path);
1860 // For large files, read and output in 64KB chunks.
1861 $handle = fopen($path, 'r');
1862 if ($handle === false) {
1867 $size = min($left, 65536);
1868 $buffer = fread($handle, $size);
1869 if ($buffer === false) {
1880 * Enhanced readfile() with optional acceleration.
1881 * @param string|stored_file $file
1882 * @param string $mimetype
1883 * @param bool $accelerate
1886 function readfile_accel($file, $mimetype, $accelerate) {
1889 if ($mimetype === 'text/plain') {
1890 // there is no encoding specified in text files, we need something consistent
1891 header('Content-Type: text/plain; charset=utf-8');
1893 header('Content-Type: '.$mimetype);
1896 $lastmodified = is_object($file) ?
$file->get_timemodified() : filemtime($file);
1897 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1899 if (is_object($file)) {
1900 header('Etag: "' . $file->get_contenthash() . '"');
1901 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1902 header('HTTP/1.1 304 Not Modified');
1907 // if etag present for stored file rely on it exclusively
1908 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1909 // get unixtime of request header; clip extra junk off first
1910 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1911 if ($since && $since >= $lastmodified) {
1912 header('HTTP/1.1 304 Not Modified');
1917 if ($accelerate and !empty($CFG->xsendfile
)) {
1918 if (empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
1919 header('Accept-Ranges: bytes');
1921 header('Accept-Ranges: none');
1924 if (is_object($file)) {
1925 $fs = get_file_storage();
1926 if ($fs->xsendfile($file->get_contenthash())) {
1931 require_once("$CFG->libdir/xsendfilelib.php");
1932 if (xsendfile($file)) {
1938 $filesize = is_object($file) ?
$file->get_filesize() : filesize($file);
1940 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1942 if ($accelerate and empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
1943 header('Accept-Ranges: bytes');
1945 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1946 // byteserving stuff - for acrobat reader and download accelerators
1947 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1948 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1950 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
1951 foreach ($ranges as $key=>$value) {
1952 if ($ranges[$key][1] == '') {
1954 $ranges[$key][1] = $filesize - $ranges[$key][2];
1955 $ranges[$key][2] = $filesize - 1;
1956 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
1958 $ranges[$key][2] = $filesize - 1;
1960 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1961 //invalid byte-range ==> ignore header
1965 //prepare multipart header
1966 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
1967 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1973 if (is_object($file)) {
1974 $handle = $file->get_content_file_handle();
1976 $handle = fopen($file, 'rb');
1978 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1983 header('Accept-Ranges: none');
1986 header('Content-Length: '.$filesize);
1988 if ($filesize > 10000000) {
1989 // for large files try to flush and close all buffers to conserve memory
1990 while(@ob_get_level
()) {
1991 if (!@ob_end_flush
()) {
1997 // send the whole file content
1998 if (is_object($file)) {
2001 readfile_allow_large($file, $filesize);
2006 * Similar to readfile_accel() but designed for strings.
2007 * @param string $string
2008 * @param string $mimetype
2009 * @param bool $accelerate
2012 function readstring_accel($string, $mimetype, $accelerate) {
2015 if ($mimetype === 'text/plain') {
2016 // there is no encoding specified in text files, we need something consistent
2017 header('Content-Type: text/plain; charset=utf-8');
2019 header('Content-Type: '.$mimetype);
2021 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2022 header('Accept-Ranges: none');
2024 if ($accelerate and !empty($CFG->xsendfile
)) {
2025 $fs = get_file_storage();
2026 if ($fs->xsendfile(sha1($string))) {
2031 header('Content-Length: '.strlen($string));
2036 * Handles the sending of temporary file to user, download is forced.
2037 * File is deleted after abort or successful sending, does not return, script terminated
2039 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2040 * @param string $filename proposed file name when saving file
2041 * @param bool $pathisstring If the path is string
2043 function send_temp_file($path, $filename, $pathisstring=false) {
2046 // Guess the file's MIME type.
2047 $mimetype = get_mimetype_for_sending($filename);
2049 // close session - not needed anymore
2050 \core\session\manager
::write_close();
2052 if (!$pathisstring) {
2053 if (!file_exists($path)) {
2055 print_error('filenotfound', 'error', $CFG->wwwroot
.'/');
2057 // executed after normal finish or abort
2058 core_shutdown_manager
::register_function('send_temp_file_finished', array($path));
2061 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2062 if (core_useragent
::is_ie()) {
2063 $filename = urlencode($filename);
2066 header('Content-Disposition: attachment; filename="'.$filename.'"');
2067 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2068 header('Cache-Control: private, max-age=10, no-transform');
2069 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2071 } else { //normal http - prevent caching at all cost
2072 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2073 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2074 header('Pragma: no-cache');
2077 // send the contents - we can not accelerate this because the file will be deleted asap
2078 if ($pathisstring) {
2079 readstring_accel($path, $mimetype, false);
2081 readfile_accel($path, $mimetype, false);
2085 die; //no more chars to output
2089 * Internal callback function used by send_temp_file()
2091 * @param string $path
2093 function send_temp_file_finished($path) {
2094 if (file_exists($path)) {
2100 * Serve content which is not meant to be cached.
2102 * This is only intended to be used for volatile public files, for instance
2103 * when development is enabled, or when caching is not required on a public resource.
2105 * @param string $content Raw content.
2106 * @param string $filename The file name.
2109 function send_content_uncached($content, $filename) {
2110 $mimetype = mimeinfo('type', $filename);
2111 $charset = strpos($mimetype, 'text/') === 0 ?
'; charset=utf-8' : '';
2113 header('Content-Disposition: inline; filename="' . $filename . '"');
2114 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2115 header('Expires: ' . gmdate('D, d M Y H:i:s', time() +
2) . ' GMT');
2117 header('Accept-Ranges: none');
2118 header('Content-Type: ' . $mimetype . $charset);
2119 header('Content-Length: ' . strlen($content));
2126 * Safely save content to a certain path.
2128 * This function tries hard to be atomic by first copying the content
2129 * to a separate file, and then moving the file across. It also prevents
2130 * the user to abort a request to prevent half-safed files.
2132 * This function is intended to be used when saving some content to cache like
2133 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2135 * @param string $content The file content.
2136 * @param string $destination The absolute path of the final file.
2139 function file_safe_save_content($content, $destination) {
2143 if (!file_exists(dirname($destination))) {
2144 @mkdir
(dirname($destination), $CFG->directorypermissions
, true);
2147 // Prevent serving of incomplete file from concurrent request,
2148 // the rename() should be more atomic than fwrite().
2149 ignore_user_abort(true);
2150 if ($fp = fopen($destination . '.tmp', 'xb')) {
2151 fwrite($fp, $content);
2153 rename($destination . '.tmp', $destination);
2154 @chmod
($destination, $CFG->filepermissions
);
2155 @unlink
($destination . '.tmp'); // Just in case anything fails.
2157 ignore_user_abort(false);
2158 if (connection_aborted()) {
2164 * Handles the sending of file data to the user's browser, including support for
2168 * @param string|stored_file $path Path of file on disk (including real filename),
2169 * or actual content of file as string,
2170 * or stored_file object
2171 * @param string $filename Filename to send
2172 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2173 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2174 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2175 * Forced to false when $path is a stored_file object.
2176 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2177 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2178 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2179 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2180 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2181 * and should not be reopened.
2182 * @param array $options An array of options, currently accepts:
2183 * - (string) cacheability: public, or private.
2184 * - (string|null) immutable
2185 * @return null script execution stopped unless $dontdie is true
2187 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2188 $dontdie=false, array $options = array()) {
2189 global $CFG, $COURSE;
2192 ignore_user_abort(true);
2195 if ($lifetime === 'default' or is_null($lifetime)) {
2196 $lifetime = $CFG->filelifetime
;
2199 if (is_object($path)) {
2200 $pathisstring = false;
2203 \core\session\manager
::write_close(); // Unlock session during file serving.
2205 // Use given MIME type if specified, otherwise guess it.
2206 if (!$mimetype ||
$mimetype === 'document/unknown') {
2207 $mimetype = get_mimetype_for_sending($filename);
2210 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2211 if (core_useragent
::is_ie()) {
2212 $filename = rawurlencode($filename);
2215 if ($forcedownload) {
2216 header('Content-Disposition: attachment; filename="'.$filename.'"');
2217 } else if ($mimetype !== 'application/x-shockwave-flash') {
2218 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2219 // as an upload and enforces security that may prevent the file from being loaded.
2221 header('Content-Disposition: inline; filename="'.$filename.'"');
2224 if ($lifetime > 0) {
2226 if (!empty($options['immutable'])) {
2227 $immutable = ', immutable';
2228 // Overwrite lifetime accordingly:
2229 // 90 days only - based on Moodle point release cadence being every 3 months.
2230 $lifetimemin = 60 * 60 * 24 * 90;
2231 $lifetime = max($lifetime, $lifetimemin);
2233 $cacheability = ' public,';
2234 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2235 // This file must be cache-able by both browsers and proxies.
2236 $cacheability = ' public,';
2237 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2238 // This file must be cache-able only by browsers.
2239 $cacheability = ' private,';
2240 } else if (isloggedin() and !isguestuser()) {
2241 // By default, under the conditions above, this file must be cache-able only by browsers.
2242 $cacheability = ' private,';
2244 $nobyteserving = false;
2245 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2246 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
2249 } else { // Do not cache files in proxies and browsers
2250 $nobyteserving = true;
2251 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2252 header('Cache-Control: private, max-age=10, no-transform');
2253 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2255 } else { //normal http - prevent caching at all cost
2256 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2257 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2258 header('Pragma: no-cache');
2262 if (empty($filter)) {
2263 // send the contents
2264 if ($pathisstring) {
2265 readstring_accel($path, $mimetype, !$dontdie);
2267 readfile_accel($path, $mimetype, !$dontdie);
2271 // Try to put the file through filters
2272 if ($mimetype == 'text/html' ||
$mimetype == 'application/xhtml+xml') {
2273 $options = new stdClass();
2274 $options->noclean
= true;
2275 $options->nocache
= true; // temporary workaround for MDL-5136
2276 if (is_object($path)) {
2277 $text = $path->get_content();
2278 } else if ($pathisstring) {
2281 $text = implode('', file($path));
2283 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
2285 readstring_accel($output, $mimetype, false);
2287 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2288 // only filter text if filter all files is selected
2289 $options = new stdClass();
2290 $options->newlines
= false;
2291 $options->noclean
= true;
2292 if (is_object($path)) {
2293 $text = htmlentities($path->get_content(), ENT_QUOTES
, 'UTF-8');
2294 } else if ($pathisstring) {
2295 $text = htmlentities($path, ENT_QUOTES
, 'UTF-8');
2297 $text = htmlentities(implode('', file($path)), ENT_QUOTES
, 'UTF-8');
2299 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
2301 readstring_accel($output, $mimetype, false);
2304 // send the contents
2305 if ($pathisstring) {
2306 readstring_accel($path, $mimetype, !$dontdie);
2308 readfile_accel($path, $mimetype, !$dontdie);
2315 die; //no more chars to output!!!
2319 * Handles the sending of file data to the user's browser, including support for
2322 * The $options parameter supports the following keys:
2323 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2324 * (string|null) filename - overrides the implicit filename
2325 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2326 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2327 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2328 * and should not be reopened
2329 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2330 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2331 * defaults to "public".
2332 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2333 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2336 * @param stored_file $stored_file local file object
2337 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2338 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2339 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2340 * @param array $options additional options affecting the file serving
2341 * @return null script execution stopped unless $options['dontdie'] is true
2343 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2344 global $CFG, $COURSE;
2346 if (empty($options['filename'])) {
2349 $filename = $options['filename'];
2352 if (empty($options['dontdie'])) {
2358 if ($lifetime === 'default' or is_null($lifetime)) {
2359 $lifetime = $CFG->filelifetime
;
2362 if (!empty($options['preview'])) {
2363 // replace the file with its preview
2364 $fs = get_file_storage();
2365 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2366 if (!$preview_file) {
2367 // unable to create a preview of the file, send its default mime icon instead
2368 if ($options['preview'] === 'tinyicon') {
2370 } else if ($options['preview'] === 'thumb') {
2375 $fileicon = file_file_icon($stored_file, $size);
2376 send_file($CFG->dirroot
.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2378 // preview images have fixed cache lifetime and they ignore forced download
2379 // (they are generated by GD and therefore they are considered reasonably safe).
2380 $stored_file = $preview_file;
2381 $lifetime = DAYSECS
;
2383 $forcedownload = false;
2387 // handle external resource
2388 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2389 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2393 if (!$stored_file or $stored_file->is_directory()) {
2401 $filename = is_null($filename) ?
$stored_file->get_filename() : $filename;
2403 // Use given MIME type if specified.
2404 $mimetype = $stored_file->get_mimetype();
2406 // Allow cross-origin requests only for Web Services.
2407 // This allow to receive requests done by Web Workers or webapps in different domains.
2409 header('Access-Control-Allow-Origin: *');
2412 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2416 * Recursively delete the file or folder with path $location. That is,
2417 * if it is a file delete it. If it is a folder, delete all its content
2418 * then delete it. If $location does not exist to start, that is not
2419 * considered an error.
2421 * @param string $location the path to remove.
2424 function fulldelete($location) {
2425 if (empty($location)) {
2426 // extra safety against wrong param
2429 if (is_dir($location)) {
2430 if (!$currdir = opendir($location)) {
2433 while (false !== ($file = readdir($currdir))) {
2434 if ($file <> ".." && $file <> ".") {
2435 $fullfile = $location."/".$file;
2436 if (is_dir($fullfile)) {
2437 if (!fulldelete($fullfile)) {
2441 if (!unlink($fullfile)) {
2448 if (! rmdir($location)) {
2452 } else if (file_exists($location)) {
2453 if (!unlink($location)) {
2461 * Send requested byterange of file.
2463 * @param resource $handle A file handle
2464 * @param string $mimetype The mimetype for the output
2465 * @param array $ranges An array of ranges to send
2466 * @param string $filesize The size of the content if only one range is used
2468 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2469 // better turn off any kind of compression and buffering
2470 ini_set('zlib.output_compression', 'Off');
2472 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2473 if ($handle === false) {
2476 if (count($ranges) == 1) { //only one range requested
2477 $length = $ranges[0][2] - $ranges[0][1] +
1;
2478 header('HTTP/1.1 206 Partial content');
2479 header('Content-Length: '.$length);
2480 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2481 header('Content-Type: '.$mimetype);
2483 while(@ob_get_level
()) {
2484 if (!@ob_end_flush
()) {
2489 fseek($handle, $ranges[0][1]);
2490 while (!feof($handle) && $length > 0) {
2491 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2492 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2495 $length -= strlen($buffer);
2499 } else { // multiple ranges requested - not tested much
2501 foreach($ranges as $range) {
2502 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
2504 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
2505 header('HTTP/1.1 206 Partial content');
2506 header('Content-Length: '.$totallength);
2507 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
2509 while(@ob_get_level
()) {
2510 if (!@ob_end_flush
()) {
2515 foreach($ranges as $range) {
2516 $length = $range[2] - $range[1] +
1;
2518 fseek($handle, $range[1]);
2519 while (!feof($handle) && $length > 0) {
2520 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2521 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2524 $length -= strlen($buffer);
2527 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
2534 * Tells whether the filename is executable.
2536 * @link http://php.net/manual/en/function.is-executable.php
2537 * @link https://bugs.php.net/bug.php?id=41062
2538 * @param string $filename Path to the file.
2539 * @return bool True if the filename exists and is executable; otherwise, false.
2541 function file_is_executable($filename) {
2542 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
2543 if (is_executable($filename)) {
2546 $fileext = strrchr($filename, '.');
2547 // If we have an extension we can check if it is listed as executable.
2548 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2549 $winpathext = strtolower(getenv('PATHEXT'));
2550 $winpathexts = explode(';', $winpathext);
2552 return in_array(strtolower($fileext), $winpathexts);
2558 return is_executable($filename);
2563 * Overwrite an existing file in a draft area.
2565 * @param stored_file $newfile the new file with the new content and meta-data
2566 * @param stored_file $existingfile the file that will be overwritten
2567 * @throws moodle_exception
2570 function file_overwrite_existing_draftfile(stored_file
$newfile, stored_file
$existingfile) {
2571 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2572 throw new coding_exception('The file to overwrite is not in a draft area.');
2575 $fs = get_file_storage();
2576 // Remember original file source field.
2577 $source = @unserialize
($existingfile->get_source());
2578 // Remember the original sortorder.
2579 $sortorder = $existingfile->get_sortorder();
2580 if ($newfile->is_external_file()) {
2581 // New file is a reference. Check that existing file does not have any other files referencing to it
2582 if (isset($source->original
) && $fs->search_references_count($source->original
)) {
2583 throw new moodle_exception('errordoublereference', 'repository');
2587 // Delete existing file to release filename.
2588 $newfilerecord = array(
2589 'contextid' => $existingfile->get_contextid(),
2590 'component' => 'user',
2591 'filearea' => 'draft',
2592 'itemid' => $existingfile->get_itemid(),
2593 'timemodified' => time()
2595 $existingfile->delete();
2598 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2599 // Preserve original file location (stored in source field) for handling references.
2600 if (isset($source->original
)) {
2601 if (!($newfilesource = @unserialize
($newfile->get_source()))) {
2602 $newfilesource = new stdClass();
2604 $newfilesource->original
= $source->original
;
2605 $newfile->set_source(serialize($newfilesource));
2607 $newfile->set_sortorder($sortorder);
2611 * Add files from a draft area into a final area.
2613 * Most of the time you do not want to use this. It is intended to be used
2614 * by asynchronous services which cannot direcly manipulate a final
2615 * area through a draft area. Instead they add files to a new draft
2616 * area and merge that new draft into the final area when ready.
2618 * @param int $draftitemid the id of the draft area to use.
2619 * @param int $contextid this parameter and the next two identify the file area to save to.
2620 * @param string $component component name
2621 * @param string $filearea indentifies the file area
2622 * @param int $itemid identifies the item id or false for all items in the file area
2623 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2624 * @see file_save_draft_area_files
2627 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2628 array $options = null) {
2629 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2631 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2632 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2633 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2637 * Merge files from two draftarea areas.
2639 * This does not handle conflict resolution, files in the destination area which appear
2640 * to be more recent will be kept disregarding the intended ones.
2642 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2643 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2644 * @throws coding_exception
2647 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2650 $fs = get_file_storage();
2651 $contextid = context_user
::instance($USER->id
)->id
;
2653 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2654 throw new coding_exception('Nothing to merge or area does not belong to current user');
2657 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2659 // Get hashes of the files to merge.
2660 $newhashes = array();
2661 foreach ($filestomerge as $filetomerge) {
2662 $filepath = $filetomerge->get_filepath();
2663 $filename = $filetomerge->get_filename();
2665 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2666 $newhashes[$newhash] = $filetomerge;
2669 // Calculate wich files must be added.
2670 foreach ($currentfiles as $file) {
2671 $filehash = $file->get_pathnamehash();
2672 // One file to be merged already exists.
2673 if (isset($newhashes[$filehash])) {
2674 $updatedfile = $newhashes[$filehash];
2676 // Avoid race conditions.
2677 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2678 // The existing file is more recent, do not copy the suposedly "new" one.
2679 unset($newhashes[$filehash]);
2682 // Update existing file (not only content, meta-data too).
2683 file_overwrite_existing_draftfile($updatedfile, $file);
2684 unset($newhashes[$filehash]);
2688 foreach ($newhashes as $newfile) {
2689 $newfilerecord = array(
2690 'contextid' => $contextid,
2691 'component' => 'user',
2692 'filearea' => 'draft',
2693 'itemid' => $mergeintodraftid,
2694 'timemodified' => time()
2697 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2702 * RESTful cURL class
2704 * This is a wrapper class for curl, it is quite easy to use:
2708 * $c = new curl(array('cache'=>true));
2710 * $c = new curl(array('cookie'=>true));
2712 * $c = new curl(array('proxy'=>true));
2714 * // HTTP GET Method
2715 * $html = $c->get('http://example.com');
2716 * // HTTP POST Method
2717 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2718 * // HTTP PUT Method
2719 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2722 * @package core_files
2724 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2725 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2728 /** @var bool Caches http request contents */
2729 public $cache = false;
2730 /** @var bool Uses proxy, null means automatic based on URL */
2731 public $proxy = null;
2732 /** @var string library version */
2733 public $version = '0.4 dev';
2734 /** @var array http's response */
2735 public $response = array();
2736 /** @var array Raw response headers, needed for BC in download_file_content(). */
2737 public $rawresponse = array();
2738 /** @var array http header */
2739 public $header = array();
2740 /** @var string cURL information */
2742 /** @var string error */
2744 /** @var int error code */
2746 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2747 public $emulateredirects = null;
2749 /** @var array cURL options */
2752 /** @var string Proxy host */
2753 private $proxy_host = '';
2754 /** @var string Proxy auth */
2755 private $proxy_auth = '';
2756 /** @var string Proxy type */
2757 private $proxy_type = '';
2758 /** @var bool Debug mode on */
2759 private $debug = false;
2760 /** @var bool|string Path to cookie file */
2761 private $cookie = false;
2762 /** @var bool tracks multiple headers in response - redirect detection */
2763 private $responsefinished = false;
2764 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2765 private $securityhelper;
2766 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2767 private $ignoresecurity;
2768 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
2769 private static $mockresponses = [];
2774 * Allowed settings are:
2775 * proxy: (bool) use proxy server, null means autodetect non-local from url
2776 * debug: (bool) use debug output
2777 * cookie: (string) path to cookie file, false if none
2778 * cache: (bool) use cache
2779 * module_cache: (string) type of cache
2780 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
2781 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
2783 * @param array $settings
2785 public function __construct($settings = array()) {
2787 if (!function_exists('curl_init')) {
2788 $this->error
= 'cURL module must be enabled!';
2789 trigger_error($this->error
, E_USER_ERROR
);
2793 // All settings of this class should be init here.
2795 if (!empty($settings['debug'])) {
2796 $this->debug
= true;
2798 if (!empty($settings['cookie'])) {
2799 if($settings['cookie'] === true) {
2800 $this->cookie
= $CFG->dataroot
.'/curl_cookie.txt';
2802 $this->cookie
= $settings['cookie'];
2805 if (!empty($settings['cache'])) {
2806 if (class_exists('curl_cache')) {
2807 if (!empty($settings['module_cache'])) {
2808 $this->cache
= new curl_cache($settings['module_cache']);
2810 $this->cache
= new curl_cache('misc');
2814 if (!empty($CFG->proxyhost
)) {
2815 if (empty($CFG->proxyport
)) {
2816 $this->proxy_host
= $CFG->proxyhost
;
2818 $this->proxy_host
= $CFG->proxyhost
.':'.$CFG->proxyport
;
2820 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
2821 $this->proxy_auth
= $CFG->proxyuser
.':'.$CFG->proxypassword
;
2822 $this->setopt(array(
2823 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM
,
2824 'proxyuserpwd'=>$this->proxy_auth
));
2826 if (!empty($CFG->proxytype
)) {
2827 if ($CFG->proxytype
== 'SOCKS5') {
2828 $this->proxy_type
= CURLPROXY_SOCKS5
;
2830 $this->proxy_type
= CURLPROXY_HTTP
;
2831 $this->setopt(array('httpproxytunnel'=>false));
2833 $this->setopt(array('proxytype'=>$this->proxy_type
));
2836 if (isset($settings['proxy'])) {
2837 $this->proxy
= $settings['proxy'];
2840 $this->proxy
= false;
2843 if (!isset($this->emulateredirects
)) {
2844 $this->emulateredirects
= ini_get('open_basedir');
2847 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
2848 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base
) {
2849 $this->set_security($settings['securityhelper']);
2851 $this->set_security(new \core\files\
curl_security_helper());
2853 $this->ignoresecurity
= isset($settings['ignoresecurity']) ?
$settings['ignoresecurity'] : false;
2857 * Resets the CURL options that have already been set
2859 public function resetopt() {
2860 $this->options
= array();
2861 $this->options
['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2862 // True to include the header in the output
2863 $this->options
['CURLOPT_HEADER'] = 0;
2864 // True to Exclude the body from the output
2865 $this->options
['CURLOPT_NOBODY'] = 0;
2866 // Redirect ny default.
2867 $this->options
['CURLOPT_FOLLOWLOCATION'] = 1;
2868 $this->options
['CURLOPT_MAXREDIRS'] = 10;
2869 $this->options
['CURLOPT_ENCODING'] = '';
2870 // TRUE to return the transfer as a string of the return
2871 // value of curl_exec() instead of outputting it out directly.
2872 $this->options
['CURLOPT_RETURNTRANSFER'] = 1;
2873 $this->options
['CURLOPT_SSL_VERIFYPEER'] = 0;
2874 $this->options
['CURLOPT_SSL_VERIFYHOST'] = 2;
2875 $this->options
['CURLOPT_CONNECTTIMEOUT'] = 30;
2877 if ($cacert = self
::get_cacert()) {
2878 $this->options
['CURLOPT_CAINFO'] = $cacert;
2883 * Get the location of ca certificates.
2884 * @return string absolute file path or empty if default used
2886 public static function get_cacert() {
2889 // Bundle in dataroot always wins.
2890 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2891 return realpath("$CFG->dataroot/moodleorgca.crt");
2894 // Next comes the default from php.ini
2895 $cacert = ini_get('curl.cainfo');
2896 if (!empty($cacert) and is_readable($cacert)) {
2897 return realpath($cacert);
2900 // Windows PHP does not have any certs, we need to use something.
2901 if ($CFG->ostype
=== 'WINDOWS') {
2902 if (is_readable("$CFG->libdir/cacert.pem")) {
2903 return realpath("$CFG->libdir/cacert.pem");
2907 // Use default, this should work fine on all properly configured *nix systems.
2914 public function resetcookie() {
2915 if (!empty($this->cookie
)) {
2916 if (is_file($this->cookie
)) {
2917 $fp = fopen($this->cookie
, 'w');
2929 * Do not use the curl constants to define the options, pass a string
2930 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2931 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2933 * @param array $options If array is null, this function will reset the options to default value.
2935 * @throws coding_exception If an option uses constant value instead of option name.
2937 public function setopt($options = array()) {
2938 if (is_array($options)) {
2939 foreach ($options as $name => $val) {
2940 if (!is_string($name)) {
2941 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2943 if (stripos($name, 'CURLOPT_') === false) {
2944 $name = strtoupper('CURLOPT_'.$name);
2946 $name = strtoupper($name);
2948 $this->options
[$name] = $val;
2956 public function cleanopt() {
2957 unset($this->options
['CURLOPT_HTTPGET']);
2958 unset($this->options
['CURLOPT_POST']);
2959 unset($this->options
['CURLOPT_POSTFIELDS']);
2960 unset($this->options
['CURLOPT_PUT']);
2961 unset($this->options
['CURLOPT_INFILE']);
2962 unset($this->options
['CURLOPT_INFILESIZE']);
2963 unset($this->options
['CURLOPT_CUSTOMREQUEST']);
2964 unset($this->options
['CURLOPT_FILE']);
2968 * Resets the HTTP Request headers (to prepare for the new request)
2970 public function resetHeader() {
2971 $this->header
= array();
2975 * Set HTTP Request Header
2977 * @param array $header
2979 public function setHeader($header) {
2980 if (is_array($header)) {
2981 foreach ($header as $v) {
2982 $this->setHeader($v);
2985 // Remove newlines, they are not allowed in headers.
2986 $newvalue = preg_replace('/[\r\n]/', '', $header);
2987 if (!in_array($newvalue, $this->header
)) {
2988 $this->header
[] = $newvalue;
2994 * Get HTTP Response Headers
2995 * @return array of arrays
2997 public function getResponse() {
2998 return $this->response
;
3002 * Get raw HTTP Response Headers
3003 * @return array of strings
3005 public function get_raw_response() {
3006 return $this->rawresponse
;
3010 * private callback function
3011 * Formatting HTTP Response Header
3013 * We only keep the last headers returned. For example during a redirect the
3014 * redirect headers will not appear in {@link self::getResponse()}, if you need
3015 * to use those headers, refer to {@link self::get_raw_response()}.
3017 * @param resource $ch Apparently not used
3018 * @param string $header
3019 * @return int The strlen of the header
3021 private function formatHeader($ch, $header) {
3022 $this->rawresponse
[] = $header;
3024 if (trim($header, "\r\n") === '') {
3025 // This must be the last header.
3026 $this->responsefinished
= true;
3029 if (strlen($header) > 2) {
3030 if ($this->responsefinished
) {
3031 // We still have headers after the supposedly last header, we must be
3032 // in a redirect so let's empty the response to keep the last headers.
3033 $this->responsefinished
= false;
3034 $this->response
= array();
3036 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3037 $key = rtrim($parts[0], ':');
3038 $value = isset($parts[1]) ?
$parts[1] : null;
3039 if (!empty($this->response
[$key])) {
3040 if (is_array($this->response
[$key])) {
3041 $this->response
[$key][] = $value;
3043 $tmp = $this->response
[$key];
3044 $this->response
[$key] = array();
3045 $this->response
[$key][] = $tmp;
3046 $this->response
[$key][] = $value;
3050 $this->response
[$key] = $value;
3053 return strlen($header);
3057 * Set options for individual curl instance
3059 * @param resource $curl A curl handle
3060 * @param array $options
3061 * @return resource The curl handle
3063 private function apply_opt($curl, $options) {
3067 if (!empty($this->cookie
) ||
!empty($options['cookie'])) {
3068 $this->setopt(array('cookiejar'=>$this->cookie
,
3069 'cookiefile'=>$this->cookie
3073 // Bypass proxy if required.
3074 if ($this->proxy
=== null) {
3075 if (!empty($this->options
['CURLOPT_URL']) and is_proxybypass($this->options
['CURLOPT_URL'])) {
3081 $proxy = (bool)$this->proxy
;
3086 $options['CURLOPT_PROXY'] = $this->proxy_host
;
3088 unset($this->options
['CURLOPT_PROXY']);
3091 $this->setopt($options);
3093 // Reset before set options.
3094 curl_setopt($curl, CURLOPT_HEADERFUNCTION
, array(&$this,'formatHeader'));
3096 // Setting the User-Agent based on options provided.
3099 if (!empty($options['CURLOPT_USERAGENT'])) {
3100 $useragent = $options['CURLOPT_USERAGENT'];
3101 } else if (!empty($this->options
['CURLOPT_USERAGENT'])) {
3102 $useragent = $this->options
['CURLOPT_USERAGENT'];
3104 $useragent = 'MoodleBot/1.0';
3108 if (empty($this->header
)) {
3109 $this->setHeader(array(
3110 'User-Agent: ' . $useragent,
3111 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3112 'Connection: keep-alive'
3114 } else if (!in_array('User-Agent: ' . $useragent, $this->header
)) {
3115 // Remove old User-Agent if one existed.
3116 // We have to partial search since we don't know what the original User-Agent is.
3117 if ($match = preg_grep('/User-Agent.*/', $this->header
)) {
3118 $key = array_keys($match)[0];
3119 unset($this->header
[$key]);
3121 $this->setHeader(array('User-Agent: ' . $useragent));
3123 curl_setopt($curl, CURLOPT_HTTPHEADER
, $this->header
);
3126 echo '<h1>Options</h1>';
3127 var_dump($this->options
);
3128 echo '<h1>Header</h1>';
3129 var_dump($this->header
);
3132 // Do not allow infinite redirects.
3133 if (!isset($this->options
['CURLOPT_MAXREDIRS'])) {
3134 $this->options
['CURLOPT_MAXREDIRS'] = 0;
3135 } else if ($this->options
['CURLOPT_MAXREDIRS'] > 100) {
3136 $this->options
['CURLOPT_MAXREDIRS'] = 100;
3138 $this->options
['CURLOPT_MAXREDIRS'] = (int)$this->options
['CURLOPT_MAXREDIRS'];
3141 // Make sure we always know if redirects expected.
3142 if (!isset($this->options
['CURLOPT_FOLLOWLOCATION'])) {
3143 $this->options
['CURLOPT_FOLLOWLOCATION'] = 0;
3146 // Limit the protocols to HTTP and HTTPS.
3147 if (defined('CURLOPT_PROTOCOLS')) {
3148 $this->options
['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3149 $this->options
['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3153 foreach($this->options
as $name => $val) {
3154 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects
) {
3155 // The redirects are emulated elsewhere.
3156 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, 0);
3159 $name = constant($name);
3160 curl_setopt($curl, $name, $val);
3167 * Download multiple files in parallel
3169 * Calls {@link multi()} with specific download headers
3173 * $file1 = fopen('a', 'wb');
3174 * $file2 = fopen('b', 'wb');
3175 * $c->download(array(
3176 * array('url'=>'http://localhost/', 'file'=>$file1),
3177 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3187 * $c->download(array(
3188 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3189 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3193 * @param array $requests An array of files to request {
3194 * url => url to download the file [required]
3195 * file => file handler, or
3196 * filepath => file path
3198 * If 'file' and 'filepath' parameters are both specified in one request, the
3199 * open file handle in the 'file' parameter will take precedence and 'filepath'
3202 * @param array $options An array of options to set
3203 * @return array An array of results
3205 public function download($requests, $options = array()) {
3206 $options['RETURNTRANSFER'] = false;
3207 return $this->multi($requests, $options);
3211 * Returns the current curl security helper.
3213 * @return \core\files\curl_security_helper instance.
3215 public function get_security() {
3216 return $this->securityhelper
;
3220 * Sets the curl security helper.
3222 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3223 * @return bool true if the security helper could be set, false otherwise.
3225 public function set_security($securityobject) {
3226 if ($securityobject instanceof \core\files\curl_security_helper
) {
3227 $this->securityhelper
= $securityobject;
3234 * Multi HTTP Requests
3235 * This function could run multi-requests in parallel.
3237 * @param array $requests An array of files to request
3238 * @param array $options An array of options to set
3239 * @return array An array of results
3241 protected function multi($requests, $options = array()) {
3242 $count = count($requests);
3245 $main = curl_multi_init();
3246 for ($i = 0; $i < $count; $i++
) {
3247 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3249 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3250 $requests[$i]['auto-handle'] = true;
3252 foreach($requests[$i] as $n=>$v) {
3255 $handles[$i] = curl_init($requests[$i]['url']);
3256 $this->apply_opt($handles[$i], $options);
3257 curl_multi_add_handle($main, $handles[$i]);
3261 curl_multi_exec($main, $running);
3262 } while($running > 0);
3263 for ($i = 0; $i < $count; $i++
) {
3264 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3267 $results[] = curl_multi_getcontent($handles[$i]);
3269 curl_multi_remove_handle($main, $handles[$i]);
3271 curl_multi_close($main);
3273 for ($i = 0; $i < $count; $i++
) {
3274 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3275 // close file handler if file is opened in this function
3276 fclose($requests[$i]['file']);
3283 * Helper function to reset the request state vars.
3287 protected function reset_request_state_vars() {
3288 $this->info
= array();
3291 $this->response
= array();
3292 $this->rawresponse
= array();
3293 $this->responsefinished
= false;
3297 * For use only in unit tests - we can pre-set the next curl response.
3298 * This is useful for unit testing APIs that call external systems.
3299 * @param string $response
3301 public static function mock_response($response) {
3302 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST
)) {
3303 array_push(self
::$mockresponses, $response);
3305 throw new coding_excpetion('mock_response function is only available for unit tests.');
3310 * Single HTTP Request
3312 * @param string $url The URL to request
3313 * @param array $options
3316 protected function request($url, $options = array()) {
3317 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3318 $this->reset_request_state_vars();
3320 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST
)) {
3321 if ($mockresponse = array_pop(self
::$mockresponses)) {
3322 $this->info
= [ 'http_code' => 200 ];
3323 return $mockresponse;
3327 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3328 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3329 if (!$this->ignoresecurity
&& $this->securityhelper
->url_is_blocked($url)) {
3330 $this->error
= $this->securityhelper
->get_blocked_url_string();
3331 return $this->error
;
3334 // Set the URL as a curl option.
3335 $this->setopt(array('CURLOPT_URL' => $url));
3337 // Create curl instance.
3338 $curl = curl_init();
3340 $this->apply_opt($curl, $options);
3341 if ($this->cache
&& $ret = $this->cache
->get($this->options
)) {
3345 $ret = curl_exec($curl);
3346 $this->info
= curl_getinfo($curl);
3347 $this->error
= curl_error($curl);
3348 $this->errno
= curl_errno($curl);
3349 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3351 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3352 if (intval($this->info
['redirect_count']) > 0 && !$this->ignoresecurity
3353 && $this->securityhelper
->url_is_blocked($this->info
['url'])) {
3354 $this->reset_request_state_vars();
3355 $this->error
= $this->securityhelper
->get_blocked_url_string();
3357 return $this->error
;
3360 if ($this->emulateredirects
and $this->options
['CURLOPT_FOLLOWLOCATION'] and $this->info
['http_code'] != 200) {
3363 while($redirects <= $this->options
['CURLOPT_MAXREDIRS']) {
3365 if ($this->info
['http_code'] == 301) {
3366 // Moved Permanently - repeat the same request on new URL.
3368 } else if ($this->info
['http_code'] == 302) {
3369 // Found - the standard redirect - repeat the same request on new URL.
3371 } else if ($this->info
['http_code'] == 303) {
3372 // 303 See Other - repeat only if GET, do not bother with POSTs.
3373 if (empty($this->options
['CURLOPT_HTTPGET'])) {
3377 } else if ($this->info
['http_code'] == 307) {
3378 // Temporary Redirect - must repeat using the same request type.
3380 } else if ($this->info
['http_code'] == 308) {
3381 // Permanent Redirect - must repeat using the same request type.
3384 // Some other http code means do not retry!
3390 $redirecturl = null;
3391 if (isset($this->info
['redirect_url'])) {
3392 if (preg_match('|^https?://|i', $this->info
['redirect_url'])) {
3393 $redirecturl = $this->info
['redirect_url'];
3396 if (!$redirecturl) {
3397 foreach ($this->response
as $k => $v) {
3398 if (strtolower($k) === 'location') {
3403 if (preg_match('|^https?://|i', $redirecturl)) {
3404 // Great, this is the correct location format!
3406 } else if ($redirecturl) {
3407 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL
);
3408 if (strpos($redirecturl, '/') === 0) {
3409 // Relative to server root - just guess.
3410 $pos = strpos('/', $current, 8);
3411 if ($pos === false) {
3412 $redirecturl = $current.$redirecturl;
3414 $redirecturl = substr($current, 0, $pos).$redirecturl;
3417 // Relative to current script.
3418 $redirecturl = dirname($current).'/'.$redirecturl;
3423 curl_setopt($curl, CURLOPT_URL
, $redirecturl);
3424 $ret = curl_exec($curl);
3426 $this->info
= curl_getinfo($curl);
3427 $this->error
= curl_error($curl);
3428 $this->errno
= curl_errno($curl);
3430 $this->info
['redirect_count'] = $redirects;
3432 if ($this->info
['http_code'] === 200) {
3433 // Finally this is what we wanted.
3436 if ($this->errno
!= CURLE_OK
) {
3437 // Something wrong is going on.
3441 if ($redirects > $this->options
['CURLOPT_MAXREDIRS']) {
3442 $this->errno
= CURLE_TOO_MANY_REDIRECTS
;
3443 $this->error
= 'Maximum ('.$this->options
['CURLOPT_MAXREDIRS'].') redirects followed';
3448 $this->cache
->set($this->options
, $ret);
3452 echo '<h1>Return Data</h1>';
3454 echo '<h1>Info</h1>';
3455 var_dump($this->info
);
3456 echo '<h1>Error</h1>';
3457 var_dump($this->error
);
3462 if (empty($this->error
)) {
3465 return $this->error
;
3466 // exception is not ajax friendly
3467 //throw new moodle_exception($this->error, 'curl');
3476 * @param string $url
3477 * @param array $options
3480 public function head($url, $options = array()) {
3481 $options['CURLOPT_HTTPGET'] = 0;
3482 $options['CURLOPT_HEADER'] = 1;
3483 $options['CURLOPT_NOBODY'] = 1;
3484 return $this->request($url, $options);
3490 * @param string $url
3491 * @param array|string $params
3492 * @param array $options
3495 public function patch($url, $params = '', $options = array()) {
3496 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3497 if (is_array($params)) {
3498 $this->_tmp_file_post_params
= array();
3499 foreach ($params as $key => $value) {
3500 if ($value instanceof stored_file
) {
3501 $value->add_to_curl_request($this, $key);
3503 $this->_tmp_file_post_params
[$key] = $value;
3506 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
3507 unset($this->_tmp_file_post_params
);
3509 // The variable $params is the raw post data.
3510 $options['CURLOPT_POSTFIELDS'] = $params;
3512 return $this->request($url, $options);
3518 * @param string $url
3519 * @param array|string $params
3520 * @param array $options
3523 public function post($url, $params = '', $options = array()) {
3524 $options['CURLOPT_POST'] = 1;
3525 if (is_array($params)) {
3526 $this->_tmp_file_post_params
= array();
3527 foreach ($params as $key => $value) {
3528 if ($value instanceof stored_file
) {
3529 $value->add_to_curl_request($this, $key);
3531 $this->_tmp_file_post_params
[$key] = $value;
3534 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
3535 unset($this->_tmp_file_post_params
);
3537 // $params is the raw post data
3538 $options['CURLOPT_POSTFIELDS'] = $params;
3540 return $this->request($url, $options);
3546 * @param string $url
3547 * @param array $params
3548 * @param array $options
3551 public function get($url, $params = array(), $options = array()) {
3552 $options['CURLOPT_HTTPGET'] = 1;
3554 if (!empty($params)) {
3555 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3556 $url .= http_build_query($params, '', '&');
3558 return $this->request($url, $options);
3562 * Downloads one file and writes it to the specified file handler
3566 * $file = fopen('savepath', 'w');
3567 * $result = $c->download_one('http://localhost/', null,
3568 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3570 * $download_info = $c->get_info();
3571 * if ($result === true) {
3572 * // file downloaded successfully
3574 * $error_text = $result;
3575 * $error_code = $c->get_errno();
3581 * $result = $c->download_one('http://localhost/', null,
3582 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3583 * // ... see above, no need to close handle and remove file if unsuccessful
3586 * @param string $url
3587 * @param array|null $params key-value pairs to be added to $url as query string
3588 * @param array $options request options. Must include either 'file' or 'filepath'
3589 * @return bool|string true on success or error string on failure
3591 public function download_one($url, $params, $options = array()) {
3592 $options['CURLOPT_HTTPGET'] = 1;
3593 if (!empty($params)) {
3594 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3595 $url .= http_build_query($params, '', '&');
3597 if (!empty($options['filepath']) && empty($options['file'])) {
3599 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3601 return get_string('cannotwritefile', 'error', $options['filepath']);
3603 $filepath = $options['filepath'];
3605 unset($options['filepath']);
3606 $result = $this->request($url, $options);
3607 if (isset($filepath)) {
3608 fclose($options['file']);
3609 if ($result !== true) {
3619 * @param string $url
3620 * @param array $params
3621 * @param array $options
3624 public function put($url, $params = array(), $options = array()) {
3627 if (isset($params['file'])) {
3628 $file = $params['file'];
3629 if (is_file($file)) {
3630 $fp = fopen($file, 'r');
3631 $size = filesize($file);
3632 $options['CURLOPT_PUT'] = 1;
3633 $options['CURLOPT_INFILESIZE'] = $size;
3634 $options['CURLOPT_INFILE'] = $fp;
3638 if (!isset($this->options
['CURLOPT_USERPWD'])) {
3639 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3642 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3643 $options['CURLOPT_POSTFIELDS'] = $params;
3646 $ret = $this->request($url, $options);
3647 if ($fp !== false) {
3654 * HTTP DELETE method
3656 * @param string $url
3657 * @param array $param
3658 * @param array $options
3661 public function delete($url, $param = array(), $options = array()) {
3662 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3663 if (!isset($options['CURLOPT_USERPWD'])) {
3664 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3666 $ret = $this->request($url, $options);
3673 * @param string $url
3674 * @param array $options
3677 public function trace($url, $options = array()) {
3678 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3679 $ret = $this->request($url, $options);
3684 * HTTP OPTIONS method
3686 * @param string $url
3687 * @param array $options
3690 public function options($url, $options = array()) {
3691 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3692 $ret = $this->request($url, $options);
3697 * Get curl information
3701 public function get_info() {
3706 * Get curl error code
3710 public function get_errno() {
3711 return $this->errno
;
3715 * When using a proxy, an additional HTTP response code may appear at
3716 * the start of the header. For example, when using https over a proxy
3717 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3718 * also possible and some may come with their own headers.
3720 * If using the return value containing all headers, this function can be
3721 * called to remove unwanted doubles.
3723 * Note that it is not possible to distinguish this situation from valid
3724 * data unless you know the actual response part (below the headers)
3725 * will not be included in this string, or else will not 'look like' HTTP
3726 * headers. As a result it is not safe to call this function for general
3729 * @param string $input Input HTTP response
3730 * @return string HTTP response with additional headers stripped if any
3732 public static function strip_double_headers($input) {
3733 // I have tried to make this regular expression as specific as possible
3734 // to avoid any case where it does weird stuff if you happen to put
3735 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3736 // also make it faster because it can abandon regex processing as soon
3737 // as it hits something that doesn't look like an http header. The
3738 // header definition is taken from RFC 822, except I didn't support
3739 // folding which is never used in practice.
3741 return preg_replace(
3742 // HTTP version and status code (ignore value of code).
3743 '~^HTTP/1\..*' . $crlf .
3744 // Header name: character between 33 and 126 decimal, except colon.
3745 // Colon. Header value: any character except \r and \n. CRLF.
3746 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3747 // Headers are terminated by another CRLF (blank line).
3749 // Second HTTP status code, this time must be 200.
3750 '(HTTP/1.[01] 200 )~', '$1', $input);
3755 * This class is used by cURL class, use case:
3758 * $CFG->repositorycacheexpire = 120;
3759 * $CFG->curlcache = 120;
3761 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3762 * $ret = $c->get('http://www.google.com');
3765 * @package core_files
3766 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3767 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3770 /** @var string Path to cache directory */
3776 * @global stdClass $CFG
3777 * @param string $module which module is using curl_cache
3779 public function __construct($module = 'repository') {
3781 if (!empty($module)) {
3782 $this->dir
= $CFG->cachedir
.'/'.$module.'/';
3784 $this->dir
= $CFG->cachedir
.'/misc/';
3786 if (!file_exists($this->dir
)) {
3787 mkdir($this->dir
, $CFG->directorypermissions
, true);
3789 if ($module == 'repository') {
3790 if (empty($CFG->repositorycacheexpire
)) {
3791 $CFG->repositorycacheexpire
= 120;
3793 $this->ttl
= $CFG->repositorycacheexpire
;
3795 if (empty($CFG->curlcache
)) {
3796 $CFG->curlcache
= 120;
3798 $this->ttl
= $CFG->curlcache
;
3805 * @global stdClass $CFG
3806 * @global stdClass $USER
3807 * @param mixed $param
3808 * @return bool|string
3810 public function get($param) {
3812 $this->cleanup($this->ttl
);
3813 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
3814 if(file_exists($this->dir
.$filename)) {
3815 $lasttime = filemtime($this->dir
.$filename);
3816 if (time()-$lasttime > $this->ttl
) {
3819 $fp = fopen($this->dir
.$filename, 'r');
3820 $size = filesize($this->dir
.$filename);
3821 $content = fread($fp, $size);
3822 return unserialize($content);
3831 * @global object $CFG
3832 * @global object $USER
3833 * @param mixed $param
3836 public function set($param, $val) {
3838 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
3839 $fp = fopen($this->dir
.$filename, 'w');
3840 fwrite($fp, serialize($val));
3842 @chmod
($this->dir
.$filename, $CFG->filepermissions
);
3846 * Remove cache files
3848 * @param int $expire The number of seconds before expiry
3850 public function cleanup($expire) {
3851 if ($dir = opendir($this->dir
)) {
3852 while (false !== ($file = readdir($dir))) {
3853 if(!is_dir($file) && $file != '.' && $file != '..') {
3854 $lasttime = @filemtime
($this->dir
.$file);
3855 if (time() - $lasttime > $expire) {
3856 @unlink
($this->dir
.$file);
3864 * delete current user's cache file
3866 * @global object $CFG
3867 * @global object $USER
3869 public function refresh() {
3871 if ($dir = opendir($this->dir
)) {
3872 while (false !== ($file = readdir($dir))) {
3873 if (!is_dir($file) && $file != '.' && $file != '..') {
3874 if (strpos($file, 'u'.$USER->id
.'_') !== false) {
3875 @unlink
($this->dir
.$file);
3884 * This function delegates file serving to individual plugins
3886 * @param string $relativepath
3887 * @param bool $forcedownload
3888 * @param null|string $preview the preview mode, defaults to serving the original file
3889 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
3890 * offline (e.g. mobile app).
3891 * @param bool $embed Whether this file will be served embed into an iframe.
3892 * @todo MDL-31088 file serving improments
3894 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
3895 global $DB, $CFG, $USER;
3896 // relative path must start with '/'
3897 if (!$relativepath) {
3898 print_error('invalidargorconf');
3899 } else if ($relativepath[0] != '/') {
3900 print_error('pathdoesnotstartslash');
3903 // extract relative path components
3904 $args = explode('/', ltrim($relativepath, '/'));
3906 if (count($args) < 3) { // always at least context, component and filearea
3907 print_error('invalidarguments');
3910 $contextid = (int)array_shift($args);
3911 $component = clean_param(array_shift($args), PARAM_COMPONENT
);
3912 $filearea = clean_param(array_shift($args), PARAM_AREA
);
3914 list($context, $course, $cm) = get_context_info_array($contextid);
3916 $fs = get_file_storage();
3918 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
3920 // ========================================================================================================================
3921 if ($component === 'blog') {
3922 // Blog file serving
3923 if ($context->contextlevel
!= CONTEXT_SYSTEM
) {
3924 send_file_not_found();
3926 if ($filearea !== 'attachment' and $filearea !== 'post') {
3927 send_file_not_found();
3930 if (empty($CFG->enableblogs
)) {
3931 print_error('siteblogdisable', 'blog');
3934 $entryid = (int)array_shift($args);
3935 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3936 send_file_not_found();
3938 if ($CFG->bloglevel
< BLOG_GLOBAL_LEVEL
) {
3940 if (isguestuser()) {
3941 print_error('noguest');
3943 if ($CFG->bloglevel
== BLOG_USER_LEVEL
) {
3944 if ($USER->id
!= $entry->userid
) {
3945 send_file_not_found();
3950 if ($entry->publishstate
=== 'public') {
3951 if ($CFG->forcelogin
) {
3955 } else if ($entry->publishstate
=== 'site') {
3958 } else if ($entry->publishstate
=== 'draft') {
3960 if ($USER->id
!= $entry->userid
) {
3961 send_file_not_found();
3965 $filename = array_pop($args);
3966 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
3968 if (!$file = $fs->get_file($context->id
, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3969 send_file_not_found();
3972 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
3974 // ========================================================================================================================
3975 } else if ($component === 'grade') {
3976 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel
== CONTEXT_SYSTEM
) {
3977 // Global gradebook files
3978 if ($CFG->forcelogin
) {
3982 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3984 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3985 send_file_not_found();
3988 \core\session\manager
::write_close(); // Unlock session during file serving.
3989 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
3991 } else if ($filearea === 'feedback' and $context->contextlevel
== CONTEXT_COURSE
) {
3992 //TODO: nobody implemented this yet in grade edit form!!
3993 send_file_not_found();
3995 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
3996 require_login($course);
3999 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4001 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4002 send_file_not_found();
4005 \core\session\manager
::write_close(); // Unlock session during file serving.
4006 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4008 send_file_not_found();
4011 // ========================================================================================================================
4012 } else if ($component === 'tag') {
4013 if ($filearea === 'description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
4015 // All tag descriptions are going to be public but we still need to respect forcelogin
4016 if ($CFG->forcelogin
) {
4020 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4022 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4023 send_file_not_found();
4026 \core\session\manager
::write_close(); // Unlock session during file serving.
4027 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4030 send_file_not_found();
4032 // ========================================================================================================================
4033 } else if ($component === 'badges') {
4034 require_once($CFG->libdir
. '/badgeslib.php');
4036 $badgeid = (int)array_shift($args);
4037 $badge = new badge($badgeid);
4038 $filename = array_pop($args);
4040 if ($filearea === 'badgeimage') {
4041 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4042 send_file_not_found();
4044 if (!$file = $fs->get_file($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $filename.'.png')) {
4045 send_file_not_found();
4048 \core\session\manager
::write_close();
4049 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4050 } else if ($filearea === 'userbadge' and $context->contextlevel
== CONTEXT_USER
) {
4051 if (!$file = $fs->get_file($context->id
, 'badges', 'userbadge', $badge->id
, '/', $filename.'.png')) {
4052 send_file_not_found();
4055 \core\session\manager
::write_close();
4056 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4058 // ========================================================================================================================
4059 } else if ($component === 'calendar') {
4060 if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
4062 // All events here are public the one requirement is that we respect forcelogin
4063 if ($CFG->forcelogin
) {
4067 // Get the event if from the args array
4068 $eventid = array_shift($args);
4070 // Load the event from the database
4071 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4072 send_file_not_found();
4075 // Get the file and serve if successful
4076 $filename = array_pop($args);
4077 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4078 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4079 send_file_not_found();
4082 \core\session\manager
::write_close(); // Unlock session during file serving.
4083 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4085 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_USER
) {
4087 // Must be logged in, if they are not then they obviously can't be this user
4090 // Don't want guests here, potentially saves a DB call
4091 if (isguestuser()) {
4092 send_file_not_found();
4095 // Get the event if from the args array
4096 $eventid = array_shift($args);
4098 // Load the event from the database - user id must match
4099 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id
, 'eventtype'=>'user'))) {
4100 send_file_not_found();
4103 // Get the file and serve if successful
4104 $filename = array_pop($args);
4105 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4106 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4107 send_file_not_found();
4110 \core\session\manager
::write_close(); // Unlock session during file serving.
4111 send_stored_file($file, 0, 0, true, $sendfileoptions);
4113 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_COURSE
) {
4115 // Respect forcelogin and require login unless this is the site.... it probably
4116 // should NEVER be the site
4117 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
4118 require_login($course);
4121 // Must be able to at least view the course. This does not apply to the front page.
4122 if ($course->id
!= SITEID
&& (!is_enrolled($context)) && (!is_viewing($context))) {
4123 //TODO: hmm, do we really want to block guests here?
4124 send_file_not_found();
4128 $eventid = array_shift($args);
4130 // Load the event from the database we need to check whether it is
4131 // a) valid course event
4133 // Group events use the course context (there is no group context)
4134 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id
))) {
4135 send_file_not_found();
4138 // If its a group event require either membership of view all groups capability
4139 if ($event->eventtype
=== 'group') {
4140 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid
, $USER->id
)) {
4141 send_file_not_found();
4143 } else if ($event->eventtype
=== 'course' ||
$event->eventtype
=== 'site') {
4144 // Ok. Please note that the event type 'site' still uses a course context.
4147 send_file_not_found();
4150 // If we get this far we can serve the file
4151 $filename = array_pop($args);
4152 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4153 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4154 send_file_not_found();
4157 \core\session\manager
::write_close(); // Unlock session during file serving.
4158 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4161 send_file_not_found();
4164 // ========================================================================================================================
4165 } else if ($component === 'user') {
4166 if ($filearea === 'icon' and $context->contextlevel
== CONTEXT_USER
) {
4167 if (count($args) == 1) {
4168 $themename = theme_config
::DEFAULT_THEME
;
4169 $filename = array_shift($args);
4171 $themename = array_shift($args);
4172 $filename = array_shift($args);
4175 // fix file name automatically
4176 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4180 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
4181 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
4182 // protect images if login required and not logged in;
4183 // also if login is required for profile images and is not logged in or guest
4184 // do not use require_login() because it is expensive and not suitable here anyway
4185 $theme = theme_config
::load($themename);
4186 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4189 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.png')) {
4190 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4191 if ($filename === 'f3') {
4192 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4193 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.png')) {
4194 $file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.jpg');
4200 // bad reference - try to prevent future retries as hard as possible!
4201 if ($user = $DB->get_record('user', array('id'=>$context->instanceid
), 'id, picture')) {
4202 if ($user->picture
> 0) {
4203 $DB->set_field('user', 'picture', 0, array('id'=>$user->id
));
4206 // no redirect here because it is not cached
4207 $theme = theme_config
::load($themename);
4208 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4209 send_file($imagefile, basename($imagefile), 60*60*24*14);
4212 $options = $sendfileoptions;
4213 if (empty($CFG->forcelogin
) && empty($CFG->forceloginforprofileimage
)) {
4214 // Profile images should be cache-able by both browsers and proxies according
4215 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4216 $options['cacheability'] = 'public';
4218 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4220 } else if ($filearea === 'private' and $context->contextlevel
== CONTEXT_USER
) {
4223 if (isguestuser()) {
4224 send_file_not_found();
4227 if ($USER->id
!== $context->instanceid
) {
4228 send_file_not_found();
4231 $filename = array_pop($args);
4232 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4233 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4234 send_file_not_found();
4237 \core\session\manager
::write_close(); // Unlock session during file serving.
4238 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4240 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_USER
) {
4242 if ($CFG->forcelogin
) {
4246 $userid = $context->instanceid
;
4248 if ($USER->id
== $userid) {
4249 // always can access own
4251 } else if (!empty($CFG->forceloginforprofiles
)) {
4254 if (isguestuser()) {
4255 send_file_not_found();
4258 // we allow access to site profile of all course contacts (usually teachers)
4259 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4260 send_file_not_found();
4264 if (has_capability('moodle/user:viewdetails', $context)) {
4267 $courses = enrol_get_my_courses();
4270 while (!$canview && count($courses) > 0) {
4271 $course = array_shift($courses);
4272 if (has_capability('moodle/user:viewdetails', context_course
::instance($course->id
))) {
4278 $filename = array_pop($args);
4279 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4280 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4281 send_file_not_found();
4284 \core\session\manager
::write_close(); // Unlock session during file serving.
4285 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4287 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_COURSE
) {
4288 $userid = (int)array_shift($args);
4289 $usercontext = context_user
::instance($userid);
4291 if ($CFG->forcelogin
) {
4295 if (!empty($CFG->forceloginforprofiles
)) {
4297 if (isguestuser()) {
4298 print_error('noguest');
4301 //TODO: review this logic of user profile access prevention
4302 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4303 print_error('usernotavailable');
4305 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4306 print_error('cannotviewprofile');
4308 if (!is_enrolled($context, $userid)) {
4309 print_error('notenrolledprofile');
4311 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
4312 print_error('groupnotamember');
4316 $filename = array_pop($args);
4317 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4318 if (!$file = $fs->get_file($usercontext->id
, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4319 send_file_not_found();
4322 \core\session\manager
::write_close(); // Unlock session during file serving.
4323 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4325 } else if ($filearea === 'backup' and $context->contextlevel
== CONTEXT_USER
) {
4328 if (isguestuser()) {
4329 send_file_not_found();
4331 $userid = $context->instanceid
;
4333 if ($USER->id
!= $userid) {
4334 send_file_not_found();
4337 $filename = array_pop($args);
4338 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4339 if (!$file = $fs->get_file($context->id
, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4340 send_file_not_found();
4343 \core\session\manager
::write_close(); // Unlock session during file serving.
4344 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4347 send_file_not_found();
4350 // ========================================================================================================================
4351 } else if ($component === 'coursecat') {
4352 if ($context->contextlevel
!= CONTEXT_COURSECAT
) {
4353 send_file_not_found();
4356 if ($filearea === 'description') {
4357 if ($CFG->forcelogin
) {
4358 // no login necessary - unless login forced everywhere
4362 // Check if user can view this category.
4363 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4364 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid
));
4365 if (!$coursecatvisible) {
4366 send_file_not_found();
4370 $filename = array_pop($args);
4371 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4372 if (!$file = $fs->get_file($context->id
, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4373 send_file_not_found();
4376 \core\session\manager
::write_close(); // Unlock session during file serving.
4377 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4379 send_file_not_found();
4382 // ========================================================================================================================
4383 } else if ($component === 'course') {
4384 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4385 send_file_not_found();
4388 if ($filearea === 'summary' ||
$filearea === 'overviewfiles') {
4389 if ($CFG->forcelogin
) {
4393 $filename = array_pop($args);
4394 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4395 if (!$file = $fs->get_file($context->id
, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4396 send_file_not_found();
4399 \core\session\manager
::write_close(); // Unlock session during file serving.
4400 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4402 } else if ($filearea === 'section') {
4403 if ($CFG->forcelogin
) {
4404 require_login($course);
4405 } else if ($course->id
!= SITEID
) {
4406 require_login($course);
4409 $sectionid = (int)array_shift($args);
4411 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id
))) {
4412 send_file_not_found();
4415 $filename = array_pop($args);
4416 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4417 if (!$file = $fs->get_file($context->id
, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4418 send_file_not_found();
4421 \core\session\manager
::write_close(); // Unlock session during file serving.
4422 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4425 send_file_not_found();
4428 } else if ($component === 'cohort') {
4430 $cohortid = (int)array_shift($args);
4431 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
4432 $cohortcontext = context
::instance_by_id($cohort->contextid
);
4434 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4435 if ($context->id
!= $cohort->contextid
&&
4436 ($context->contextlevel
!= CONTEXT_COURSE ||
!in_array($cohort->contextid
, $context->get_parent_context_ids()))) {
4437 send_file_not_found();
4440 // User is able to access cohort if they have view cap on cohort level or
4441 // the cohort is visible and they have view cap on course level.
4442 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4443 ($cohort->visible
&& has_capability('moodle/cohort:view', $context));
4445 if ($filearea === 'description' && $canview) {
4446 $filename = array_pop($args);
4447 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4448 if (($file = $fs->get_file($cohortcontext->id
, 'cohort', 'description', $cohort->id
, $filepath, $filename))
4449 && !$file->is_directory()) {
4450 \core\session\manager
::write_close(); // Unlock session during file serving.
4451 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4455 send_file_not_found();
4457 } else if ($component === 'group') {
4458 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4459 send_file_not_found();
4462 require_course_login($course, true, null, false);
4464 $groupid = (int)array_shift($args);
4466 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id
), '*', MUST_EXIST
);
4467 if (($course->groupmodeforce
and $course->groupmode
== SEPARATEGROUPS
) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id
, $USER->id
)) {
4468 // do not allow access to separate group info if not member or teacher
4469 send_file_not_found();
4472 if ($filearea === 'description') {
4474 require_login($course);
4476 $filename = array_pop($args);
4477 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4478 if (!$file = $fs->get_file($context->id
, 'group', 'description', $group->id
, $filepath, $filename) or $file->is_directory()) {
4479 send_file_not_found();
4482 \core\session\manager
::write_close(); // Unlock session during file serving.
4483 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4485 } else if ($filearea === 'icon') {
4486 $filename = array_pop($args);
4488 if ($filename !== 'f1' and $filename !== 'f2') {
4489 send_file_not_found();
4491 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.png')) {
4492 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.jpg')) {
4493 send_file_not_found();
4497 \core\session\manager
::write_close(); // Unlock session during file serving.
4498 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4501 send_file_not_found();
4504 } else if ($component === 'grouping') {
4505 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4506 send_file_not_found();
4509 require_login($course);
4511 $groupingid = (int)array_shift($args);
4513 // note: everybody has access to grouping desc images for now
4514 if ($filearea === 'description') {
4516 $filename = array_pop($args);
4517 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4518 if (!$file = $fs->get_file($context->id
, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4519 send_file_not_found();
4522 \core\session\manager
::write_close(); // Unlock session during file serving.
4523 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4526 send_file_not_found();
4529 // ========================================================================================================================
4530 } else if ($component === 'backup') {
4531 if ($filearea === 'course' and $context->contextlevel
== CONTEXT_COURSE
) {
4532 require_login($course);
4533 require_capability('moodle/backup:downloadfile', $context);
4535 $filename = array_pop($args);
4536 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4537 if (!$file = $fs->get_file($context->id
, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4538 send_file_not_found();
4541 \core\session\manager
::write_close(); // Unlock session during file serving.
4542 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4544 } else if ($filearea === 'section' and $context->contextlevel
== CONTEXT_COURSE
) {
4545 require_login($course);
4546 require_capability('moodle/backup:downloadfile', $context);
4548 $sectionid = (int)array_shift($args);
4550 $filename = array_pop($args);
4551 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4552 if (!$file = $fs->get_file($context->id
, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4553 send_file_not_found();
4556 \core\session\manager
::write_close();
4557 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4559 } else if ($filearea === 'activity' and $context->contextlevel
== CONTEXT_MODULE
) {
4560 require_login($course, false, $cm);
4561 require_capability('moodle/backup:downloadfile', $context);
4563 $filename = array_pop($args);
4564 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4565 if (!$file = $fs->get_file($context->id
, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4566 send_file_not_found();
4569 \core\session\manager
::write_close();
4570 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4572 } else if ($filearea === 'automated' and $context->contextlevel
== CONTEXT_COURSE
) {
4573 // Backup files that were generated by the automated backup systems.
4575 require_login($course);
4576 require_capability('moodle/site:config', $context);
4578 $filename = array_pop($args);
4579 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4580 if (!$file = $fs->get_file($context->id
, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4581 send_file_not_found();
4584 \core\session\manager
::write_close(); // Unlock session during file serving.
4585 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4588 send_file_not_found();
4591 // ========================================================================================================================
4592 } else if ($component === 'question') {
4593 require_once($CFG->libdir
. '/questionlib.php');
4594 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4595 send_file_not_found();
4597 // ========================================================================================================================
4598 } else if ($component === 'grading') {
4599 if ($filearea === 'description') {
4600 // files embedded into the form definition description
4602 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4605 } else if ($context->contextlevel
>= CONTEXT_COURSE
) {
4606 require_login($course, false, $cm);
4609 send_file_not_found();
4612 $formid = (int)array_shift($args);
4614 $sql = "SELECT ga.id
4615 FROM {grading_areas} ga
4616 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4617 WHERE gd.id = ? AND ga.contextid = ?";
4618 $areaid = $DB->get_field_sql($sql, array($formid, $context->id
), IGNORE_MISSING
);
4621 send_file_not_found();
4624 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4626 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4627 send_file_not_found();
4630 \core\session\manager
::write_close(); // Unlock session during file serving.
4631 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4634 // ========================================================================================================================
4635 } else if (strpos($component, 'mod_') === 0) {
4636 $modname = substr($component, 4);
4637 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4638 send_file_not_found();
4640 require_once("$CFG->dirroot/mod/$modname/lib.php");
4642 if ($context->contextlevel
== CONTEXT_MODULE
) {
4643 if ($cm->modname
!== $modname) {
4644 // somebody tries to gain illegal access, cm type must match the component!
4645 send_file_not_found();
4649 if ($filearea === 'intro') {
4650 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO
, true)) {
4651 send_file_not_found();
4654 // Require login to the course first (without login to the module).
4655 require_course_login($course, true);
4657 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4658 $cminfo = cm_info
::create($cm);
4659 if (!$cminfo->uservisible
) {
4660 if (!$cm->showdescription ||
!$cminfo->is_visible_on_course_page()) {
4661 // Module intro is not visible on the course page and module is not available, show access error.
4662 require_course_login($course, true, $cminfo);
4666 // all users may access it
4667 $filename = array_pop($args);
4668 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4669 if (!$file = $fs->get_file($context->id
, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4670 send_file_not_found();
4673 // finally send the file
4674 send_stored_file($file, null, 0, false, $sendfileoptions);
4677 $filefunction = $component.'_pluginfile';
4678 $filefunctionold = $modname.'_pluginfile';
4679 if (function_exists($filefunction)) {
4680 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4681 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4682 } else if (function_exists($filefunctionold)) {
4683 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4684 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4687 send_file_not_found();
4689 // ========================================================================================================================
4690 } else if (strpos($component, 'block_') === 0) {
4691 $blockname = substr($component, 6);
4692 // note: no more class methods in blocks please, that is ....
4693 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4694 send_file_not_found();
4696 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4698 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4699 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid
), '*',MUST_EXIST
);
4700 if ($birecord->blockname
!== $blockname) {
4701 // somebody tries to gain illegal access, cm type must match the component!
4702 send_file_not_found();
4705 if ($context->get_course_context(false)) {
4706 // If block is in course context, then check if user has capability to access course.
4707 require_course_login($course);
4708 } else if ($CFG->forcelogin
) {
4709 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4713 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id
, 'blockinstanceid' => $context->instanceid
));
4714 // User can't access file, if block is hidden or doesn't have block:view capability
4715 if (($bprecord && !$bprecord->visible
) ||
!has_capability('moodle/block:view', $context)) {
4716 send_file_not_found();
4722 $filefunction = $component.'_pluginfile';
4723 if (function_exists($filefunction)) {
4724 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4725 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4728 send_file_not_found();
4730 // ========================================================================================================================
4731 } else if (strpos($component, '_') === false) {
4732 // all core subsystems have to be specified above, no more guessing here!
4733 send_file_not_found();
4736 // try to serve general plugin file in arbitrary context
4737 $dir = core_component
::get_component_directory($component);
4738 if (!file_exists("$dir/lib.php")) {
4739 send_file_not_found();
4741 include_once("$dir/lib.php");
4743 $filefunction = $component.'_pluginfile';
4744 if (function_exists($filefunction)) {
4745 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4746 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4749 send_file_not_found();