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->pix_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->pix_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->pix_url(file_file_icon($file, 24))->out(false);
709 $item->thumbnail
= $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
710 if ($imageinfo = $file->get_imageinfo()) {
711 $item->realthumbnail
= $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
712 $item->realicon
= $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
713 $item->image_width
= $imageinfo['width'];
714 $item->image_height
= $imageinfo['height'];
720 $data->itemid
= $draftitemid;
726 * Returns draft area itemid for a given element.
729 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
730 * @return int the itemid, or 0 if there is not one yet.
732 function file_get_submitted_draft_itemid($elname) {
733 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
734 if (!isset($_REQUEST[$elname])) {
737 if (is_array($_REQUEST[$elname])) {
738 $param = optional_param_array($elname, 0, PARAM_INT
);
739 if (!empty($param['itemid'])) {
740 $param = $param['itemid'];
742 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER
);
747 $param = optional_param($elname, 0, PARAM_INT
);
758 * Restore the original source field from draft files
760 * Do not use this function because it makes field files.source inconsistent
761 * for draft area files. This function will be deprecated in 2.6
763 * @param stored_file $storedfile This only works with draft files
764 * @return stored_file
766 function file_restore_source_field_from_draft_file($storedfile) {
767 $source = @unserialize
($storedfile->get_source());
768 if (!empty($source)) {
769 if (is_object($source)) {
770 $restoredsource = $source->source
;
771 $storedfile->set_source($restoredsource);
773 throw new moodle_exception('invalidsourcefield', 'error');
779 * Saves files from a draft file area to a real one (merging the list of files).
780 * Can rewrite URLs in some content at the same time if desired.
783 * @global stdClass $USER
784 * @param int $draftitemid the id of the draft area to use. Normally obtained
785 * from file_get_submitted_draft_itemid('elementname') or similar.
786 * @param int $contextid This parameter and the next two identify the file area to save to.
787 * @param string $component
788 * @param string $filearea indentifies the file area.
789 * @param int $itemid helps identifies the file area.
790 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
791 * @param string $text some html content that needs to have embedded links rewritten
792 * to the @@PLUGINFILE@@ form for saving in the database.
793 * @param bool $forcehttps force https urls.
794 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
796 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
799 $usercontext = context_user
::instance($USER->id
);
800 $fs = get_file_storage();
802 $options = (array)$options;
803 if (!isset($options['subdirs'])) {
804 $options['subdirs'] = false;
806 if (!isset($options['maxfiles'])) {
807 $options['maxfiles'] = -1; // unlimited
809 if (!isset($options['maxbytes']) ||
$options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
810 $options['maxbytes'] = 0; // unlimited
812 if (!isset($options['areamaxbytes'])) {
813 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED
; // Unlimited.
815 $allowreferences = true;
816 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE
)) {
817 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
818 // this is not exactly right. BUT there are many places in code where filemanager options
819 // are not passed to file_save_draft_area_files()
820 $allowreferences = false;
823 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
824 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
825 // anything at all in the next area.
826 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
830 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id');
831 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
833 // One file in filearea means it is empty (it has only top-level directory '.').
834 if (count($draftfiles) > 1 ||
count($oldfiles) > 1) {
835 // we have to merge old and new files - we want to keep file ids for files that were not changed
836 // we change time modified for all new and changed files, we keep time created as is
838 $newhashes = array();
840 foreach ($draftfiles as $file) {
841 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
844 if (!$allowreferences && $file->is_external_file()) {
847 if (!$file->is_directory()) {
848 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
849 // oversized file - should not get here at all
852 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
853 // more files - should not get here at all
858 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
859 $newhashes[$newhash] = $file;
862 // Loop through oldfiles and decide which we need to delete and which to update.
863 // After this cycle the array $newhashes will only contain the files that need to be added.
864 foreach ($oldfiles as $oldfile) {
865 $oldhash = $oldfile->get_pathnamehash();
866 if (!isset($newhashes[$oldhash])) {
867 // delete files not needed any more - deleted by user
872 $newfile = $newhashes[$oldhash];
873 // Now we know that we have $oldfile and $newfile for the same path.
874 // Let's check if we can update this file or we need to delete and create.
875 if ($newfile->is_directory()) {
876 // Directories are always ok to just update.
877 } else if (($source = @unserialize
($newfile->get_source())) && isset($source->original
)) {
878 // File has the 'original' - we need to update the file (it may even have not been changed at all).
879 $original = file_storage
::unpack_reference($source->original
);
880 if ($original['filename'] !== $oldfile->get_filename() ||
$original['filepath'] !== $oldfile->get_filepath()) {
881 // Very odd, original points to another file. Delete and create file.
886 // The same file name but absence of 'original' means that file was deteled and uploaded again.
887 // By deleting and creating new file we properly manage all existing references.
892 // status changed, we delete old file, and create a new one
893 if ($oldfile->get_status() != $newfile->get_status()) {
894 // file was changed, use updated with new timemodified data
896 // This file will be added later
901 if ($oldfile->get_author() != $newfile->get_author()) {
902 $oldfile->set_author($newfile->get_author());
905 if ($oldfile->get_license() != $newfile->get_license()) {
906 $oldfile->set_license($newfile->get_license());
909 // Updated file source
910 // Field files.source for draftarea files contains serialised object with source and original information.
911 // We only store the source part of it for non-draft file area.
912 $newsource = $newfile->get_source();
913 if ($source = @unserialize
($newfile->get_source())) {
914 $newsource = $source->source
;
916 if ($oldfile->get_source() !== $newsource) {
917 $oldfile->set_source($newsource);
920 // Updated sort order
921 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
922 $oldfile->set_sortorder($newfile->get_sortorder());
925 // Update file timemodified
926 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
927 $oldfile->set_timemodified($newfile->get_timemodified());
930 // Replaced file content
931 if (!$oldfile->is_directory() &&
932 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
933 $oldfile->get_filesize() != $newfile->get_filesize() ||
934 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
935 $oldfile->get_userid() != $newfile->get_userid())) {
936 $oldfile->replace_file_with($newfile);
939 // unchanged file or directory - we keep it as is
940 unset($newhashes[$oldhash]);
943 // Add fresh file or the file which has changed status
944 // the size and subdirectory tests are extra safety only, the UI should prevent it
945 foreach ($newhashes as $file) {
946 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
947 if ($source = @unserialize
($file->get_source())) {
948 // Field files.source for draftarea files contains serialised object with source and original information.
949 // We only store the source part of it for non-draft file area.
950 $file_record['source'] = $source->source
;
953 if ($file->is_external_file()) {
954 $repoid = $file->get_repository_id();
955 if (!empty($repoid)) {
956 $file_record['repositoryid'] = $repoid;
957 $file_record['reference'] = $file->get_reference();
961 $fs->create_file_from_storedfile($file_record, $file);
965 // note: do not purge the draft area - we clean up areas later in cron,
966 // the reason is that user might press submit twice and they would loose the files,
967 // also sometimes we might want to use hacks that save files into two different areas
969 if (is_null($text)) {
972 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
977 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
978 * ready to be saved in the database. Normally, this is done automatically by
979 * {@link file_save_draft_area_files()}.
982 * @param string $text the content to process.
983 * @param int $draftitemid the draft file area the content was using.
984 * @param bool $forcehttps whether the content contains https URLs. Default false.
985 * @return string the processed content.
987 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
990 $usercontext = context_user
::instance($USER->id
);
992 $wwwroot = $CFG->wwwroot
;
994 $wwwroot = str_replace('http://', 'https://', $wwwroot);
997 // relink embedded files if text submitted - no absolute links allowed in database!
998 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1000 if (strpos($text, 'draftfile.php?file=') !== false) {
1002 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1004 foreach ($matches[0] as $match) {
1005 $replace = str_ireplace('%2F', '/', $match);
1006 $text = str_replace($match, $replace, $text);
1009 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1016 * Set file sort order
1018 * @global moodle_database $DB
1019 * @param int $contextid the context id
1020 * @param string $component file component
1021 * @param string $filearea file area.
1022 * @param int $itemid itemid.
1023 * @param string $filepath file path.
1024 * @param string $filename file name.
1025 * @param int $sortorder the sort order of file.
1028 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1030 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1031 if ($file_record = $DB->get_record('files', $conditions)) {
1032 $sortorder = (int)$sortorder;
1033 $file_record->sortorder
= $sortorder;
1034 $DB->update_record('files', $file_record);
1041 * reset file sort order number to 0
1042 * @global moodle_database $DB
1043 * @param int $contextid the context id
1044 * @param string $component
1045 * @param string $filearea file area.
1046 * @param int|bool $itemid itemid.
1049 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1052 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1053 if ($itemid !== false) {
1054 $conditions['itemid'] = $itemid;
1057 $file_records = $DB->get_records('files', $conditions);
1058 foreach ($file_records as $file_record) {
1059 $file_record->sortorder
= 0;
1060 $DB->update_record('files', $file_record);
1066 * Returns description of upload error
1068 * @param int $errorcode found in $_FILES['filename.ext']['error']
1069 * @return string error description string, '' if ok
1071 function file_get_upload_error($errorcode) {
1073 switch ($errorcode) {
1074 case 0: // UPLOAD_ERR_OK - no error
1078 case 1: // UPLOAD_ERR_INI_SIZE
1079 $errmessage = get_string('uploadserverlimit');
1082 case 2: // UPLOAD_ERR_FORM_SIZE
1083 $errmessage = get_string('uploadformlimit');
1086 case 3: // UPLOAD_ERR_PARTIAL
1087 $errmessage = get_string('uploadpartialfile');
1090 case 4: // UPLOAD_ERR_NO_FILE
1091 $errmessage = get_string('uploadnofilefound');
1094 // Note: there is no error with a value of 5
1096 case 6: // UPLOAD_ERR_NO_TMP_DIR
1097 $errmessage = get_string('uploadnotempdir');
1100 case 7: // UPLOAD_ERR_CANT_WRITE
1101 $errmessage = get_string('uploadcantwrite');
1104 case 8: // UPLOAD_ERR_EXTENSION
1105 $errmessage = get_string('uploadextension');
1109 $errmessage = get_string('uploadproblem');
1116 * Recursive function formating an array in POST parameter
1117 * @param array $arraydata - the array that we are going to format and add into &$data array
1118 * @param string $currentdata - a row of the final postdata array at instant T
1119 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1120 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1122 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1123 foreach ($arraydata as $k=>$v) {
1124 $newcurrentdata = $currentdata;
1125 if (is_array($v)) { //the value is an array, call the function recursively
1126 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1127 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1128 } else { //add the POST parameter to the $data array
1129 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1135 * Transform a PHP array into POST parameter
1136 * (see the recursive function format_array_postdata_for_curlcall)
1137 * @param array $postdata
1138 * @return array containing all POST parameters (1 row = 1 POST parameter)
1140 function format_postdata_for_curlcall($postdata) {
1142 foreach ($postdata as $k=>$v) {
1144 $currentdata = urlencode($k);
1145 format_array_postdata_for_curlcall($v, $currentdata, $data);
1147 $data[] = urlencode($k).'='.urlencode($v);
1150 $convertedpostdata = implode('&', $data);
1151 return $convertedpostdata;
1155 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1156 * Due to security concerns only downloads from http(s) sources are supported.
1159 * @param string $url file url starting with http(s)://
1160 * @param array $headers http headers, null if none. If set, should be an
1161 * associative array of header name => value pairs.
1162 * @param array $postdata array means use POST request with given parameters
1163 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1164 * (if false, just returns content)
1165 * @param int $timeout timeout for complete download process including all file transfer
1166 * (default 5 minutes)
1167 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1168 * usually happens if the remote server is completely down (default 20 seconds);
1169 * may not work when using proxy
1170 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1171 * Only use this when already in a trusted location.
1172 * @param string $tofile store the downloaded content to file instead of returning it.
1173 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1174 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1175 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1176 * if file downloaded into $tofile successfully or the file content as a string.
1178 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1181 // Only http and https links supported.
1182 if (!preg_match('|^https?://|i', $url)) {
1183 if ($fullresponse) {
1184 $response = new stdClass();
1185 $response->status
= 0;
1186 $response->headers
= array();
1187 $response->response_code
= 'Invalid protocol specified in url';
1188 $response->results
= '';
1189 $response->error
= 'Invalid protocol specified in url';
1198 $headers2 = array();
1199 if (is_array($headers)) {
1200 foreach ($headers as $key => $value) {
1201 if (is_numeric($key)) {
1202 $headers2[] = $value;
1204 $headers2[] = "$key: $value";
1209 if ($skipcertverify) {
1210 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1212 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1215 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1217 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1218 $options['CURLOPT_MAXREDIRS'] = 5;
1220 // Use POST if requested.
1221 if (is_array($postdata)) {
1222 $postdata = format_postdata_for_curlcall($postdata);
1223 } else if (empty($postdata)) {
1227 // Optionally attempt to get more correct timeout by fetching the file size.
1228 if (!isset($CFG->curltimeoutkbitrate
)) {
1229 // Use very slow rate of 56kbps as a timeout speed when not set.
1232 $bitrate = $CFG->curltimeoutkbitrate
;
1234 if ($calctimeout and !isset($postdata)) {
1236 $curl->setHeader($headers2);
1238 $curl->head($url, $postdata, $options);
1240 $info = $curl->get_info();
1241 $error_no = $curl->get_errno();
1242 if (!$error_no && $info['download_content_length'] > 0) {
1243 // No curl errors - adjust for large files only - take max timeout.
1244 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1249 $curl->setHeader($headers2);
1251 $options['CURLOPT_RETURNTRANSFER'] = true;
1252 $options['CURLOPT_NOBODY'] = false;
1253 $options['CURLOPT_TIMEOUT'] = $timeout;
1256 $fh = fopen($tofile, 'w');
1258 if ($fullresponse) {
1259 $response = new stdClass();
1260 $response->status
= 0;
1261 $response->headers
= array();
1262 $response->response_code
= 'Can not write to file';
1263 $response->results
= false;
1264 $response->error
= 'Can not write to file';
1270 $options['CURLOPT_FILE'] = $fh;
1273 if (isset($postdata)) {
1274 $content = $curl->post($url, $postdata, $options);
1276 $content = $curl->get($url, null, $options);
1281 @chmod
($tofile, $CFG->filepermissions
);
1285 // Try to detect encoding problems.
1286 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1287 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1288 $result = curl_exec($ch);
1292 $info = $curl->get_info();
1293 $error_no = $curl->get_errno();
1294 $rawheaders = $curl->get_raw_response();
1298 if (!$fullresponse) {
1299 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
1303 $response = new stdClass();
1304 if ($error_no == 28) {
1305 $response->status
= '-100'; // Mimic snoopy.
1307 $response->status
= '0';
1309 $response->headers
= array();
1310 $response->response_code
= $error;
1311 $response->results
= false;
1312 $response->error
= $error;
1320 if (empty($info['http_code'])) {
1321 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1322 $response = new stdClass();
1323 $response->status
= '0';
1324 $response->headers
= array();
1325 $response->response_code
= 'Unknown cURL error';
1326 $response->results
= false; // do NOT change this, we really want to ignore the result!
1327 $response->error
= 'Unknown cURL error';
1330 $response = new stdClass();
1331 $response->status
= (string)$info['http_code'];
1332 $response->headers
= $rawheaders;
1333 $response->results
= $content;
1334 $response->error
= '';
1336 // There might be multiple headers on redirect, find the status of the last one.
1338 foreach ($rawheaders as $line) {
1340 $response->response_code
= $line;
1343 if (trim($line, "\r\n") === '') {
1349 if ($fullresponse) {
1353 if ($info['http_code'] != 200) {
1354 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
1357 return $response->results
;
1361 * Returns a list of information about file types based on extensions.
1363 * The following elements expected in value array for each extension:
1365 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1366 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1367 * also files with bigger sizes under names
1368 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1369 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1370 * commonly used in moodle the following groups:
1371 * - web_image - image that can be included as <img> in HTML
1372 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1373 * - video - file that can be imported as video in text editor
1374 * - audio - file that can be imported as audio in text editor
1375 * - archive - we can extract files from this archive
1376 * - spreadsheet - used for portfolio format
1377 * - document - used for portfolio format
1378 * - presentation - used for portfolio format
1379 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1380 * human-readable description for this filetype;
1381 * Function {@link get_mimetype_description()} first looks at the presence of string for
1382 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1383 * attribute, if not found returns the value of 'type';
1384 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1385 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1386 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1389 * @return array List of information about file types based on extensions.
1390 * Associative array of extension (lower-case) to associative array
1391 * from 'element name' to data. Current element names are 'type' and 'icon'.
1392 * Unknown types should use the 'xxx' entry which includes defaults.
1394 function &get_mimetypes_array() {
1395 // Get types from the core_filetypes function, which includes caching.
1396 return core_filetypes
::get_types();
1400 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1402 * This function retrieves a file's MIME type for a file that will be sent to the user.
1403 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1404 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1405 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1407 * @param string $filename The file's filename.
1408 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1410 function get_mimetype_for_sending($filename = '') {
1411 // Guess the file's MIME type using mimeinfo.
1412 $mimetype = mimeinfo('type', $filename);
1414 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1415 if (!$mimetype ||
$mimetype === 'document/unknown') {
1416 $mimetype = 'application/octet-stream';
1423 * Obtains information about a filetype based on its extension. Will
1424 * use a default if no information is present about that particular
1428 * @param string $element Desired information (usually 'icon'
1429 * for icon filename or 'type' for MIME type. Can also be
1430 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1431 * @param string $filename Filename we're looking up
1432 * @return string Requested piece of information from array
1434 function mimeinfo($element, $filename) {
1436 $mimeinfo = & get_mimetypes_array();
1437 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1439 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1440 if (empty($filetype)) {
1441 $filetype = 'xxx'; // file without extension
1443 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1444 $iconsize = max(array(16, (int)$iconsizematch[1]));
1445 $filenames = array($mimeinfo['xxx']['icon']);
1446 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1447 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1449 // find the file with the closest size, first search for specific icon then for default icon
1450 foreach ($filenames as $filename) {
1451 foreach ($iconpostfixes as $size => $postfix) {
1452 $fullname = $CFG->dirroot
.'/pix/f/'.$filename.$postfix;
1453 if ($iconsize >= $size && (file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1454 return $filename.$postfix;
1458 } else if (isset($mimeinfo[$filetype][$element])) {
1459 return $mimeinfo[$filetype][$element];
1460 } else if (isset($mimeinfo['xxx'][$element])) {
1461 return $mimeinfo['xxx'][$element]; // By default
1468 * Obtains information about a filetype based on the MIME type rather than
1469 * the other way around.
1472 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1473 * @param string $mimetype MIME type we're looking up
1474 * @return string Requested piece of information from array
1476 function mimeinfo_from_type($element, $mimetype) {
1477 /* array of cached mimetype->extension associations */
1478 static $cached = array();
1479 $mimeinfo = & get_mimetypes_array();
1481 if (!array_key_exists($mimetype, $cached)) {
1482 $cached[$mimetype] = null;
1483 foreach($mimeinfo as $filetype => $values) {
1484 if ($values['type'] == $mimetype) {
1485 if ($cached[$mimetype] === null) {
1486 $cached[$mimetype] = '.'.$filetype;
1488 if (!empty($values['defaulticon'])) {
1489 $cached[$mimetype] = '.'.$filetype;
1494 if (empty($cached[$mimetype])) {
1495 $cached[$mimetype] = '.xxx';
1498 if ($element === 'extension') {
1499 return $cached[$mimetype];
1501 return mimeinfo($element, $cached[$mimetype]);
1506 * Return the relative icon path for a given file
1510 * // $file - instance of stored_file or file_info
1511 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1512 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1516 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1519 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1520 * and $file->mimetype are expected)
1521 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1524 function file_file_icon($file, $size = null) {
1525 if (!is_object($file)) {
1526 $file = (object)$file;
1528 if (isset($file->filename
)) {
1529 $filename = $file->filename
;
1530 } else if (method_exists($file, 'get_filename')) {
1531 $filename = $file->get_filename();
1532 } else if (method_exists($file, 'get_visible_name')) {
1533 $filename = $file->get_visible_name();
1537 if (isset($file->mimetype
)) {
1538 $mimetype = $file->mimetype
;
1539 } else if (method_exists($file, 'get_mimetype')) {
1540 $mimetype = $file->get_mimetype();
1544 $mimetypes = &get_mimetypes_array();
1546 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1547 if ($extension && !empty($mimetypes[$extension])) {
1548 // if file name has known extension, return icon for this extension
1549 return file_extension_icon($filename, $size);
1552 return file_mimetype_icon($mimetype, $size);
1556 * Return the relative icon path for a folder image
1560 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1561 * echo html_writer::empty_tag('img', array('src' => $icon));
1565 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1568 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1571 function file_folder_icon($iconsize = null) {
1573 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1574 static $cached = array();
1575 $iconsize = max(array(16, (int)$iconsize));
1576 if (!array_key_exists($iconsize, $cached)) {
1577 foreach ($iconpostfixes as $size => $postfix) {
1578 $fullname = $CFG->dirroot
.'/pix/f/folder'.$postfix;
1579 if ($iconsize >= $size && (file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1580 $cached[$iconsize] = 'f/folder'.$postfix;
1585 return $cached[$iconsize];
1589 * Returns the relative icon path for a given mime type
1591 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1592 * a return the full path to an icon.
1595 * $mimetype = 'image/jpg';
1596 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1597 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1601 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1602 * to conform with that.
1603 * @param string $mimetype The mimetype to fetch an icon for
1604 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1605 * @return string The relative path to the icon
1607 function file_mimetype_icon($mimetype, $size = NULL) {
1608 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1612 * Returns the relative icon path for a given file name
1614 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1615 * a return the full path to an icon.
1618 * $filename = '.jpg';
1619 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1620 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1623 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1624 * to conform with that.
1625 * @todo MDL-31074 Implement $size
1627 * @param string $filename The filename to get the icon for
1628 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1631 function file_extension_icon($filename, $size = NULL) {
1632 return 'f/'.mimeinfo('icon'.$size, $filename);
1636 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1637 * mimetypes.php language file.
1639 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1640 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1641 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1642 * @param bool $capitalise If true, capitalises first character of result
1643 * @return string Text description
1645 function get_mimetype_description($obj, $capitalise=false) {
1646 $filename = $mimetype = '';
1647 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1648 // this is an instance of stored_file
1649 $mimetype = $obj->get_mimetype();
1650 $filename = $obj->get_filename();
1651 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1652 // this is an instance of file_info
1653 $mimetype = $obj->get_mimetype();
1654 $filename = $obj->get_visible_name();
1655 } else if (is_array($obj) ||
is_object ($obj)) {
1657 if (!empty($obj['filename'])) {
1658 $filename = $obj['filename'];
1660 if (!empty($obj['mimetype'])) {
1661 $mimetype = $obj['mimetype'];
1666 $mimetypefromext = mimeinfo('type', $filename);
1667 if (empty($mimetype) ||
$mimetypefromext !== 'document/unknown') {
1668 // if file has a known extension, overwrite the specified mimetype
1669 $mimetype = $mimetypefromext;
1671 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1672 if (empty($extension)) {
1673 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1674 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1676 $mimetypestr = mimeinfo('string', $filename);
1678 $chunks = explode('/', $mimetype, 2);
1681 'mimetype' => $mimetype,
1682 'ext' => $extension,
1683 'mimetype1' => $chunks[0],
1684 'mimetype2' => $chunks[1],
1687 foreach ($attr as $key => $value) {
1689 $a[strtoupper($key)] = strtoupper($value);
1690 $a[ucfirst($key)] = ucfirst($value);
1693 // MIME types may include + symbol but this is not permitted in string ids.
1694 $safemimetype = str_replace('+', '_', $mimetype);
1695 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1696 $customdescription = mimeinfo('customdescription', $filename);
1697 if ($customdescription) {
1698 // Call format_string on the custom description so that multilang
1699 // filter can be used (if enabled on system context). We use system
1700 // context because it is possible that the page context might not have
1701 // been defined yet.
1702 $result = format_string($customdescription, true,
1703 array('context' => context_system
::instance()));
1704 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1705 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1706 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1707 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1708 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1709 $result = get_string('default', 'mimetypes', (object)$a);
1711 $result = $mimetype;
1714 $result=ucfirst($result);
1720 * Returns array of elements of type $element in type group(s)
1722 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1723 * @param string|array $groups one group or array of groups/extensions/mimetypes
1726 function file_get_typegroup($element, $groups) {
1727 static $cached = array();
1728 if (!is_array($groups)) {
1729 $groups = array($groups);
1731 if (!array_key_exists($element, $cached)) {
1732 $cached[$element] = array();
1735 foreach ($groups as $group) {
1736 if (!array_key_exists($group, $cached[$element])) {
1737 // retrieive and cache all elements of type $element for group $group
1738 $mimeinfo = & get_mimetypes_array();
1739 $cached[$element][$group] = array();
1740 foreach ($mimeinfo as $extension => $value) {
1741 $value['extension'] = '.'.$extension;
1742 if (empty($value[$element])) {
1745 if (($group === '.'.$extension ||
$group === $value['type'] ||
1746 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1747 !in_array($value[$element], $cached[$element][$group])) {
1748 $cached[$element][$group][] = $value[$element];
1752 $result = array_merge($result, $cached[$element][$group]);
1754 return array_values(array_unique($result));
1758 * Checks if file with name $filename has one of the extensions in groups $groups
1760 * @see get_mimetypes_array()
1761 * @param string $filename name of the file to check
1762 * @param string|array $groups one group or array of groups to check
1763 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1764 * file mimetype is in mimetypes in groups $groups
1767 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1768 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
1769 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1772 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1776 * Checks if mimetype $mimetype belongs to one of the groups $groups
1778 * @see get_mimetypes_array()
1779 * @param string $mimetype
1780 * @param string|array $groups one group or array of groups to check
1783 function file_mimetype_in_typegroup($mimetype, $groups) {
1784 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1788 * Requested file is not found or not accessible, does not return, terminates script
1790 * @global stdClass $CFG
1791 * @global stdClass $COURSE
1793 function send_file_not_found() {
1794 global $CFG, $COURSE;
1796 // Allow cross-origin requests only for Web Services.
1797 // This allow to receive requests done by Web Workers or webapps in different domains.
1799 header('Access-Control-Allow-Origin: *');
1803 print_error('filenotfound', 'error', $CFG->wwwroot
.'/course/view.php?id='.$COURSE->id
); //this is not displayed on IIS??
1806 * Helper function to send correct 404 for server.
1808 function send_header_404() {
1809 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1810 header("Status: 404 Not Found");
1812 header('HTTP/1.0 404 not found');
1817 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1818 * platforms). This wrapper uses readfile for small files and custom code for
1821 * @param string $path Path to file
1822 * @param int $filesize Size of file (if left out, will get it automatically)
1823 * @return int|bool Size read (will always be $filesize) or false if failed
1825 function readfile_allow_large($path, $filesize = -1) {
1826 // Automatically get size if not specified.
1827 if ($filesize === -1) {
1828 $filesize = filesize($path);
1830 if ($filesize <= 2147483647) {
1831 // If the file is up to 2^31 - 1, send it normally using readfile.
1832 return readfile($path);
1834 // For large files, read and output in 64KB chunks.
1835 $handle = fopen($path, 'r');
1836 if ($handle === false) {
1841 $size = min($left, 65536);
1842 $buffer = fread($handle, $size);
1843 if ($buffer === false) {
1854 * Enhanced readfile() with optional acceleration.
1855 * @param string|stored_file $file
1856 * @param string $mimetype
1857 * @param bool $accelerate
1860 function readfile_accel($file, $mimetype, $accelerate) {
1863 if ($mimetype === 'text/plain') {
1864 // there is no encoding specified in text files, we need something consistent
1865 header('Content-Type: text/plain; charset=utf-8');
1867 header('Content-Type: '.$mimetype);
1870 $lastmodified = is_object($file) ?
$file->get_timemodified() : filemtime($file);
1871 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1873 if (is_object($file)) {
1874 header('Etag: "' . $file->get_contenthash() . '"');
1875 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1876 header('HTTP/1.1 304 Not Modified');
1881 // if etag present for stored file rely on it exclusively
1882 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1883 // get unixtime of request header; clip extra junk off first
1884 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1885 if ($since && $since >= $lastmodified) {
1886 header('HTTP/1.1 304 Not Modified');
1891 if ($accelerate and !empty($CFG->xsendfile
)) {
1892 if (empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
1893 header('Accept-Ranges: bytes');
1895 header('Accept-Ranges: none');
1898 if (is_object($file)) {
1899 $fs = get_file_storage();
1900 if ($fs->xsendfile($file->get_contenthash())) {
1905 require_once("$CFG->libdir/xsendfilelib.php");
1906 if (xsendfile($file)) {
1912 $filesize = is_object($file) ?
$file->get_filesize() : filesize($file);
1914 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1916 if ($accelerate and empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
1917 header('Accept-Ranges: bytes');
1919 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1920 // byteserving stuff - for acrobat reader and download accelerators
1921 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1922 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1924 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
1925 foreach ($ranges as $key=>$value) {
1926 if ($ranges[$key][1] == '') {
1928 $ranges[$key][1] = $filesize - $ranges[$key][2];
1929 $ranges[$key][2] = $filesize - 1;
1930 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
1932 $ranges[$key][2] = $filesize - 1;
1934 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1935 //invalid byte-range ==> ignore header
1939 //prepare multipart header
1940 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
1941 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1947 if (is_object($file)) {
1948 $handle = $file->get_content_file_handle();
1950 $handle = fopen($file, 'rb');
1952 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1957 header('Accept-Ranges: none');
1960 header('Content-Length: '.$filesize);
1962 if ($filesize > 10000000) {
1963 // for large files try to flush and close all buffers to conserve memory
1964 while(@ob_get_level
()) {
1965 if (!@ob_end_flush
()) {
1971 // send the whole file content
1972 if (is_object($file)) {
1975 readfile_allow_large($file, $filesize);
1980 * Similar to readfile_accel() but designed for strings.
1981 * @param string $string
1982 * @param string $mimetype
1983 * @param bool $accelerate
1986 function readstring_accel($string, $mimetype, $accelerate) {
1989 if ($mimetype === 'text/plain') {
1990 // there is no encoding specified in text files, we need something consistent
1991 header('Content-Type: text/plain; charset=utf-8');
1993 header('Content-Type: '.$mimetype);
1995 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
1996 header('Accept-Ranges: none');
1998 if ($accelerate and !empty($CFG->xsendfile
)) {
1999 $fs = get_file_storage();
2000 if ($fs->xsendfile(sha1($string))) {
2005 header('Content-Length: '.strlen($string));
2010 * Handles the sending of temporary file to user, download is forced.
2011 * File is deleted after abort or successful sending, does not return, script terminated
2013 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2014 * @param string $filename proposed file name when saving file
2015 * @param bool $pathisstring If the path is string
2017 function send_temp_file($path, $filename, $pathisstring=false) {
2020 // Guess the file's MIME type.
2021 $mimetype = get_mimetype_for_sending($filename);
2023 // close session - not needed anymore
2024 \core\session\manager
::write_close();
2026 if (!$pathisstring) {
2027 if (!file_exists($path)) {
2029 print_error('filenotfound', 'error', $CFG->wwwroot
.'/');
2031 // executed after normal finish or abort
2032 core_shutdown_manager
::register_function('send_temp_file_finished', array($path));
2035 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2036 if (core_useragent
::is_ie()) {
2037 $filename = urlencode($filename);
2040 header('Content-Disposition: attachment; filename="'.$filename.'"');
2041 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2042 header('Cache-Control: private, max-age=10, no-transform');
2043 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2045 } else { //normal http - prevent caching at all cost
2046 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2047 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2048 header('Pragma: no-cache');
2051 // send the contents - we can not accelerate this because the file will be deleted asap
2052 if ($pathisstring) {
2053 readstring_accel($path, $mimetype, false);
2055 readfile_accel($path, $mimetype, false);
2059 die; //no more chars to output
2063 * Internal callback function used by send_temp_file()
2065 * @param string $path
2067 function send_temp_file_finished($path) {
2068 if (file_exists($path)) {
2074 * Serve content which is not meant to be cached.
2076 * This is only intended to be used for volatile public files, for instance
2077 * when development is enabled, or when caching is not required on a public resource.
2079 * @param string $content Raw content.
2080 * @param string $filename The file name.
2083 function send_content_uncached($content, $filename) {
2084 $mimetype = mimeinfo('type', $filename);
2085 $charset = strpos($mimetype, 'text/') === 0 ?
'; charset=utf-8' : '';
2087 header('Content-Disposition: inline; filename="' . $filename . '"');
2088 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2089 header('Expires: ' . gmdate('D, d M Y H:i:s', time() +
2) . ' GMT');
2091 header('Accept-Ranges: none');
2092 header('Content-Type: ' . $mimetype . $charset);
2093 header('Content-Length: ' . strlen($content));
2100 * Safely save content to a certain path.
2102 * This function tries hard to be atomic by first copying the content
2103 * to a separate file, and then moving the file across. It also prevents
2104 * the user to abort a request to prevent half-safed files.
2106 * This function is intended to be used when saving some content to cache like
2107 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2109 * @param string $content The file content.
2110 * @param string $destination The absolute path of the final file.
2113 function file_safe_save_content($content, $destination) {
2117 if (!file_exists(dirname($destination))) {
2118 @mkdir
(dirname($destination), $CFG->directorypermissions
, true);
2121 // Prevent serving of incomplete file from concurrent request,
2122 // the rename() should be more atomic than fwrite().
2123 ignore_user_abort(true);
2124 if ($fp = fopen($destination . '.tmp', 'xb')) {
2125 fwrite($fp, $content);
2127 rename($destination . '.tmp', $destination);
2128 @chmod
($destination, $CFG->filepermissions
);
2129 @unlink
($destination . '.tmp'); // Just in case anything fails.
2131 ignore_user_abort(false);
2132 if (connection_aborted()) {
2138 * Handles the sending of file data to the user's browser, including support for
2142 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2143 * @param string $filename Filename to send
2144 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2145 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2146 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2147 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2148 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2149 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2150 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2151 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2152 * and should not be reopened.
2153 * @param array $options An array of options, currently accepts:
2154 * - (string) cacheability: public, or private.
2155 * @return null script execution stopped unless $dontdie is true
2157 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2158 $dontdie=false, array $options = array()) {
2159 global $CFG, $COURSE;
2162 ignore_user_abort(true);
2165 if ($lifetime === 'default' or is_null($lifetime)) {
2166 $lifetime = $CFG->filelifetime
;
2169 \core\session\manager
::write_close(); // Unlock session during file serving.
2171 // Use given MIME type if specified, otherwise guess it.
2172 if (!$mimetype ||
$mimetype === 'document/unknown') {
2173 $mimetype = get_mimetype_for_sending($filename);
2176 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2177 if (core_useragent
::is_ie()) {
2178 $filename = rawurlencode($filename);
2181 if ($forcedownload) {
2182 header('Content-Disposition: attachment; filename="'.$filename.'"');
2183 } else if ($mimetype !== 'application/x-shockwave-flash') {
2184 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2185 // as an upload and enforces security that may prevent the file from being loaded.
2187 header('Content-Disposition: inline; filename="'.$filename.'"');
2190 if ($lifetime > 0) {
2191 $cacheability = ' public,';
2192 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2193 // This file must be cache-able by both browsers and proxies.
2194 $cacheability = ' public,';
2195 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2196 // This file must be cache-able only by browsers.
2197 $cacheability = ' private,';
2198 } else if (isloggedin() and !isguestuser()) {
2199 // By default, under the conditions above, this file must be cache-able only by browsers.
2200 $cacheability = ' private,';
2202 $nobyteserving = false;
2203 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2204 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
2207 } else { // Do not cache files in proxies and browsers
2208 $nobyteserving = true;
2209 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2210 header('Cache-Control: private, max-age=10, no-transform');
2211 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2213 } else { //normal http - prevent caching at all cost
2214 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2215 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2216 header('Pragma: no-cache');
2220 if (empty($filter)) {
2221 // send the contents
2222 if ($pathisstring) {
2223 readstring_accel($path, $mimetype, !$dontdie);
2225 readfile_accel($path, $mimetype, !$dontdie);
2229 // Try to put the file through filters
2230 if ($mimetype == 'text/html' ||
$mimetype == 'application/xhtml+xml') {
2231 $options = new stdClass();
2232 $options->noclean
= true;
2233 $options->nocache
= true; // temporary workaround for MDL-5136
2234 $text = $pathisstring ?
$path : implode('', file($path));
2236 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
2238 readstring_accel($output, $mimetype, false);
2240 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2241 // only filter text if filter all files is selected
2242 $options = new stdClass();
2243 $options->newlines
= false;
2244 $options->noclean
= true;
2245 $text = htmlentities($pathisstring ?
$path : implode('', file($path)), ENT_QUOTES
, 'UTF-8');
2246 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
2248 readstring_accel($output, $mimetype, false);
2251 // send the contents
2252 if ($pathisstring) {
2253 readstring_accel($path, $mimetype, !$dontdie);
2255 readfile_accel($path, $mimetype, !$dontdie);
2262 die; //no more chars to output!!!
2266 * Handles the sending of file data to the user's browser, including support for
2269 * The $options parameter supports the following keys:
2270 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2271 * (string|null) filename - overrides the implicit filename
2272 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2273 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2274 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2275 * and should not be reopened
2276 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2277 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2278 * defaults to "public".
2281 * @param stored_file $stored_file local file object
2282 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2283 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2284 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2285 * @param array $options additional options affecting the file serving
2286 * @return null script execution stopped unless $options['dontdie'] is true
2288 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2289 global $CFG, $COURSE;
2291 if (empty($options['filename'])) {
2294 $filename = $options['filename'];
2297 if (empty($options['dontdie'])) {
2303 if ($lifetime === 'default' or is_null($lifetime)) {
2304 $lifetime = $CFG->filelifetime
;
2307 if (!empty($options['preview'])) {
2308 // replace the file with its preview
2309 $fs = get_file_storage();
2310 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2311 if (!$preview_file) {
2312 // unable to create a preview of the file, send its default mime icon instead
2313 if ($options['preview'] === 'tinyicon') {
2315 } else if ($options['preview'] === 'thumb') {
2320 $fileicon = file_file_icon($stored_file, $size);
2321 send_file($CFG->dirroot
.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2323 // preview images have fixed cache lifetime and they ignore forced download
2324 // (they are generated by GD and therefore they are considered reasonably safe).
2325 $stored_file = $preview_file;
2326 $lifetime = DAYSECS
;
2328 $forcedownload = false;
2332 // handle external resource
2333 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2334 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2338 if (!$stored_file or $stored_file->is_directory()) {
2347 ignore_user_abort(true);
2350 \core\session\manager
::write_close(); // Unlock session during file serving.
2352 $filename = is_null($filename) ?
$stored_file->get_filename() : $filename;
2354 // Use given MIME type if specified.
2355 $mimetype = $stored_file->get_mimetype();
2357 // Otherwise guess it.
2358 if (!$mimetype ||
$mimetype === 'document/unknown') {
2359 $mimetype = get_mimetype_for_sending($filename);
2362 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2363 if (core_useragent
::is_ie()) {
2364 $filename = rawurlencode($filename);
2367 if ($forcedownload) {
2368 header('Content-Disposition: attachment; filename="'.$filename.'"');
2369 } else if ($mimetype !== 'application/x-shockwave-flash') {
2370 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2371 // as an upload and enforces security that may prevent the file from being loaded.
2373 header('Content-Disposition: inline; filename="'.$filename.'"');
2376 if ($lifetime > 0) {
2377 $cacheability = ' public,';
2378 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2379 // This file must be cache-able by both browsers and proxies.
2380 $cacheability = ' public,';
2381 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2382 // This file must be cache-able only by browsers.
2383 $cacheability = ' private,';
2384 } else if (isloggedin() and !isguestuser()) {
2385 $cacheability = ' private,';
2387 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2388 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
2391 } else { // Do not cache files in proxies and browsers
2392 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2393 header('Cache-Control: private, max-age=10, no-transform');
2394 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2396 } else { //normal http - prevent caching at all cost
2397 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2398 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2399 header('Pragma: no-cache');
2403 // Allow cross-origin requests only for Web Services.
2404 // This allow to receive requests done by Web Workers or webapps in different domains.
2406 header('Access-Control-Allow-Origin: *');
2409 if (empty($filter)) {
2410 // send the contents
2411 readfile_accel($stored_file, $mimetype, !$dontdie);
2413 } else { // Try to put the file through filters
2414 if ($mimetype == 'text/html' ||
$mimetype == 'application/xhtml+xml') {
2415 $options = new stdClass();
2416 $options->noclean
= true;
2417 $options->nocache
= true; // temporary workaround for MDL-5136
2418 $text = $stored_file->get_content();
2419 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
2421 readstring_accel($output, $mimetype, false);
2423 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2424 // only filter text if filter all files is selected
2425 $options = new stdClass();
2426 $options->newlines
= false;
2427 $options->noclean
= true;
2428 $text = $stored_file->get_content();
2429 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
2431 readstring_accel($output, $mimetype, false);
2433 } else { // Just send it out raw
2434 readfile_accel($stored_file, $mimetype, !$dontdie);
2440 die; //no more chars to output!!!
2444 * Recursively delete the file or folder with path $location. That is,
2445 * if it is a file delete it. If it is a folder, delete all its content
2446 * then delete it. If $location does not exist to start, that is not
2447 * considered an error.
2449 * @param string $location the path to remove.
2452 function fulldelete($location) {
2453 if (empty($location)) {
2454 // extra safety against wrong param
2457 if (is_dir($location)) {
2458 if (!$currdir = opendir($location)) {
2461 while (false !== ($file = readdir($currdir))) {
2462 if ($file <> ".." && $file <> ".") {
2463 $fullfile = $location."/".$file;
2464 if (is_dir($fullfile)) {
2465 if (!fulldelete($fullfile)) {
2469 if (!unlink($fullfile)) {
2476 if (! rmdir($location)) {
2480 } else if (file_exists($location)) {
2481 if (!unlink($location)) {
2489 * Send requested byterange of file.
2491 * @param resource $handle A file handle
2492 * @param string $mimetype The mimetype for the output
2493 * @param array $ranges An array of ranges to send
2494 * @param string $filesize The size of the content if only one range is used
2496 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2497 // better turn off any kind of compression and buffering
2498 ini_set('zlib.output_compression', 'Off');
2500 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2501 if ($handle === false) {
2504 if (count($ranges) == 1) { //only one range requested
2505 $length = $ranges[0][2] - $ranges[0][1] +
1;
2506 header('HTTP/1.1 206 Partial content');
2507 header('Content-Length: '.$length);
2508 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2509 header('Content-Type: '.$mimetype);
2511 while(@ob_get_level
()) {
2512 if (!@ob_end_flush
()) {
2517 fseek($handle, $ranges[0][1]);
2518 while (!feof($handle) && $length > 0) {
2519 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2520 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2523 $length -= strlen($buffer);
2527 } else { // multiple ranges requested - not tested much
2529 foreach($ranges as $range) {
2530 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
2532 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
2533 header('HTTP/1.1 206 Partial content');
2534 header('Content-Length: '.$totallength);
2535 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
2537 while(@ob_get_level
()) {
2538 if (!@ob_end_flush
()) {
2543 foreach($ranges as $range) {
2544 $length = $range[2] - $range[1] +
1;
2546 fseek($handle, $range[1]);
2547 while (!feof($handle) && $length > 0) {
2548 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2549 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2552 $length -= strlen($buffer);
2555 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
2562 * Tells whether the filename is executable.
2564 * @link http://php.net/manual/en/function.is-executable.php
2565 * @link https://bugs.php.net/bug.php?id=41062
2566 * @param string $filename Path to the file.
2567 * @return bool True if the filename exists and is executable; otherwise, false.
2569 function file_is_executable($filename) {
2570 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
2571 if (is_executable($filename)) {
2574 $fileext = strrchr($filename, '.');
2575 // If we have an extension we can check if it is listed as executable.
2576 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2577 $winpathext = strtolower(getenv('PATHEXT'));
2578 $winpathexts = explode(';', $winpathext);
2580 return in_array(strtolower($fileext), $winpathexts);
2586 return is_executable($filename);
2591 * Overwrite an existing file in a draft area.
2593 * @param stored_file $newfile the new file with the new content and meta-data
2594 * @param stored_file $existingfile the file that will be overwritten
2595 * @throws moodle_exception
2598 function file_overwrite_existing_draftfile(stored_file
$newfile, stored_file
$existingfile) {
2599 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2600 throw new coding_exception('The file to overwrite is not in a draft area.');
2603 $fs = get_file_storage();
2604 // Remember original file source field.
2605 $source = @unserialize
($existingfile->get_source());
2606 // Remember the original sortorder.
2607 $sortorder = $existingfile->get_sortorder();
2608 if ($newfile->is_external_file()) {
2609 // New file is a reference. Check that existing file does not have any other files referencing to it
2610 if (isset($source->original
) && $fs->search_references_count($source->original
)) {
2611 throw new moodle_exception('errordoublereference', 'repository');
2615 // Delete existing file to release filename.
2616 $newfilerecord = array(
2617 'contextid' => $existingfile->get_contextid(),
2618 'component' => 'user',
2619 'filearea' => 'draft',
2620 'itemid' => $existingfile->get_itemid(),
2621 'timemodified' => time()
2623 $existingfile->delete();
2626 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2627 // Preserve original file location (stored in source field) for handling references.
2628 if (isset($source->original
)) {
2629 if (!($newfilesource = @unserialize
($newfile->get_source()))) {
2630 $newfilesource = new stdClass();
2632 $newfilesource->original
= $source->original
;
2633 $newfile->set_source(serialize($newfilesource));
2635 $newfile->set_sortorder($sortorder);
2639 * Add files from a draft area into a final area.
2641 * Most of the time you do not want to use this. It is intended to be used
2642 * by asynchronous services which cannot direcly manipulate a final
2643 * area through a draft area. Instead they add files to a new draft
2644 * area and merge that new draft into the final area when ready.
2646 * @param int $draftitemid the id of the draft area to use.
2647 * @param int $contextid this parameter and the next two identify the file area to save to.
2648 * @param string $component component name
2649 * @param string $filearea indentifies the file area
2650 * @param int $itemid identifies the item id or false for all items in the file area
2651 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2652 * @see file_save_draft_area_files
2655 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2656 array $options = null) {
2657 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2659 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2660 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2661 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2665 * Merge files from two draftarea areas.
2667 * This does not handle conflict resolution, files in the destination area which appear
2668 * to be more recent will be kept disregarding the intended ones.
2670 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2671 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2672 * @throws coding_exception
2675 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2678 $fs = get_file_storage();
2679 $contextid = context_user
::instance($USER->id
)->id
;
2681 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2682 throw new coding_exception('Nothing to merge or area does not belong to current user');
2685 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2687 // Get hashes of the files to merge.
2688 $newhashes = array();
2689 foreach ($filestomerge as $filetomerge) {
2690 $filepath = $filetomerge->get_filepath();
2691 $filename = $filetomerge->get_filename();
2693 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2694 $newhashes[$newhash] = $filetomerge;
2697 // Calculate wich files must be added.
2698 foreach ($currentfiles as $file) {
2699 $filehash = $file->get_pathnamehash();
2700 // One file to be merged already exists.
2701 if (isset($newhashes[$filehash])) {
2702 $updatedfile = $newhashes[$filehash];
2704 // Avoid race conditions.
2705 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2706 // The existing file is more recent, do not copy the suposedly "new" one.
2707 unset($newhashes[$filehash]);
2710 // Update existing file (not only content, meta-data too).
2711 file_overwrite_existing_draftfile($updatedfile, $file);
2712 unset($newhashes[$filehash]);
2716 foreach ($newhashes as $newfile) {
2717 $newfilerecord = array(
2718 'contextid' => $contextid,
2719 'component' => 'user',
2720 'filearea' => 'draft',
2721 'itemid' => $mergeintodraftid,
2722 'timemodified' => time()
2725 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2730 * RESTful cURL class
2732 * This is a wrapper class for curl, it is quite easy to use:
2736 * $c = new curl(array('cache'=>true));
2738 * $c = new curl(array('cookie'=>true));
2740 * $c = new curl(array('proxy'=>true));
2742 * // HTTP GET Method
2743 * $html = $c->get('http://example.com');
2744 * // HTTP POST Method
2745 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2746 * // HTTP PUT Method
2747 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2750 * @package core_files
2752 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2753 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2756 /** @var bool Caches http request contents */
2757 public $cache = false;
2758 /** @var bool Uses proxy, null means automatic based on URL */
2759 public $proxy = null;
2760 /** @var string library version */
2761 public $version = '0.4 dev';
2762 /** @var array http's response */
2763 public $response = array();
2764 /** @var array Raw response headers, needed for BC in download_file_content(). */
2765 public $rawresponse = array();
2766 /** @var array http header */
2767 public $header = array();
2768 /** @var string cURL information */
2770 /** @var string error */
2772 /** @var int error code */
2774 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2775 public $emulateredirects = null;
2777 /** @var array cURL options */
2780 /** @var string Proxy host */
2781 private $proxy_host = '';
2782 /** @var string Proxy auth */
2783 private $proxy_auth = '';
2784 /** @var string Proxy type */
2785 private $proxy_type = '';
2786 /** @var bool Debug mode on */
2787 private $debug = false;
2788 /** @var bool|string Path to cookie file */
2789 private $cookie = false;
2790 /** @var bool tracks multiple headers in response - redirect detection */
2791 private $responsefinished = false;
2792 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
2793 private $securityhelper;
2794 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
2795 private $ignoresecurity;
2800 * Allowed settings are:
2801 * proxy: (bool) use proxy server, null means autodetect non-local from url
2802 * debug: (bool) use debug output
2803 * cookie: (string) path to cookie file, false if none
2804 * cache: (bool) use cache
2805 * module_cache: (string) type of cache
2806 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
2807 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
2809 * @param array $settings
2811 public function __construct($settings = array()) {
2813 if (!function_exists('curl_init')) {
2814 $this->error
= 'cURL module must be enabled!';
2815 trigger_error($this->error
, E_USER_ERROR
);
2819 // All settings of this class should be init here.
2821 if (!empty($settings['debug'])) {
2822 $this->debug
= true;
2824 if (!empty($settings['cookie'])) {
2825 if($settings['cookie'] === true) {
2826 $this->cookie
= $CFG->dataroot
.'/curl_cookie.txt';
2828 $this->cookie
= $settings['cookie'];
2831 if (!empty($settings['cache'])) {
2832 if (class_exists('curl_cache')) {
2833 if (!empty($settings['module_cache'])) {
2834 $this->cache
= new curl_cache($settings['module_cache']);
2836 $this->cache
= new curl_cache('misc');
2840 if (!empty($CFG->proxyhost
)) {
2841 if (empty($CFG->proxyport
)) {
2842 $this->proxy_host
= $CFG->proxyhost
;
2844 $this->proxy_host
= $CFG->proxyhost
.':'.$CFG->proxyport
;
2846 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
2847 $this->proxy_auth
= $CFG->proxyuser
.':'.$CFG->proxypassword
;
2848 $this->setopt(array(
2849 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM
,
2850 'proxyuserpwd'=>$this->proxy_auth
));
2852 if (!empty($CFG->proxytype
)) {
2853 if ($CFG->proxytype
== 'SOCKS5') {
2854 $this->proxy_type
= CURLPROXY_SOCKS5
;
2856 $this->proxy_type
= CURLPROXY_HTTP
;
2857 $this->setopt(array('httpproxytunnel'=>false));
2859 $this->setopt(array('proxytype'=>$this->proxy_type
));
2862 if (isset($settings['proxy'])) {
2863 $this->proxy
= $settings['proxy'];
2866 $this->proxy
= false;
2869 if (!isset($this->emulateredirects
)) {
2870 $this->emulateredirects
= ini_get('open_basedir');
2873 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
2874 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base
) {
2875 $this->set_security($settings['securityhelper']);
2877 $this->set_security(new \core\files\
curl_security_helper());
2879 $this->ignoresecurity
= isset($settings['ignoresecurity']) ?
$settings['ignoresecurity'] : false;
2883 * Resets the CURL options that have already been set
2885 public function resetopt() {
2886 $this->options
= array();
2887 $this->options
['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2888 // True to include the header in the output
2889 $this->options
['CURLOPT_HEADER'] = 0;
2890 // True to Exclude the body from the output
2891 $this->options
['CURLOPT_NOBODY'] = 0;
2892 // Redirect ny default.
2893 $this->options
['CURLOPT_FOLLOWLOCATION'] = 1;
2894 $this->options
['CURLOPT_MAXREDIRS'] = 10;
2895 $this->options
['CURLOPT_ENCODING'] = '';
2896 // TRUE to return the transfer as a string of the return
2897 // value of curl_exec() instead of outputting it out directly.
2898 $this->options
['CURLOPT_RETURNTRANSFER'] = 1;
2899 $this->options
['CURLOPT_SSL_VERIFYPEER'] = 0;
2900 $this->options
['CURLOPT_SSL_VERIFYHOST'] = 2;
2901 $this->options
['CURLOPT_CONNECTTIMEOUT'] = 30;
2903 if ($cacert = self
::get_cacert()) {
2904 $this->options
['CURLOPT_CAINFO'] = $cacert;
2909 * Get the location of ca certificates.
2910 * @return string absolute file path or empty if default used
2912 public static function get_cacert() {
2915 // Bundle in dataroot always wins.
2916 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2917 return realpath("$CFG->dataroot/moodleorgca.crt");
2920 // Next comes the default from php.ini
2921 $cacert = ini_get('curl.cainfo');
2922 if (!empty($cacert) and is_readable($cacert)) {
2923 return realpath($cacert);
2926 // Windows PHP does not have any certs, we need to use something.
2927 if ($CFG->ostype
=== 'WINDOWS') {
2928 if (is_readable("$CFG->libdir/cacert.pem")) {
2929 return realpath("$CFG->libdir/cacert.pem");
2933 // Use default, this should work fine on all properly configured *nix systems.
2940 public function resetcookie() {
2941 if (!empty($this->cookie
)) {
2942 if (is_file($this->cookie
)) {
2943 $fp = fopen($this->cookie
, 'w');
2955 * Do not use the curl constants to define the options, pass a string
2956 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2957 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2959 * @param array $options If array is null, this function will reset the options to default value.
2961 * @throws coding_exception If an option uses constant value instead of option name.
2963 public function setopt($options = array()) {
2964 if (is_array($options)) {
2965 foreach ($options as $name => $val) {
2966 if (!is_string($name)) {
2967 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2969 if (stripos($name, 'CURLOPT_') === false) {
2970 $name = strtoupper('CURLOPT_'.$name);
2972 $name = strtoupper($name);
2974 $this->options
[$name] = $val;
2982 public function cleanopt() {
2983 unset($this->options
['CURLOPT_HTTPGET']);
2984 unset($this->options
['CURLOPT_POST']);
2985 unset($this->options
['CURLOPT_POSTFIELDS']);
2986 unset($this->options
['CURLOPT_PUT']);
2987 unset($this->options
['CURLOPT_INFILE']);
2988 unset($this->options
['CURLOPT_INFILESIZE']);
2989 unset($this->options
['CURLOPT_CUSTOMREQUEST']);
2990 unset($this->options
['CURLOPT_FILE']);
2994 * Resets the HTTP Request headers (to prepare for the new request)
2996 public function resetHeader() {
2997 $this->header
= array();
3001 * Set HTTP Request Header
3003 * @param array $header
3005 public function setHeader($header) {
3006 if (is_array($header)) {
3007 foreach ($header as $v) {
3008 $this->setHeader($v);
3011 // Remove newlines, they are not allowed in headers.
3012 $this->header
[] = preg_replace('/[\r\n]/', '', $header);
3017 * Get HTTP Response Headers
3018 * @return array of arrays
3020 public function getResponse() {
3021 return $this->response
;
3025 * Get raw HTTP Response Headers
3026 * @return array of strings
3028 public function get_raw_response() {
3029 return $this->rawresponse
;
3033 * private callback function
3034 * Formatting HTTP Response Header
3036 * We only keep the last headers returned. For example during a redirect the
3037 * redirect headers will not appear in {@link self::getResponse()}, if you need
3038 * to use those headers, refer to {@link self::get_raw_response()}.
3040 * @param resource $ch Apparently not used
3041 * @param string $header
3042 * @return int The strlen of the header
3044 private function formatHeader($ch, $header) {
3045 $this->rawresponse
[] = $header;
3047 if (trim($header, "\r\n") === '') {
3048 // This must be the last header.
3049 $this->responsefinished
= true;
3052 if (strlen($header) > 2) {
3053 if ($this->responsefinished
) {
3054 // We still have headers after the supposedly last header, we must be
3055 // in a redirect so let's empty the response to keep the last headers.
3056 $this->responsefinished
= false;
3057 $this->response
= array();
3059 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3060 $key = rtrim($key, ':');
3061 if (!empty($this->response
[$key])) {
3062 if (is_array($this->response
[$key])) {
3063 $this->response
[$key][] = $value;
3065 $tmp = $this->response
[$key];
3066 $this->response
[$key] = array();
3067 $this->response
[$key][] = $tmp;
3068 $this->response
[$key][] = $value;
3072 $this->response
[$key] = $value;
3075 return strlen($header);
3079 * Set options for individual curl instance
3081 * @param resource $curl A curl handle
3082 * @param array $options
3083 * @return resource The curl handle
3085 private function apply_opt($curl, $options) {
3089 if (!empty($this->cookie
) ||
!empty($options['cookie'])) {
3090 $this->setopt(array('cookiejar'=>$this->cookie
,
3091 'cookiefile'=>$this->cookie
3095 // Bypass proxy if required.
3096 if ($this->proxy
=== null) {
3097 if (!empty($this->options
['CURLOPT_URL']) and is_proxybypass($this->options
['CURLOPT_URL'])) {
3103 $proxy = (bool)$this->proxy
;
3108 $options['CURLOPT_PROXY'] = $this->proxy_host
;
3110 unset($this->options
['CURLOPT_PROXY']);
3113 $this->setopt($options);
3115 // Reset before set options.
3116 curl_setopt($curl, CURLOPT_HEADERFUNCTION
, array(&$this,'formatHeader'));
3118 // Setting the User-Agent based on options provided.
3121 if (!empty($options['CURLOPT_USERAGENT'])) {
3122 $useragent = $options['CURLOPT_USERAGENT'];
3123 } else if (!empty($this->options
['CURLOPT_USERAGENT'])) {
3124 $useragent = $this->options
['CURLOPT_USERAGENT'];
3126 $useragent = 'MoodleBot/1.0';
3130 if (empty($this->header
)) {
3131 $this->setHeader(array(
3132 'User-Agent: ' . $useragent,
3133 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3134 'Connection: keep-alive'
3136 } else if (!in_array('User-Agent: ' . $useragent, $this->header
)) {
3137 // Remove old User-Agent if one existed.
3138 // We have to partial search since we don't know what the original User-Agent is.
3139 if ($match = preg_grep('/User-Agent.*/', $this->header
)) {
3140 $key = array_keys($match)[0];
3141 unset($this->header
[$key]);
3143 $this->setHeader(array('User-Agent: ' . $useragent));
3145 curl_setopt($curl, CURLOPT_HTTPHEADER
, $this->header
);
3148 echo '<h1>Options</h1>';
3149 var_dump($this->options
);
3150 echo '<h1>Header</h1>';
3151 var_dump($this->header
);
3154 // Do not allow infinite redirects.
3155 if (!isset($this->options
['CURLOPT_MAXREDIRS'])) {
3156 $this->options
['CURLOPT_MAXREDIRS'] = 0;
3157 } else if ($this->options
['CURLOPT_MAXREDIRS'] > 100) {
3158 $this->options
['CURLOPT_MAXREDIRS'] = 100;
3160 $this->options
['CURLOPT_MAXREDIRS'] = (int)$this->options
['CURLOPT_MAXREDIRS'];
3163 // Make sure we always know if redirects expected.
3164 if (!isset($this->options
['CURLOPT_FOLLOWLOCATION'])) {
3165 $this->options
['CURLOPT_FOLLOWLOCATION'] = 0;
3168 // Limit the protocols to HTTP and HTTPS.
3169 if (defined('CURLOPT_PROTOCOLS')) {
3170 $this->options
['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3171 $this->options
['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3175 foreach($this->options
as $name => $val) {
3176 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects
) {
3177 // The redirects are emulated elsewhere.
3178 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, 0);
3181 $name = constant($name);
3182 curl_setopt($curl, $name, $val);
3189 * Download multiple files in parallel
3191 * Calls {@link multi()} with specific download headers
3195 * $file1 = fopen('a', 'wb');
3196 * $file2 = fopen('b', 'wb');
3197 * $c->download(array(
3198 * array('url'=>'http://localhost/', 'file'=>$file1),
3199 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3209 * $c->download(array(
3210 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3211 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3215 * @param array $requests An array of files to request {
3216 * url => url to download the file [required]
3217 * file => file handler, or
3218 * filepath => file path
3220 * If 'file' and 'filepath' parameters are both specified in one request, the
3221 * open file handle in the 'file' parameter will take precedence and 'filepath'
3224 * @param array $options An array of options to set
3225 * @return array An array of results
3227 public function download($requests, $options = array()) {
3228 $options['RETURNTRANSFER'] = false;
3229 return $this->multi($requests, $options);
3233 * Returns the current curl security helper.
3235 * @return \core\files\curl_security_helper instance.
3237 public function get_security() {
3238 return $this->securityhelper
;
3242 * Sets the curl security helper.
3244 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3245 * @return bool true if the security helper could be set, false otherwise.
3247 public function set_security($securityobject) {
3248 if ($securityobject instanceof \core\files\curl_security_helper
) {
3249 $this->securityhelper
= $securityobject;
3256 * Multi HTTP Requests
3257 * This function could run multi-requests in parallel.
3259 * @param array $requests An array of files to request
3260 * @param array $options An array of options to set
3261 * @return array An array of results
3263 protected function multi($requests, $options = array()) {
3264 $count = count($requests);
3267 $main = curl_multi_init();
3268 for ($i = 0; $i < $count; $i++
) {
3269 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3271 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3272 $requests[$i]['auto-handle'] = true;
3274 foreach($requests[$i] as $n=>$v) {
3277 $handles[$i] = curl_init($requests[$i]['url']);
3278 $this->apply_opt($handles[$i], $options);
3279 curl_multi_add_handle($main, $handles[$i]);
3283 curl_multi_exec($main, $running);
3284 } while($running > 0);
3285 for ($i = 0; $i < $count; $i++
) {
3286 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3289 $results[] = curl_multi_getcontent($handles[$i]);
3291 curl_multi_remove_handle($main, $handles[$i]);
3293 curl_multi_close($main);
3295 for ($i = 0; $i < $count; $i++
) {
3296 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3297 // close file handler if file is opened in this function
3298 fclose($requests[$i]['file']);
3305 * Helper function to reset the request state vars.
3309 protected function reset_request_state_vars() {
3310 $this->info
= array();
3313 $this->response
= array();
3314 $this->rawresponse
= array();
3315 $this->responsefinished
= false;
3319 * Single HTTP Request
3321 * @param string $url The URL to request
3322 * @param array $options
3325 protected function request($url, $options = array()) {
3326 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3327 $this->reset_request_state_vars();
3329 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3330 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3331 if (!$this->ignoresecurity
&& $this->securityhelper
->url_is_blocked($url)) {
3332 $this->error
= $this->securityhelper
->get_blocked_url_string();
3333 return $this->error
;
3336 // Set the URL as a curl option.
3337 $this->setopt(array('CURLOPT_URL' => $url));
3339 // Create curl instance.
3340 $curl = curl_init();
3342 $this->apply_opt($curl, $options);
3343 if ($this->cache
&& $ret = $this->cache
->get($this->options
)) {
3347 $ret = curl_exec($curl);
3348 $this->info
= curl_getinfo($curl);
3349 $this->error
= curl_error($curl);
3350 $this->errno
= curl_errno($curl);
3351 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3353 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3354 if (intval($this->info
['redirect_count']) > 0 && !$this->ignoresecurity
3355 && $this->securityhelper
->url_is_blocked($this->info
['url'])) {
3356 $this->reset_request_state_vars();
3357 $this->error
= $this->securityhelper
->get_blocked_url_string();
3359 return $this->error
;
3362 if ($this->emulateredirects
and $this->options
['CURLOPT_FOLLOWLOCATION'] and $this->info
['http_code'] != 200) {
3365 while($redirects <= $this->options
['CURLOPT_MAXREDIRS']) {
3367 if ($this->info
['http_code'] == 301) {
3368 // Moved Permanently - repeat the same request on new URL.
3370 } else if ($this->info
['http_code'] == 302) {
3371 // Found - the standard redirect - repeat the same request on new URL.
3373 } else if ($this->info
['http_code'] == 303) {
3374 // 303 See Other - repeat only if GET, do not bother with POSTs.
3375 if (empty($this->options
['CURLOPT_HTTPGET'])) {
3379 } else if ($this->info
['http_code'] == 307) {
3380 // Temporary Redirect - must repeat using the same request type.
3382 } else if ($this->info
['http_code'] == 308) {
3383 // Permanent Redirect - must repeat using the same request type.
3386 // Some other http code means do not retry!
3392 $redirecturl = null;
3393 if (isset($this->info
['redirect_url'])) {
3394 if (preg_match('|^https?://|i', $this->info
['redirect_url'])) {
3395 $redirecturl = $this->info
['redirect_url'];
3398 if (!$redirecturl) {
3399 foreach ($this->response
as $k => $v) {
3400 if (strtolower($k) === 'location') {
3405 if (preg_match('|^https?://|i', $redirecturl)) {
3406 // Great, this is the correct location format!
3408 } else if ($redirecturl) {
3409 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL
);
3410 if (strpos($redirecturl, '/') === 0) {
3411 // Relative to server root - just guess.
3412 $pos = strpos('/', $current, 8);
3413 if ($pos === false) {
3414 $redirecturl = $current.$redirecturl;
3416 $redirecturl = substr($current, 0, $pos).$redirecturl;
3419 // Relative to current script.
3420 $redirecturl = dirname($current).'/'.$redirecturl;
3425 curl_setopt($curl, CURLOPT_URL
, $redirecturl);
3426 $ret = curl_exec($curl);
3428 $this->info
= curl_getinfo($curl);
3429 $this->error
= curl_error($curl);
3430 $this->errno
= curl_errno($curl);
3432 $this->info
['redirect_count'] = $redirects;
3434 if ($this->info
['http_code'] === 200) {
3435 // Finally this is what we wanted.
3438 if ($this->errno
!= CURLE_OK
) {
3439 // Something wrong is going on.
3443 if ($redirects > $this->options
['CURLOPT_MAXREDIRS']) {
3444 $this->errno
= CURLE_TOO_MANY_REDIRECTS
;
3445 $this->error
= 'Maximum ('.$this->options
['CURLOPT_MAXREDIRS'].') redirects followed';
3450 $this->cache
->set($this->options
, $ret);
3454 echo '<h1>Return Data</h1>';
3456 echo '<h1>Info</h1>';
3457 var_dump($this->info
);
3458 echo '<h1>Error</h1>';
3459 var_dump($this->error
);
3464 if (empty($this->error
)) {
3467 return $this->error
;
3468 // exception is not ajax friendly
3469 //throw new moodle_exception($this->error, 'curl');
3478 * @param string $url
3479 * @param array $options
3482 public function head($url, $options = array()) {
3483 $options['CURLOPT_HTTPGET'] = 0;
3484 $options['CURLOPT_HEADER'] = 1;
3485 $options['CURLOPT_NOBODY'] = 1;
3486 return $this->request($url, $options);
3492 * @param string $url
3493 * @param array|string $params
3494 * @param array $options
3497 public function post($url, $params = '', $options = array()) {
3498 $options['CURLOPT_POST'] = 1;
3499 if (is_array($params)) {
3500 $this->_tmp_file_post_params
= array();
3501 foreach ($params as $key => $value) {
3502 if ($value instanceof stored_file
) {
3503 $value->add_to_curl_request($this, $key);
3505 $this->_tmp_file_post_params
[$key] = $value;
3508 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
3509 unset($this->_tmp_file_post_params
);
3511 // $params is the raw post data
3512 $options['CURLOPT_POSTFIELDS'] = $params;
3514 return $this->request($url, $options);
3520 * @param string $url
3521 * @param array $params
3522 * @param array $options
3525 public function get($url, $params = array(), $options = array()) {
3526 $options['CURLOPT_HTTPGET'] = 1;
3528 if (!empty($params)) {
3529 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3530 $url .= http_build_query($params, '', '&');
3532 return $this->request($url, $options);
3536 * Downloads one file and writes it to the specified file handler
3540 * $file = fopen('savepath', 'w');
3541 * $result = $c->download_one('http://localhost/', null,
3542 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3544 * $download_info = $c->get_info();
3545 * if ($result === true) {
3546 * // file downloaded successfully
3548 * $error_text = $result;
3549 * $error_code = $c->get_errno();
3555 * $result = $c->download_one('http://localhost/', null,
3556 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3557 * // ... see above, no need to close handle and remove file if unsuccessful
3560 * @param string $url
3561 * @param array|null $params key-value pairs to be added to $url as query string
3562 * @param array $options request options. Must include either 'file' or 'filepath'
3563 * @return bool|string true on success or error string on failure
3565 public function download_one($url, $params, $options = array()) {
3566 $options['CURLOPT_HTTPGET'] = 1;
3567 if (!empty($params)) {
3568 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3569 $url .= http_build_query($params, '', '&');
3571 if (!empty($options['filepath']) && empty($options['file'])) {
3573 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3575 return get_string('cannotwritefile', 'error', $options['filepath']);
3577 $filepath = $options['filepath'];
3579 unset($options['filepath']);
3580 $result = $this->request($url, $options);
3581 if (isset($filepath)) {
3582 fclose($options['file']);
3583 if ($result !== true) {
3593 * @param string $url
3594 * @param array $params
3595 * @param array $options
3598 public function put($url, $params = array(), $options = array()) {
3599 $file = $params['file'];
3600 if (!is_file($file)) {
3603 $fp = fopen($file, 'r');
3604 $size = filesize($file);
3605 $options['CURLOPT_PUT'] = 1;
3606 $options['CURLOPT_INFILESIZE'] = $size;
3607 $options['CURLOPT_INFILE'] = $fp;
3608 if (!isset($this->options
['CURLOPT_USERPWD'])) {
3609 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3611 $ret = $this->request($url, $options);
3617 * HTTP DELETE method
3619 * @param string $url
3620 * @param array $param
3621 * @param array $options
3624 public function delete($url, $param = array(), $options = array()) {
3625 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3626 if (!isset($options['CURLOPT_USERPWD'])) {
3627 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3629 $ret = $this->request($url, $options);
3636 * @param string $url
3637 * @param array $options
3640 public function trace($url, $options = array()) {
3641 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3642 $ret = $this->request($url, $options);
3647 * HTTP OPTIONS method
3649 * @param string $url
3650 * @param array $options
3653 public function options($url, $options = array()) {
3654 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3655 $ret = $this->request($url, $options);
3660 * Get curl information
3664 public function get_info() {
3669 * Get curl error code
3673 public function get_errno() {
3674 return $this->errno
;
3678 * When using a proxy, an additional HTTP response code may appear at
3679 * the start of the header. For example, when using https over a proxy
3680 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3681 * also possible and some may come with their own headers.
3683 * If using the return value containing all headers, this function can be
3684 * called to remove unwanted doubles.
3686 * Note that it is not possible to distinguish this situation from valid
3687 * data unless you know the actual response part (below the headers)
3688 * will not be included in this string, or else will not 'look like' HTTP
3689 * headers. As a result it is not safe to call this function for general
3692 * @param string $input Input HTTP response
3693 * @return string HTTP response with additional headers stripped if any
3695 public static function strip_double_headers($input) {
3696 // I have tried to make this regular expression as specific as possible
3697 // to avoid any case where it does weird stuff if you happen to put
3698 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3699 // also make it faster because it can abandon regex processing as soon
3700 // as it hits something that doesn't look like an http header. The
3701 // header definition is taken from RFC 822, except I didn't support
3702 // folding which is never used in practice.
3704 return preg_replace(
3705 // HTTP version and status code (ignore value of code).
3706 '~^HTTP/1\..*' . $crlf .
3707 // Header name: character between 33 and 126 decimal, except colon.
3708 // Colon. Header value: any character except \r and \n. CRLF.
3709 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3710 // Headers are terminated by another CRLF (blank line).
3712 // Second HTTP status code, this time must be 200.
3713 '(HTTP/1.[01] 200 )~', '$1', $input);
3718 * This class is used by cURL class, use case:
3721 * $CFG->repositorycacheexpire = 120;
3722 * $CFG->curlcache = 120;
3724 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3725 * $ret = $c->get('http://www.google.com');
3728 * @package core_files
3729 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3733 /** @var string Path to cache directory */
3739 * @global stdClass $CFG
3740 * @param string $module which module is using curl_cache
3742 public function __construct($module = 'repository') {
3744 if (!empty($module)) {
3745 $this->dir
= $CFG->cachedir
.'/'.$module.'/';
3747 $this->dir
= $CFG->cachedir
.'/misc/';
3749 if (!file_exists($this->dir
)) {
3750 mkdir($this->dir
, $CFG->directorypermissions
, true);
3752 if ($module == 'repository') {
3753 if (empty($CFG->repositorycacheexpire
)) {
3754 $CFG->repositorycacheexpire
= 120;
3756 $this->ttl
= $CFG->repositorycacheexpire
;
3758 if (empty($CFG->curlcache
)) {
3759 $CFG->curlcache
= 120;
3761 $this->ttl
= $CFG->curlcache
;
3768 * @global stdClass $CFG
3769 * @global stdClass $USER
3770 * @param mixed $param
3771 * @return bool|string
3773 public function get($param) {
3775 $this->cleanup($this->ttl
);
3776 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
3777 if(file_exists($this->dir
.$filename)) {
3778 $lasttime = filemtime($this->dir
.$filename);
3779 if (time()-$lasttime > $this->ttl
) {
3782 $fp = fopen($this->dir
.$filename, 'r');
3783 $size = filesize($this->dir
.$filename);
3784 $content = fread($fp, $size);
3785 return unserialize($content);
3794 * @global object $CFG
3795 * @global object $USER
3796 * @param mixed $param
3799 public function set($param, $val) {
3801 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
3802 $fp = fopen($this->dir
.$filename, 'w');
3803 fwrite($fp, serialize($val));
3805 @chmod
($this->dir
.$filename, $CFG->filepermissions
);
3809 * Remove cache files
3811 * @param int $expire The number of seconds before expiry
3813 public function cleanup($expire) {
3814 if ($dir = opendir($this->dir
)) {
3815 while (false !== ($file = readdir($dir))) {
3816 if(!is_dir($file) && $file != '.' && $file != '..') {
3817 $lasttime = @filemtime
($this->dir
.$file);
3818 if (time() - $lasttime > $expire) {
3819 @unlink
($this->dir
.$file);
3827 * delete current user's cache file
3829 * @global object $CFG
3830 * @global object $USER
3832 public function refresh() {
3834 if ($dir = opendir($this->dir
)) {
3835 while (false !== ($file = readdir($dir))) {
3836 if (!is_dir($file) && $file != '.' && $file != '..') {
3837 if (strpos($file, 'u'.$USER->id
.'_') !== false) {
3838 @unlink
($this->dir
.$file);
3847 * This function delegates file serving to individual plugins
3849 * @param string $relativepath
3850 * @param bool $forcedownload
3851 * @param null|string $preview the preview mode, defaults to serving the original file
3852 * @todo MDL-31088 file serving improments
3854 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3855 global $DB, $CFG, $USER;
3856 // relative path must start with '/'
3857 if (!$relativepath) {
3858 print_error('invalidargorconf');
3859 } else if ($relativepath[0] != '/') {
3860 print_error('pathdoesnotstartslash');
3863 // extract relative path components
3864 $args = explode('/', ltrim($relativepath, '/'));
3866 if (count($args) < 3) { // always at least context, component and filearea
3867 print_error('invalidarguments');
3870 $contextid = (int)array_shift($args);
3871 $component = clean_param(array_shift($args), PARAM_COMPONENT
);
3872 $filearea = clean_param(array_shift($args), PARAM_AREA
);
3874 list($context, $course, $cm) = get_context_info_array($contextid);
3876 $fs = get_file_storage();
3878 // ========================================================================================================================
3879 if ($component === 'blog') {
3880 // Blog file serving
3881 if ($context->contextlevel
!= CONTEXT_SYSTEM
) {
3882 send_file_not_found();
3884 if ($filearea !== 'attachment' and $filearea !== 'post') {
3885 send_file_not_found();
3888 if (empty($CFG->enableblogs
)) {
3889 print_error('siteblogdisable', 'blog');
3892 $entryid = (int)array_shift($args);
3893 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3894 send_file_not_found();
3896 if ($CFG->bloglevel
< BLOG_GLOBAL_LEVEL
) {
3898 if (isguestuser()) {
3899 print_error('noguest');
3901 if ($CFG->bloglevel
== BLOG_USER_LEVEL
) {
3902 if ($USER->id
!= $entry->userid
) {
3903 send_file_not_found();
3908 if ($entry->publishstate
=== 'public') {
3909 if ($CFG->forcelogin
) {
3913 } else if ($entry->publishstate
=== 'site') {
3916 } else if ($entry->publishstate
=== 'draft') {
3918 if ($USER->id
!= $entry->userid
) {
3919 send_file_not_found();
3923 $filename = array_pop($args);
3924 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
3926 if (!$file = $fs->get_file($context->id
, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3927 send_file_not_found();
3930 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3932 // ========================================================================================================================
3933 } else if ($component === 'grade') {
3934 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel
== CONTEXT_SYSTEM
) {
3935 // Global gradebook files
3936 if ($CFG->forcelogin
) {
3940 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3942 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3943 send_file_not_found();
3946 \core\session\manager
::write_close(); // Unlock session during file serving.
3947 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3949 } else if ($filearea === 'feedback' and $context->contextlevel
== CONTEXT_COURSE
) {
3950 //TODO: nobody implemented this yet in grade edit form!!
3951 send_file_not_found();
3953 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
3954 require_login($course);
3957 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3959 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3960 send_file_not_found();
3963 \core\session\manager
::write_close(); // Unlock session during file serving.
3964 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3966 send_file_not_found();
3969 // ========================================================================================================================
3970 } else if ($component === 'tag') {
3971 if ($filearea === 'description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
3973 // All tag descriptions are going to be public but we still need to respect forcelogin
3974 if ($CFG->forcelogin
) {
3978 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3980 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3981 send_file_not_found();
3984 \core\session\manager
::write_close(); // Unlock session during file serving.
3985 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3988 send_file_not_found();
3990 // ========================================================================================================================
3991 } else if ($component === 'badges') {
3992 require_once($CFG->libdir
. '/badgeslib.php');
3994 $badgeid = (int)array_shift($args);
3995 $badge = new badge($badgeid);
3996 $filename = array_pop($args);
3998 if ($filearea === 'badgeimage') {
3999 if ($filename !== 'f1' && $filename !== 'f2') {
4000 send_file_not_found();
4002 if (!$file = $fs->get_file($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $filename.'.png')) {
4003 send_file_not_found();
4006 \core\session\manager
::write_close();
4007 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4008 } else if ($filearea === 'userbadge' and $context->contextlevel
== CONTEXT_USER
) {
4009 if (!$file = $fs->get_file($context->id
, 'badges', 'userbadge', $badge->id
, '/', $filename.'.png')) {
4010 send_file_not_found();
4013 \core\session\manager
::write_close();
4014 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
4016 // ========================================================================================================================
4017 } else if ($component === 'calendar') {
4018 if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
4020 // All events here are public the one requirement is that we respect forcelogin
4021 if ($CFG->forcelogin
) {
4025 // Get the event if from the args array
4026 $eventid = array_shift($args);
4028 // Load the event from the database
4029 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4030 send_file_not_found();
4033 // Get the file and serve if successful
4034 $filename = array_pop($args);
4035 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4036 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4037 send_file_not_found();
4040 \core\session\manager
::write_close(); // Unlock session during file serving.
4041 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4043 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_USER
) {
4045 // Must be logged in, if they are not then they obviously can't be this user
4048 // Don't want guests here, potentially saves a DB call
4049 if (isguestuser()) {
4050 send_file_not_found();
4053 // Get the event if from the args array
4054 $eventid = array_shift($args);
4056 // Load the event from the database - user id must match
4057 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id
, 'eventtype'=>'user'))) {
4058 send_file_not_found();
4061 // Get the file and serve if successful
4062 $filename = array_pop($args);
4063 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4064 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4065 send_file_not_found();
4068 \core\session\manager
::write_close(); // Unlock session during file serving.
4069 send_stored_file($file, 0, 0, true, array('preview' => $preview));
4071 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_COURSE
) {
4073 // Respect forcelogin and require login unless this is the site.... it probably
4074 // should NEVER be the site
4075 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
4076 require_login($course);
4079 // Must be able to at least view the course. This does not apply to the front page.
4080 if ($course->id
!= SITEID
&& (!is_enrolled($context)) && (!is_viewing($context))) {
4081 //TODO: hmm, do we really want to block guests here?
4082 send_file_not_found();
4086 $eventid = array_shift($args);
4088 // Load the event from the database we need to check whether it is
4089 // a) valid course event
4091 // Group events use the course context (there is no group context)
4092 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id
))) {
4093 send_file_not_found();
4096 // If its a group event require either membership of view all groups capability
4097 if ($event->eventtype
=== 'group') {
4098 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid
, $USER->id
)) {
4099 send_file_not_found();
4101 } else if ($event->eventtype
=== 'course' ||
$event->eventtype
=== 'site') {
4102 // Ok. Please note that the event type 'site' still uses a course context.
4105 send_file_not_found();
4108 // If we get this far we can serve the file
4109 $filename = array_pop($args);
4110 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4111 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4112 send_file_not_found();
4115 \core\session\manager
::write_close(); // Unlock session during file serving.
4116 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4119 send_file_not_found();
4122 // ========================================================================================================================
4123 } else if ($component === 'user') {
4124 if ($filearea === 'icon' and $context->contextlevel
== CONTEXT_USER
) {
4125 if (count($args) == 1) {
4126 $themename = theme_config
::DEFAULT_THEME
;
4127 $filename = array_shift($args);
4129 $themename = array_shift($args);
4130 $filename = array_shift($args);
4133 // fix file name automatically
4134 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4138 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
4139 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
4140 // protect images if login required and not logged in;
4141 // also if login is required for profile images and is not logged in or guest
4142 // do not use require_login() because it is expensive and not suitable here anyway
4143 $theme = theme_config
::load($themename);
4144 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
4147 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.png')) {
4148 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4149 if ($filename === 'f3') {
4150 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4151 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.png')) {
4152 $file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.jpg');
4158 // bad reference - try to prevent future retries as hard as possible!
4159 if ($user = $DB->get_record('user', array('id'=>$context->instanceid
), 'id, picture')) {
4160 if ($user->picture
> 0) {
4161 $DB->set_field('user', 'picture', 0, array('id'=>$user->id
));
4164 // no redirect here because it is not cached
4165 $theme = theme_config
::load($themename);
4166 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4167 send_file($imagefile, basename($imagefile), 60*60*24*14);
4170 $options = array('preview' => $preview);
4171 if (empty($CFG->forcelogin
) && empty($CFG->forceloginforprofileimage
)) {
4172 // Profile images should be cache-able by both browsers and proxies according
4173 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4174 $options['cacheability'] = 'public';
4176 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4178 } else if ($filearea === 'private' and $context->contextlevel
== CONTEXT_USER
) {
4181 if (isguestuser()) {
4182 send_file_not_found();
4185 if ($USER->id
!== $context->instanceid
) {
4186 send_file_not_found();
4189 $filename = array_pop($args);
4190 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4191 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4192 send_file_not_found();
4195 \core\session\manager
::write_close(); // Unlock session during file serving.
4196 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4198 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_USER
) {
4200 if ($CFG->forcelogin
) {
4204 $userid = $context->instanceid
;
4206 if ($USER->id
== $userid) {
4207 // always can access own
4209 } else if (!empty($CFG->forceloginforprofiles
)) {
4212 if (isguestuser()) {
4213 send_file_not_found();
4216 // we allow access to site profile of all course contacts (usually teachers)
4217 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4218 send_file_not_found();
4222 if (has_capability('moodle/user:viewdetails', $context)) {
4225 $courses = enrol_get_my_courses();
4228 while (!$canview && count($courses) > 0) {
4229 $course = array_shift($courses);
4230 if (has_capability('moodle/user:viewdetails', context_course
::instance($course->id
))) {
4236 $filename = array_pop($args);
4237 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4238 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4239 send_file_not_found();
4242 \core\session\manager
::write_close(); // Unlock session during file serving.
4243 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4245 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_COURSE
) {
4246 $userid = (int)array_shift($args);
4247 $usercontext = context_user
::instance($userid);
4249 if ($CFG->forcelogin
) {
4253 if (!empty($CFG->forceloginforprofiles
)) {
4255 if (isguestuser()) {
4256 print_error('noguest');
4259 //TODO: review this logic of user profile access prevention
4260 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4261 print_error('usernotavailable');
4263 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4264 print_error('cannotviewprofile');
4266 if (!is_enrolled($context, $userid)) {
4267 print_error('notenrolledprofile');
4269 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
4270 print_error('groupnotamember');
4274 $filename = array_pop($args);
4275 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4276 if (!$file = $fs->get_file($usercontext->id
, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4277 send_file_not_found();
4280 \core\session\manager
::write_close(); // Unlock session during file serving.
4281 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4283 } else if ($filearea === 'backup' and $context->contextlevel
== CONTEXT_USER
) {
4286 if (isguestuser()) {
4287 send_file_not_found();
4289 $userid = $context->instanceid
;
4291 if ($USER->id
!= $userid) {
4292 send_file_not_found();
4295 $filename = array_pop($args);
4296 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4297 if (!$file = $fs->get_file($context->id
, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4298 send_file_not_found();
4301 \core\session\manager
::write_close(); // Unlock session during file serving.
4302 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4305 send_file_not_found();
4308 // ========================================================================================================================
4309 } else if ($component === 'coursecat') {
4310 if ($context->contextlevel
!= CONTEXT_COURSECAT
) {
4311 send_file_not_found();
4314 if ($filearea === 'description') {
4315 if ($CFG->forcelogin
) {
4316 // no login necessary - unless login forced everywhere
4320 // Check if user can view this category.
4321 if (!has_capability('moodle/category:viewhiddencategories', $context)) {
4322 $coursecatvisible = $DB->get_field('course_categories', 'visible', array('id' => $context->instanceid
));
4323 if (!$coursecatvisible) {
4324 send_file_not_found();
4328 $filename = array_pop($args);
4329 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4330 if (!$file = $fs->get_file($context->id
, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4331 send_file_not_found();
4334 \core\session\manager
::write_close(); // Unlock session during file serving.
4335 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4337 send_file_not_found();
4340 // ========================================================================================================================
4341 } else if ($component === 'course') {
4342 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4343 send_file_not_found();
4346 if ($filearea === 'summary' ||
$filearea === 'overviewfiles') {
4347 if ($CFG->forcelogin
) {
4351 $filename = array_pop($args);
4352 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4353 if (!$file = $fs->get_file($context->id
, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4354 send_file_not_found();
4357 \core\session\manager
::write_close(); // Unlock session during file serving.
4358 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4360 } else if ($filearea === 'section') {
4361 if ($CFG->forcelogin
) {
4362 require_login($course);
4363 } else if ($course->id
!= SITEID
) {
4364 require_login($course);
4367 $sectionid = (int)array_shift($args);
4369 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id
))) {
4370 send_file_not_found();
4373 $filename = array_pop($args);
4374 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4375 if (!$file = $fs->get_file($context->id
, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4376 send_file_not_found();
4379 \core\session\manager
::write_close(); // Unlock session during file serving.
4380 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4383 send_file_not_found();
4386 } else if ($component === 'cohort') {
4388 $cohortid = (int)array_shift($args);
4389 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
4390 $cohortcontext = context
::instance_by_id($cohort->contextid
);
4392 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4393 if ($context->id
!= $cohort->contextid
&&
4394 ($context->contextlevel
!= CONTEXT_COURSE ||
!in_array($cohort->contextid
, $context->get_parent_context_ids()))) {
4395 send_file_not_found();
4398 // User is able to access cohort if they have view cap on cohort level or
4399 // the cohort is visible and they have view cap on course level.
4400 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4401 ($cohort->visible
&& has_capability('moodle/cohort:view', $context));
4403 if ($filearea === 'description' && $canview) {
4404 $filename = array_pop($args);
4405 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4406 if (($file = $fs->get_file($cohortcontext->id
, 'cohort', 'description', $cohort->id
, $filepath, $filename))
4407 && !$file->is_directory()) {
4408 \core\session\manager
::write_close(); // Unlock session during file serving.
4409 send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
4413 send_file_not_found();
4415 } else if ($component === 'group') {
4416 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4417 send_file_not_found();
4420 require_course_login($course, true, null, false);
4422 $groupid = (int)array_shift($args);
4424 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id
), '*', MUST_EXIST
);
4425 if (($course->groupmodeforce
and $course->groupmode
== SEPARATEGROUPS
) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id
, $USER->id
)) {
4426 // do not allow access to separate group info if not member or teacher
4427 send_file_not_found();
4430 if ($filearea === 'description') {
4432 require_login($course);
4434 $filename = array_pop($args);
4435 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4436 if (!$file = $fs->get_file($context->id
, 'group', 'description', $group->id
, $filepath, $filename) or $file->is_directory()) {
4437 send_file_not_found();
4440 \core\session\manager
::write_close(); // Unlock session during file serving.
4441 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4443 } else if ($filearea === 'icon') {
4444 $filename = array_pop($args);
4446 if ($filename !== 'f1' and $filename !== 'f2') {
4447 send_file_not_found();
4449 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.png')) {
4450 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.jpg')) {
4451 send_file_not_found();
4455 \core\session\manager
::write_close(); // Unlock session during file serving.
4456 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4459 send_file_not_found();
4462 } else if ($component === 'grouping') {
4463 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4464 send_file_not_found();
4467 require_login($course);
4469 $groupingid = (int)array_shift($args);
4471 // note: everybody has access to grouping desc images for now
4472 if ($filearea === 'description') {
4474 $filename = array_pop($args);
4475 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4476 if (!$file = $fs->get_file($context->id
, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4477 send_file_not_found();
4480 \core\session\manager
::write_close(); // Unlock session during file serving.
4481 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4484 send_file_not_found();
4487 // ========================================================================================================================
4488 } else if ($component === 'backup') {
4489 if ($filearea === 'course' and $context->contextlevel
== CONTEXT_COURSE
) {
4490 require_login($course);
4491 require_capability('moodle/backup:downloadfile', $context);
4493 $filename = array_pop($args);
4494 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4495 if (!$file = $fs->get_file($context->id
, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4496 send_file_not_found();
4499 \core\session\manager
::write_close(); // Unlock session during file serving.
4500 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4502 } else if ($filearea === 'section' and $context->contextlevel
== CONTEXT_COURSE
) {
4503 require_login($course);
4504 require_capability('moodle/backup:downloadfile', $context);
4506 $sectionid = (int)array_shift($args);
4508 $filename = array_pop($args);
4509 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4510 if (!$file = $fs->get_file($context->id
, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4511 send_file_not_found();
4514 \core\session\manager
::write_close();
4515 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4517 } else if ($filearea === 'activity' and $context->contextlevel
== CONTEXT_MODULE
) {
4518 require_login($course, false, $cm);
4519 require_capability('moodle/backup:downloadfile', $context);
4521 $filename = array_pop($args);
4522 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4523 if (!$file = $fs->get_file($context->id
, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4524 send_file_not_found();
4527 \core\session\manager
::write_close();
4528 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4530 } else if ($filearea === 'automated' and $context->contextlevel
== CONTEXT_COURSE
) {
4531 // Backup files that were generated by the automated backup systems.
4533 require_login($course);
4534 require_capability('moodle/site:config', $context);
4536 $filename = array_pop($args);
4537 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4538 if (!$file = $fs->get_file($context->id
, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4539 send_file_not_found();
4542 \core\session\manager
::write_close(); // Unlock session during file serving.
4543 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4546 send_file_not_found();
4549 // ========================================================================================================================
4550 } else if ($component === 'question') {
4551 require_once($CFG->libdir
. '/questionlib.php');
4552 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4553 send_file_not_found();
4555 // ========================================================================================================================
4556 } else if ($component === 'grading') {
4557 if ($filearea === 'description') {
4558 // files embedded into the form definition description
4560 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4563 } else if ($context->contextlevel
>= CONTEXT_COURSE
) {
4564 require_login($course, false, $cm);
4567 send_file_not_found();
4570 $formid = (int)array_shift($args);
4572 $sql = "SELECT ga.id
4573 FROM {grading_areas} ga
4574 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4575 WHERE gd.id = ? AND ga.contextid = ?";
4576 $areaid = $DB->get_field_sql($sql, array($formid, $context->id
), IGNORE_MISSING
);
4579 send_file_not_found();
4582 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4584 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4585 send_file_not_found();
4588 \core\session\manager
::write_close(); // Unlock session during file serving.
4589 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4592 // ========================================================================================================================
4593 } else if (strpos($component, 'mod_') === 0) {
4594 $modname = substr($component, 4);
4595 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4596 send_file_not_found();
4598 require_once("$CFG->dirroot/mod/$modname/lib.php");
4600 if ($context->contextlevel
== CONTEXT_MODULE
) {
4601 if ($cm->modname
!== $modname) {
4602 // somebody tries to gain illegal access, cm type must match the component!
4603 send_file_not_found();
4607 if ($filearea === 'intro') {
4608 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO
, true)) {
4609 send_file_not_found();
4611 require_course_login($course, true, $cm);
4613 // all users may access it
4614 $filename = array_pop($args);
4615 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4616 if (!$file = $fs->get_file($context->id
, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4617 send_file_not_found();
4620 // finally send the file
4621 send_stored_file($file, null, 0, false, array('preview' => $preview));
4624 $filefunction = $component.'_pluginfile';
4625 $filefunctionold = $modname.'_pluginfile';
4626 if (function_exists($filefunction)) {
4627 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4628 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4629 } else if (function_exists($filefunctionold)) {
4630 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4631 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4634 send_file_not_found();
4636 // ========================================================================================================================
4637 } else if (strpos($component, 'block_') === 0) {
4638 $blockname = substr($component, 6);
4639 // note: no more class methods in blocks please, that is ....
4640 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4641 send_file_not_found();
4643 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4645 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4646 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid
), '*',MUST_EXIST
);
4647 if ($birecord->blockname
!== $blockname) {
4648 // somebody tries to gain illegal access, cm type must match the component!
4649 send_file_not_found();
4652 if ($context->get_course_context(false)) {
4653 // If block is in course context, then check if user has capability to access course.
4654 require_course_login($course);
4655 } else if ($CFG->forcelogin
) {
4656 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4660 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id
, 'blockinstanceid' => $context->instanceid
));
4661 // User can't access file, if block is hidden or doesn't have block:view capability
4662 if (($bprecord && !$bprecord->visible
) ||
!has_capability('moodle/block:view', $context)) {
4663 send_file_not_found();
4669 $filefunction = $component.'_pluginfile';
4670 if (function_exists($filefunction)) {
4671 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4672 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4675 send_file_not_found();
4677 // ========================================================================================================================
4678 } else if (strpos($component, '_') === false) {
4679 // all core subsystems have to be specified above, no more guessing here!
4680 send_file_not_found();
4683 // try to serve general plugin file in arbitrary context
4684 $dir = core_component
::get_component_directory($component);
4685 if (!file_exists("$dir/lib.php")) {
4686 send_file_not_found();
4688 include_once("$dir/lib.php");
4690 $filefunction = $component.'_pluginfile';
4691 if (function_exists($filefunction)) {
4692 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4693 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4696 send_file_not_found();