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');
34 * Do not process file merging when working with draft area files.
36 define('IGNORE_FILE_MERGE', -1);
39 * Unlimited area size constant
41 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
43 require_once("$CFG->libdir/filestorage/file_exceptions.php");
44 require_once("$CFG->libdir/filestorage/file_storage.php");
45 require_once("$CFG->libdir/filestorage/zip_packer.php");
46 require_once("$CFG->libdir/filebrowser/file_browser.php");
49 * Encodes file serving url
51 * @deprecated use moodle_url factory methods instead
53 * @todo MDL-31071 deprecate this function
54 * @global stdClass $CFG
55 * @param string $urlbase
56 * @param string $path /filearea/itemid/dir/dir/file.exe
57 * @param bool $forcedownload
58 * @param bool $https https url required
59 * @return string encoded file url
61 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
64 //TODO: deprecate this
66 if ($CFG->slasharguments
) {
67 $parts = explode('/', $path);
68 $parts = array_map('rawurlencode', $parts);
69 $path = implode('/', $parts);
70 $return = $urlbase.$path;
72 $return .= '?forcedownload=1';
75 $path = rawurlencode($path);
76 $return = $urlbase.'?file='.$path;
78 $return .= '&forcedownload=1';
83 $return = str_replace('http://', 'https://', $return);
90 * Detects if area contains subdirs,
91 * this is intended for file areas that are attached to content
92 * migrated from 1.x where subdirs were allowed everywhere.
94 * @param context $context
95 * @param string $component
96 * @param string $filearea
97 * @param string $itemid
100 function file_area_contains_subdirs(context
$context, $component, $filearea, $itemid) {
103 if (!isset($itemid)) {
104 // Not initialised yet.
108 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
109 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
110 $params = array('contextid'=>$context->id
, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
111 return $DB->record_exists_select('files', $select, $params);
115 * Prepares 'editor' formslib element from data in database
117 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
118 * function then copies the embedded files into draft area (assigning itemids automatically),
119 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
121 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
122 * your mform's set_data() supplying the object returned by this function.
125 * @param stdClass $data database field that holds the html text with embedded media
126 * @param string $field the name of the database field that holds the html text with embedded media
127 * @param array $options editor options (like maxifiles, maxbytes etc.)
128 * @param stdClass $context context of the editor
129 * @param string $component
130 * @param string $filearea file area name
131 * @param int $itemid item id, required if item exists
132 * @return stdClass modified data object
134 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
135 $options = (array)$options;
136 if (!isset($options['trusttext'])) {
137 $options['trusttext'] = false;
139 if (!isset($options['forcehttps'])) {
140 $options['forcehttps'] = false;
142 if (!isset($options['subdirs'])) {
143 $options['subdirs'] = false;
145 if (!isset($options['maxfiles'])) {
146 $options['maxfiles'] = 0; // no files by default
148 if (!isset($options['noclean'])) {
149 $options['noclean'] = false;
152 //sanity check for passed context. This function doesn't expect $option['context'] to be set
153 //But this function is called before creating editor hence, this is one of the best places to check
154 //if context is used properly. This check notify developer that they missed passing context to editor.
155 if (isset($context) && !isset($options['context'])) {
156 //if $context is not null then make sure $option['context'] is also set.
157 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER
);
158 } else if (isset($options['context']) && isset($context)) {
159 //If both are passed then they should be equal.
160 if ($options['context']->id
!= $context->id
) {
161 $exceptionmsg = 'Editor context ['.$options['context']->id
.'] is not equal to passed context ['.$context->id
.']';
162 throw new coding_exception($exceptionmsg);
166 if (is_null($itemid) or is_null($context)) {
170 $data = new stdClass();
172 if (!isset($data->{$field})) {
173 $data->{$field} = '';
175 if (!isset($data->{$field.'format'})) {
176 $data->{$field.'format'} = editors_get_preferred_format();
178 if (!$options['noclean']) {
179 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
183 if ($options['trusttext']) {
184 // noclean ignored if trusttext enabled
185 if (!isset($data->{$field.'trust'})) {
186 $data->{$field.'trust'} = 0;
188 $data = trusttext_pre_edit($data, $field, $context);
190 if (!$options['noclean']) {
191 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
194 $contextid = $context->id
;
197 if ($options['maxfiles'] != 0) {
198 $draftid_editor = file_get_submitted_draft_itemid($field);
199 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
200 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
202 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
209 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
211 * This function moves files from draft area to the destination area and
212 * encodes URLs to the draft files so they can be safely saved into DB. The
213 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
214 * is the name of the database field to hold the wysiwyg editor content. The
215 * editor data comes as an array with text, format and itemid properties. This
216 * function automatically adds $data properties foobar, foobarformat and
217 * foobartrust, where foobar has URL to embedded files encoded.
220 * @param stdClass $data raw data submitted by the form
221 * @param string $field name of the database field containing the html with embedded media files
222 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
223 * @param stdClass $context context, required for existing data
224 * @param string $component file component
225 * @param string $filearea file area name
226 * @param int $itemid item id, required if item exists
227 * @return stdClass modified data object
229 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
230 $options = (array)$options;
231 if (!isset($options['trusttext'])) {
232 $options['trusttext'] = false;
234 if (!isset($options['forcehttps'])) {
235 $options['forcehttps'] = false;
237 if (!isset($options['subdirs'])) {
238 $options['subdirs'] = false;
240 if (!isset($options['maxfiles'])) {
241 $options['maxfiles'] = 0; // no files by default
243 if (!isset($options['maxbytes'])) {
244 $options['maxbytes'] = 0; // unlimited
246 if (!isset($options['removeorphaneddrafts'])) {
247 $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
250 if ($options['trusttext']) {
251 $data->{$field.'trust'} = trusttext_trusted($context);
253 $data->{$field.'trust'} = 0;
256 $editor = $data->{$field.'_editor'};
258 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
259 $data->{$field} = $editor['text'];
261 // Clean the user drafts area of any files not referenced in the editor text.
262 if ($options['removeorphaneddrafts']) {
263 file_remove_editor_orphaned_files($editor);
265 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id
, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
267 $data->{$field.'format'} = $editor['format'];
273 * Saves text and files modified by Editor formslib element
276 * @param stdClass $data $database entry field
277 * @param string $field name of data field
278 * @param array $options various options
279 * @param stdClass $context context - must already exist
280 * @param string $component
281 * @param string $filearea file area name
282 * @param int $itemid must already exist, usually means data is in db
283 * @return stdClass modified data obejct
285 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
286 $options = (array)$options;
287 if (!isset($options['subdirs'])) {
288 $options['subdirs'] = false;
290 if (is_null($itemid) or is_null($context)) {
294 $contextid = $context->id
;
297 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
298 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
299 $data->{$field.'_filemanager'} = $draftid_editor;
305 * Saves files modified by File manager formslib element
307 * @todo MDL-31073 review this function
309 * @param stdClass $data $database entry field
310 * @param string $field name of data field
311 * @param array $options various options
312 * @param stdClass $context context - must already exist
313 * @param string $component
314 * @param string $filearea file area name
315 * @param int $itemid must already exist, usually means data is in db
316 * @return stdClass modified data obejct
318 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
319 $options = (array)$options;
320 if (!isset($options['subdirs'])) {
321 $options['subdirs'] = false;
323 if (!isset($options['maxfiles'])) {
324 $options['maxfiles'] = -1; // unlimited
326 if (!isset($options['maxbytes'])) {
327 $options['maxbytes'] = 0; // unlimited
330 if (empty($data->{$field.'_filemanager'})) {
334 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id
, $component, $filearea, $itemid, $options);
335 $fs = get_file_storage();
337 if ($fs->get_area_files($context->id
, $component, $filearea, $itemid)) {
338 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
348 * Generate a draft itemid
351 * @global moodle_database $DB
352 * @global stdClass $USER
353 * @return int a random but available draft itemid that can be used to create a new draft
356 function file_get_unused_draft_itemid() {
359 if (isguestuser() or !isloggedin()) {
360 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
361 print_error('noguest');
364 $contextid = context_user
::instance($USER->id
)->id
;
366 $fs = get_file_storage();
367 $draftitemid = rand(1, 999999999);
368 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
369 $draftitemid = rand(1, 999999999);
376 * Initialise a draft file area from a real one by copying the files. A draft
377 * area will be created if one does not already exist. Normally you should
378 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
381 * @global stdClass $CFG
382 * @global stdClass $USER
383 * @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.
384 * @param int $contextid This parameter and the next two identify the file area to copy files from.
385 * @param string $component
386 * @param string $filearea helps indentify the file area.
387 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
388 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
389 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
390 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
392 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
393 global $CFG, $USER, $CFG;
395 $options = (array)$options;
396 if (!isset($options['subdirs'])) {
397 $options['subdirs'] = false;
399 if (!isset($options['forcehttps'])) {
400 $options['forcehttps'] = false;
403 $usercontext = context_user
::instance($USER->id
);
404 $fs = get_file_storage();
406 if (empty($draftitemid)) {
407 // create a new area and copy existing files into
408 $draftitemid = file_get_unused_draft_itemid();
409 $file_record = array('contextid'=>$usercontext->id
, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
410 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
411 foreach ($files as $file) {
412 if ($file->is_directory() and $file->get_filepath() === '/') {
413 // we need a way to mark the age of each draft area,
414 // by not copying the root dir we force it to be created automatically with current timestamp
417 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
420 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
421 // XXX: This is a hack for file manager (MDL-28666)
422 // File manager needs to know the original file information before copying
423 // to draft area, so we append these information in mdl_files.source field
424 // {@link file_storage::search_references()}
425 // {@link file_storage::search_references_count()}
426 $sourcefield = $file->get_source();
427 $newsourcefield = new stdClass
;
428 $newsourcefield->source
= $sourcefield;
429 $original = new stdClass
;
430 $original->contextid
= $contextid;
431 $original->component
= $component;
432 $original->filearea
= $filearea;
433 $original->itemid
= $itemid;
434 $original->filename
= $file->get_filename();
435 $original->filepath
= $file->get_filepath();
436 $newsourcefield->original
= file_storage
::pack_reference($original);
437 $draftfile->set_source(serialize($newsourcefield));
438 // End of file manager hack
441 if (!is_null($text)) {
442 // at this point there should not be any draftfile links yet,
443 // because this is a new text from database that should still contain the @@pluginfile@@ links
444 // this happens when developers forget to post process the text
445 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
451 if (is_null($text)) {
455 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
456 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id
, 'user', 'draft', $draftitemid, $options);
460 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
461 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
462 * in the @@PLUGINFILE@@ form.
464 * @param string $text The content that may contain ULRs in need of rewriting.
465 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
466 * @param int $contextid This parameter and the next two identify the file area to use.
467 * @param string $component
468 * @param string $filearea helps identify the file area.
469 * @param int $itemid helps identify the file area.
470 * @param array $options
471 * bool $options.forcehttps Force the user of https
472 * bool $options.reverse Reverse the behaviour of the function
473 * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
474 * string The processed text.
476 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
479 $options = (array)$options;
480 if (!isset($options['forcehttps'])) {
481 $options['forcehttps'] = false;
484 $baseurl = "{$CFG->wwwroot}/{$file}";
485 if (!empty($options['includetoken'])) {
486 $userid = $options['includetoken'] === true ?
$USER->id
: $options['includetoken'];
487 $token = get_user_key('core_files', $userid);
488 $finalfile = basename($file);
489 $tokenfile = "token{$finalfile}";
490 $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
491 $baseurl = "{$CFG->wwwroot}/{$file}";
493 if (!$CFG->slasharguments
) {
494 $baseurl .= "?token={$token}&file=";
496 $baseurl .= "/{$token}";
500 $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
502 if ($itemid !== null) {
503 $baseurl .= "$itemid/";
506 if ($options['forcehttps']) {
507 $baseurl = str_replace('http://', 'https://', $baseurl);
510 if (!empty($options['reverse'])) {
511 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
513 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
518 * Returns information about files in a draft area.
520 * @global stdClass $CFG
521 * @global stdClass $USER
522 * @param int $draftitemid the draft area item id.
523 * @param string $filepath path to the directory from which the information have to be retrieved.
524 * @return array with the following entries:
525 * 'filecount' => number of files in the draft area.
526 * 'filesize' => total size of the files in the draft area.
527 * 'foldercount' => number of folders in the draft area.
528 * 'filesize_without_references' => total size of the area excluding file references.
529 * (more information will be added as needed).
531 function file_get_draft_area_info($draftitemid, $filepath = '/') {
534 $usercontext = context_user
::instance($USER->id
);
535 return file_get_file_area_info($usercontext->id
, 'user', 'draft', $draftitemid, $filepath);
539 * Returns information about files in an area.
541 * @param int $contextid context id
542 * @param string $component component
543 * @param string $filearea file area name
544 * @param int $itemid item id or all files if not specified
545 * @param string $filepath path to the directory from which the information have to be retrieved.
546 * @return array with the following entries:
547 * 'filecount' => number of files in the area.
548 * 'filesize' => total size of the files in the area.
549 * 'foldercount' => number of folders in the area.
550 * 'filesize_without_references' => total size of the area excluding file references.
553 function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
555 $fs = get_file_storage();
561 'filesize_without_references' => 0
564 $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
566 foreach ($draftfiles as $file) {
567 if ($file->is_directory()) {
568 $results['foldercount'] +
= 1;
570 $results['filecount'] +
= 1;
573 $filesize = $file->get_filesize();
574 $results['filesize'] +
= $filesize;
575 if (!$file->is_external_file()) {
576 $results['filesize_without_references'] +
= $filesize;
584 * Returns whether a draft area has exceeded/will exceed its size limit.
586 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
588 * @param int $draftitemid the draft area item id.
589 * @param int $areamaxbytes the maximum size allowed in this draft area.
590 * @param int $newfilesize the size that would be added to the current area.
591 * @param bool $includereferences true to include the size of the references in the area size.
592 * @return bool true if the area will/has exceeded its limit.
595 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
596 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED
) {
597 $draftinfo = file_get_draft_area_info($draftitemid);
598 $areasize = $draftinfo['filesize_without_references'];
599 if ($includereferences) {
600 $areasize = $draftinfo['filesize'];
602 if ($areasize +
$newfilesize > $areamaxbytes) {
610 * Get used space of files
611 * @global moodle_database $DB
612 * @global stdClass $USER
613 * @return int total bytes
615 function file_get_user_used_space() {
618 $usercontext = context_user
::instance($USER->id
);
619 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
620 JOIN (SELECT contenthash, filename, MAX(id) AS id
622 WHERE contextid = ? AND component = ? AND filearea != ?
623 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
624 $params = array('contextid'=>$usercontext->id
, 'component'=>'user', 'filearea'=>'draft');
625 $record = $DB->get_record_sql($sql, $params);
626 return (int)$record->totalbytes
;
630 * Convert any string to a valid filepath
631 * @todo review this function
633 * @return string path
635 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
636 if ($str == '/' or empty($str)) {
639 return '/'.trim($str, '/').'/';
644 * Generate a folder tree of draft area of current USER recursively
646 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
647 * @param int $draftitemid
648 * @param string $filepath
651 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
652 global $USER, $OUTPUT, $CFG;
653 $data->children
= array();
654 $context = context_user
::instance($USER->id
);
655 $fs = get_file_storage();
656 if ($files = $fs->get_directory_files($context->id
, 'user', 'draft', $draftitemid, $filepath, false)) {
657 foreach ($files as $file) {
658 if ($file->is_directory()) {
659 $item = new stdClass();
660 $item->sortorder
= $file->get_sortorder();
661 $item->filepath
= $file->get_filepath();
663 $foldername = explode('/', trim($item->filepath
, '/'));
664 $item->fullname
= trim(array_pop($foldername), '/');
666 $item->id
= uniqid();
667 file_get_drafarea_folders($draftitemid, $item->filepath
, $item);
668 $data->children
[] = $item;
677 * Listing all files (including folders) in current path (draft area)
678 * used by file manager
679 * @param int $draftitemid
680 * @param string $filepath
683 function file_get_drafarea_files($draftitemid, $filepath = '/') {
684 global $USER, $OUTPUT, $CFG;
686 $context = context_user
::instance($USER->id
);
687 $fs = get_file_storage();
689 $data = new stdClass();
690 $data->path
= array();
691 $data->path
[] = array('name'=>get_string('files'), 'path'=>'/');
693 // will be used to build breadcrumb
695 if ($filepath !== '/') {
696 $filepath = file_correct_filepath($filepath);
697 $parts = explode('/', $filepath);
698 foreach ($parts as $part) {
699 if ($part != '' && $part != null) {
700 $trail .= ($part.'/');
701 $data->path
[] = array('name'=>$part, 'path'=>$trail);
708 if ($files = $fs->get_directory_files($context->id
, 'user', 'draft', $draftitemid, $filepath, false)) {
709 foreach ($files as $file) {
710 $item = new stdClass();
711 $item->filename
= $file->get_filename();
712 $item->filepath
= $file->get_filepath();
713 $item->fullname
= trim($item->filename
, '/');
714 $filesize = $file->get_filesize();
715 $item->size
= $filesize ?
$filesize : null;
716 $item->filesize
= $filesize ?
display_size($filesize) : '';
718 $item->sortorder
= $file->get_sortorder();
719 $item->author
= $file->get_author();
720 $item->license
= $file->get_license();
721 $item->datemodified
= $file->get_timemodified();
722 $item->datecreated
= $file->get_timecreated();
723 $item->isref
= $file->is_external_file();
724 if ($item->isref
&& $file->get_status() == 666) {
725 $item->originalmissing
= true;
727 // find the file this draft file was created from and count all references in local
728 // system pointing to that file
729 $source = @unserialize
($file->get_source());
730 if (isset($source->original
)) {
731 $item->refcount
= $fs->search_references_count($source->original
);
734 if ($file->is_directory()) {
736 $item->icon
= $OUTPUT->image_url(file_folder_icon(24))->out(false);
737 $item->type
= 'folder';
738 $foldername = explode('/', trim($item->filepath
, '/'));
739 $item->fullname
= trim(array_pop($foldername), '/');
740 $item->thumbnail
= $OUTPUT->image_url(file_folder_icon(90))->out(false);
742 // do NOT use file browser here!
743 $item->mimetype
= get_mimetype_description($file);
744 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
747 $item->type
= 'file';
749 $itemurl = moodle_url
::make_draftfile_url($draftitemid, $item->filepath
, $item->filename
);
750 $item->url
= $itemurl->out();
751 $item->icon
= $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
752 $item->thumbnail
= $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
754 // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
755 // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
756 // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
757 // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
758 // used by the widget to display a warning about the problem files.
759 // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
760 $item->status
= $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ?
0 : 1;
761 if ($item->status
== 0) {
762 if ($imageinfo = $file->get_imageinfo()) {
763 $item->realthumbnail
= $itemurl->out(false, array('preview' => 'thumb',
764 'oid' => $file->get_timemodified()));
765 $item->realicon
= $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
766 $item->image_width
= $imageinfo['width'];
767 $item->image_height
= $imageinfo['height'];
774 $data->itemid
= $draftitemid;
780 * Returns all of the files in the draftarea.
782 * @param int $draftitemid The draft item ID
783 * @param string $filepath path for the uploaded files.
784 * @return array An array of files associated with this draft item id.
786 function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
788 $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
789 file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
791 if (!empty($draftfiles)) {
792 foreach ($draftfiles->list as $draftfile) {
793 if ($draftfile->type
== 'file') {
794 $files[] = $draftfile;
798 if (isset($draftfiles->children
)) {
799 foreach ($draftfiles->children
as $draftfile) {
800 $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath
));
808 * Returns draft area itemid for a given element.
811 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
812 * @return int the itemid, or 0 if there is not one yet.
814 function file_get_submitted_draft_itemid($elname) {
815 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
816 if (!isset($_REQUEST[$elname])) {
819 if (is_array($_REQUEST[$elname])) {
820 $param = optional_param_array($elname, 0, PARAM_INT
);
821 if (!empty($param['itemid'])) {
822 $param = $param['itemid'];
824 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER
);
829 $param = optional_param($elname, 0, PARAM_INT
);
840 * Restore the original source field from draft files
842 * Do not use this function because it makes field files.source inconsistent
843 * for draft area files. This function will be deprecated in 2.6
845 * @param stored_file $storedfile This only works with draft files
846 * @return stored_file
848 function file_restore_source_field_from_draft_file($storedfile) {
849 $source = @unserialize
($storedfile->get_source());
850 if (!empty($source)) {
851 if (is_object($source)) {
852 $restoredsource = $source->source
;
853 $storedfile->set_source($restoredsource);
855 throw new moodle_exception('invalidsourcefield', 'error');
862 * Removes those files from the user drafts filearea which are not referenced in the editor text.
864 * @param stdClass $editor The online text editor element from the submitted form data.
866 function file_remove_editor_orphaned_files($editor) {
869 // Find those draft files included in the text, and generate their hashes.
870 $context = context_user
::instance($USER->id
);
871 $baseurl = $CFG->wwwroot
. '/draftfile.php/' . $context->id
. '/user/draft/' . $editor['itemid'] . '/';
872 $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
873 preg_match_all($pattern, $editor['text'], $matches);
874 $usedfilehashes = [];
875 foreach ($matches[1] as $matchedfilename) {
876 $matchedfilename = urldecode($matchedfilename);
877 $usedfilehashes[] = \file_storage
::get_pathname_hash($context->id
, 'user', 'draft', $editor['itemid'], '/',
881 // Now, compare the hashes of all draft files, and remove those which don't match used files.
882 $fs = get_file_storage();
883 $files = $fs->get_area_files($context->id
, 'user', 'draft', $editor['itemid'], 'id', false);
884 foreach ($files as $file) {
885 $tmphash = $file->get_pathnamehash();
886 if (!in_array($tmphash, $usedfilehashes)) {
893 * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
894 * content from another draft area it's possible for a single textarea to reference multiple draft areas.
897 * @param int $draftitemid the id of the primary draft area.
898 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
899 * @param int $usercontextid the user's context id.
900 * @param string $text some html content that needs to have files copied to the correct draft area.
901 * @param bool $forcehttps force https urls.
903 * @return string $text html content modified with new draft links
905 function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
906 if (is_null($text)) {
910 // Do not merge files, leave it as it was.
911 if ($draftitemid === IGNORE_FILE_MERGE
) {
915 $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
917 // No draft areas to rewrite.
922 foreach ($urls as $url) {
923 // Do not process the "home" draft area.
924 if ($url['itemid'] == $draftitemid) {
928 // Decode the filename.
929 $filename = urldecode($url['filename']);
932 file_copy_file_to_file_area($url, $filename, $draftitemid);
934 // Rewrite draft area.
935 $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
941 * Rewrites a file area in arbitrary text.
943 * @param array $file General information about the file.
944 * @param int $newid The new file area itemid.
945 * @param string $text The text to rewrite.
946 * @param bool $forcehttps force https urls.
947 * @return string The rewritten text.
949 function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
952 $wwwroot = $CFG->wwwroot
;
954 $wwwroot = str_replace('http://', 'https://', $wwwroot);
976 $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
981 * Copies a file from one file area to another.
983 * @param array $file Information about the file to be copied.
984 * @param string $filename The filename.
985 * @param int $itemid The new file area.
987 function file_copy_file_to_file_area($file, $filename, $itemid) {
988 $fs = get_file_storage();
990 // Load the current file in the old draft area.
992 'component' => $file['component'],
993 'filearea' => $file['filearea'],
994 'itemid' => $file['itemid'],
995 'contextid' => $file['contextid'],
997 'filename' => $filename
999 $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
1000 $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
1001 $newfileinfo = array(
1002 'component' => $file['component'],
1003 'filearea' => $file['filearea'],
1004 'itemid' => $itemid,
1005 'contextid' => $file['contextid'],
1007 'filename' => $filename
1010 $newcontextid = $newfileinfo['contextid'];
1011 $newcomponent = $newfileinfo['component'];
1012 $newfilearea = $newfileinfo['filearea'];
1013 $newitemid = $newfileinfo['itemid'];
1014 $newfilepath = $newfileinfo['filepath'];
1015 $newfilename = $newfileinfo['filename'];
1017 // Check if the file exists.
1018 if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1019 $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1024 * Saves files from a draft file area to a real one (merging the list of files).
1025 * Can rewrite URLs in some content at the same time if desired.
1028 * @global stdClass $USER
1029 * @param int $draftitemid the id of the draft area to use. Normally obtained
1030 * from file_get_submitted_draft_itemid('elementname') or similar.
1031 * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
1032 * @param int $contextid This parameter and the next two identify the file area to save to.
1033 * @param string $component
1034 * @param string $filearea indentifies the file area.
1035 * @param int $itemid helps identifies the file area.
1036 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1037 * @param string $text some html content that needs to have embedded links rewritten
1038 * to the @@PLUGINFILE@@ form for saving in the database.
1039 * @param bool $forcehttps force https urls.
1040 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1042 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1045 // Do not merge files, leave it as it was.
1046 if ($draftitemid === IGNORE_FILE_MERGE
) {
1047 // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
1051 $usercontext = context_user
::instance($USER->id
);
1052 $fs = get_file_storage();
1054 $options = (array)$options;
1055 if (!isset($options['subdirs'])) {
1056 $options['subdirs'] = false;
1058 if (!isset($options['maxfiles'])) {
1059 $options['maxfiles'] = -1; // unlimited
1061 if (!isset($options['maxbytes']) ||
$options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
1062 $options['maxbytes'] = 0; // unlimited
1064 if (!isset($options['areamaxbytes'])) {
1065 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED
; // Unlimited.
1067 $allowreferences = true;
1068 if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK
))) {
1069 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1070 // this is not exactly right. BUT there are many places in code where filemanager options
1071 // are not passed to file_save_draft_area_files()
1072 $allowreferences = false;
1075 // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1076 // areas and need to be copied into the current draft area.
1077 $text = file_merge_draft_areas($draftitemid, $usercontext->id
, $text, $forcehttps);
1079 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1080 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1081 // anything at all in the next area.
1082 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1086 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id');
1087 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1089 // One file in filearea means it is empty (it has only top-level directory '.').
1090 if (count($draftfiles) > 1 ||
count($oldfiles) > 1) {
1091 // we have to merge old and new files - we want to keep file ids for files that were not changed
1092 // we change time modified for all new and changed files, we keep time created as is
1094 $newhashes = array();
1096 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1097 foreach ($draftfiles as $file) {
1098 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1101 if (!$allowreferences && $file->is_external_file()) {
1104 if (!$file->is_directory()) {
1105 // Check to see if this file was uploaded by someone who can ignore the file size limits.
1106 $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1107 if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1108 && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1112 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1113 // more files - should not get here at all
1118 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1119 $newhashes[$newhash] = $file;
1122 // Loop through oldfiles and decide which we need to delete and which to update.
1123 // After this cycle the array $newhashes will only contain the files that need to be added.
1124 foreach ($oldfiles as $oldfile) {
1125 $oldhash = $oldfile->get_pathnamehash();
1126 if (!isset($newhashes[$oldhash])) {
1127 // delete files not needed any more - deleted by user
1132 $newfile = $newhashes[$oldhash];
1133 // Now we know that we have $oldfile and $newfile for the same path.
1134 // Let's check if we can update this file or we need to delete and create.
1135 if ($newfile->is_directory()) {
1136 // Directories are always ok to just update.
1137 } else if (($source = @unserialize
($newfile->get_source())) && isset($source->original
)) {
1138 // File has the 'original' - we need to update the file (it may even have not been changed at all).
1139 $original = file_storage
::unpack_reference($source->original
);
1140 if ($original['filename'] !== $oldfile->get_filename() ||
$original['filepath'] !== $oldfile->get_filepath()) {
1141 // Very odd, original points to another file. Delete and create file.
1146 // The same file name but absence of 'original' means that file was deteled and uploaded again.
1147 // By deleting and creating new file we properly manage all existing references.
1152 // status changed, we delete old file, and create a new one
1153 if ($oldfile->get_status() != $newfile->get_status()) {
1154 // file was changed, use updated with new timemodified data
1156 // This file will be added later
1161 if ($oldfile->get_author() != $newfile->get_author()) {
1162 $oldfile->set_author($newfile->get_author());
1165 if ($oldfile->get_license() != $newfile->get_license()) {
1166 $oldfile->set_license($newfile->get_license());
1169 // Updated file source
1170 // Field files.source for draftarea files contains serialised object with source and original information.
1171 // We only store the source part of it for non-draft file area.
1172 $newsource = $newfile->get_source();
1173 if ($source = @unserialize
($newfile->get_source())) {
1174 $newsource = $source->source
;
1176 if ($oldfile->get_source() !== $newsource) {
1177 $oldfile->set_source($newsource);
1180 // Updated sort order
1181 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1182 $oldfile->set_sortorder($newfile->get_sortorder());
1185 // Update file timemodified
1186 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1187 $oldfile->set_timemodified($newfile->get_timemodified());
1190 // Replaced file content
1191 if (!$oldfile->is_directory() &&
1192 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1193 $oldfile->get_filesize() != $newfile->get_filesize() ||
1194 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1195 $oldfile->get_userid() != $newfile->get_userid())) {
1196 $oldfile->replace_file_with($newfile);
1199 // unchanged file or directory - we keep it as is
1200 unset($newhashes[$oldhash]);
1203 // Add fresh file or the file which has changed status
1204 // the size and subdirectory tests are extra safety only, the UI should prevent it
1205 foreach ($newhashes as $file) {
1206 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1207 if ($source = @unserialize
($file->get_source())) {
1208 // Field files.source for draftarea files contains serialised object with source and original information.
1209 // We only store the source part of it for non-draft file area.
1210 $file_record['source'] = $source->source
;
1213 if ($file->is_external_file()) {
1214 $repoid = $file->get_repository_id();
1215 if (!empty($repoid)) {
1216 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1217 $repo = repository
::get_repository_by_id($repoid, $context);
1218 if (!empty($options)) {
1219 $repo->options
= $options;
1221 $file_record['repositoryid'] = $repoid;
1222 // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1223 // to the file store. E.g. transfer ownership of the file to a system account etc.
1224 $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1226 $file_record['reference'] = $reference;
1230 $fs->create_file_from_storedfile($file_record, $file);
1234 // note: do not purge the draft area - we clean up areas later in cron,
1235 // the reason is that user might press submit twice and they would loose the files,
1236 // also sometimes we might want to use hacks that save files into two different areas
1238 if (is_null($text)) {
1241 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1246 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1247 * ready to be saved in the database. Normally, this is done automatically by
1248 * {@link file_save_draft_area_files()}.
1251 * @param string $text the content to process.
1252 * @param int $draftitemid the draft file area the content was using.
1253 * @param bool $forcehttps whether the content contains https URLs. Default false.
1254 * @return string the processed content.
1256 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1259 $usercontext = context_user
::instance($USER->id
);
1261 $wwwroot = $CFG->wwwroot
;
1263 $wwwroot = str_replace('http://', 'https://', $wwwroot);
1266 // relink embedded files if text submitted - no absolute links allowed in database!
1267 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1269 if (strpos($text, 'draftfile.php?file=') !== false) {
1271 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1273 foreach ($matches[0] as $match) {
1274 $replace = str_ireplace('%2F', '/', $match);
1275 $text = str_replace($match, $replace, $text);
1278 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1285 * Set file sort order
1287 * @global moodle_database $DB
1288 * @param int $contextid the context id
1289 * @param string $component file component
1290 * @param string $filearea file area.
1291 * @param int $itemid itemid.
1292 * @param string $filepath file path.
1293 * @param string $filename file name.
1294 * @param int $sortorder the sort order of file.
1297 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1299 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1300 if ($file_record = $DB->get_record('files', $conditions)) {
1301 $sortorder = (int)$sortorder;
1302 $file_record->sortorder
= $sortorder;
1303 $DB->update_record('files', $file_record);
1310 * reset file sort order number to 0
1311 * @global moodle_database $DB
1312 * @param int $contextid the context id
1313 * @param string $component
1314 * @param string $filearea file area.
1315 * @param int|bool $itemid itemid.
1318 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1321 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1322 if ($itemid !== false) {
1323 $conditions['itemid'] = $itemid;
1326 $file_records = $DB->get_records('files', $conditions);
1327 foreach ($file_records as $file_record) {
1328 $file_record->sortorder
= 0;
1329 $DB->update_record('files', $file_record);
1335 * Returns description of upload error
1337 * @param int $errorcode found in $_FILES['filename.ext']['error']
1338 * @return string error description string, '' if ok
1340 function file_get_upload_error($errorcode) {
1342 switch ($errorcode) {
1343 case 0: // UPLOAD_ERR_OK - no error
1347 case 1: // UPLOAD_ERR_INI_SIZE
1348 $errmessage = get_string('uploadserverlimit');
1351 case 2: // UPLOAD_ERR_FORM_SIZE
1352 $errmessage = get_string('uploadformlimit');
1355 case 3: // UPLOAD_ERR_PARTIAL
1356 $errmessage = get_string('uploadpartialfile');
1359 case 4: // UPLOAD_ERR_NO_FILE
1360 $errmessage = get_string('uploadnofilefound');
1363 // Note: there is no error with a value of 5
1365 case 6: // UPLOAD_ERR_NO_TMP_DIR
1366 $errmessage = get_string('uploadnotempdir');
1369 case 7: // UPLOAD_ERR_CANT_WRITE
1370 $errmessage = get_string('uploadcantwrite');
1373 case 8: // UPLOAD_ERR_EXTENSION
1374 $errmessage = get_string('uploadextension');
1378 $errmessage = get_string('uploadproblem');
1385 * Recursive function formating an array in POST parameter
1386 * @param array $arraydata - the array that we are going to format and add into &$data array
1387 * @param string $currentdata - a row of the final postdata array at instant T
1388 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1389 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1391 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1392 foreach ($arraydata as $k=>$v) {
1393 $newcurrentdata = $currentdata;
1394 if (is_array($v)) { //the value is an array, call the function recursively
1395 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1396 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1397 } else { //add the POST parameter to the $data array
1398 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1404 * Transform a PHP array into POST parameter
1405 * (see the recursive function format_array_postdata_for_curlcall)
1406 * @param array $postdata
1407 * @return array containing all POST parameters (1 row = 1 POST parameter)
1409 function format_postdata_for_curlcall($postdata) {
1411 foreach ($postdata as $k=>$v) {
1413 $currentdata = urlencode($k);
1414 format_array_postdata_for_curlcall($v, $currentdata, $data);
1416 $data[] = urlencode($k).'='.urlencode($v);
1419 $convertedpostdata = implode('&', $data);
1420 return $convertedpostdata;
1424 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1425 * Due to security concerns only downloads from http(s) sources are supported.
1428 * @param string $url file url starting with http(s)://
1429 * @param array $headers http headers, null if none. If set, should be an
1430 * associative array of header name => value pairs.
1431 * @param array $postdata array means use POST request with given parameters
1432 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1433 * (if false, just returns content)
1434 * @param int $timeout timeout for complete download process including all file transfer
1435 * (default 5 minutes)
1436 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1437 * usually happens if the remote server is completely down (default 20 seconds);
1438 * may not work when using proxy
1439 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1440 * Only use this when already in a trusted location.
1441 * @param string $tofile store the downloaded content to file instead of returning it.
1442 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1443 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1444 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1445 * if file downloaded into $tofile successfully or the file content as a string.
1447 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1450 // Only http and https links supported.
1451 if (!preg_match('|^https?://|i', $url)) {
1452 if ($fullresponse) {
1453 $response = new stdClass();
1454 $response->status
= 0;
1455 $response->headers
= array();
1456 $response->response_code
= 'Invalid protocol specified in url';
1457 $response->results
= '';
1458 $response->error
= 'Invalid protocol specified in url';
1467 $headers2 = array();
1468 if (is_array($headers)) {
1469 foreach ($headers as $key => $value) {
1470 if (is_numeric($key)) {
1471 $headers2[] = $value;
1473 $headers2[] = "$key: $value";
1478 if ($skipcertverify) {
1479 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1481 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1484 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1486 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1487 $options['CURLOPT_MAXREDIRS'] = 5;
1489 // Use POST if requested.
1490 if (is_array($postdata)) {
1491 $postdata = format_postdata_for_curlcall($postdata);
1492 } else if (empty($postdata)) {
1496 // Optionally attempt to get more correct timeout by fetching the file size.
1497 if (!isset($CFG->curltimeoutkbitrate
)) {
1498 // Use very slow rate of 56kbps as a timeout speed when not set.
1501 $bitrate = $CFG->curltimeoutkbitrate
;
1503 if ($calctimeout and !isset($postdata)) {
1505 $curl->setHeader($headers2);
1507 $curl->head($url, $postdata, $options);
1509 $info = $curl->get_info();
1510 $error_no = $curl->get_errno();
1511 if (!$error_no && $info['download_content_length'] > 0) {
1512 // No curl errors - adjust for large files only - take max timeout.
1513 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1518 $curl->setHeader($headers2);
1520 $options['CURLOPT_RETURNTRANSFER'] = true;
1521 $options['CURLOPT_NOBODY'] = false;
1522 $options['CURLOPT_TIMEOUT'] = $timeout;
1525 $fh = fopen($tofile, 'w');
1527 if ($fullresponse) {
1528 $response = new stdClass();
1529 $response->status
= 0;
1530 $response->headers
= array();
1531 $response->response_code
= 'Can not write to file';
1532 $response->results
= false;
1533 $response->error
= 'Can not write to file';
1539 $options['CURLOPT_FILE'] = $fh;
1542 if (isset($postdata)) {
1543 $content = $curl->post($url, $postdata, $options);
1545 $content = $curl->get($url, null, $options);
1550 @chmod
($tofile, $CFG->filepermissions
);
1554 // Try to detect encoding problems.
1555 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1556 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1557 $result = curl_exec($ch);
1561 $info = $curl->get_info();
1562 $error_no = $curl->get_errno();
1563 $rawheaders = $curl->get_raw_response();
1567 if (!$fullresponse) {
1568 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
1572 $response = new stdClass();
1573 if ($error_no == 28) {
1574 $response->status
= '-100'; // Mimic snoopy.
1576 $response->status
= '0';
1578 $response->headers
= array();
1579 $response->response_code
= $error;
1580 $response->results
= false;
1581 $response->error
= $error;
1589 if (empty($info['http_code'])) {
1590 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1591 $response = new stdClass();
1592 $response->status
= '0';
1593 $response->headers
= array();
1594 $response->response_code
= 'Unknown cURL error';
1595 $response->results
= false; // do NOT change this, we really want to ignore the result!
1596 $response->error
= 'Unknown cURL error';
1599 $response = new stdClass();
1600 $response->status
= (string)$info['http_code'];
1601 $response->headers
= $rawheaders;
1602 $response->results
= $content;
1603 $response->error
= '';
1605 // There might be multiple headers on redirect, find the status of the last one.
1607 foreach ($rawheaders as $line) {
1609 $response->response_code
= $line;
1612 if (trim($line, "\r\n") === '') {
1618 if ($fullresponse) {
1622 if ($info['http_code'] != 200) {
1623 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
1626 return $response->results
;
1630 * Returns a list of information about file types based on extensions.
1632 * The following elements expected in value array for each extension:
1634 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1635 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1636 * also files with bigger sizes under names
1637 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1638 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1639 * commonly used in moodle the following groups:
1640 * - web_image - image that can be included as <img> in HTML
1641 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1642 * - video - file that can be imported as video in text editor
1643 * - audio - file that can be imported as audio in text editor
1644 * - archive - we can extract files from this archive
1645 * - spreadsheet - used for portfolio format
1646 * - document - used for portfolio format
1647 * - presentation - used for portfolio format
1648 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1649 * human-readable description for this filetype;
1650 * Function {@link get_mimetype_description()} first looks at the presence of string for
1651 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1652 * attribute, if not found returns the value of 'type';
1653 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1654 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1655 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1658 * @return array List of information about file types based on extensions.
1659 * Associative array of extension (lower-case) to associative array
1660 * from 'element name' to data. Current element names are 'type' and 'icon'.
1661 * Unknown types should use the 'xxx' entry which includes defaults.
1663 function &get_mimetypes_array() {
1664 // Get types from the core_filetypes function, which includes caching.
1665 return core_filetypes
::get_types();
1669 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1671 * This function retrieves a file's MIME type for a file that will be sent to the user.
1672 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1673 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1674 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1676 * @param string $filename The file's filename.
1677 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1679 function get_mimetype_for_sending($filename = '') {
1680 // Guess the file's MIME type using mimeinfo.
1681 $mimetype = mimeinfo('type', $filename);
1683 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1684 if (!$mimetype ||
$mimetype === 'document/unknown') {
1685 $mimetype = 'application/octet-stream';
1692 * Obtains information about a filetype based on its extension. Will
1693 * use a default if no information is present about that particular
1697 * @param string $element Desired information (usually 'icon'
1698 * for icon filename or 'type' for MIME type. Can also be
1699 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1700 * @param string $filename Filename we're looking up
1701 * @return string Requested piece of information from array
1703 function mimeinfo($element, $filename) {
1705 $mimeinfo = & get_mimetypes_array();
1706 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1708 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1709 if (empty($filetype)) {
1710 $filetype = 'xxx'; // file without extension
1712 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1713 $iconsize = max(array(16, (int)$iconsizematch[1]));
1714 $filenames = array($mimeinfo['xxx']['icon']);
1715 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1716 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1718 // find the file with the closest size, first search for specific icon then for default icon
1719 foreach ($filenames as $filename) {
1720 foreach ($iconpostfixes as $size => $postfix) {
1721 $fullname = $CFG->dirroot
.'/pix/f/'.$filename.$postfix;
1722 if ($iconsize >= $size &&
1723 (file_exists($fullname.'.svg') ||
file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1724 return $filename.$postfix;
1728 } else if (isset($mimeinfo[$filetype][$element])) {
1729 return $mimeinfo[$filetype][$element];
1730 } else if (isset($mimeinfo['xxx'][$element])) {
1731 return $mimeinfo['xxx'][$element]; // By default
1738 * Obtains information about a filetype based on the MIME type rather than
1739 * the other way around.
1742 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1743 * @param string $mimetype MIME type we're looking up
1744 * @return string Requested piece of information from array
1746 function mimeinfo_from_type($element, $mimetype) {
1747 /* array of cached mimetype->extension associations */
1748 static $cached = array();
1749 $mimeinfo = & get_mimetypes_array();
1751 if (!array_key_exists($mimetype, $cached)) {
1752 $cached[$mimetype] = null;
1753 foreach($mimeinfo as $filetype => $values) {
1754 if ($values['type'] == $mimetype) {
1755 if ($cached[$mimetype] === null) {
1756 $cached[$mimetype] = '.'.$filetype;
1758 if (!empty($values['defaulticon'])) {
1759 $cached[$mimetype] = '.'.$filetype;
1764 if (empty($cached[$mimetype])) {
1765 $cached[$mimetype] = '.xxx';
1768 if ($element === 'extension') {
1769 return $cached[$mimetype];
1771 return mimeinfo($element, $cached[$mimetype]);
1776 * Return the relative icon path for a given file
1780 * // $file - instance of stored_file or file_info
1781 * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1782 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1786 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1789 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1790 * and $file->mimetype are expected)
1791 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1794 function file_file_icon($file, $size = null) {
1795 if (!is_object($file)) {
1796 $file = (object)$file;
1798 if (isset($file->filename
)) {
1799 $filename = $file->filename
;
1800 } else if (method_exists($file, 'get_filename')) {
1801 $filename = $file->get_filename();
1802 } else if (method_exists($file, 'get_visible_name')) {
1803 $filename = $file->get_visible_name();
1807 if (isset($file->mimetype
)) {
1808 $mimetype = $file->mimetype
;
1809 } else if (method_exists($file, 'get_mimetype')) {
1810 $mimetype = $file->get_mimetype();
1814 $mimetypes = &get_mimetypes_array();
1816 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1817 if ($extension && !empty($mimetypes[$extension])) {
1818 // if file name has known extension, return icon for this extension
1819 return file_extension_icon($filename, $size);
1822 return file_mimetype_icon($mimetype, $size);
1826 * Return the relative icon path for a folder image
1830 * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1831 * echo html_writer::empty_tag('img', array('src' => $icon));
1835 * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1838 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1841 function file_folder_icon($iconsize = null) {
1843 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1844 static $cached = array();
1845 $iconsize = max(array(16, (int)$iconsize));
1846 if (!array_key_exists($iconsize, $cached)) {
1847 foreach ($iconpostfixes as $size => $postfix) {
1848 $fullname = $CFG->dirroot
.'/pix/f/folder'.$postfix;
1849 if ($iconsize >= $size &&
1850 (file_exists($fullname.'.svg') ||
file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1851 $cached[$iconsize] = 'f/folder'.$postfix;
1856 return $cached[$iconsize];
1860 * Returns the relative icon path for a given mime type
1862 * This function should be used in conjunction with $OUTPUT->image_url to produce
1863 * a return the full path to an icon.
1866 * $mimetype = 'image/jpg';
1867 * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1868 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1872 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1873 * to conform with that.
1874 * @param string $mimetype The mimetype to fetch an icon for
1875 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1876 * @return string The relative path to the icon
1878 function file_mimetype_icon($mimetype, $size = NULL) {
1879 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1883 * Returns the relative icon path for a given file name
1885 * This function should be used in conjunction with $OUTPUT->image_url to produce
1886 * a return the full path to an icon.
1889 * $filename = '.jpg';
1890 * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1891 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1894 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1895 * to conform with that.
1896 * @todo MDL-31074 Implement $size
1898 * @param string $filename The filename to get the icon for
1899 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1902 function file_extension_icon($filename, $size = NULL) {
1903 return 'f/'.mimeinfo('icon'.$size, $filename);
1907 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1908 * mimetypes.php language file.
1910 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1911 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1912 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1913 * @param bool $capitalise If true, capitalises first character of result
1914 * @return string Text description
1916 function get_mimetype_description($obj, $capitalise=false) {
1917 $filename = $mimetype = '';
1918 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1919 // this is an instance of stored_file
1920 $mimetype = $obj->get_mimetype();
1921 $filename = $obj->get_filename();
1922 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1923 // this is an instance of file_info
1924 $mimetype = $obj->get_mimetype();
1925 $filename = $obj->get_visible_name();
1926 } else if (is_array($obj) ||
is_object ($obj)) {
1928 if (!empty($obj['filename'])) {
1929 $filename = $obj['filename'];
1931 if (!empty($obj['mimetype'])) {
1932 $mimetype = $obj['mimetype'];
1937 $mimetypefromext = mimeinfo('type', $filename);
1938 if (empty($mimetype) ||
$mimetypefromext !== 'document/unknown') {
1939 // if file has a known extension, overwrite the specified mimetype
1940 $mimetype = $mimetypefromext;
1942 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1943 if (empty($extension)) {
1944 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1945 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1947 $mimetypestr = mimeinfo('string', $filename);
1949 $chunks = explode('/', $mimetype, 2);
1952 'mimetype' => $mimetype,
1953 'ext' => $extension,
1954 'mimetype1' => $chunks[0],
1955 'mimetype2' => $chunks[1],
1958 foreach ($attr as $key => $value) {
1960 $a[strtoupper($key)] = strtoupper($value);
1961 $a[ucfirst($key)] = ucfirst($value);
1964 // MIME types may include + symbol but this is not permitted in string ids.
1965 $safemimetype = str_replace('+', '_', $mimetype);
1966 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1967 $customdescription = mimeinfo('customdescription', $filename);
1968 if ($customdescription) {
1969 // Call format_string on the custom description so that multilang
1970 // filter can be used (if enabled on system context). We use system
1971 // context because it is possible that the page context might not have
1972 // been defined yet.
1973 $result = format_string($customdescription, true,
1974 array('context' => context_system
::instance()));
1975 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1976 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1977 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1978 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1979 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1980 $result = get_string('default', 'mimetypes', (object)$a);
1982 $result = $mimetype;
1985 $result=ucfirst($result);
1991 * Returns array of elements of type $element in type group(s)
1993 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1994 * @param string|array $groups one group or array of groups/extensions/mimetypes
1997 function file_get_typegroup($element, $groups) {
1998 static $cached = array();
1999 if (!is_array($groups)) {
2000 $groups = array($groups);
2002 if (!array_key_exists($element, $cached)) {
2003 $cached[$element] = array();
2006 foreach ($groups as $group) {
2007 if (!array_key_exists($group, $cached[$element])) {
2008 // retrieive and cache all elements of type $element for group $group
2009 $mimeinfo = & get_mimetypes_array();
2010 $cached[$element][$group] = array();
2011 foreach ($mimeinfo as $extension => $value) {
2012 $value['extension'] = '.'.$extension;
2013 if (empty($value[$element])) {
2016 if (($group === '.'.$extension ||
$group === $value['type'] ||
2017 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
2018 !in_array($value[$element], $cached[$element][$group])) {
2019 $cached[$element][$group][] = $value[$element];
2023 $result = array_merge($result, $cached[$element][$group]);
2025 return array_values(array_unique($result));
2029 * Checks if file with name $filename has one of the extensions in groups $groups
2031 * @see get_mimetypes_array()
2032 * @param string $filename name of the file to check
2033 * @param string|array $groups one group or array of groups to check
2034 * @param bool $checktype if true and extension check fails, find the mimetype and check if
2035 * file mimetype is in mimetypes in groups $groups
2038 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2039 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
2040 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2043 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2047 * Checks if mimetype $mimetype belongs to one of the groups $groups
2049 * @see get_mimetypes_array()
2050 * @param string $mimetype
2051 * @param string|array $groups one group or array of groups to check
2054 function file_mimetype_in_typegroup($mimetype, $groups) {
2055 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2059 * Requested file is not found or not accessible, does not return, terminates script
2061 * @global stdClass $CFG
2062 * @global stdClass $COURSE
2064 function send_file_not_found() {
2065 global $CFG, $COURSE;
2067 // Allow cross-origin requests only for Web Services.
2068 // This allow to receive requests done by Web Workers or webapps in different domains.
2070 header('Access-Control-Allow-Origin: *');
2074 print_error('filenotfound', 'error', $CFG->wwwroot
.'/course/view.php?id='.$COURSE->id
); //this is not displayed on IIS??
2077 * Helper function to send correct 404 for server.
2079 function send_header_404() {
2080 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2081 header("Status: 404 Not Found");
2083 header('HTTP/1.0 404 not found');
2088 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2089 * platforms). This wrapper uses readfile for small files and custom code for
2092 * @param string $path Path to file
2093 * @param int $filesize Size of file (if left out, will get it automatically)
2094 * @return int|bool Size read (will always be $filesize) or false if failed
2096 function readfile_allow_large($path, $filesize = -1) {
2097 // Automatically get size if not specified.
2098 if ($filesize === -1) {
2099 $filesize = filesize($path);
2101 if ($filesize <= 2147483647) {
2102 // If the file is up to 2^31 - 1, send it normally using readfile.
2103 return readfile($path);
2105 // For large files, read and output in 64KB chunks.
2106 $handle = fopen($path, 'r');
2107 if ($handle === false) {
2112 $size = min($left, 65536);
2113 $buffer = fread($handle, $size);
2114 if ($buffer === false) {
2125 * Enhanced readfile() with optional acceleration.
2126 * @param string|stored_file $file
2127 * @param string $mimetype
2128 * @param bool $accelerate
2131 function readfile_accel($file, $mimetype, $accelerate) {
2134 if ($mimetype === 'text/plain') {
2135 // there is no encoding specified in text files, we need something consistent
2136 header('Content-Type: text/plain; charset=utf-8');
2138 header('Content-Type: '.$mimetype);
2141 $lastmodified = is_object($file) ?
$file->get_timemodified() : filemtime($file);
2142 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2144 if (is_object($file)) {
2145 header('Etag: "' . $file->get_contenthash() . '"');
2146 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2147 header('HTTP/1.1 304 Not Modified');
2152 // if etag present for stored file rely on it exclusively
2153 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2154 // get unixtime of request header; clip extra junk off first
2155 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2156 if ($since && $since >= $lastmodified) {
2157 header('HTTP/1.1 304 Not Modified');
2162 if ($accelerate and empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
2163 header('Accept-Ranges: bytes');
2165 header('Accept-Ranges: none');
2169 if (is_object($file)) {
2170 $fs = get_file_storage();
2171 if ($fs->supports_xsendfile()) {
2172 if ($fs->xsendfile($file->get_contenthash())) {
2177 if (!empty($CFG->xsendfile
)) {
2178 require_once("$CFG->libdir/xsendfilelib.php");
2179 if (xsendfile($file)) {
2186 $filesize = is_object($file) ?
$file->get_filesize() : filesize($file);
2188 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2190 if ($accelerate and empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
2192 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2193 // byteserving stuff - for acrobat reader and download accelerators
2194 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2195 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2197 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
2198 foreach ($ranges as $key=>$value) {
2199 if ($ranges[$key][1] == '') {
2201 $ranges[$key][1] = $filesize - $ranges[$key][2];
2202 $ranges[$key][2] = $filesize - 1;
2203 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
2205 $ranges[$key][2] = $filesize - 1;
2207 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2208 //invalid byte-range ==> ignore header
2212 //prepare multipart header
2213 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
2214 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2220 if (is_object($file)) {
2221 $handle = $file->get_content_file_handle();
2223 $handle = fopen($file, 'rb');
2225 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2230 header('Content-Length: '.$filesize);
2232 if ($filesize > 10000000) {
2233 // for large files try to flush and close all buffers to conserve memory
2234 while(@ob_get_level
()) {
2235 if (!@ob_end_flush
()) {
2241 // send the whole file content
2242 if (is_object($file)) {
2245 readfile_allow_large($file, $filesize);
2250 * Similar to readfile_accel() but designed for strings.
2251 * @param string $string
2252 * @param string $mimetype
2253 * @param bool $accelerate Ignored
2256 function readstring_accel($string, $mimetype, $accelerate = false) {
2259 if ($mimetype === 'text/plain') {
2260 // there is no encoding specified in text files, we need something consistent
2261 header('Content-Type: text/plain; charset=utf-8');
2263 header('Content-Type: '.$mimetype);
2265 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2266 header('Accept-Ranges: none');
2267 header('Content-Length: '.strlen($string));
2272 * Handles the sending of temporary file to user, download is forced.
2273 * File is deleted after abort or successful sending, does not return, script terminated
2275 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2276 * @param string $filename proposed file name when saving file
2277 * @param bool $pathisstring If the path is string
2279 function send_temp_file($path, $filename, $pathisstring=false) {
2282 // Guess the file's MIME type.
2283 $mimetype = get_mimetype_for_sending($filename);
2285 // close session - not needed anymore
2286 \core\session\manager
::write_close();
2288 if (!$pathisstring) {
2289 if (!file_exists($path)) {
2291 print_error('filenotfound', 'error', $CFG->wwwroot
.'/');
2293 // executed after normal finish or abort
2294 core_shutdown_manager
::register_function('send_temp_file_finished', array($path));
2297 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2298 if (core_useragent
::is_ie() || core_useragent
::is_edge()) {
2299 $filename = urlencode($filename);
2302 header('Content-Disposition: attachment; filename="'.$filename.'"');
2303 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2304 header('Cache-Control: private, max-age=10, no-transform');
2305 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2307 } else { //normal http - prevent caching at all cost
2308 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2309 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2310 header('Pragma: no-cache');
2313 // send the contents - we can not accelerate this because the file will be deleted asap
2314 if ($pathisstring) {
2315 readstring_accel($path, $mimetype);
2317 readfile_accel($path, $mimetype, false);
2321 die; //no more chars to output
2325 * Internal callback function used by send_temp_file()
2327 * @param string $path
2329 function send_temp_file_finished($path) {
2330 if (file_exists($path)) {
2336 * Serve content which is not meant to be cached.
2338 * This is only intended to be used for volatile public files, for instance
2339 * when development is enabled, or when caching is not required on a public resource.
2341 * @param string $content Raw content.
2342 * @param string $filename The file name.
2345 function send_content_uncached($content, $filename) {
2346 $mimetype = mimeinfo('type', $filename);
2347 $charset = strpos($mimetype, 'text/') === 0 ?
'; charset=utf-8' : '';
2349 header('Content-Disposition: inline; filename="' . $filename . '"');
2350 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2351 header('Expires: ' . gmdate('D, d M Y H:i:s', time() +
2) . ' GMT');
2353 header('Accept-Ranges: none');
2354 header('Content-Type: ' . $mimetype . $charset);
2355 header('Content-Length: ' . strlen($content));
2362 * Safely save content to a certain path.
2364 * This function tries hard to be atomic by first copying the content
2365 * to a separate file, and then moving the file across. It also prevents
2366 * the user to abort a request to prevent half-safed files.
2368 * This function is intended to be used when saving some content to cache like
2369 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2371 * @param string $content The file content.
2372 * @param string $destination The absolute path of the final file.
2375 function file_safe_save_content($content, $destination) {
2379 if (!file_exists(dirname($destination))) {
2380 @mkdir
(dirname($destination), $CFG->directorypermissions
, true);
2383 // Prevent serving of incomplete file from concurrent request,
2384 // the rename() should be more atomic than fwrite().
2385 ignore_user_abort(true);
2386 if ($fp = fopen($destination . '.tmp', 'xb')) {
2387 fwrite($fp, $content);
2389 rename($destination . '.tmp', $destination);
2390 @chmod
($destination, $CFG->filepermissions
);
2391 @unlink
($destination . '.tmp'); // Just in case anything fails.
2393 ignore_user_abort(false);
2394 if (connection_aborted()) {
2400 * Handles the sending of file data to the user's browser, including support for
2404 * @param string|stored_file $path Path of file on disk (including real filename),
2405 * or actual content of file as string,
2406 * or stored_file object
2407 * @param string $filename Filename to send
2408 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2409 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2410 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2411 * Forced to false when $path is a stored_file object.
2412 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2413 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2414 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2415 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2416 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2417 * and should not be reopened.
2418 * @param array $options An array of options, currently accepts:
2419 * - (string) cacheability: public, or private.
2420 * - (string|null) immutable
2421 * @return null script execution stopped unless $dontdie is true
2423 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2424 $dontdie=false, array $options = array()) {
2425 global $CFG, $COURSE;
2428 ignore_user_abort(true);
2431 if ($lifetime === 'default' or is_null($lifetime)) {
2432 $lifetime = $CFG->filelifetime
;
2435 if (is_object($path)) {
2436 $pathisstring = false;
2439 \core\session\manager
::write_close(); // Unlock session during file serving.
2441 // Use given MIME type if specified, otherwise guess it.
2442 if (!$mimetype ||
$mimetype === 'document/unknown') {
2443 $mimetype = get_mimetype_for_sending($filename);
2446 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2447 if (core_useragent
::is_ie() || core_useragent
::is_edge()) {
2448 $filename = rawurlencode($filename);
2451 if ($forcedownload) {
2452 header('Content-Disposition: attachment; filename="'.$filename.'"');
2453 } else if ($mimetype !== 'application/x-shockwave-flash') {
2454 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2455 // as an upload and enforces security that may prevent the file from being loaded.
2457 header('Content-Disposition: inline; filename="'.$filename.'"');
2460 if ($lifetime > 0) {
2462 if (!empty($options['immutable'])) {
2463 $immutable = ', immutable';
2464 // Overwrite lifetime accordingly:
2465 // 90 days only - based on Moodle point release cadence being every 3 months.
2466 $lifetimemin = 60 * 60 * 24 * 90;
2467 $lifetime = max($lifetime, $lifetimemin);
2469 $cacheability = ' public,';
2470 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2471 // This file must be cache-able by both browsers and proxies.
2472 $cacheability = ' public,';
2473 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2474 // This file must be cache-able only by browsers.
2475 $cacheability = ' private,';
2476 } else if (isloggedin() and !isguestuser()) {
2477 // By default, under the conditions above, this file must be cache-able only by browsers.
2478 $cacheability = ' private,';
2480 $nobyteserving = false;
2481 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2482 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
2485 } else { // Do not cache files in proxies and browsers
2486 $nobyteserving = true;
2487 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2488 header('Cache-Control: private, max-age=10, no-transform');
2489 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2491 } else { //normal http - prevent caching at all cost
2492 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2493 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2494 header('Pragma: no-cache');
2498 if (empty($filter)) {
2499 // send the contents
2500 if ($pathisstring) {
2501 readstring_accel($path, $mimetype);
2503 readfile_accel($path, $mimetype, !$dontdie);
2507 // Try to put the file through filters
2508 if ($mimetype == 'text/html' ||
$mimetype == 'application/xhtml+xml') {
2509 $options = new stdClass();
2510 $options->noclean
= true;
2511 $options->nocache
= true; // temporary workaround for MDL-5136
2512 if (is_object($path)) {
2513 $text = $path->get_content();
2514 } else if ($pathisstring) {
2517 $text = implode('', file($path));
2519 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
2521 readstring_accel($output, $mimetype);
2523 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2524 // only filter text if filter all files is selected
2525 $options = new stdClass();
2526 $options->newlines
= false;
2527 $options->noclean
= true;
2528 if (is_object($path)) {
2529 $text = htmlentities($path->get_content(), ENT_QUOTES
, 'UTF-8');
2530 } else if ($pathisstring) {
2531 $text = htmlentities($path, ENT_QUOTES
, 'UTF-8');
2533 $text = htmlentities(implode('', file($path)), ENT_QUOTES
, 'UTF-8');
2535 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
2537 readstring_accel($output, $mimetype);
2540 // send the contents
2541 if ($pathisstring) {
2542 readstring_accel($path, $mimetype);
2544 readfile_accel($path, $mimetype, !$dontdie);
2551 die; //no more chars to output!!!
2555 * Handles the sending of file data to the user's browser, including support for
2558 * The $options parameter supports the following keys:
2559 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2560 * (string|null) filename - overrides the implicit filename
2561 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2562 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2563 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2564 * and should not be reopened
2565 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2566 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2567 * defaults to "public".
2568 * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2569 * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2572 * @param stored_file $stored_file local file object
2573 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2574 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2575 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2576 * @param array $options additional options affecting the file serving
2577 * @return null script execution stopped unless $options['dontdie'] is true
2579 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2580 global $CFG, $COURSE;
2582 if (empty($options['filename'])) {
2585 $filename = $options['filename'];
2588 if (empty($options['dontdie'])) {
2594 if ($lifetime === 'default' or is_null($lifetime)) {
2595 $lifetime = $CFG->filelifetime
;
2598 if (!empty($options['preview'])) {
2599 // replace the file with its preview
2600 $fs = get_file_storage();
2601 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2602 if (!$preview_file) {
2603 // unable to create a preview of the file, send its default mime icon instead
2604 if ($options['preview'] === 'tinyicon') {
2606 } else if ($options['preview'] === 'thumb') {
2611 $fileicon = file_file_icon($stored_file, $size);
2612 send_file($CFG->dirroot
.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2614 // preview images have fixed cache lifetime and they ignore forced download
2615 // (they are generated by GD and therefore they are considered reasonably safe).
2616 $stored_file = $preview_file;
2617 $lifetime = DAYSECS
;
2619 $forcedownload = false;
2623 // handle external resource
2624 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2625 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2629 if (!$stored_file or $stored_file->is_directory()) {
2637 $filename = is_null($filename) ?
$stored_file->get_filename() : $filename;
2639 // Use given MIME type if specified.
2640 $mimetype = $stored_file->get_mimetype();
2642 // Allow cross-origin requests only for Web Services.
2643 // This allow to receive requests done by Web Workers or webapps in different domains.
2645 header('Access-Control-Allow-Origin: *');
2648 send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2652 * Recursively delete the file or folder with path $location. That is,
2653 * if it is a file delete it. If it is a folder, delete all its content
2654 * then delete it. If $location does not exist to start, that is not
2655 * considered an error.
2657 * @param string $location the path to remove.
2660 function fulldelete($location) {
2661 if (empty($location)) {
2662 // extra safety against wrong param
2665 if (is_dir($location)) {
2666 if (!$currdir = opendir($location)) {
2669 while (false !== ($file = readdir($currdir))) {
2670 if ($file <> ".." && $file <> ".") {
2671 $fullfile = $location."/".$file;
2672 if (is_dir($fullfile)) {
2673 if (!fulldelete($fullfile)) {
2677 if (!unlink($fullfile)) {
2684 if (! rmdir($location)) {
2688 } else if (file_exists($location)) {
2689 if (!unlink($location)) {
2697 * Send requested byterange of file.
2699 * @param resource $handle A file handle
2700 * @param string $mimetype The mimetype for the output
2701 * @param array $ranges An array of ranges to send
2702 * @param string $filesize The size of the content if only one range is used
2704 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2705 // better turn off any kind of compression and buffering
2706 ini_set('zlib.output_compression', 'Off');
2708 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2709 if ($handle === false) {
2712 if (count($ranges) == 1) { //only one range requested
2713 $length = $ranges[0][2] - $ranges[0][1] +
1;
2714 header('HTTP/1.1 206 Partial content');
2715 header('Content-Length: '.$length);
2716 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2717 header('Content-Type: '.$mimetype);
2719 while(@ob_get_level
()) {
2720 if (!@ob_end_flush
()) {
2725 fseek($handle, $ranges[0][1]);
2726 while (!feof($handle) && $length > 0) {
2727 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2728 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2731 $length -= strlen($buffer);
2735 } else { // multiple ranges requested - not tested much
2737 foreach($ranges as $range) {
2738 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
2740 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
2741 header('HTTP/1.1 206 Partial content');
2742 header('Content-Length: '.$totallength);
2743 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
2745 while(@ob_get_level
()) {
2746 if (!@ob_end_flush
()) {
2751 foreach($ranges as $range) {
2752 $length = $range[2] - $range[1] +
1;
2754 fseek($handle, $range[1]);
2755 while (!feof($handle) && $length > 0) {
2756 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2757 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2760 $length -= strlen($buffer);
2763 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
2770 * Tells whether the filename is executable.
2772 * @link http://php.net/manual/en/function.is-executable.php
2773 * @link https://bugs.php.net/bug.php?id=41062
2774 * @param string $filename Path to the file.
2775 * @return bool True if the filename exists and is executable; otherwise, false.
2777 function file_is_executable($filename) {
2778 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
2779 if (is_executable($filename)) {
2782 $fileext = strrchr($filename, '.');
2783 // If we have an extension we can check if it is listed as executable.
2784 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2785 $winpathext = strtolower(getenv('PATHEXT'));
2786 $winpathexts = explode(';', $winpathext);
2788 return in_array(strtolower($fileext), $winpathexts);
2794 return is_executable($filename);
2799 * Overwrite an existing file in a draft area.
2801 * @param stored_file $newfile the new file with the new content and meta-data
2802 * @param stored_file $existingfile the file that will be overwritten
2803 * @throws moodle_exception
2806 function file_overwrite_existing_draftfile(stored_file
$newfile, stored_file
$existingfile) {
2807 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2808 throw new coding_exception('The file to overwrite is not in a draft area.');
2811 $fs = get_file_storage();
2812 // Remember original file source field.
2813 $source = @unserialize
($existingfile->get_source());
2814 // Remember the original sortorder.
2815 $sortorder = $existingfile->get_sortorder();
2816 if ($newfile->is_external_file()) {
2817 // New file is a reference. Check that existing file does not have any other files referencing to it
2818 if (isset($source->original
) && $fs->search_references_count($source->original
)) {
2819 throw new moodle_exception('errordoublereference', 'repository');
2823 // Delete existing file to release filename.
2824 $newfilerecord = array(
2825 'contextid' => $existingfile->get_contextid(),
2826 'component' => 'user',
2827 'filearea' => 'draft',
2828 'itemid' => $existingfile->get_itemid(),
2829 'timemodified' => time()
2831 $existingfile->delete();
2834 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2835 // Preserve original file location (stored in source field) for handling references.
2836 if (isset($source->original
)) {
2837 if (!($newfilesource = @unserialize
($newfile->get_source()))) {
2838 $newfilesource = new stdClass();
2840 $newfilesource->original
= $source->original
;
2841 $newfile->set_source(serialize($newfilesource));
2843 $newfile->set_sortorder($sortorder);
2847 * Add files from a draft area into a final area.
2849 * Most of the time you do not want to use this. It is intended to be used
2850 * by asynchronous services which cannot direcly manipulate a final
2851 * area through a draft area. Instead they add files to a new draft
2852 * area and merge that new draft into the final area when ready.
2854 * @param int $draftitemid the id of the draft area to use.
2855 * @param int $contextid this parameter and the next two identify the file area to save to.
2856 * @param string $component component name
2857 * @param string $filearea indentifies the file area
2858 * @param int $itemid identifies the item id or false for all items in the file area
2859 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2860 * @see file_save_draft_area_files
2863 function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2864 array $options = null) {
2865 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2867 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2868 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2869 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2873 * Merge files from two draftarea areas.
2875 * This does not handle conflict resolution, files in the destination area which appear
2876 * to be more recent will be kept disregarding the intended ones.
2878 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2879 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2880 * @throws coding_exception
2883 function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2886 $fs = get_file_storage();
2887 $contextid = context_user
::instance($USER->id
)->id
;
2889 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2890 throw new coding_exception('Nothing to merge or area does not belong to current user');
2893 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2895 // Get hashes of the files to merge.
2896 $newhashes = array();
2897 foreach ($filestomerge as $filetomerge) {
2898 $filepath = $filetomerge->get_filepath();
2899 $filename = $filetomerge->get_filename();
2901 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2902 $newhashes[$newhash] = $filetomerge;
2905 // Calculate wich files must be added.
2906 foreach ($currentfiles as $file) {
2907 $filehash = $file->get_pathnamehash();
2908 // One file to be merged already exists.
2909 if (isset($newhashes[$filehash])) {
2910 $updatedfile = $newhashes[$filehash];
2912 // Avoid race conditions.
2913 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2914 // The existing file is more recent, do not copy the suposedly "new" one.
2915 unset($newhashes[$filehash]);
2918 // Update existing file (not only content, meta-data too).
2919 file_overwrite_existing_draftfile($updatedfile, $file);
2920 unset($newhashes[$filehash]);
2924 foreach ($newhashes as $newfile) {
2925 $newfilerecord = array(
2926 'contextid' => $contextid,
2927 'component' => 'user',
2928 'filearea' => 'draft',
2929 'itemid' => $mergeintodraftid,
2930 'timemodified' => time()
2933 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2938 * RESTful cURL class
2940 * This is a wrapper class for curl, it is quite easy to use:
2944 * $c = new curl(array('cache'=>true));
2946 * $c = new curl(array('cookie'=>true));
2948 * $c = new curl(array('proxy'=>true));
2950 * // HTTP GET Method
2951 * $html = $c->get('http://example.com');
2952 * // HTTP POST Method
2953 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2954 * // HTTP PUT Method
2955 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2958 * @package core_files
2960 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2961 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2964 /** @var bool Caches http request contents */
2965 public $cache = false;
2966 /** @var bool Uses proxy, null means automatic based on URL */
2967 public $proxy = null;
2968 /** @var string library version */
2969 public $version = '0.4 dev';
2970 /** @var array http's response */
2971 public $response = array();
2972 /** @var array Raw response headers, needed for BC in download_file_content(). */
2973 public $rawresponse = array();
2974 /** @var array http header */
2975 public $header = array();
2976 /** @var string cURL information */
2978 /** @var string error */
2980 /** @var int error code */
2982 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2983 public $emulateredirects = null;
2985 /** @var array cURL options */
2988 /** @var string Proxy host */
2989 private $proxy_host = '';
2990 /** @var string Proxy auth */
2991 private $proxy_auth = '';
2992 /** @var string Proxy type */
2993 private $proxy_type = '';
2994 /** @var bool Debug mode on */
2995 private $debug = false;
2996 /** @var bool|string Path to cookie file */
2997 private $cookie = false;
2998 /** @var bool tracks multiple headers in response - redirect detection */
2999 private $responsefinished = false;
3000 /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
3001 private $securityhelper;
3002 /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
3003 private $ignoresecurity;
3004 /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
3005 private static $mockresponses = [];
3010 * Allowed settings are:
3011 * proxy: (bool) use proxy server, null means autodetect non-local from url
3012 * debug: (bool) use debug output
3013 * cookie: (string) path to cookie file, false if none
3014 * cache: (bool) use cache
3015 * module_cache: (string) type of cache
3016 * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3017 * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3019 * @param array $settings
3021 public function __construct($settings = array()) {
3023 if (!function_exists('curl_init')) {
3024 $this->error
= 'cURL module must be enabled!';
3025 trigger_error($this->error
, E_USER_ERROR
);
3029 // All settings of this class should be init here.
3031 if (!empty($settings['debug'])) {
3032 $this->debug
= true;
3034 if (!empty($settings['cookie'])) {
3035 if($settings['cookie'] === true) {
3036 $this->cookie
= $CFG->dataroot
.'/curl_cookie.txt';
3038 $this->cookie
= $settings['cookie'];
3041 if (!empty($settings['cache'])) {
3042 if (class_exists('curl_cache')) {
3043 if (!empty($settings['module_cache'])) {
3044 $this->cache
= new curl_cache($settings['module_cache']);
3046 $this->cache
= new curl_cache('misc');
3050 if (!empty($CFG->proxyhost
)) {
3051 if (empty($CFG->proxyport
)) {
3052 $this->proxy_host
= $CFG->proxyhost
;
3054 $this->proxy_host
= $CFG->proxyhost
.':'.$CFG->proxyport
;
3056 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
3057 $this->proxy_auth
= $CFG->proxyuser
.':'.$CFG->proxypassword
;
3058 $this->setopt(array(
3059 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM
,
3060 'proxyuserpwd'=>$this->proxy_auth
));
3062 if (!empty($CFG->proxytype
)) {
3063 if ($CFG->proxytype
== 'SOCKS5') {
3064 $this->proxy_type
= CURLPROXY_SOCKS5
;
3066 $this->proxy_type
= CURLPROXY_HTTP
;
3067 $this->setopt(array('httpproxytunnel'=>false));
3069 $this->setopt(array('proxytype'=>$this->proxy_type
));
3072 if (isset($settings['proxy'])) {
3073 $this->proxy
= $settings['proxy'];
3076 $this->proxy
= false;
3079 if (!isset($this->emulateredirects
)) {
3080 $this->emulateredirects
= ini_get('open_basedir');
3083 // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3084 if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base
) {
3085 $this->set_security($settings['securityhelper']);
3087 $this->set_security(new \core\files\
curl_security_helper());
3089 $this->ignoresecurity
= isset($settings['ignoresecurity']) ?
$settings['ignoresecurity'] : false;
3093 * Resets the CURL options that have already been set
3095 public function resetopt() {
3096 $this->options
= array();
3097 $this->options
['CURLOPT_USERAGENT'] = \core_useragent
::get_moodlebot_useragent();
3098 // True to include the header in the output
3099 $this->options
['CURLOPT_HEADER'] = 0;
3100 // True to Exclude the body from the output
3101 $this->options
['CURLOPT_NOBODY'] = 0;
3102 // Redirect ny default.
3103 $this->options
['CURLOPT_FOLLOWLOCATION'] = 1;
3104 $this->options
['CURLOPT_MAXREDIRS'] = 10;
3105 $this->options
['CURLOPT_ENCODING'] = '';
3106 // TRUE to return the transfer as a string of the return
3107 // value of curl_exec() instead of outputting it out directly.
3108 $this->options
['CURLOPT_RETURNTRANSFER'] = 1;
3109 $this->options
['CURLOPT_SSL_VERIFYPEER'] = 0;
3110 $this->options
['CURLOPT_SSL_VERIFYHOST'] = 2;
3111 $this->options
['CURLOPT_CONNECTTIMEOUT'] = 30;
3113 if ($cacert = self
::get_cacert()) {
3114 $this->options
['CURLOPT_CAINFO'] = $cacert;
3119 * Get the location of ca certificates.
3120 * @return string absolute file path or empty if default used
3122 public static function get_cacert() {
3125 // Bundle in dataroot always wins.
3126 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3127 return realpath("$CFG->dataroot/moodleorgca.crt");
3130 // Next comes the default from php.ini
3131 $cacert = ini_get('curl.cainfo');
3132 if (!empty($cacert) and is_readable($cacert)) {
3133 return realpath($cacert);
3136 // Windows PHP does not have any certs, we need to use something.
3137 if ($CFG->ostype
=== 'WINDOWS') {
3138 if (is_readable("$CFG->libdir/cacert.pem")) {
3139 return realpath("$CFG->libdir/cacert.pem");
3143 // Use default, this should work fine on all properly configured *nix systems.
3150 public function resetcookie() {
3151 if (!empty($this->cookie
)) {
3152 if (is_file($this->cookie
)) {
3153 $fp = fopen($this->cookie
, 'w');
3165 * Do not use the curl constants to define the options, pass a string
3166 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3167 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3169 * @param array $options If array is null, this function will reset the options to default value.
3171 * @throws coding_exception If an option uses constant value instead of option name.
3173 public function setopt($options = array()) {
3174 if (is_array($options)) {
3175 foreach ($options as $name => $val) {
3176 if (!is_string($name)) {
3177 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3179 if (stripos($name, 'CURLOPT_') === false) {
3180 $name = strtoupper('CURLOPT_'.$name);
3182 $name = strtoupper($name);
3184 $this->options
[$name] = $val;
3192 public function cleanopt() {
3193 unset($this->options
['CURLOPT_HTTPGET']);
3194 unset($this->options
['CURLOPT_POST']);
3195 unset($this->options
['CURLOPT_POSTFIELDS']);
3196 unset($this->options
['CURLOPT_PUT']);
3197 unset($this->options
['CURLOPT_INFILE']);
3198 unset($this->options
['CURLOPT_INFILESIZE']);
3199 unset($this->options
['CURLOPT_CUSTOMREQUEST']);
3200 unset($this->options
['CURLOPT_FILE']);
3204 * Resets the HTTP Request headers (to prepare for the new request)
3206 public function resetHeader() {
3207 $this->header
= array();
3211 * Set HTTP Request Header
3213 * @param array $header
3215 public function setHeader($header) {
3216 if (is_array($header)) {
3217 foreach ($header as $v) {
3218 $this->setHeader($v);
3221 // Remove newlines, they are not allowed in headers.
3222 $newvalue = preg_replace('/[\r\n]/', '', $header);
3223 if (!in_array($newvalue, $this->header
)) {
3224 $this->header
[] = $newvalue;
3230 * Get HTTP Response Headers
3231 * @return array of arrays
3233 public function getResponse() {
3234 return $this->response
;
3238 * Get raw HTTP Response Headers
3239 * @return array of strings
3241 public function get_raw_response() {
3242 return $this->rawresponse
;
3246 * private callback function
3247 * Formatting HTTP Response Header
3249 * We only keep the last headers returned. For example during a redirect the
3250 * redirect headers will not appear in {@link self::getResponse()}, if you need
3251 * to use those headers, refer to {@link self::get_raw_response()}.
3253 * @param resource $ch Apparently not used
3254 * @param string $header
3255 * @return int The strlen of the header
3257 private function formatHeader($ch, $header) {
3258 $this->rawresponse
[] = $header;
3260 if (trim($header, "\r\n") === '') {
3261 // This must be the last header.
3262 $this->responsefinished
= true;
3265 if (strlen($header) > 2) {
3266 if ($this->responsefinished
) {
3267 // We still have headers after the supposedly last header, we must be
3268 // in a redirect so let's empty the response to keep the last headers.
3269 $this->responsefinished
= false;
3270 $this->response
= array();
3272 $parts = explode(" ", rtrim($header, "\r\n"), 2);
3273 $key = rtrim($parts[0], ':');
3274 $value = isset($parts[1]) ?
$parts[1] : null;
3275 if (!empty($this->response
[$key])) {
3276 if (is_array($this->response
[$key])) {
3277 $this->response
[$key][] = $value;
3279 $tmp = $this->response
[$key];
3280 $this->response
[$key] = array();
3281 $this->response
[$key][] = $tmp;
3282 $this->response
[$key][] = $value;
3286 $this->response
[$key] = $value;
3289 return strlen($header);
3293 * Set options for individual curl instance
3295 * @param resource $curl A curl handle
3296 * @param array $options
3297 * @return resource The curl handle
3299 private function apply_opt($curl, $options) {
3303 if (!empty($this->cookie
) ||
!empty($options['cookie'])) {
3304 $this->setopt(array('cookiejar'=>$this->cookie
,
3305 'cookiefile'=>$this->cookie
3309 // Bypass proxy if required.
3310 if ($this->proxy
=== null) {
3311 if (!empty($this->options
['CURLOPT_URL']) and is_proxybypass($this->options
['CURLOPT_URL'])) {
3317 $proxy = (bool)$this->proxy
;
3322 $options['CURLOPT_PROXY'] = $this->proxy_host
;
3324 unset($this->options
['CURLOPT_PROXY']);
3327 $this->setopt($options);
3329 // Reset before set options.
3330 curl_setopt($curl, CURLOPT_HEADERFUNCTION
, array(&$this,'formatHeader'));
3332 // Setting the User-Agent based on options provided.
3335 if (!empty($options['CURLOPT_USERAGENT'])) {
3336 $useragent = $options['CURLOPT_USERAGENT'];
3337 } else if (!empty($this->options
['CURLOPT_USERAGENT'])) {
3338 $useragent = $this->options
['CURLOPT_USERAGENT'];
3340 $useragent = \core_useragent
::get_moodlebot_useragent();
3344 if (empty($this->header
)) {
3345 $this->setHeader(array(
3346 'User-Agent: ' . $useragent,
3347 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3348 'Connection: keep-alive'
3350 } else if (!in_array('User-Agent: ' . $useragent, $this->header
)) {
3351 // Remove old User-Agent if one existed.
3352 // We have to partial search since we don't know what the original User-Agent is.
3353 if ($match = preg_grep('/User-Agent.*/', $this->header
)) {
3354 $key = array_keys($match)[0];
3355 unset($this->header
[$key]);
3357 $this->setHeader(array('User-Agent: ' . $useragent));
3359 curl_setopt($curl, CURLOPT_HTTPHEADER
, $this->header
);
3362 echo '<h1>Options</h1>';
3363 var_dump($this->options
);
3364 echo '<h1>Header</h1>';
3365 var_dump($this->header
);
3368 // Do not allow infinite redirects.
3369 if (!isset($this->options
['CURLOPT_MAXREDIRS'])) {
3370 $this->options
['CURLOPT_MAXREDIRS'] = 0;
3371 } else if ($this->options
['CURLOPT_MAXREDIRS'] > 100) {
3372 $this->options
['CURLOPT_MAXREDIRS'] = 100;
3374 $this->options
['CURLOPT_MAXREDIRS'] = (int)$this->options
['CURLOPT_MAXREDIRS'];
3377 // Make sure we always know if redirects expected.
3378 if (!isset($this->options
['CURLOPT_FOLLOWLOCATION'])) {
3379 $this->options
['CURLOPT_FOLLOWLOCATION'] = 0;
3382 // Limit the protocols to HTTP and HTTPS.
3383 if (defined('CURLOPT_PROTOCOLS')) {
3384 $this->options
['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3385 $this->options
['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3389 foreach($this->options
as $name => $val) {
3390 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects
) {
3391 // The redirects are emulated elsewhere.
3392 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, 0);
3395 $name = constant($name);
3396 curl_setopt($curl, $name, $val);
3403 * Download multiple files in parallel
3405 * Calls {@link multi()} with specific download headers
3409 * $file1 = fopen('a', 'wb');
3410 * $file2 = fopen('b', 'wb');
3411 * $c->download(array(
3412 * array('url'=>'http://localhost/', 'file'=>$file1),
3413 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3423 * $c->download(array(
3424 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3425 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3429 * @param array $requests An array of files to request {
3430 * url => url to download the file [required]
3431 * file => file handler, or
3432 * filepath => file path
3434 * If 'file' and 'filepath' parameters are both specified in one request, the
3435 * open file handle in the 'file' parameter will take precedence and 'filepath'
3438 * @param array $options An array of options to set
3439 * @return array An array of results
3441 public function download($requests, $options = array()) {
3442 $options['RETURNTRANSFER'] = false;
3443 return $this->multi($requests, $options);
3447 * Returns the current curl security helper.
3449 * @return \core\files\curl_security_helper instance.
3451 public function get_security() {
3452 return $this->securityhelper
;
3456 * Sets the curl security helper.
3458 * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3459 * @return bool true if the security helper could be set, false otherwise.
3461 public function set_security($securityobject) {
3462 if ($securityobject instanceof \core\files\curl_security_helper
) {
3463 $this->securityhelper
= $securityobject;
3470 * Multi HTTP Requests
3471 * This function could run multi-requests in parallel.
3473 * @param array $requests An array of files to request
3474 * @param array $options An array of options to set
3475 * @return array An array of results
3477 protected function multi($requests, $options = array()) {
3478 $count = count($requests);
3481 $main = curl_multi_init();
3482 for ($i = 0; $i < $count; $i++
) {
3483 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3485 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3486 $requests[$i]['auto-handle'] = true;
3488 foreach($requests[$i] as $n=>$v) {
3491 $handles[$i] = curl_init($requests[$i]['url']);
3492 $this->apply_opt($handles[$i], $options);
3493 curl_multi_add_handle($main, $handles[$i]);
3497 curl_multi_exec($main, $running);
3498 } while($running > 0);
3499 for ($i = 0; $i < $count; $i++
) {
3500 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3503 $results[] = curl_multi_getcontent($handles[$i]);
3505 curl_multi_remove_handle($main, $handles[$i]);
3507 curl_multi_close($main);
3509 for ($i = 0; $i < $count; $i++
) {
3510 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3511 // close file handler if file is opened in this function
3512 fclose($requests[$i]['file']);
3519 * Helper function to reset the request state vars.
3523 protected function reset_request_state_vars() {
3524 $this->info
= array();
3527 $this->response
= array();
3528 $this->rawresponse
= array();
3529 $this->responsefinished
= false;
3533 * For use only in unit tests - we can pre-set the next curl response.
3534 * This is useful for unit testing APIs that call external systems.
3535 * @param string $response
3537 public static function mock_response($response) {
3538 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST
)) {
3539 array_push(self
::$mockresponses, $response);
3541 throw new coding_exception('mock_response function is only available for unit tests.');
3546 * Single HTTP Request
3548 * @param string $url The URL to request
3549 * @param array $options
3552 protected function request($url, $options = array()) {
3553 // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3554 $this->reset_request_state_vars();
3556 if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST
)) {
3557 if ($mockresponse = array_pop(self
::$mockresponses)) {
3558 $this->info
= [ 'http_code' => 200 ];
3559 return $mockresponse;
3563 // If curl security is enabled, check the URL against the blacklist before calling curl_exec.
3564 // Note: This will only check the base url. In the case of redirects, the blacklist is also after the curl_exec.
3565 if (!$this->ignoresecurity
&& $this->securityhelper
->url_is_blocked($url)) {
3566 $this->error
= $this->securityhelper
->get_blocked_url_string();
3567 return $this->error
;
3570 // Set the URL as a curl option.
3571 $this->setopt(array('CURLOPT_URL' => $url));
3573 // Create curl instance.
3574 $curl = curl_init();
3576 $this->apply_opt($curl, $options);
3577 if ($this->cache
&& $ret = $this->cache
->get($this->options
)) {
3581 $ret = curl_exec($curl);
3582 $this->info
= curl_getinfo($curl);
3583 $this->error
= curl_error($curl);
3584 $this->errno
= curl_errno($curl);
3585 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3587 // In the case of redirects (which curl blindly follows), check the post-redirect URL against the blacklist entries too.
3588 if (intval($this->info
['redirect_count']) > 0 && !$this->ignoresecurity
3589 && $this->securityhelper
->url_is_blocked($this->info
['url'])) {
3590 $this->reset_request_state_vars();
3591 $this->error
= $this->securityhelper
->get_blocked_url_string();
3593 return $this->error
;
3596 if ($this->emulateredirects
and $this->options
['CURLOPT_FOLLOWLOCATION'] and $this->info
['http_code'] != 200) {
3599 while($redirects <= $this->options
['CURLOPT_MAXREDIRS']) {
3601 if ($this->info
['http_code'] == 301) {
3602 // Moved Permanently - repeat the same request on new URL.
3604 } else if ($this->info
['http_code'] == 302) {
3605 // Found - the standard redirect - repeat the same request on new URL.
3607 } else if ($this->info
['http_code'] == 303) {
3608 // 303 See Other - repeat only if GET, do not bother with POSTs.
3609 if (empty($this->options
['CURLOPT_HTTPGET'])) {
3613 } else if ($this->info
['http_code'] == 307) {
3614 // Temporary Redirect - must repeat using the same request type.
3616 } else if ($this->info
['http_code'] == 308) {
3617 // Permanent Redirect - must repeat using the same request type.
3620 // Some other http code means do not retry!
3626 $redirecturl = null;
3627 if (isset($this->info
['redirect_url'])) {
3628 if (preg_match('|^https?://|i', $this->info
['redirect_url'])) {
3629 $redirecturl = $this->info
['redirect_url'];
3632 if (!$redirecturl) {
3633 foreach ($this->response
as $k => $v) {
3634 if (strtolower($k) === 'location') {
3639 if (preg_match('|^https?://|i', $redirecturl)) {
3640 // Great, this is the correct location format!
3642 } else if ($redirecturl) {
3643 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL
);
3644 if (strpos($redirecturl, '/') === 0) {
3645 // Relative to server root - just guess.
3646 $pos = strpos('/', $current, 8);
3647 if ($pos === false) {
3648 $redirecturl = $current.$redirecturl;
3650 $redirecturl = substr($current, 0, $pos).$redirecturl;
3653 // Relative to current script.
3654 $redirecturl = dirname($current).'/'.$redirecturl;
3659 curl_setopt($curl, CURLOPT_URL
, $redirecturl);
3660 $ret = curl_exec($curl);
3662 $this->info
= curl_getinfo($curl);
3663 $this->error
= curl_error($curl);
3664 $this->errno
= curl_errno($curl);
3666 $this->info
['redirect_count'] = $redirects;
3668 if ($this->info
['http_code'] === 200) {
3669 // Finally this is what we wanted.
3672 if ($this->errno
!= CURLE_OK
) {
3673 // Something wrong is going on.
3677 if ($redirects > $this->options
['CURLOPT_MAXREDIRS']) {
3678 $this->errno
= CURLE_TOO_MANY_REDIRECTS
;
3679 $this->error
= 'Maximum ('.$this->options
['CURLOPT_MAXREDIRS'].') redirects followed';
3684 $this->cache
->set($this->options
, $ret);
3688 echo '<h1>Return Data</h1>';
3690 echo '<h1>Info</h1>';
3691 var_dump($this->info
);
3692 echo '<h1>Error</h1>';
3693 var_dump($this->error
);
3698 if (empty($this->error
)) {
3701 return $this->error
;
3702 // exception is not ajax friendly
3703 //throw new moodle_exception($this->error, 'curl');
3712 * @param string $url
3713 * @param array $options
3716 public function head($url, $options = array()) {
3717 $options['CURLOPT_HTTPGET'] = 0;
3718 $options['CURLOPT_HEADER'] = 1;
3719 $options['CURLOPT_NOBODY'] = 1;
3720 return $this->request($url, $options);
3726 * @param string $url
3727 * @param array|string $params
3728 * @param array $options
3731 public function patch($url, $params = '', $options = array()) {
3732 $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3733 if (is_array($params)) {
3734 $this->_tmp_file_post_params
= array();
3735 foreach ($params as $key => $value) {
3736 if ($value instanceof stored_file
) {
3737 $value->add_to_curl_request($this, $key);
3739 $this->_tmp_file_post_params
[$key] = $value;
3742 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
3743 unset($this->_tmp_file_post_params
);
3745 // The variable $params is the raw post data.
3746 $options['CURLOPT_POSTFIELDS'] = $params;
3748 return $this->request($url, $options);
3754 * @param string $url
3755 * @param array|string $params
3756 * @param array $options
3759 public function post($url, $params = '', $options = array()) {
3760 $options['CURLOPT_POST'] = 1;
3761 if (is_array($params)) {
3762 $this->_tmp_file_post_params
= array();
3763 foreach ($params as $key => $value) {
3764 if ($value instanceof stored_file
) {
3765 $value->add_to_curl_request($this, $key);
3767 $this->_tmp_file_post_params
[$key] = $value;
3770 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
3771 unset($this->_tmp_file_post_params
);
3773 // $params is the raw post data
3774 $options['CURLOPT_POSTFIELDS'] = $params;
3776 return $this->request($url, $options);
3782 * @param string $url
3783 * @param array $params
3784 * @param array $options
3787 public function get($url, $params = array(), $options = array()) {
3788 $options['CURLOPT_HTTPGET'] = 1;
3790 if (!empty($params)) {
3791 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3792 $url .= http_build_query($params, '', '&');
3794 return $this->request($url, $options);
3798 * Downloads one file and writes it to the specified file handler
3802 * $file = fopen('savepath', 'w');
3803 * $result = $c->download_one('http://localhost/', null,
3804 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3806 * $download_info = $c->get_info();
3807 * if ($result === true) {
3808 * // file downloaded successfully
3810 * $error_text = $result;
3811 * $error_code = $c->get_errno();
3817 * $result = $c->download_one('http://localhost/', null,
3818 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3819 * // ... see above, no need to close handle and remove file if unsuccessful
3822 * @param string $url
3823 * @param array|null $params key-value pairs to be added to $url as query string
3824 * @param array $options request options. Must include either 'file' or 'filepath'
3825 * @return bool|string true on success or error string on failure
3827 public function download_one($url, $params, $options = array()) {
3828 $options['CURLOPT_HTTPGET'] = 1;
3829 if (!empty($params)) {
3830 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3831 $url .= http_build_query($params, '', '&');
3833 if (!empty($options['filepath']) && empty($options['file'])) {
3835 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3837 return get_string('cannotwritefile', 'error', $options['filepath']);
3839 $filepath = $options['filepath'];
3841 unset($options['filepath']);
3842 $result = $this->request($url, $options);
3843 if (isset($filepath)) {
3844 fclose($options['file']);
3845 if ($result !== true) {
3855 * @param string $url
3856 * @param array $params
3857 * @param array $options
3860 public function put($url, $params = array(), $options = array()) {
3863 if (isset($params['file'])) {
3864 $file = $params['file'];
3865 if (is_file($file)) {
3866 $fp = fopen($file, 'r');
3867 $size = filesize($file);
3868 $options['CURLOPT_PUT'] = 1;
3869 $options['CURLOPT_INFILESIZE'] = $size;
3870 $options['CURLOPT_INFILE'] = $fp;
3874 if (!isset($this->options
['CURLOPT_USERPWD'])) {
3875 $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3878 $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3879 $options['CURLOPT_POSTFIELDS'] = $params;
3882 $ret = $this->request($url, $options);
3883 if ($fp !== false) {
3890 * HTTP DELETE method
3892 * @param string $url
3893 * @param array $param
3894 * @param array $options
3897 public function delete($url, $param = array(), $options = array()) {
3898 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3899 if (!isset($options['CURLOPT_USERPWD'])) {
3900 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3902 $ret = $this->request($url, $options);
3909 * @param string $url
3910 * @param array $options
3913 public function trace($url, $options = array()) {
3914 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3915 $ret = $this->request($url, $options);
3920 * HTTP OPTIONS method
3922 * @param string $url
3923 * @param array $options
3926 public function options($url, $options = array()) {
3927 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3928 $ret = $this->request($url, $options);
3933 * Get curl information
3937 public function get_info() {
3942 * Get curl error code
3946 public function get_errno() {
3947 return $this->errno
;
3951 * When using a proxy, an additional HTTP response code may appear at
3952 * the start of the header. For example, when using https over a proxy
3953 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3954 * also possible and some may come with their own headers.
3956 * If using the return value containing all headers, this function can be
3957 * called to remove unwanted doubles.
3959 * Note that it is not possible to distinguish this situation from valid
3960 * data unless you know the actual response part (below the headers)
3961 * will not be included in this string, or else will not 'look like' HTTP
3962 * headers. As a result it is not safe to call this function for general
3965 * @param string $input Input HTTP response
3966 * @return string HTTP response with additional headers stripped if any
3968 public static function strip_double_headers($input) {
3969 // I have tried to make this regular expression as specific as possible
3970 // to avoid any case where it does weird stuff if you happen to put
3971 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3972 // also make it faster because it can abandon regex processing as soon
3973 // as it hits something that doesn't look like an http header. The
3974 // header definition is taken from RFC 822, except I didn't support
3975 // folding which is never used in practice.
3977 return preg_replace(
3978 // HTTP version and status code (ignore value of code).
3979 '~^HTTP/1\..*' . $crlf .
3980 // Header name: character between 33 and 126 decimal, except colon.
3981 // Colon. Header value: any character except \r and \n. CRLF.
3982 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3983 // Headers are terminated by another CRLF (blank line).
3985 // Second HTTP status code, this time must be 200.
3986 '(HTTP/1.[01] 200 )~', '$1', $input);
3991 * This class is used by cURL class, use case:
3994 * $CFG->repositorycacheexpire = 120;
3995 * $CFG->curlcache = 120;
3997 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3998 * $ret = $c->get('http://www.google.com');
4001 * @package core_files
4002 * @copyright Dongsheng Cai <dongsheng@moodle.com>
4003 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4006 /** @var string Path to cache directory */
4012 * @global stdClass $CFG
4013 * @param string $module which module is using curl_cache
4015 public function __construct($module = 'repository') {
4017 if (!empty($module)) {
4018 $this->dir
= $CFG->cachedir
.'/'.$module.'/';
4020 $this->dir
= $CFG->cachedir
.'/misc/';
4022 if (!file_exists($this->dir
)) {
4023 mkdir($this->dir
, $CFG->directorypermissions
, true);
4025 if ($module == 'repository') {
4026 if (empty($CFG->repositorycacheexpire
)) {
4027 $CFG->repositorycacheexpire
= 120;
4029 $this->ttl
= $CFG->repositorycacheexpire
;
4031 if (empty($CFG->curlcache
)) {
4032 $CFG->curlcache
= 120;
4034 $this->ttl
= $CFG->curlcache
;
4041 * @global stdClass $CFG
4042 * @global stdClass $USER
4043 * @param mixed $param
4044 * @return bool|string
4046 public function get($param) {
4048 $this->cleanup($this->ttl
);
4049 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
4050 if(file_exists($this->dir
.$filename)) {
4051 $lasttime = filemtime($this->dir
.$filename);
4052 if (time()-$lasttime > $this->ttl
) {
4055 $fp = fopen($this->dir
.$filename, 'r');
4056 $size = filesize($this->dir
.$filename);
4057 $content = fread($fp, $size);
4058 return unserialize($content);
4067 * @global object $CFG
4068 * @global object $USER
4069 * @param mixed $param
4072 public function set($param, $val) {
4074 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
4075 $fp = fopen($this->dir
.$filename, 'w');
4076 fwrite($fp, serialize($val));
4078 @chmod
($this->dir
.$filename, $CFG->filepermissions
);
4082 * Remove cache files
4084 * @param int $expire The number of seconds before expiry
4086 public function cleanup($expire) {
4087 if ($dir = opendir($this->dir
)) {
4088 while (false !== ($file = readdir($dir))) {
4089 if(!is_dir($file) && $file != '.' && $file != '..') {
4090 $lasttime = @filemtime
($this->dir
.$file);
4091 if (time() - $lasttime > $expire) {
4092 @unlink
($this->dir
.$file);
4100 * delete current user's cache file
4102 * @global object $CFG
4103 * @global object $USER
4105 public function refresh() {
4107 if ($dir = opendir($this->dir
)) {
4108 while (false !== ($file = readdir($dir))) {
4109 if (!is_dir($file) && $file != '.' && $file != '..') {
4110 if (strpos($file, 'u'.$USER->id
.'_') !== false) {
4111 @unlink
($this->dir
.$file);
4120 * This function delegates file serving to individual plugins
4122 * @param string $relativepath
4123 * @param bool $forcedownload
4124 * @param null|string $preview the preview mode, defaults to serving the original file
4125 * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4126 * offline (e.g. mobile app).
4127 * @param bool $embed Whether this file will be served embed into an iframe.
4128 * @todo MDL-31088 file serving improments
4130 function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4131 global $DB, $CFG, $USER;
4132 // relative path must start with '/'
4133 if (!$relativepath) {
4134 print_error('invalidargorconf');
4135 } else if ($relativepath[0] != '/') {
4136 print_error('pathdoesnotstartslash');
4139 // extract relative path components
4140 $args = explode('/', ltrim($relativepath, '/'));
4142 if (count($args) < 3) { // always at least context, component and filearea
4143 print_error('invalidarguments');
4146 $contextid = (int)array_shift($args);
4147 $component = clean_param(array_shift($args), PARAM_COMPONENT
);
4148 $filearea = clean_param(array_shift($args), PARAM_AREA
);
4150 list($context, $course, $cm) = get_context_info_array($contextid);
4152 $fs = get_file_storage();
4154 $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4156 // ========================================================================================================================
4157 if ($component === 'blog') {
4158 // Blog file serving
4159 if ($context->contextlevel
!= CONTEXT_SYSTEM
) {
4160 send_file_not_found();
4162 if ($filearea !== 'attachment' and $filearea !== 'post') {
4163 send_file_not_found();
4166 if (empty($CFG->enableblogs
)) {
4167 print_error('siteblogdisable', 'blog');
4170 $entryid = (int)array_shift($args);
4171 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4172 send_file_not_found();
4174 if ($CFG->bloglevel
< BLOG_GLOBAL_LEVEL
) {
4176 if (isguestuser()) {
4177 print_error('noguest');
4179 if ($CFG->bloglevel
== BLOG_USER_LEVEL
) {
4180 if ($USER->id
!= $entry->userid
) {
4181 send_file_not_found();
4186 if ($entry->publishstate
=== 'public') {
4187 if ($CFG->forcelogin
) {
4191 } else if ($entry->publishstate
=== 'site') {
4194 } else if ($entry->publishstate
=== 'draft') {
4196 if ($USER->id
!= $entry->userid
) {
4197 send_file_not_found();
4201 $filename = array_pop($args);
4202 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4204 if (!$file = $fs->get_file($context->id
, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4205 send_file_not_found();
4208 send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4210 // ========================================================================================================================
4211 } else if ($component === 'grade') {
4213 require_once($CFG->libdir
. '/grade/constants.php');
4215 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel
== CONTEXT_SYSTEM
) {
4216 // Global gradebook files
4217 if ($CFG->forcelogin
) {
4221 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4223 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4224 send_file_not_found();
4227 \core\session\manager
::write_close(); // Unlock session during file serving.
4228 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4230 } else if ($filearea == GRADE_FEEDBACK_FILEAREA ||
$filearea == GRADE_HISTORY_FEEDBACK_FILEAREA
) {
4231 if ($context->contextlevel
!= CONTEXT_MODULE
) {
4232 send_file_not_found();
4235 require_login($course, false);
4237 $gradeid = (int) array_shift($args);
4238 $filename = array_pop($args);
4239 if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA
) {
4240 $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4242 $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4246 send_file_not_found();
4249 $iscurrentuser = $USER->id
== $grade->userid
;
4251 if (!$iscurrentuser) {
4252 $coursecontext = context_course
::instance($course->id
);
4253 if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4254 send_file_not_found();
4258 $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4260 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4261 send_file_not_found();
4264 \core\session\manager
::write_close(); // Unlock session during file serving.
4265 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4267 send_file_not_found();
4270 // ========================================================================================================================
4271 } else if ($component === 'tag') {
4272 if ($filearea === 'description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
4274 // All tag descriptions are going to be public but we still need to respect forcelogin
4275 if ($CFG->forcelogin
) {
4279 $fullpath = "/$context->id/tag/description/".implode('/', $args);
4281 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4282 send_file_not_found();
4285 \core\session\manager
::write_close(); // Unlock session during file serving.
4286 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4289 send_file_not_found();
4291 // ========================================================================================================================
4292 } else if ($component === 'badges') {
4293 require_once($CFG->libdir
. '/badgeslib.php');
4295 $badgeid = (int)array_shift($args);
4296 $badge = new badge($badgeid);
4297 $filename = array_pop($args);
4299 if ($filearea === 'badgeimage') {
4300 if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4301 send_file_not_found();
4303 if (!$file = $fs->get_file($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $filename.'.png')) {
4304 send_file_not_found();
4307 \core\session\manager
::write_close();
4308 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4309 } else if ($filearea === 'userbadge' and $context->contextlevel
== CONTEXT_USER
) {
4310 if (!$file = $fs->get_file($context->id
, 'badges', 'userbadge', $badge->id
, '/', $filename.'.png')) {
4311 send_file_not_found();
4314 \core\session\manager
::write_close();
4315 send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4317 // ========================================================================================================================
4318 } else if ($component === 'calendar') {
4319 if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
4321 // All events here are public the one requirement is that we respect forcelogin
4322 if ($CFG->forcelogin
) {
4326 // Get the event if from the args array
4327 $eventid = array_shift($args);
4329 // Load the event from the database
4330 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4331 send_file_not_found();
4334 // Get the file and serve if successful
4335 $filename = array_pop($args);
4336 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4337 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4338 send_file_not_found();
4341 \core\session\manager
::write_close(); // Unlock session during file serving.
4342 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4344 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_USER
) {
4346 // Must be logged in, if they are not then they obviously can't be this user
4349 // Don't want guests here, potentially saves a DB call
4350 if (isguestuser()) {
4351 send_file_not_found();
4354 // Get the event if from the args array
4355 $eventid = array_shift($args);
4357 // Load the event from the database - user id must match
4358 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id
, 'eventtype'=>'user'))) {
4359 send_file_not_found();
4362 // Get the file and serve if successful
4363 $filename = array_pop($args);
4364 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4365 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4366 send_file_not_found();
4369 \core\session\manager
::write_close(); // Unlock session during file serving.
4370 send_stored_file($file, 0, 0, true, $sendfileoptions);
4372 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_COURSE
) {
4374 // Respect forcelogin and require login unless this is the site.... it probably
4375 // should NEVER be the site
4376 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
4377 require_login($course);
4380 // Must be able to at least view the course. This does not apply to the front page.
4381 if ($course->id
!= SITEID
&& (!is_enrolled($context)) && (!is_viewing($context))) {
4382 //TODO: hmm, do we really want to block guests here?
4383 send_file_not_found();
4387 $eventid = array_shift($args);
4389 // Load the event from the database we need to check whether it is
4390 // a) valid course event
4392 // Group events use the course context (there is no group context)
4393 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id
))) {
4394 send_file_not_found();
4397 // If its a group event require either membership of view all groups capability
4398 if ($event->eventtype
=== 'group') {
4399 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid
, $USER->id
)) {
4400 send_file_not_found();
4402 } else if ($event->eventtype
=== 'course' ||
$event->eventtype
=== 'site') {
4403 // Ok. Please note that the event type 'site' still uses a course context.
4406 send_file_not_found();
4409 // If we get this far we can serve the file
4410 $filename = array_pop($args);
4411 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4412 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4413 send_file_not_found();
4416 \core\session\manager
::write_close(); // Unlock session during file serving.
4417 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4420 send_file_not_found();
4423 // ========================================================================================================================
4424 } else if ($component === 'user') {
4425 if ($filearea === 'icon' and $context->contextlevel
== CONTEXT_USER
) {
4426 if (count($args) == 1) {
4427 $themename = theme_config
::DEFAULT_THEME
;
4428 $filename = array_shift($args);
4430 $themename = array_shift($args);
4431 $filename = array_shift($args);
4434 // fix file name automatically
4435 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4439 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
4440 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
4441 // protect images if login required and not logged in;
4442 // also if login is required for profile images and is not logged in or guest
4443 // do not use require_login() because it is expensive and not suitable here anyway
4444 $theme = theme_config
::load($themename);
4445 redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4448 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.png')) {
4449 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4450 if ($filename === 'f3') {
4451 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4452 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.png')) {
4453 $file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.jpg');
4459 // bad reference - try to prevent future retries as hard as possible!
4460 if ($user = $DB->get_record('user', array('id'=>$context->instanceid
), 'id, picture')) {
4461 if ($user->picture
> 0) {
4462 $DB->set_field('user', 'picture', 0, array('id'=>$user->id
));
4465 // no redirect here because it is not cached
4466 $theme = theme_config
::load($themename);
4467 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4468 send_file($imagefile, basename($imagefile), 60*60*24*14);
4471 $options = $sendfileoptions;
4472 if (empty($CFG->forcelogin
) && empty($CFG->forceloginforprofileimage
)) {
4473 // Profile images should be cache-able by both browsers and proxies according
4474 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4475 $options['cacheability'] = 'public';
4477 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4479 } else if ($filearea === 'private' and $context->contextlevel
== CONTEXT_USER
) {
4482 if (isguestuser()) {
4483 send_file_not_found();
4486 if ($USER->id
!== $context->instanceid
) {
4487 send_file_not_found();
4490 $filename = array_pop($args);
4491 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4492 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4493 send_file_not_found();
4496 \core\session\manager
::write_close(); // Unlock session during file serving.
4497 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4499 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_USER
) {
4501 if ($CFG->forcelogin
) {
4505 $userid = $context->instanceid
;
4507 if ($USER->id
== $userid) {
4508 // always can access own
4510 } else if (!empty($CFG->forceloginforprofiles
)) {
4513 if (isguestuser()) {
4514 send_file_not_found();
4517 // we allow access to site profile of all course contacts (usually teachers)
4518 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4519 send_file_not_found();
4523 if (has_capability('moodle/user:viewdetails', $context)) {
4526 $courses = enrol_get_my_courses();
4529 while (!$canview && count($courses) > 0) {
4530 $course = array_shift($courses);
4531 if (has_capability('moodle/user:viewdetails', context_course
::instance($course->id
))) {
4537 $filename = array_pop($args);
4538 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4539 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4540 send_file_not_found();
4543 \core\session\manager
::write_close(); // Unlock session during file serving.
4544 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4546 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_COURSE
) {
4547 $userid = (int)array_shift($args);
4548 $usercontext = context_user
::instance($userid);
4550 if ($CFG->forcelogin
) {
4554 if (!empty($CFG->forceloginforprofiles
)) {
4556 if (isguestuser()) {
4557 print_error('noguest');
4560 //TODO: review this logic of user profile access prevention
4561 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4562 print_error('usernotavailable');
4564 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4565 print_error('cannotviewprofile');
4567 if (!is_enrolled($context, $userid)) {
4568 print_error('notenrolledprofile');
4570 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
4571 print_error('groupnotamember');
4575 $filename = array_pop($args);
4576 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4577 if (!$file = $fs->get_file($usercontext->id
, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4578 send_file_not_found();
4581 \core\session\manager
::write_close(); // Unlock session during file serving.
4582 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4584 } else if ($filearea === 'backup' and $context->contextlevel
== CONTEXT_USER
) {
4587 if (isguestuser()) {
4588 send_file_not_found();
4590 $userid = $context->instanceid
;
4592 if ($USER->id
!= $userid) {
4593 send_file_not_found();
4596 $filename = array_pop($args);
4597 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4598 if (!$file = $fs->get_file($context->id
, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4599 send_file_not_found();
4602 \core\session\manager
::write_close(); // Unlock session during file serving.
4603 send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4606 send_file_not_found();
4609 // ========================================================================================================================
4610 } else if ($component === 'coursecat') {
4611 if ($context->contextlevel
!= CONTEXT_COURSECAT
) {
4612 send_file_not_found();
4615 if ($filearea === 'description') {
4616 if ($CFG->forcelogin
) {
4617 // no login necessary - unless login forced everywhere
4621 // Check if user can view this category.
4622 if (!core_course_category
::get($context->instanceid
, IGNORE_MISSING
)) {
4623 send_file_not_found();
4626 $filename = array_pop($args);
4627 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4628 if (!$file = $fs->get_file($context->id
, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4629 send_file_not_found();
4632 \core\session\manager
::write_close(); // Unlock session during file serving.
4633 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4635 send_file_not_found();
4638 // ========================================================================================================================
4639 } else if ($component === 'course') {
4640 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4641 send_file_not_found();
4644 if ($filearea === 'summary' ||
$filearea === 'overviewfiles') {
4645 if ($CFG->forcelogin
) {
4649 $filename = array_pop($args);
4650 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4651 if (!$file = $fs->get_file($context->id
, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4652 send_file_not_found();
4655 \core\session\manager
::write_close(); // Unlock session during file serving.
4656 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4658 } else if ($filearea === 'section') {
4659 if ($CFG->forcelogin
) {
4660 require_login($course);
4661 } else if ($course->id
!= SITEID
) {
4662 require_login($course);
4665 $sectionid = (int)array_shift($args);
4667 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id
))) {
4668 send_file_not_found();
4671 $filename = array_pop($args);
4672 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4673 if (!$file = $fs->get_file($context->id
, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4674 send_file_not_found();
4677 \core\session\manager
::write_close(); // Unlock session during file serving.
4678 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4681 send_file_not_found();
4684 } else if ($component === 'cohort') {
4686 $cohortid = (int)array_shift($args);
4687 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
4688 $cohortcontext = context
::instance_by_id($cohort->contextid
);
4690 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4691 if ($context->id
!= $cohort->contextid
&&
4692 ($context->contextlevel
!= CONTEXT_COURSE ||
!in_array($cohort->contextid
, $context->get_parent_context_ids()))) {
4693 send_file_not_found();
4696 // User is able to access cohort if they have view cap on cohort level or
4697 // the cohort is visible and they have view cap on course level.
4698 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4699 ($cohort->visible
&& has_capability('moodle/cohort:view', $context));
4701 if ($filearea === 'description' && $canview) {
4702 $filename = array_pop($args);
4703 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4704 if (($file = $fs->get_file($cohortcontext->id
, 'cohort', 'description', $cohort->id
, $filepath, $filename))
4705 && !$file->is_directory()) {
4706 \core\session\manager
::write_close(); // Unlock session during file serving.
4707 send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4711 send_file_not_found();
4713 } else if ($component === 'group') {
4714 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4715 send_file_not_found();
4718 require_course_login($course, true, null, false);
4720 $groupid = (int)array_shift($args);
4722 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id
), '*', MUST_EXIST
);
4723 if (($course->groupmodeforce
and $course->groupmode
== SEPARATEGROUPS
) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id
, $USER->id
)) {
4724 // do not allow access to separate group info if not member or teacher
4725 send_file_not_found();
4728 if ($filearea === 'description') {
4730 require_login($course);
4732 $filename = array_pop($args);
4733 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4734 if (!$file = $fs->get_file($context->id
, 'group', 'description', $group->id
, $filepath, $filename) or $file->is_directory()) {
4735 send_file_not_found();
4738 \core\session\manager
::write_close(); // Unlock session during file serving.
4739 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4741 } else if ($filearea === 'icon') {
4742 $filename = array_pop($args);
4744 if ($filename !== 'f1' and $filename !== 'f2') {
4745 send_file_not_found();
4747 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.png')) {
4748 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.jpg')) {
4749 send_file_not_found();
4753 \core\session\manager
::write_close(); // Unlock session during file serving.
4754 send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4757 send_file_not_found();
4760 } else if ($component === 'grouping') {
4761 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4762 send_file_not_found();
4765 require_login($course);
4767 $groupingid = (int)array_shift($args);
4769 // note: everybody has access to grouping desc images for now
4770 if ($filearea === 'description') {
4772 $filename = array_pop($args);
4773 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4774 if (!$file = $fs->get_file($context->id
, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4775 send_file_not_found();
4778 \core\session\manager
::write_close(); // Unlock session during file serving.
4779 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4782 send_file_not_found();
4785 // ========================================================================================================================
4786 } else if ($component === 'backup') {
4787 if ($filearea === 'course' and $context->contextlevel
== CONTEXT_COURSE
) {
4788 require_login($course);
4789 require_capability('moodle/backup:downloadfile', $context);
4791 $filename = array_pop($args);
4792 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4793 if (!$file = $fs->get_file($context->id
, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4794 send_file_not_found();
4797 \core\session\manager
::write_close(); // Unlock session during file serving.
4798 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4800 } else if ($filearea === 'section' and $context->contextlevel
== CONTEXT_COURSE
) {
4801 require_login($course);
4802 require_capability('moodle/backup:downloadfile', $context);
4804 $sectionid = (int)array_shift($args);
4806 $filename = array_pop($args);
4807 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4808 if (!$file = $fs->get_file($context->id
, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4809 send_file_not_found();
4812 \core\session\manager
::write_close();
4813 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4815 } else if ($filearea === 'activity' and $context->contextlevel
== CONTEXT_MODULE
) {
4816 require_login($course, false, $cm);
4817 require_capability('moodle/backup:downloadfile', $context);
4819 $filename = array_pop($args);
4820 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4821 if (!$file = $fs->get_file($context->id
, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4822 send_file_not_found();
4825 \core\session\manager
::write_close();
4826 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4828 } else if ($filearea === 'automated' and $context->contextlevel
== CONTEXT_COURSE
) {
4829 // Backup files that were generated by the automated backup systems.
4831 require_login($course);
4832 require_capability('moodle/backup:downloadfile', $context);
4833 require_capability('moodle/restore:userinfo', $context);
4835 $filename = array_pop($args);
4836 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4837 if (!$file = $fs->get_file($context->id
, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4838 send_file_not_found();
4841 \core\session\manager
::write_close(); // Unlock session during file serving.
4842 send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4845 send_file_not_found();
4848 // ========================================================================================================================
4849 } else if ($component === 'question') {
4850 require_once($CFG->libdir
. '/questionlib.php');
4851 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4852 send_file_not_found();
4854 // ========================================================================================================================
4855 } else if ($component === 'grading') {
4856 if ($filearea === 'description') {
4857 // files embedded into the form definition description
4859 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4862 } else if ($context->contextlevel
>= CONTEXT_COURSE
) {
4863 require_login($course, false, $cm);
4866 send_file_not_found();
4869 $formid = (int)array_shift($args);
4871 $sql = "SELECT ga.id
4872 FROM {grading_areas} ga
4873 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4874 WHERE gd.id = ? AND ga.contextid = ?";
4875 $areaid = $DB->get_field_sql($sql, array($formid, $context->id
), IGNORE_MISSING
);
4878 send_file_not_found();
4881 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4883 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4884 send_file_not_found();
4887 \core\session\manager
::write_close(); // Unlock session during file serving.
4888 send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4891 // ========================================================================================================================
4892 } else if (strpos($component, 'mod_') === 0) {
4893 $modname = substr($component, 4);
4894 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4895 send_file_not_found();
4897 require_once("$CFG->dirroot/mod/$modname/lib.php");
4899 if ($context->contextlevel
== CONTEXT_MODULE
) {
4900 if ($cm->modname
!== $modname) {
4901 // somebody tries to gain illegal access, cm type must match the component!
4902 send_file_not_found();
4906 if ($filearea === 'intro') {
4907 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO
, true)) {
4908 send_file_not_found();
4911 // Require login to the course first (without login to the module).
4912 require_course_login($course, true);
4914 // Now check if module is available OR it is restricted but the intro is shown on the course page.
4915 $cminfo = cm_info
::create($cm);
4916 if (!$cminfo->uservisible
) {
4917 if (!$cm->showdescription ||
!$cminfo->is_visible_on_course_page()) {
4918 // Module intro is not visible on the course page and module is not available, show access error.
4919 require_course_login($course, true, $cminfo);
4923 // all users may access it
4924 $filename = array_pop($args);
4925 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4926 if (!$file = $fs->get_file($context->id
, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4927 send_file_not_found();
4930 // finally send the file
4931 send_stored_file($file, null, 0, false, $sendfileoptions);
4934 $filefunction = $component.'_pluginfile';
4935 $filefunctionold = $modname.'_pluginfile';
4936 if (function_exists($filefunction)) {
4937 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4938 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4939 } else if (function_exists($filefunctionold)) {
4940 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4941 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4944 send_file_not_found();
4946 // ========================================================================================================================
4947 } else if (strpos($component, 'block_') === 0) {
4948 $blockname = substr($component, 6);
4949 // note: no more class methods in blocks please, that is ....
4950 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4951 send_file_not_found();
4953 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4955 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4956 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid
), '*',MUST_EXIST
);
4957 if ($birecord->blockname
!== $blockname) {
4958 // somebody tries to gain illegal access, cm type must match the component!
4959 send_file_not_found();
4962 if ($context->get_course_context(false)) {
4963 // If block is in course context, then check if user has capability to access course.
4964 require_course_login($course);
4965 } else if ($CFG->forcelogin
) {
4966 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4970 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id
, 'blockinstanceid' => $context->instanceid
));
4971 // User can't access file, if block is hidden or doesn't have block:view capability
4972 if (($bprecord && !$bprecord->visible
) ||
!has_capability('moodle/block:view', $context)) {
4973 send_file_not_found();
4979 $filefunction = $component.'_pluginfile';
4980 if (function_exists($filefunction)) {
4981 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4982 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
4985 send_file_not_found();
4987 // ========================================================================================================================
4988 } else if (strpos($component, '_') === false) {
4989 // all core subsystems have to be specified above, no more guessing here!
4990 send_file_not_found();
4993 // try to serve general plugin file in arbitrary context
4994 $dir = core_component
::get_component_directory($component);
4995 if (!file_exists("$dir/lib.php")) {
4996 send_file_not_found();
4998 include_once("$dir/lib.php");
5000 $filefunction = $component.'_pluginfile';
5001 if (function_exists($filefunction)) {
5002 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5003 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5006 send_file_not_found();