2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Functions for file handling.
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
58 //TODO: deprecate this
60 if ($CFG->slasharguments
) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
66 $return .= '?forcedownload=1';
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
72 $return .= '&forcedownload=1';
77 $return = str_replace('http://', 'https://', $return);
84 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
94 function file_area_contains_subdirs(context
$context, $component, $filearea, $itemid) {
97 if (!isset($itemid)) {
98 // Not initialised yet.
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id
, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER
);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id
!= $context->id
) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id
.'] is not equal to passed context ['.$context->id
.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id
;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
241 if ($options['trusttext']) {
242 $data->{$field.'trust'} = trusttext_trusted($context);
244 $data->{$field.'trust'} = 0;
247 $editor = $data->{$field.'_editor'};
249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
250 $data->{$field} = $editor['text'];
252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id
, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
254 $data->{$field.'format'} = $editor['format'];
260 * Saves text and files modified by Editor formslib element
263 * @param stdClass $data $database entry field
264 * @param string $field name of data field
265 * @param array $options various options
266 * @param stdClass $context context - must already exist
267 * @param string $component
268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
270 * @return stdClass modified data obejct
272 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
277 if (is_null($itemid) or is_null($context)) {
281 $contextid = $context->id
;
284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
286 $data->{$field.'_filemanager'} = $draftid_editor;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
296 * @param stdClass $data $database entry field
297 * @param string $field name of data field
298 * @param array $options various options
299 * @param stdClass $context context - must already exist
300 * @param string $component
301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
303 * @return stdClass modified data obejct
305 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
317 if (empty($data->{$field.'_filemanager'})) {
321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id
, $component, $filearea, $itemid, $options);
322 $fs = get_file_storage();
324 if ($fs->get_area_files($context->id
, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
335 * Generate a draft itemid
338 * @global moodle_database $DB
339 * @global stdClass $USER
340 * @return int a random but available draft itemid that can be used to create a new draft
343 function file_get_unused_draft_itemid() {
346 if (isguestuser() or !isloggedin()) {
347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
348 print_error('noguest');
351 $contextid = context_user
::instance($USER->id
)->id
;
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
356 $draftitemid = rand(1, 999999999);
363 * Initialise a draft file area from a real one by copying the files. A draft
364 * area will be created if one does not already exist. Normally you should
365 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
368 * @global stdClass $CFG
369 * @global stdClass $USER
370 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
371 * @param int $contextid This parameter and the next two identify the file area to copy files from.
372 * @param string $component
373 * @param string $filearea helps indentify the file area.
374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
379 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
380 global $CFG, $USER, $CFG;
382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
386 if (!isset($options['forcehttps'])) {
387 $options['forcehttps'] = false;
390 $usercontext = context_user
::instance($USER->id
);
391 $fs = get_file_storage();
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
395 $draftitemid = file_get_unused_draft_itemid();
396 $file_record = array('contextid'=>$usercontext->id
, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
397 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
398 foreach ($files as $file) {
399 if ($file->is_directory() and $file->get_filepath() === '/') {
400 // we need a way to mark the age of each draft area,
401 // by not copying the root dir we force it to be created automatically with current timestamp
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
408 // XXX: This is a hack for file manager (MDL-28666)
409 // File manager needs to know the original file information before copying
410 // to draft area, so we append these information in mdl_files.source field
411 // {@link file_storage::search_references()}
412 // {@link file_storage::search_references_count()}
413 $sourcefield = $file->get_source();
414 $newsourcefield = new stdClass
;
415 $newsourcefield->source
= $sourcefield;
416 $original = new stdClass
;
417 $original->contextid
= $contextid;
418 $original->component
= $component;
419 $original->filearea
= $filearea;
420 $original->itemid
= $itemid;
421 $original->filename
= $file->get_filename();
422 $original->filepath
= $file->get_filepath();
423 $newsourcefield->original
= file_storage
::pack_reference($original);
424 $draftfile->set_source(serialize($newsourcefield));
425 // End of file manager hack
428 if (!is_null($text)) {
429 // at this point there should not be any draftfile links yet,
430 // because this is a new text from database that should still contain the @@pluginfile@@ links
431 // this happens when developers forget to post process the text
432 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
438 if (is_null($text)) {
442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id
, 'user', 'draft', $draftitemid, $options);
447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
448 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
449 * in the @@PLUGINFILE@@ form.
452 * @global stdClass $CFG
453 * @param string $text The content that may contain ULRs in need of rewriting.
454 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
455 * @param int $contextid This parameter and the next two identify the file area to use.
456 * @param string $component
457 * @param string $filearea helps identify the file area.
458 * @param int $itemid helps identify the file area.
459 * @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function.
460 * @return string the processed text.
462 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
465 $options = (array)$options;
466 if (!isset($options['forcehttps'])) {
467 $options['forcehttps'] = false;
470 if (!$CFG->slasharguments
) {
471 $file = $file . '?file=';
474 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
476 if ($itemid !== null) {
477 $baseurl .= "$itemid/";
480 if ($options['forcehttps']) {
481 $baseurl = str_replace('http://', 'https://', $baseurl);
484 if (!empty($options['reverse'])) {
485 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
487 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
492 * Returns information about files in a draft area.
494 * @global stdClass $CFG
495 * @global stdClass $USER
496 * @param int $draftitemid the draft area item id.
497 * @param string $filepath path to the directory from which the information have to be retrieved.
498 * @return array with the following entries:
499 * 'filecount' => number of files in the draft area.
500 * 'filesize' => total size of the files in the draft area.
501 * 'foldercount' => number of folders in the draft area.
502 * 'filesize_without_references' => total size of the area excluding file references.
503 * (more information will be added as needed).
505 function file_get_draft_area_info($draftitemid, $filepath = '/') {
508 $usercontext = context_user
::instance($USER->id
);
509 $fs = get_file_storage();
515 'filesize_without_references' => 0
518 if ($filepath != '/') {
519 $draftfiles = $fs->get_directory_files($usercontext->id
, 'user', 'draft', $draftitemid, $filepath, true, true);
521 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id', true);
523 foreach ($draftfiles as $file) {
524 if ($file->is_directory()) {
525 $results['foldercount'] +
= 1;
527 $results['filecount'] +
= 1;
530 $filesize = $file->get_filesize();
531 $results['filesize'] +
= $filesize;
532 if (!$file->is_external_file()) {
533 $results['filesize_without_references'] +
= $filesize;
541 * Returns whether a draft area has exceeded/will exceed its size limit.
543 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
545 * @param int $draftitemid the draft area item id.
546 * @param int $areamaxbytes the maximum size allowed in this draft area.
547 * @param int $newfilesize the size that would be added to the current area.
548 * @param bool $includereferences true to include the size of the references in the area size.
549 * @return bool true if the area will/has exceeded its limit.
552 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
553 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED
) {
554 $draftinfo = file_get_draft_area_info($draftitemid);
555 $areasize = $draftinfo['filesize_without_references'];
556 if ($includereferences) {
557 $areasize = $draftinfo['filesize'];
559 if ($areasize +
$newfilesize > $areamaxbytes) {
567 * Get used space of files
568 * @global moodle_database $DB
569 * @global stdClass $USER
570 * @return int total bytes
572 function file_get_user_used_space() {
575 $usercontext = context_user
::instance($USER->id
);
576 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
577 JOIN (SELECT contenthash, filename, MAX(id) AS id
579 WHERE contextid = ? AND component = ? AND filearea != ?
580 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
581 $params = array('contextid'=>$usercontext->id
, 'component'=>'user', 'filearea'=>'draft');
582 $record = $DB->get_record_sql($sql, $params);
583 return (int)$record->totalbytes
;
587 * Convert any string to a valid filepath
588 * @todo review this function
590 * @return string path
592 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
593 if ($str == '/' or empty($str)) {
596 return '/'.trim($str, '/').'/';
601 * Generate a folder tree of draft area of current USER recursively
603 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
604 * @param int $draftitemid
605 * @param string $filepath
608 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
609 global $USER, $OUTPUT, $CFG;
610 $data->children
= array();
611 $context = context_user
::instance($USER->id
);
612 $fs = get_file_storage();
613 if ($files = $fs->get_directory_files($context->id
, 'user', 'draft', $draftitemid, $filepath, false)) {
614 foreach ($files as $file) {
615 if ($file->is_directory()) {
616 $item = new stdClass();
617 $item->sortorder
= $file->get_sortorder();
618 $item->filepath
= $file->get_filepath();
620 $foldername = explode('/', trim($item->filepath
, '/'));
621 $item->fullname
= trim(array_pop($foldername), '/');
623 $item->id
= uniqid();
624 file_get_drafarea_folders($draftitemid, $item->filepath
, $item);
625 $data->children
[] = $item;
634 * Listing all files (including folders) in current path (draft area)
635 * used by file manager
636 * @param int $draftitemid
637 * @param string $filepath
640 function file_get_drafarea_files($draftitemid, $filepath = '/') {
641 global $USER, $OUTPUT, $CFG;
643 $context = context_user
::instance($USER->id
);
644 $fs = get_file_storage();
646 $data = new stdClass();
647 $data->path
= array();
648 $data->path
[] = array('name'=>get_string('files'), 'path'=>'/');
650 // will be used to build breadcrumb
652 if ($filepath !== '/') {
653 $filepath = file_correct_filepath($filepath);
654 $parts = explode('/', $filepath);
655 foreach ($parts as $part) {
656 if ($part != '' && $part != null) {
657 $trail .= ($part.'/');
658 $data->path
[] = array('name'=>$part, 'path'=>$trail);
665 if ($files = $fs->get_directory_files($context->id
, 'user', 'draft', $draftitemid, $filepath, false)) {
666 foreach ($files as $file) {
667 $item = new stdClass();
668 $item->filename
= $file->get_filename();
669 $item->filepath
= $file->get_filepath();
670 $item->fullname
= trim($item->filename
, '/');
671 $filesize = $file->get_filesize();
672 $item->size
= $filesize ?
$filesize : null;
673 $item->filesize
= $filesize ?
display_size($filesize) : '';
675 $item->sortorder
= $file->get_sortorder();
676 $item->author
= $file->get_author();
677 $item->license
= $file->get_license();
678 $item->datemodified
= $file->get_timemodified();
679 $item->datecreated
= $file->get_timecreated();
680 $item->isref
= $file->is_external_file();
681 if ($item->isref
&& $file->get_status() == 666) {
682 $item->originalmissing
= true;
684 // find the file this draft file was created from and count all references in local
685 // system pointing to that file
686 $source = @unserialize
($file->get_source());
687 if (isset($source->original
)) {
688 $item->refcount
= $fs->search_references_count($source->original
);
691 if ($file->is_directory()) {
693 $item->icon
= $OUTPUT->pix_url(file_folder_icon(24))->out(false);
694 $item->type
= 'folder';
695 $foldername = explode('/', trim($item->filepath
, '/'));
696 $item->fullname
= trim(array_pop($foldername), '/');
697 $item->thumbnail
= $OUTPUT->pix_url(file_folder_icon(90))->out(false);
699 // do NOT use file browser here!
700 $item->mimetype
= get_mimetype_description($file);
701 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
704 $item->type
= 'file';
706 $itemurl = moodle_url
::make_draftfile_url($draftitemid, $item->filepath
, $item->filename
);
707 $item->url
= $itemurl->out();
708 $item->icon
= $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
709 $item->thumbnail
= $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
710 if ($imageinfo = $file->get_imageinfo()) {
711 $item->realthumbnail
= $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
712 $item->realicon
= $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
713 $item->image_width
= $imageinfo['width'];
714 $item->image_height
= $imageinfo['height'];
720 $data->itemid
= $draftitemid;
726 * Returns draft area itemid for a given element.
729 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
730 * @return int the itemid, or 0 if there is not one yet.
732 function file_get_submitted_draft_itemid($elname) {
733 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
734 if (!isset($_REQUEST[$elname])) {
737 if (is_array($_REQUEST[$elname])) {
738 $param = optional_param_array($elname, 0, PARAM_INT
);
739 if (!empty($param['itemid'])) {
740 $param = $param['itemid'];
742 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER
);
747 $param = optional_param($elname, 0, PARAM_INT
);
758 * Restore the original source field from draft files
760 * Do not use this function because it makes field files.source inconsistent
761 * for draft area files. This function will be deprecated in 2.6
763 * @param stored_file $storedfile This only works with draft files
764 * @return stored_file
766 function file_restore_source_field_from_draft_file($storedfile) {
767 $source = @unserialize
($storedfile->get_source());
768 if (!empty($source)) {
769 if (is_object($source)) {
770 $restoredsource = $source->source
;
771 $storedfile->set_source($restoredsource);
773 throw new moodle_exception('invalidsourcefield', 'error');
779 * Saves files from a draft file area to a real one (merging the list of files).
780 * Can rewrite URLs in some content at the same time if desired.
783 * @global stdClass $USER
784 * @param int $draftitemid the id of the draft area to use. Normally obtained
785 * from file_get_submitted_draft_itemid('elementname') or similar.
786 * @param int $contextid This parameter and the next two identify the file area to save to.
787 * @param string $component
788 * @param string $filearea indentifies the file area.
789 * @param int $itemid helps identifies the file area.
790 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
791 * @param string $text some html content that needs to have embedded links rewritten
792 * to the @@PLUGINFILE@@ form for saving in the database.
793 * @param bool $forcehttps force https urls.
794 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
796 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
799 $usercontext = context_user
::instance($USER->id
);
800 $fs = get_file_storage();
802 $options = (array)$options;
803 if (!isset($options['subdirs'])) {
804 $options['subdirs'] = false;
806 if (!isset($options['maxfiles'])) {
807 $options['maxfiles'] = -1; // unlimited
809 if (!isset($options['maxbytes']) ||
$options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
810 $options['maxbytes'] = 0; // unlimited
812 if (!isset($options['areamaxbytes'])) {
813 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED
; // Unlimited.
815 $allowreferences = true;
816 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE
)) {
817 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
818 // this is not exactly right. BUT there are many places in code where filemanager options
819 // are not passed to file_save_draft_area_files()
820 $allowreferences = false;
823 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
824 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
825 // anything at all in the next area.
826 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
830 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id');
831 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
833 // One file in filearea means it is empty (it has only top-level directory '.').
834 if (count($draftfiles) > 1 ||
count($oldfiles) > 1) {
835 // we have to merge old and new files - we want to keep file ids for files that were not changed
836 // we change time modified for all new and changed files, we keep time created as is
838 $newhashes = array();
840 foreach ($draftfiles as $file) {
841 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
844 if (!$allowreferences && $file->is_external_file()) {
847 if (!$file->is_directory()) {
848 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
849 // oversized file - should not get here at all
852 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
853 // more files - should not get here at all
858 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
859 $newhashes[$newhash] = $file;
862 // Loop through oldfiles and decide which we need to delete and which to update.
863 // After this cycle the array $newhashes will only contain the files that need to be added.
864 foreach ($oldfiles as $oldfile) {
865 $oldhash = $oldfile->get_pathnamehash();
866 if (!isset($newhashes[$oldhash])) {
867 // delete files not needed any more - deleted by user
872 $newfile = $newhashes[$oldhash];
873 // Now we know that we have $oldfile and $newfile for the same path.
874 // Let's check if we can update this file or we need to delete and create.
875 if ($newfile->is_directory()) {
876 // Directories are always ok to just update.
877 } else if (($source = @unserialize
($newfile->get_source())) && isset($source->original
)) {
878 // File has the 'original' - we need to update the file (it may even have not been changed at all).
879 $original = file_storage
::unpack_reference($source->original
);
880 if ($original['filename'] !== $oldfile->get_filename() ||
$original['filepath'] !== $oldfile->get_filepath()) {
881 // Very odd, original points to another file. Delete and create file.
886 // The same file name but absence of 'original' means that file was deteled and uploaded again.
887 // By deleting and creating new file we properly manage all existing references.
892 // status changed, we delete old file, and create a new one
893 if ($oldfile->get_status() != $newfile->get_status()) {
894 // file was changed, use updated with new timemodified data
896 // This file will be added later
901 if ($oldfile->get_author() != $newfile->get_author()) {
902 $oldfile->set_author($newfile->get_author());
905 if ($oldfile->get_license() != $newfile->get_license()) {
906 $oldfile->set_license($newfile->get_license());
909 // Updated file source
910 // Field files.source for draftarea files contains serialised object with source and original information.
911 // We only store the source part of it for non-draft file area.
912 $newsource = $newfile->get_source();
913 if ($source = @unserialize
($newfile->get_source())) {
914 $newsource = $source->source
;
916 if ($oldfile->get_source() !== $newsource) {
917 $oldfile->set_source($newsource);
920 // Updated sort order
921 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
922 $oldfile->set_sortorder($newfile->get_sortorder());
925 // Update file timemodified
926 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
927 $oldfile->set_timemodified($newfile->get_timemodified());
930 // Replaced file content
931 if (!$oldfile->is_directory() &&
932 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
933 $oldfile->get_filesize() != $newfile->get_filesize() ||
934 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
935 $oldfile->get_userid() != $newfile->get_userid())) {
936 $oldfile->replace_file_with($newfile);
939 // unchanged file or directory - we keep it as is
940 unset($newhashes[$oldhash]);
943 // Add fresh file or the file which has changed status
944 // the size and subdirectory tests are extra safety only, the UI should prevent it
945 foreach ($newhashes as $file) {
946 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
947 if ($source = @unserialize
($file->get_source())) {
948 // Field files.source for draftarea files contains serialised object with source and original information.
949 // We only store the source part of it for non-draft file area.
950 $file_record['source'] = $source->source
;
953 if ($file->is_external_file()) {
954 $repoid = $file->get_repository_id();
955 if (!empty($repoid)) {
956 $file_record['repositoryid'] = $repoid;
957 $file_record['reference'] = $file->get_reference();
961 $fs->create_file_from_storedfile($file_record, $file);
965 // note: do not purge the draft area - we clean up areas later in cron,
966 // the reason is that user might press submit twice and they would loose the files,
967 // also sometimes we might want to use hacks that save files into two different areas
969 if (is_null($text)) {
972 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
977 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
978 * ready to be saved in the database. Normally, this is done automatically by
979 * {@link file_save_draft_area_files()}.
982 * @param string $text the content to process.
983 * @param int $draftitemid the draft file area the content was using.
984 * @param bool $forcehttps whether the content contains https URLs. Default false.
985 * @return string the processed content.
987 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
990 $usercontext = context_user
::instance($USER->id
);
992 $wwwroot = $CFG->wwwroot
;
994 $wwwroot = str_replace('http://', 'https://', $wwwroot);
997 // relink embedded files if text submitted - no absolute links allowed in database!
998 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1000 if (strpos($text, 'draftfile.php?file=') !== false) {
1002 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1004 foreach ($matches[0] as $match) {
1005 $replace = str_ireplace('%2F', '/', $match);
1006 $text = str_replace($match, $replace, $text);
1009 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1016 * Set file sort order
1018 * @global moodle_database $DB
1019 * @param int $contextid the context id
1020 * @param string $component file component
1021 * @param string $filearea file area.
1022 * @param int $itemid itemid.
1023 * @param string $filepath file path.
1024 * @param string $filename file name.
1025 * @param int $sortorder the sort order of file.
1028 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1030 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1031 if ($file_record = $DB->get_record('files', $conditions)) {
1032 $sortorder = (int)$sortorder;
1033 $file_record->sortorder
= $sortorder;
1034 $DB->update_record('files', $file_record);
1041 * reset file sort order number to 0
1042 * @global moodle_database $DB
1043 * @param int $contextid the context id
1044 * @param string $component
1045 * @param string $filearea file area.
1046 * @param int|bool $itemid itemid.
1049 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1052 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1053 if ($itemid !== false) {
1054 $conditions['itemid'] = $itemid;
1057 $file_records = $DB->get_records('files', $conditions);
1058 foreach ($file_records as $file_record) {
1059 $file_record->sortorder
= 0;
1060 $DB->update_record('files', $file_record);
1066 * Returns description of upload error
1068 * @param int $errorcode found in $_FILES['filename.ext']['error']
1069 * @return string error description string, '' if ok
1071 function file_get_upload_error($errorcode) {
1073 switch ($errorcode) {
1074 case 0: // UPLOAD_ERR_OK - no error
1078 case 1: // UPLOAD_ERR_INI_SIZE
1079 $errmessage = get_string('uploadserverlimit');
1082 case 2: // UPLOAD_ERR_FORM_SIZE
1083 $errmessage = get_string('uploadformlimit');
1086 case 3: // UPLOAD_ERR_PARTIAL
1087 $errmessage = get_string('uploadpartialfile');
1090 case 4: // UPLOAD_ERR_NO_FILE
1091 $errmessage = get_string('uploadnofilefound');
1094 // Note: there is no error with a value of 5
1096 case 6: // UPLOAD_ERR_NO_TMP_DIR
1097 $errmessage = get_string('uploadnotempdir');
1100 case 7: // UPLOAD_ERR_CANT_WRITE
1101 $errmessage = get_string('uploadcantwrite');
1104 case 8: // UPLOAD_ERR_EXTENSION
1105 $errmessage = get_string('uploadextension');
1109 $errmessage = get_string('uploadproblem');
1116 * Recursive function formating an array in POST parameter
1117 * @param array $arraydata - the array that we are going to format and add into &$data array
1118 * @param string $currentdata - a row of the final postdata array at instant T
1119 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1120 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1122 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1123 foreach ($arraydata as $k=>$v) {
1124 $newcurrentdata = $currentdata;
1125 if (is_array($v)) { //the value is an array, call the function recursively
1126 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1127 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1128 } else { //add the POST parameter to the $data array
1129 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1135 * Transform a PHP array into POST parameter
1136 * (see the recursive function format_array_postdata_for_curlcall)
1137 * @param array $postdata
1138 * @return array containing all POST parameters (1 row = 1 POST parameter)
1140 function format_postdata_for_curlcall($postdata) {
1142 foreach ($postdata as $k=>$v) {
1144 $currentdata = urlencode($k);
1145 format_array_postdata_for_curlcall($v, $currentdata, $data);
1147 $data[] = urlencode($k).'='.urlencode($v);
1150 $convertedpostdata = implode('&', $data);
1151 return $convertedpostdata;
1155 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1156 * Due to security concerns only downloads from http(s) sources are supported.
1159 * @param string $url file url starting with http(s)://
1160 * @param array $headers http headers, null if none. If set, should be an
1161 * associative array of header name => value pairs.
1162 * @param array $postdata array means use POST request with given parameters
1163 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1164 * (if false, just returns content)
1165 * @param int $timeout timeout for complete download process including all file transfer
1166 * (default 5 minutes)
1167 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1168 * usually happens if the remote server is completely down (default 20 seconds);
1169 * may not work when using proxy
1170 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1171 * Only use this when already in a trusted location.
1172 * @param string $tofile store the downloaded content to file instead of returning it.
1173 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1174 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1175 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1176 * if file downloaded into $tofile successfully or the file content as a string.
1178 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1181 // Only http and https links supported.
1182 if (!preg_match('|^https?://|i', $url)) {
1183 if ($fullresponse) {
1184 $response = new stdClass();
1185 $response->status
= 0;
1186 $response->headers
= array();
1187 $response->response_code
= 'Invalid protocol specified in url';
1188 $response->results
= '';
1189 $response->error
= 'Invalid protocol specified in url';
1198 $headers2 = array();
1199 if (is_array($headers)) {
1200 foreach ($headers as $key => $value) {
1201 if (is_numeric($key)) {
1202 $headers2[] = $value;
1204 $headers2[] = "$key: $value";
1209 if ($skipcertverify) {
1210 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1212 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1215 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1217 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1218 $options['CURLOPT_MAXREDIRS'] = 5;
1220 // Use POST if requested.
1221 if (is_array($postdata)) {
1222 $postdata = format_postdata_for_curlcall($postdata);
1223 } else if (empty($postdata)) {
1227 // Optionally attempt to get more correct timeout by fetching the file size.
1228 if (!isset($CFG->curltimeoutkbitrate
)) {
1229 // Use very slow rate of 56kbps as a timeout speed when not set.
1232 $bitrate = $CFG->curltimeoutkbitrate
;
1234 if ($calctimeout and !isset($postdata)) {
1236 $curl->setHeader($headers2);
1238 $curl->head($url, $postdata, $options);
1240 $info = $curl->get_info();
1241 $error_no = $curl->get_errno();
1242 if (!$error_no && $info['download_content_length'] > 0) {
1243 // No curl errors - adjust for large files only - take max timeout.
1244 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1249 $curl->setHeader($headers2);
1251 $options['CURLOPT_RETURNTRANSFER'] = true;
1252 $options['CURLOPT_NOBODY'] = false;
1253 $options['CURLOPT_TIMEOUT'] = $timeout;
1256 $fh = fopen($tofile, 'w');
1258 if ($fullresponse) {
1259 $response = new stdClass();
1260 $response->status
= 0;
1261 $response->headers
= array();
1262 $response->response_code
= 'Can not write to file';
1263 $response->results
= false;
1264 $response->error
= 'Can not write to file';
1270 $options['CURLOPT_FILE'] = $fh;
1273 if (isset($postdata)) {
1274 $content = $curl->post($url, $postdata, $options);
1276 $content = $curl->get($url, null, $options);
1281 @chmod
($tofile, $CFG->filepermissions
);
1285 // Try to detect encoding problems.
1286 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1287 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1288 $result = curl_exec($ch);
1292 $info = $curl->get_info();
1293 $error_no = $curl->get_errno();
1294 $rawheaders = $curl->get_raw_response();
1298 if (!$fullresponse) {
1299 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
1303 $response = new stdClass();
1304 if ($error_no == 28) {
1305 $response->status
= '-100'; // Mimic snoopy.
1307 $response->status
= '0';
1309 $response->headers
= array();
1310 $response->response_code
= $error;
1311 $response->results
= false;
1312 $response->error
= $error;
1320 if (empty($info['http_code'])) {
1321 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1322 $response = new stdClass();
1323 $response->status
= '0';
1324 $response->headers
= array();
1325 $response->response_code
= 'Unknown cURL error';
1326 $response->results
= false; // do NOT change this, we really want to ignore the result!
1327 $response->error
= 'Unknown cURL error';
1330 $response = new stdClass();
1331 $response->status
= (string)$info['http_code'];
1332 $response->headers
= $rawheaders;
1333 $response->results
= $content;
1334 $response->error
= '';
1336 // There might be multiple headers on redirect, find the status of the last one.
1338 foreach ($rawheaders as $line) {
1340 $response->response_code
= $line;
1343 if (trim($line, "\r\n") === '') {
1349 if ($fullresponse) {
1353 if ($info['http_code'] != 200) {
1354 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
1357 return $response->results
;
1361 * Returns a list of information about file types based on extensions.
1363 * The following elements expected in value array for each extension:
1365 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1366 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1367 * also files with bigger sizes under names
1368 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1369 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1370 * commonly used in moodle the following groups:
1371 * - web_image - image that can be included as <img> in HTML
1372 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1373 * - video - file that can be imported as video in text editor
1374 * - audio - file that can be imported as audio in text editor
1375 * - archive - we can extract files from this archive
1376 * - spreadsheet - used for portfolio format
1377 * - document - used for portfolio format
1378 * - presentation - used for portfolio format
1379 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1380 * human-readable description for this filetype;
1381 * Function {@link get_mimetype_description()} first looks at the presence of string for
1382 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1383 * attribute, if not found returns the value of 'type';
1384 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1385 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1386 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1389 * @return array List of information about file types based on extensions.
1390 * Associative array of extension (lower-case) to associative array
1391 * from 'element name' to data. Current element names are 'type' and 'icon'.
1392 * Unknown types should use the 'xxx' entry which includes defaults.
1394 function &get_mimetypes_array() {
1395 // Get types from the core_filetypes function, which includes caching.
1396 return core_filetypes
::get_types();
1400 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1402 * This function retrieves a file's MIME type for a file that will be sent to the user.
1403 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1404 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1405 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1407 * @param string $filename The file's filename.
1408 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1410 function get_mimetype_for_sending($filename = '') {
1411 // Guess the file's MIME type using mimeinfo.
1412 $mimetype = mimeinfo('type', $filename);
1414 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1415 if (!$mimetype ||
$mimetype === 'document/unknown') {
1416 $mimetype = 'application/octet-stream';
1423 * Obtains information about a filetype based on its extension. Will
1424 * use a default if no information is present about that particular
1428 * @param string $element Desired information (usually 'icon'
1429 * for icon filename or 'type' for MIME type. Can also be
1430 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1431 * @param string $filename Filename we're looking up
1432 * @return string Requested piece of information from array
1434 function mimeinfo($element, $filename) {
1436 $mimeinfo = & get_mimetypes_array();
1437 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1439 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1440 if (empty($filetype)) {
1441 $filetype = 'xxx'; // file without extension
1443 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1444 $iconsize = max(array(16, (int)$iconsizematch[1]));
1445 $filenames = array($mimeinfo['xxx']['icon']);
1446 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1447 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1449 // find the file with the closest size, first search for specific icon then for default icon
1450 foreach ($filenames as $filename) {
1451 foreach ($iconpostfixes as $size => $postfix) {
1452 $fullname = $CFG->dirroot
.'/pix/f/'.$filename.$postfix;
1453 if ($iconsize >= $size && (file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1454 return $filename.$postfix;
1458 } else if (isset($mimeinfo[$filetype][$element])) {
1459 return $mimeinfo[$filetype][$element];
1460 } else if (isset($mimeinfo['xxx'][$element])) {
1461 return $mimeinfo['xxx'][$element]; // By default
1468 * Obtains information about a filetype based on the MIME type rather than
1469 * the other way around.
1472 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1473 * @param string $mimetype MIME type we're looking up
1474 * @return string Requested piece of information from array
1476 function mimeinfo_from_type($element, $mimetype) {
1477 /* array of cached mimetype->extension associations */
1478 static $cached = array();
1479 $mimeinfo = & get_mimetypes_array();
1481 if (!array_key_exists($mimetype, $cached)) {
1482 $cached[$mimetype] = null;
1483 foreach($mimeinfo as $filetype => $values) {
1484 if ($values['type'] == $mimetype) {
1485 if ($cached[$mimetype] === null) {
1486 $cached[$mimetype] = '.'.$filetype;
1488 if (!empty($values['defaulticon'])) {
1489 $cached[$mimetype] = '.'.$filetype;
1494 if (empty($cached[$mimetype])) {
1495 $cached[$mimetype] = '.xxx';
1498 if ($element === 'extension') {
1499 return $cached[$mimetype];
1501 return mimeinfo($element, $cached[$mimetype]);
1506 * Return the relative icon path for a given file
1510 * // $file - instance of stored_file or file_info
1511 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1512 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1516 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1519 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1520 * and $file->mimetype are expected)
1521 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1524 function file_file_icon($file, $size = null) {
1525 if (!is_object($file)) {
1526 $file = (object)$file;
1528 if (isset($file->filename
)) {
1529 $filename = $file->filename
;
1530 } else if (method_exists($file, 'get_filename')) {
1531 $filename = $file->get_filename();
1532 } else if (method_exists($file, 'get_visible_name')) {
1533 $filename = $file->get_visible_name();
1537 if (isset($file->mimetype
)) {
1538 $mimetype = $file->mimetype
;
1539 } else if (method_exists($file, 'get_mimetype')) {
1540 $mimetype = $file->get_mimetype();
1544 $mimetypes = &get_mimetypes_array();
1546 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1547 if ($extension && !empty($mimetypes[$extension])) {
1548 // if file name has known extension, return icon for this extension
1549 return file_extension_icon($filename, $size);
1552 return file_mimetype_icon($mimetype, $size);
1556 * Return the relative icon path for a folder image
1560 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1561 * echo html_writer::empty_tag('img', array('src' => $icon));
1565 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1568 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1571 function file_folder_icon($iconsize = null) {
1573 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1574 static $cached = array();
1575 $iconsize = max(array(16, (int)$iconsize));
1576 if (!array_key_exists($iconsize, $cached)) {
1577 foreach ($iconpostfixes as $size => $postfix) {
1578 $fullname = $CFG->dirroot
.'/pix/f/folder'.$postfix;
1579 if ($iconsize >= $size && (file_exists($fullname.'.png') ||
file_exists($fullname.'.gif'))) {
1580 $cached[$iconsize] = 'f/folder'.$postfix;
1585 return $cached[$iconsize];
1589 * Returns the relative icon path for a given mime type
1591 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1592 * a return the full path to an icon.
1595 * $mimetype = 'image/jpg';
1596 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1597 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1601 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1602 * to conform with that.
1603 * @param string $mimetype The mimetype to fetch an icon for
1604 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1605 * @return string The relative path to the icon
1607 function file_mimetype_icon($mimetype, $size = NULL) {
1608 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1612 * Returns the relative icon path for a given file name
1614 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1615 * a return the full path to an icon.
1618 * $filename = '.jpg';
1619 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1620 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1623 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1624 * to conform with that.
1625 * @todo MDL-31074 Implement $size
1627 * @param string $filename The filename to get the icon for
1628 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1631 function file_extension_icon($filename, $size = NULL) {
1632 return 'f/'.mimeinfo('icon'.$size, $filename);
1636 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1637 * mimetypes.php language file.
1639 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1640 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1641 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1642 * @param bool $capitalise If true, capitalises first character of result
1643 * @return string Text description
1645 function get_mimetype_description($obj, $capitalise=false) {
1646 $filename = $mimetype = '';
1647 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1648 // this is an instance of stored_file
1649 $mimetype = $obj->get_mimetype();
1650 $filename = $obj->get_filename();
1651 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1652 // this is an instance of file_info
1653 $mimetype = $obj->get_mimetype();
1654 $filename = $obj->get_visible_name();
1655 } else if (is_array($obj) ||
is_object ($obj)) {
1657 if (!empty($obj['filename'])) {
1658 $filename = $obj['filename'];
1660 if (!empty($obj['mimetype'])) {
1661 $mimetype = $obj['mimetype'];
1666 $mimetypefromext = mimeinfo('type', $filename);
1667 if (empty($mimetype) ||
$mimetypefromext !== 'document/unknown') {
1668 // if file has a known extension, overwrite the specified mimetype
1669 $mimetype = $mimetypefromext;
1671 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION
));
1672 if (empty($extension)) {
1673 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1674 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1676 $mimetypestr = mimeinfo('string', $filename);
1678 $chunks = explode('/', $mimetype, 2);
1681 'mimetype' => $mimetype,
1682 'ext' => $extension,
1683 'mimetype1' => $chunks[0],
1684 'mimetype2' => $chunks[1],
1687 foreach ($attr as $key => $value) {
1689 $a[strtoupper($key)] = strtoupper($value);
1690 $a[ucfirst($key)] = ucfirst($value);
1693 // MIME types may include + symbol but this is not permitted in string ids.
1694 $safemimetype = str_replace('+', '_', $mimetype);
1695 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1696 $customdescription = mimeinfo('customdescription', $filename);
1697 if ($customdescription) {
1698 // Call format_string on the custom description so that multilang
1699 // filter can be used (if enabled on system context). We use system
1700 // context because it is possible that the page context might not have
1701 // been defined yet.
1702 $result = format_string($customdescription, true,
1703 array('context' => context_system
::instance()));
1704 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1705 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1706 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1707 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1708 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1709 $result = get_string('default', 'mimetypes', (object)$a);
1711 $result = $mimetype;
1714 $result=ucfirst($result);
1720 * Returns array of elements of type $element in type group(s)
1722 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1723 * @param string|array $groups one group or array of groups/extensions/mimetypes
1726 function file_get_typegroup($element, $groups) {
1727 static $cached = array();
1728 if (!is_array($groups)) {
1729 $groups = array($groups);
1731 if (!array_key_exists($element, $cached)) {
1732 $cached[$element] = array();
1735 foreach ($groups as $group) {
1736 if (!array_key_exists($group, $cached[$element])) {
1737 // retrieive and cache all elements of type $element for group $group
1738 $mimeinfo = & get_mimetypes_array();
1739 $cached[$element][$group] = array();
1740 foreach ($mimeinfo as $extension => $value) {
1741 $value['extension'] = '.'.$extension;
1742 if (empty($value[$element])) {
1745 if (($group === '.'.$extension ||
$group === $value['type'] ||
1746 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1747 !in_array($value[$element], $cached[$element][$group])) {
1748 $cached[$element][$group][] = $value[$element];
1752 $result = array_merge($result, $cached[$element][$group]);
1754 return array_values(array_unique($result));
1758 * Checks if file with name $filename has one of the extensions in groups $groups
1760 * @see get_mimetypes_array()
1761 * @param string $filename name of the file to check
1762 * @param string|array $groups one group or array of groups to check
1763 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1764 * file mimetype is in mimetypes in groups $groups
1767 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1768 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
1769 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1772 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1776 * Checks if mimetype $mimetype belongs to one of the groups $groups
1778 * @see get_mimetypes_array()
1779 * @param string $mimetype
1780 * @param string|array $groups one group or array of groups to check
1783 function file_mimetype_in_typegroup($mimetype, $groups) {
1784 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1788 * Requested file is not found or not accessible, does not return, terminates script
1790 * @global stdClass $CFG
1791 * @global stdClass $COURSE
1793 function send_file_not_found() {
1794 global $CFG, $COURSE;
1796 // Allow cross-origin requests only for Web Services.
1797 // This allow to receive requests done by Web Workers or webapps in different domains.
1799 header('Access-Control-Allow-Origin: *');
1803 print_error('filenotfound', 'error', $CFG->wwwroot
.'/course/view.php?id='.$COURSE->id
); //this is not displayed on IIS??
1806 * Helper function to send correct 404 for server.
1808 function send_header_404() {
1809 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1810 header("Status: 404 Not Found");
1812 header('HTTP/1.0 404 not found');
1817 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1818 * platforms). This wrapper uses readfile for small files and custom code for
1821 * @param string $path Path to file
1822 * @param int $filesize Size of file (if left out, will get it automatically)
1823 * @return int|bool Size read (will always be $filesize) or false if failed
1825 function readfile_allow_large($path, $filesize = -1) {
1826 // Automatically get size if not specified.
1827 if ($filesize === -1) {
1828 $filesize = filesize($path);
1830 if ($filesize <= 2147483647) {
1831 // If the file is up to 2^31 - 1, send it normally using readfile.
1832 return readfile($path);
1834 // For large files, read and output in 64KB chunks.
1835 $handle = fopen($path, 'r');
1836 if ($handle === false) {
1841 $size = min($left, 65536);
1842 $buffer = fread($handle, $size);
1843 if ($buffer === false) {
1854 * Enhanced readfile() with optional acceleration.
1855 * @param string|stored_file $file
1856 * @param string $mimetype
1857 * @param bool $accelerate
1860 function readfile_accel($file, $mimetype, $accelerate) {
1863 if ($mimetype === 'text/plain') {
1864 // there is no encoding specified in text files, we need something consistent
1865 header('Content-Type: text/plain; charset=utf-8');
1867 header('Content-Type: '.$mimetype);
1870 $lastmodified = is_object($file) ?
$file->get_timemodified() : filemtime($file);
1871 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1873 if (is_object($file)) {
1874 header('Etag: "' . $file->get_contenthash() . '"');
1875 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1876 header('HTTP/1.1 304 Not Modified');
1881 // if etag present for stored file rely on it exclusively
1882 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1883 // get unixtime of request header; clip extra junk off first
1884 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1885 if ($since && $since >= $lastmodified) {
1886 header('HTTP/1.1 304 Not Modified');
1891 if ($accelerate and !empty($CFG->xsendfile
)) {
1892 if (empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
1893 header('Accept-Ranges: bytes');
1895 header('Accept-Ranges: none');
1898 if (is_object($file)) {
1899 $fs = get_file_storage();
1900 if ($fs->xsendfile($file->get_contenthash())) {
1905 require_once("$CFG->libdir/xsendfilelib.php");
1906 if (xsendfile($file)) {
1912 $filesize = is_object($file) ?
$file->get_filesize() : filesize($file);
1914 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1916 if ($accelerate and empty($CFG->disablebyteserving
) and $mimetype !== 'text/plain') {
1917 header('Accept-Ranges: bytes');
1919 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1920 // byteserving stuff - for acrobat reader and download accelerators
1921 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1922 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1924 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
1925 foreach ($ranges as $key=>$value) {
1926 if ($ranges[$key][1] == '') {
1928 $ranges[$key][1] = $filesize - $ranges[$key][2];
1929 $ranges[$key][2] = $filesize - 1;
1930 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
1932 $ranges[$key][2] = $filesize - 1;
1934 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1935 //invalid byte-range ==> ignore header
1939 //prepare multipart header
1940 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
1941 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1947 if (is_object($file)) {
1948 $handle = $file->get_content_file_handle();
1950 $handle = fopen($file, 'rb');
1952 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1957 header('Accept-Ranges: none');
1960 header('Content-Length: '.$filesize);
1962 if ($filesize > 10000000) {
1963 // for large files try to flush and close all buffers to conserve memory
1964 while(@ob_get_level
()) {
1965 if (!@ob_end_flush
()) {
1971 // send the whole file content
1972 if (is_object($file)) {
1975 readfile_allow_large($file, $filesize);
1980 * Similar to readfile_accel() but designed for strings.
1981 * @param string $string
1982 * @param string $mimetype
1983 * @param bool $accelerate
1986 function readstring_accel($string, $mimetype, $accelerate) {
1989 if ($mimetype === 'text/plain') {
1990 // there is no encoding specified in text files, we need something consistent
1991 header('Content-Type: text/plain; charset=utf-8');
1993 header('Content-Type: '.$mimetype);
1995 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
1996 header('Accept-Ranges: none');
1998 if ($accelerate and !empty($CFG->xsendfile
)) {
1999 $fs = get_file_storage();
2000 if ($fs->xsendfile(sha1($string))) {
2005 header('Content-Length: '.strlen($string));
2010 * Handles the sending of temporary file to user, download is forced.
2011 * File is deleted after abort or successful sending, does not return, script terminated
2013 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2014 * @param string $filename proposed file name when saving file
2015 * @param bool $pathisstring If the path is string
2017 function send_temp_file($path, $filename, $pathisstring=false) {
2020 // Guess the file's MIME type.
2021 $mimetype = get_mimetype_for_sending($filename);
2023 // close session - not needed anymore
2024 \core\session\manager
::write_close();
2026 if (!$pathisstring) {
2027 if (!file_exists($path)) {
2029 print_error('filenotfound', 'error', $CFG->wwwroot
.'/');
2031 // executed after normal finish or abort
2032 core_shutdown_manager
::register_function('send_temp_file_finished', array($path));
2035 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2036 if (core_useragent
::is_ie()) {
2037 $filename = urlencode($filename);
2040 header('Content-Disposition: attachment; filename="'.$filename.'"');
2041 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2042 header('Cache-Control: private, max-age=10, no-transform');
2043 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2045 } else { //normal http - prevent caching at all cost
2046 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2047 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2048 header('Pragma: no-cache');
2051 // send the contents - we can not accelerate this because the file will be deleted asap
2052 if ($pathisstring) {
2053 readstring_accel($path, $mimetype, false);
2055 readfile_accel($path, $mimetype, false);
2059 die; //no more chars to output
2063 * Internal callback function used by send_temp_file()
2065 * @param string $path
2067 function send_temp_file_finished($path) {
2068 if (file_exists($path)) {
2074 * Handles the sending of file data to the user's browser, including support for
2078 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2079 * @param string $filename Filename to send
2080 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2081 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2082 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2083 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2084 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2085 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2086 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2087 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2088 * and should not be reopened.
2089 * @return null script execution stopped unless $dontdie is true
2091 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2092 global $CFG, $COURSE;
2095 ignore_user_abort(true);
2098 if ($lifetime === 'default' or is_null($lifetime)) {
2099 $lifetime = $CFG->filelifetime
;
2102 \core\session\manager
::write_close(); // Unlock session during file serving.
2104 // Use given MIME type if specified, otherwise guess it.
2105 if (!$mimetype ||
$mimetype === 'document/unknown') {
2106 $mimetype = get_mimetype_for_sending($filename);
2109 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2110 if (core_useragent
::is_ie()) {
2111 $filename = rawurlencode($filename);
2114 if ($forcedownload) {
2115 header('Content-Disposition: attachment; filename="'.$filename.'"');
2116 } else if ($mimetype !== 'application/x-shockwave-flash') {
2117 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2118 // as an upload and enforces security that may prevent the file from being loaded.
2120 header('Content-Disposition: inline; filename="'.$filename.'"');
2123 if ($lifetime > 0) {
2124 $cacheability = ' public,';
2125 if (isloggedin() and !isguestuser()) {
2126 // By default, under the conditions above, this file must be cache-able only by browsers.
2127 $cacheability = ' private,';
2129 $nobyteserving = false;
2130 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2131 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
2134 } else { // Do not cache files in proxies and browsers
2135 $nobyteserving = true;
2136 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2137 header('Cache-Control: private, max-age=10, no-transform');
2138 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2140 } else { //normal http - prevent caching at all cost
2141 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2142 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2143 header('Pragma: no-cache');
2147 if (empty($filter)) {
2148 // send the contents
2149 if ($pathisstring) {
2150 readstring_accel($path, $mimetype, !$dontdie);
2152 readfile_accel($path, $mimetype, !$dontdie);
2156 // Try to put the file through filters
2157 if ($mimetype == 'text/html' ||
$mimetype == 'application/xhtml+xml') {
2158 $options = new stdClass();
2159 $options->noclean
= true;
2160 $options->nocache
= true; // temporary workaround for MDL-5136
2161 $text = $pathisstring ?
$path : implode('', file($path));
2163 $text = file_modify_html_header($text);
2164 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
2166 readstring_accel($output, $mimetype, false);
2168 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2169 // only filter text if filter all files is selected
2170 $options = new stdClass();
2171 $options->newlines
= false;
2172 $options->noclean
= true;
2173 $text = htmlentities($pathisstring ?
$path : implode('', file($path)), ENT_QUOTES
, 'UTF-8');
2174 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
2176 readstring_accel($output, $mimetype, false);
2179 // send the contents
2180 if ($pathisstring) {
2181 readstring_accel($path, $mimetype, !$dontdie);
2183 readfile_accel($path, $mimetype, !$dontdie);
2190 die; //no more chars to output!!!
2194 * Handles the sending of file data to the user's browser, including support for
2197 * The $options parameter supports the following keys:
2198 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2199 * (string|null) filename - overrides the implicit filename
2200 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2201 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2202 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2203 * and should not be reopened
2204 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2205 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2206 * defaults to "public".
2209 * @param stored_file $stored_file local file object
2210 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2211 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2212 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2213 * @param array $options additional options affecting the file serving
2214 * @return null script execution stopped unless $options['dontdie'] is true
2216 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2217 global $CFG, $COURSE;
2219 if (empty($options['filename'])) {
2222 $filename = $options['filename'];
2225 if (empty($options['dontdie'])) {
2231 if ($lifetime === 'default' or is_null($lifetime)) {
2232 $lifetime = $CFG->filelifetime
;
2235 if (!empty($options['preview'])) {
2236 // replace the file with its preview
2237 $fs = get_file_storage();
2238 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2239 if (!$preview_file) {
2240 // unable to create a preview of the file, send its default mime icon instead
2241 if ($options['preview'] === 'tinyicon') {
2243 } else if ($options['preview'] === 'thumb') {
2248 $fileicon = file_file_icon($stored_file, $size);
2249 send_file($CFG->dirroot
.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2251 // preview images have fixed cache lifetime and they ignore forced download
2252 // (they are generated by GD and therefore they are considered reasonably safe).
2253 $stored_file = $preview_file;
2254 $lifetime = DAYSECS
;
2256 $forcedownload = false;
2260 // handle external resource
2261 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2262 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2266 if (!$stored_file or $stored_file->is_directory()) {
2275 ignore_user_abort(true);
2278 \core\session\manager
::write_close(); // Unlock session during file serving.
2280 $filename = is_null($filename) ?
$stored_file->get_filename() : $filename;
2282 // Use given MIME type if specified.
2283 $mimetype = $stored_file->get_mimetype();
2285 // Otherwise guess it.
2286 if (!$mimetype ||
$mimetype === 'document/unknown') {
2287 $mimetype = get_mimetype_for_sending($filename);
2290 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2291 if (core_useragent
::is_ie()) {
2292 $filename = rawurlencode($filename);
2295 if ($forcedownload) {
2296 header('Content-Disposition: attachment; filename="'.$filename.'"');
2297 } else if ($mimetype !== 'application/x-shockwave-flash') {
2298 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2299 // as an upload and enforces security that may prevent the file from being loaded.
2301 header('Content-Disposition: inline; filename="'.$filename.'"');
2304 if ($lifetime > 0) {
2305 $cacheability = ' public,';
2306 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2307 // This file must be cache-able by both browsers and proxies.
2308 $cacheability = ' public,';
2309 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2310 // This file must be cache-able only by browsers.
2311 $cacheability = ' private,';
2312 } else if (isloggedin() and !isguestuser()) {
2313 $cacheability = ' private,';
2315 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2316 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
2319 } else { // Do not cache files in proxies and browsers
2320 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2321 header('Cache-Control: private, max-age=10, no-transform');
2322 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2324 } else { //normal http - prevent caching at all cost
2325 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2326 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2327 header('Pragma: no-cache');
2331 // Allow cross-origin requests only for Web Services.
2332 // This allow to receive requests done by Web Workers or webapps in different domains.
2334 header('Access-Control-Allow-Origin: *');
2337 if (empty($filter)) {
2338 // send the contents
2339 readfile_accel($stored_file, $mimetype, !$dontdie);
2341 } else { // Try to put the file through filters
2342 if ($mimetype == 'text/html' ||
$mimetype == 'application/xhtml+xml') {
2343 $options = new stdClass();
2344 $options->noclean
= true;
2345 $options->nocache
= true; // temporary workaround for MDL-5136
2346 $text = $stored_file->get_content();
2347 $text = file_modify_html_header($text);
2348 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
2350 readstring_accel($output, $mimetype, false);
2352 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2353 // only filter text if filter all files is selected
2354 $options = new stdClass();
2355 $options->newlines
= false;
2356 $options->noclean
= true;
2357 $text = $stored_file->get_content();
2358 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
2360 readstring_accel($output, $mimetype, false);
2362 } else { // Just send it out raw
2363 readfile_accel($stored_file, $mimetype, !$dontdie);
2369 die; //no more chars to output!!!
2373 * Retrieves an array of records from a CSV file and places
2374 * them into a given table structure
2376 * @global stdClass $CFG
2377 * @global moodle_database $DB
2378 * @param string $file The path to a CSV file
2379 * @param string $table The table to retrieve columns from
2380 * @return bool|array Returns an array of CSV records or false
2382 function get_records_csv($file, $table) {
2385 if (!$metacolumns = $DB->get_columns($table)) {
2389 if(!($handle = @fopen
($file, 'r'))) {
2390 print_error('get_records_csv failed to open '.$file);
2393 $fieldnames = fgetcsv($handle, 4096);
2394 if(empty($fieldnames)) {
2401 foreach($metacolumns as $metacolumn) {
2402 $ord = array_search($metacolumn->name
, $fieldnames);
2404 $columns[$metacolumn->name
] = $ord;
2410 while (($data = fgetcsv($handle, 4096)) !== false) {
2411 $item = new stdClass
;
2412 foreach($columns as $name => $ord) {
2413 $item->$name = $data[$ord];
2423 * Create a file with CSV contents
2425 * @global stdClass $CFG
2426 * @global moodle_database $DB
2427 * @param string $file The file to put the CSV content into
2428 * @param array $records An array of records to write to a CSV file
2429 * @param string $table The table to get columns from
2430 * @return bool success
2432 function put_records_csv($file, $records, $table = NULL) {
2435 if (empty($records)) {
2439 $metacolumns = NULL;
2440 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2446 if(!($fp = @fopen
($CFG->tempdir
.'/'.$file, 'w'))) {
2447 print_error('put_records_csv failed to open '.$file);
2450 $proto = reset($records);
2451 if(is_object($proto)) {
2452 $fields_records = array_keys(get_object_vars($proto));
2454 else if(is_array($proto)) {
2455 $fields_records = array_keys($proto);
2462 if(!empty($metacolumns)) {
2463 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2464 $fields = array_intersect($fields_records, $fields_table);
2467 $fields = $fields_records;
2470 fwrite($fp, implode(',', $fields));
2471 fwrite($fp, "\r\n");
2473 foreach($records as $record) {
2474 $array = (array)$record;
2476 foreach($fields as $field) {
2477 if(strpos($array[$field], ',')) {
2478 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2481 $values[] = $array[$field];
2484 fwrite($fp, implode(',', $values)."\r\n");
2488 @chmod
($CFG->tempdir
.'/'.$file, $CFG->filepermissions
);
2494 * Recursively delete the file or folder with path $location. That is,
2495 * if it is a file delete it. If it is a folder, delete all its content
2496 * then delete it. If $location does not exist to start, that is not
2497 * considered an error.
2499 * @param string $location the path to remove.
2502 function fulldelete($location) {
2503 if (empty($location)) {
2504 // extra safety against wrong param
2507 if (is_dir($location)) {
2508 if (!$currdir = opendir($location)) {
2511 while (false !== ($file = readdir($currdir))) {
2512 if ($file <> ".." && $file <> ".") {
2513 $fullfile = $location."/".$file;
2514 if (is_dir($fullfile)) {
2515 if (!fulldelete($fullfile)) {
2519 if (!unlink($fullfile)) {
2526 if (! rmdir($location)) {
2530 } else if (file_exists($location)) {
2531 if (!unlink($location)) {
2539 * Send requested byterange of file.
2541 * @param resource $handle A file handle
2542 * @param string $mimetype The mimetype for the output
2543 * @param array $ranges An array of ranges to send
2544 * @param string $filesize The size of the content if only one range is used
2546 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2547 // better turn off any kind of compression and buffering
2548 ini_set('zlib.output_compression', 'Off');
2550 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2551 if ($handle === false) {
2554 if (count($ranges) == 1) { //only one range requested
2555 $length = $ranges[0][2] - $ranges[0][1] +
1;
2556 header('HTTP/1.1 206 Partial content');
2557 header('Content-Length: '.$length);
2558 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2559 header('Content-Type: '.$mimetype);
2561 while(@ob_get_level
()) {
2562 if (!@ob_end_flush
()) {
2567 fseek($handle, $ranges[0][1]);
2568 while (!feof($handle) && $length > 0) {
2569 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2570 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2573 $length -= strlen($buffer);
2577 } else { // multiple ranges requested - not tested much
2579 foreach($ranges as $range) {
2580 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
2582 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
2583 header('HTTP/1.1 206 Partial content');
2584 header('Content-Length: '.$totallength);
2585 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
2587 while(@ob_get_level
()) {
2588 if (!@ob_end_flush
()) {
2593 foreach($ranges as $range) {
2594 $length = $range[2] - $range[1] +
1;
2596 fseek($handle, $range[1]);
2597 while (!feof($handle) && $length > 0) {
2598 core_php_time_limit
::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2599 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2602 $length -= strlen($buffer);
2605 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
2612 * add includes (js and css) into uploaded files
2613 * before returning them, useful for themes and utf.js includes
2615 * @global stdClass $CFG
2616 * @param string $text text to search and replace
2617 * @return string text with added head includes
2620 function file_modify_html_header($text) {
2621 // first look for <head> tag
2624 $stylesheetshtml = '';
2626 foreach ($CFG->stylesheets as $stylesheet) {
2628 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2631 // TODO The code below is actually a waste of CPU. When MDL-29738 will be implemented it should be re-evaluated too.
2633 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2635 $replacement = '<head>'.$stylesheetshtml;
2636 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2640 // if not, look for <html> tag, and stick <head> right after
2641 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2643 // replace <html> tag with <html><head>includes</head>
2644 $replacement = '<html>'."\n".'<head>'.$stylesheetshtml.'</head>';
2645 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2649 // if not, look for <body> tag, and stick <head> before body
2650 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2652 $replacement = '<head>'.$stylesheetshtml.'</head>'."\n".'<body>';
2653 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2657 // if not, just stick a <head> tag at the beginning
2658 $text = '<head>'.$stylesheetshtml.'</head>'."\n".$text;
2663 * RESTful cURL class
2665 * This is a wrapper class for curl, it is quite easy to use:
2669 * $c = new curl(array('cache'=>true));
2671 * $c = new curl(array('cookie'=>true));
2673 * $c = new curl(array('proxy'=>true));
2675 * // HTTP GET Method
2676 * $html = $c->get('http://example.com');
2677 * // HTTP POST Method
2678 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2679 * // HTTP PUT Method
2680 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2683 * @package core_files
2685 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2686 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2689 /** @var bool Caches http request contents */
2690 public $cache = false;
2691 /** @var bool Uses proxy, null means automatic based on URL */
2692 public $proxy = null;
2693 /** @var string library version */
2694 public $version = '0.4 dev';
2695 /** @var array http's response */
2696 public $response = array();
2697 /** @var array Raw response headers, needed for BC in download_file_content(). */
2698 public $rawresponse = array();
2699 /** @var array http header */
2700 public $header = array();
2701 /** @var string cURL information */
2703 /** @var string error */
2705 /** @var int error code */
2707 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2708 public $emulateredirects = null;
2710 /** @var array cURL options */
2713 /** @var string Proxy host */
2714 private $proxy_host = '';
2715 /** @var string Proxy auth */
2716 private $proxy_auth = '';
2717 /** @var string Proxy type */
2718 private $proxy_type = '';
2719 /** @var bool Debug mode on */
2720 private $debug = false;
2721 /** @var bool|string Path to cookie file */
2722 private $cookie = false;
2723 /** @var bool tracks multiple headers in response - redirect detection */
2724 private $responsefinished = false;
2729 * Allowed settings are:
2730 * proxy: (bool) use proxy server, null means autodetect non-local from url
2731 * debug: (bool) use debug output
2732 * cookie: (string) path to cookie file, false if none
2733 * cache: (bool) use cache
2734 * module_cache: (string) type of cache
2736 * @param array $settings
2738 public function __construct($settings = array()) {
2740 if (!function_exists('curl_init')) {
2741 $this->error
= 'cURL module must be enabled!';
2742 trigger_error($this->error
, E_USER_ERROR
);
2746 // All settings of this class should be init here.
2748 if (!empty($settings['debug'])) {
2749 $this->debug
= true;
2751 if (!empty($settings['cookie'])) {
2752 if($settings['cookie'] === true) {
2753 $this->cookie
= $CFG->dataroot
.'/curl_cookie.txt';
2755 $this->cookie
= $settings['cookie'];
2758 if (!empty($settings['cache'])) {
2759 if (class_exists('curl_cache')) {
2760 if (!empty($settings['module_cache'])) {
2761 $this->cache
= new curl_cache($settings['module_cache']);
2763 $this->cache
= new curl_cache('misc');
2767 if (!empty($CFG->proxyhost
)) {
2768 if (empty($CFG->proxyport
)) {
2769 $this->proxy_host
= $CFG->proxyhost
;
2771 $this->proxy_host
= $CFG->proxyhost
.':'.$CFG->proxyport
;
2773 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
2774 $this->proxy_auth
= $CFG->proxyuser
.':'.$CFG->proxypassword
;
2775 $this->setopt(array(
2776 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM
,
2777 'proxyuserpwd'=>$this->proxy_auth
));
2779 if (!empty($CFG->proxytype
)) {
2780 if ($CFG->proxytype
== 'SOCKS5') {
2781 $this->proxy_type
= CURLPROXY_SOCKS5
;
2783 $this->proxy_type
= CURLPROXY_HTTP
;
2784 $this->setopt(array('httpproxytunnel'=>false));
2786 $this->setopt(array('proxytype'=>$this->proxy_type
));
2789 if (isset($settings['proxy'])) {
2790 $this->proxy
= $settings['proxy'];
2793 $this->proxy
= false;
2796 if (!isset($this->emulateredirects
)) {
2797 $this->emulateredirects
= ini_get('open_basedir');
2802 * Resets the CURL options that have already been set
2804 public function resetopt() {
2805 $this->options
= array();
2806 $this->options
['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2807 // True to include the header in the output
2808 $this->options
['CURLOPT_HEADER'] = 0;
2809 // True to Exclude the body from the output
2810 $this->options
['CURLOPT_NOBODY'] = 0;
2811 // Redirect ny default.
2812 $this->options
['CURLOPT_FOLLOWLOCATION'] = 1;
2813 $this->options
['CURLOPT_MAXREDIRS'] = 10;
2814 $this->options
['CURLOPT_ENCODING'] = '';
2815 // TRUE to return the transfer as a string of the return
2816 // value of curl_exec() instead of outputting it out directly.
2817 $this->options
['CURLOPT_RETURNTRANSFER'] = 1;
2818 $this->options
['CURLOPT_SSL_VERIFYPEER'] = 0;
2819 $this->options
['CURLOPT_SSL_VERIFYHOST'] = 2;
2820 $this->options
['CURLOPT_CONNECTTIMEOUT'] = 30;
2822 if ($cacert = self
::get_cacert()) {
2823 $this->options
['CURLOPT_CAINFO'] = $cacert;
2828 * Get the location of ca certificates.
2829 * @return string absolute file path or empty if default used
2831 public static function get_cacert() {
2834 // Bundle in dataroot always wins.
2835 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2836 return realpath("$CFG->dataroot/moodleorgca.crt");
2839 // Next comes the default from php.ini
2840 $cacert = ini_get('curl.cainfo');
2841 if (!empty($cacert) and is_readable($cacert)) {
2842 return realpath($cacert);
2845 // Windows PHP does not have any certs, we need to use something.
2846 if ($CFG->ostype
=== 'WINDOWS') {
2847 if (is_readable("$CFG->libdir/cacert.pem")) {
2848 return realpath("$CFG->libdir/cacert.pem");
2852 // Use default, this should work fine on all properly configured *nix systems.
2859 public function resetcookie() {
2860 if (!empty($this->cookie
)) {
2861 if (is_file($this->cookie
)) {
2862 $fp = fopen($this->cookie
, 'w');
2874 * Do not use the curl constants to define the options, pass a string
2875 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2876 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2878 * @param array $options If array is null, this function will reset the options to default value.
2880 * @throws coding_exception If an option uses constant value instead of option name.
2882 public function setopt($options = array()) {
2883 if (is_array($options)) {
2884 foreach ($options as $name => $val) {
2885 if (!is_string($name)) {
2886 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2888 if (stripos($name, 'CURLOPT_') === false) {
2889 $name = strtoupper('CURLOPT_'.$name);
2891 $name = strtoupper($name);
2893 $this->options
[$name] = $val;
2901 public function cleanopt() {
2902 unset($this->options
['CURLOPT_HTTPGET']);
2903 unset($this->options
['CURLOPT_POST']);
2904 unset($this->options
['CURLOPT_POSTFIELDS']);
2905 unset($this->options
['CURLOPT_PUT']);
2906 unset($this->options
['CURLOPT_INFILE']);
2907 unset($this->options
['CURLOPT_INFILESIZE']);
2908 unset($this->options
['CURLOPT_CUSTOMREQUEST']);
2909 unset($this->options
['CURLOPT_FILE']);
2913 * Resets the HTTP Request headers (to prepare for the new request)
2915 public function resetHeader() {
2916 $this->header
= array();
2920 * Set HTTP Request Header
2922 * @param array $header
2924 public function setHeader($header) {
2925 if (is_array($header)) {
2926 foreach ($header as $v) {
2927 $this->setHeader($v);
2930 // Remove newlines, they are not allowed in headers.
2931 $this->header
[] = preg_replace('/[\r\n]/', '', $header);
2936 * Get HTTP Response Headers
2937 * @return array of arrays
2939 public function getResponse() {
2940 return $this->response
;
2944 * Get raw HTTP Response Headers
2945 * @return array of strings
2947 public function get_raw_response() {
2948 return $this->rawresponse
;
2952 * private callback function
2953 * Formatting HTTP Response Header
2955 * We only keep the last headers returned. For example during a redirect the
2956 * redirect headers will not appear in {@link self::getResponse()}, if you need
2957 * to use those headers, refer to {@link self::get_raw_response()}.
2959 * @param resource $ch Apparently not used
2960 * @param string $header
2961 * @return int The strlen of the header
2963 private function formatHeader($ch, $header) {
2964 $this->rawresponse
[] = $header;
2966 if (trim($header, "\r\n") === '') {
2967 // This must be the last header.
2968 $this->responsefinished
= true;
2971 if (strlen($header) > 2) {
2972 if ($this->responsefinished
) {
2973 // We still have headers after the supposedly last header, we must be
2974 // in a redirect so let's empty the response to keep the last headers.
2975 $this->responsefinished
= false;
2976 $this->response
= array();
2978 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2979 $key = rtrim($key, ':');
2980 if (!empty($this->response
[$key])) {
2981 if (is_array($this->response
[$key])) {
2982 $this->response
[$key][] = $value;
2984 $tmp = $this->response
[$key];
2985 $this->response
[$key] = array();
2986 $this->response
[$key][] = $tmp;
2987 $this->response
[$key][] = $value;
2991 $this->response
[$key] = $value;
2994 return strlen($header);
2998 * Set options for individual curl instance
3000 * @param resource $curl A curl handle
3001 * @param array $options
3002 * @return resource The curl handle
3004 private function apply_opt($curl, $options) {
3008 if (!empty($this->cookie
) ||
!empty($options['cookie'])) {
3009 $this->setopt(array('cookiejar'=>$this->cookie
,
3010 'cookiefile'=>$this->cookie
3014 // Bypass proxy if required.
3015 if ($this->proxy
=== null) {
3016 if (!empty($this->options
['CURLOPT_URL']) and is_proxybypass($this->options
['CURLOPT_URL'])) {
3022 $proxy = (bool)$this->proxy
;
3027 $options['CURLOPT_PROXY'] = $this->proxy_host
;
3029 unset($this->options
['CURLOPT_PROXY']);
3032 $this->setopt($options);
3034 // Reset before set options.
3035 curl_setopt($curl, CURLOPT_HEADERFUNCTION
, array(&$this,'formatHeader'));
3037 // Setting the User-Agent based on options provided.
3040 if (!empty($options['CURLOPT_USERAGENT'])) {
3041 $useragent = $options['CURLOPT_USERAGENT'];
3042 } else if (!empty($this->options
['CURLOPT_USERAGENT'])) {
3043 $useragent = $this->options
['CURLOPT_USERAGENT'];
3045 $useragent = 'MoodleBot/1.0';
3049 if (empty($this->header
)) {
3050 $this->setHeader(array(
3051 'User-Agent: ' . $useragent,
3052 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3053 'Connection: keep-alive'
3055 } else if (!in_array('User-Agent: ' . $useragent, $this->header
)) {
3056 // Remove old User-Agent if one existed.
3057 // We have to partial search since we don't know what the original User-Agent is.
3058 if ($match = preg_grep('/User-Agent.*/', $this->header
)) {
3059 $key = array_keys($match)[0];
3060 unset($this->header
[$key]);
3062 $this->setHeader(array('User-Agent: ' . $useragent));
3064 curl_setopt($curl, CURLOPT_HTTPHEADER
, $this->header
);
3067 echo '<h1>Options</h1>';
3068 var_dump($this->options
);
3069 echo '<h1>Header</h1>';
3070 var_dump($this->header
);
3073 // Do not allow infinite redirects.
3074 if (!isset($this->options
['CURLOPT_MAXREDIRS'])) {
3075 $this->options
['CURLOPT_MAXREDIRS'] = 0;
3076 } else if ($this->options
['CURLOPT_MAXREDIRS'] > 100) {
3077 $this->options
['CURLOPT_MAXREDIRS'] = 100;
3079 $this->options
['CURLOPT_MAXREDIRS'] = (int)$this->options
['CURLOPT_MAXREDIRS'];
3082 // Make sure we always know if redirects expected.
3083 if (!isset($this->options
['CURLOPT_FOLLOWLOCATION'])) {
3084 $this->options
['CURLOPT_FOLLOWLOCATION'] = 0;
3087 // Limit the protocols to HTTP and HTTPS.
3088 if (defined('CURLOPT_PROTOCOLS')) {
3089 $this->options
['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3090 $this->options
['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS
);
3094 foreach($this->options
as $name => $val) {
3095 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects
) {
3096 // The redirects are emulated elsewhere.
3097 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, 0);
3100 $name = constant($name);
3101 curl_setopt($curl, $name, $val);
3108 * Download multiple files in parallel
3110 * Calls {@link multi()} with specific download headers
3114 * $file1 = fopen('a', 'wb');
3115 * $file2 = fopen('b', 'wb');
3116 * $c->download(array(
3117 * array('url'=>'http://localhost/', 'file'=>$file1),
3118 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3128 * $c->download(array(
3129 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3130 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3134 * @param array $requests An array of files to request {
3135 * url => url to download the file [required]
3136 * file => file handler, or
3137 * filepath => file path
3139 * If 'file' and 'filepath' parameters are both specified in one request, the
3140 * open file handle in the 'file' parameter will take precedence and 'filepath'
3143 * @param array $options An array of options to set
3144 * @return array An array of results
3146 public function download($requests, $options = array()) {
3147 $options['RETURNTRANSFER'] = false;
3148 return $this->multi($requests, $options);
3152 * Multi HTTP Requests
3153 * This function could run multi-requests in parallel.
3155 * @param array $requests An array of files to request
3156 * @param array $options An array of options to set
3157 * @return array An array of results
3159 protected function multi($requests, $options = array()) {
3160 $count = count($requests);
3163 $main = curl_multi_init();
3164 for ($i = 0; $i < $count; $i++
) {
3165 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3167 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3168 $requests[$i]['auto-handle'] = true;
3170 foreach($requests[$i] as $n=>$v) {
3173 $handles[$i] = curl_init($requests[$i]['url']);
3174 $this->apply_opt($handles[$i], $options);
3175 curl_multi_add_handle($main, $handles[$i]);
3179 curl_multi_exec($main, $running);
3180 } while($running > 0);
3181 for ($i = 0; $i < $count; $i++
) {
3182 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3185 $results[] = curl_multi_getcontent($handles[$i]);
3187 curl_multi_remove_handle($main, $handles[$i]);
3189 curl_multi_close($main);
3191 for ($i = 0; $i < $count; $i++
) {
3192 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3193 // close file handler if file is opened in this function
3194 fclose($requests[$i]['file']);
3201 * Single HTTP Request
3203 * @param string $url The URL to request
3204 * @param array $options
3207 protected function request($url, $options = array()) {
3208 // Set the URL as a curl option.
3209 $this->setopt(array('CURLOPT_URL' => $url));
3211 // Create curl instance.
3212 $curl = curl_init();
3214 // Reset here so that the data is valid when result returned from cache.
3215 $this->info
= array();
3218 $this->response
= array();
3219 $this->rawresponse
= array();
3220 $this->responsefinished
= false;
3222 $this->apply_opt($curl, $options);
3223 if ($this->cache
&& $ret = $this->cache
->get($this->options
)) {
3227 $ret = curl_exec($curl);
3228 $this->info
= curl_getinfo($curl);
3229 $this->error
= curl_error($curl);
3230 $this->errno
= curl_errno($curl);
3231 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3233 if ($this->emulateredirects
and $this->options
['CURLOPT_FOLLOWLOCATION'] and $this->info
['http_code'] != 200) {
3236 while($redirects <= $this->options
['CURLOPT_MAXREDIRS']) {
3238 if ($this->info
['http_code'] == 301) {
3239 // Moved Permanently - repeat the same request on new URL.
3241 } else if ($this->info
['http_code'] == 302) {
3242 // Found - the standard redirect - repeat the same request on new URL.
3244 } else if ($this->info
['http_code'] == 303) {
3245 // 303 See Other - repeat only if GET, do not bother with POSTs.
3246 if (empty($this->options
['CURLOPT_HTTPGET'])) {
3250 } else if ($this->info
['http_code'] == 307) {
3251 // Temporary Redirect - must repeat using the same request type.
3253 } else if ($this->info
['http_code'] == 308) {
3254 // Permanent Redirect - must repeat using the same request type.
3257 // Some other http code means do not retry!
3263 $redirecturl = null;
3264 if (isset($this->info
['redirect_url'])) {
3265 if (preg_match('|^https?://|i', $this->info
['redirect_url'])) {
3266 $redirecturl = $this->info
['redirect_url'];
3269 if (!$redirecturl) {
3270 foreach ($this->response
as $k => $v) {
3271 if (strtolower($k) === 'location') {
3276 if (preg_match('|^https?://|i', $redirecturl)) {
3277 // Great, this is the correct location format!
3279 } else if ($redirecturl) {
3280 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL
);
3281 if (strpos($redirecturl, '/') === 0) {
3282 // Relative to server root - just guess.
3283 $pos = strpos('/', $current, 8);
3284 if ($pos === false) {
3285 $redirecturl = $current.$redirecturl;
3287 $redirecturl = substr($current, 0, $pos).$redirecturl;
3290 // Relative to current script.
3291 $redirecturl = dirname($current).'/'.$redirecturl;
3296 curl_setopt($curl, CURLOPT_URL
, $redirecturl);
3297 $ret = curl_exec($curl);
3299 $this->info
= curl_getinfo($curl);
3300 $this->error
= curl_error($curl);
3301 $this->errno
= curl_errno($curl);
3303 $this->info
['redirect_count'] = $redirects;
3305 if ($this->info
['http_code'] === 200) {
3306 // Finally this is what we wanted.
3309 if ($this->errno
!= CURLE_OK
) {
3310 // Something wrong is going on.
3314 if ($redirects > $this->options
['CURLOPT_MAXREDIRS']) {
3315 $this->errno
= CURLE_TOO_MANY_REDIRECTS
;
3316 $this->error
= 'Maximum ('.$this->options
['CURLOPT_MAXREDIRS'].') redirects followed';
3321 $this->cache
->set($this->options
, $ret);
3325 echo '<h1>Return Data</h1>';
3327 echo '<h1>Info</h1>';
3328 var_dump($this->info
);
3329 echo '<h1>Error</h1>';
3330 var_dump($this->error
);
3335 if (empty($this->error
)) {
3338 return $this->error
;
3339 // exception is not ajax friendly
3340 //throw new moodle_exception($this->error, 'curl');
3349 * @param string $url
3350 * @param array $options
3353 public function head($url, $options = array()) {
3354 $options['CURLOPT_HTTPGET'] = 0;
3355 $options['CURLOPT_HEADER'] = 1;
3356 $options['CURLOPT_NOBODY'] = 1;
3357 return $this->request($url, $options);
3363 * @param string $url
3364 * @param array|string $params
3365 * @param array $options
3368 public function post($url, $params = '', $options = array()) {
3369 $options['CURLOPT_POST'] = 1;
3370 if (is_array($params)) {
3371 $this->_tmp_file_post_params
= array();
3372 foreach ($params as $key => $value) {
3373 if ($value instanceof stored_file
) {
3374 $value->add_to_curl_request($this, $key);
3376 $this->_tmp_file_post_params
[$key] = $value;
3379 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
3380 unset($this->_tmp_file_post_params
);
3382 // $params is the raw post data
3383 $options['CURLOPT_POSTFIELDS'] = $params;
3385 return $this->request($url, $options);
3391 * @param string $url
3392 * @param array $params
3393 * @param array $options
3396 public function get($url, $params = array(), $options = array()) {
3397 $options['CURLOPT_HTTPGET'] = 1;
3399 if (!empty($params)) {
3400 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3401 $url .= http_build_query($params, '', '&');
3403 return $this->request($url, $options);
3407 * Downloads one file and writes it to the specified file handler
3411 * $file = fopen('savepath', 'w');
3412 * $result = $c->download_one('http://localhost/', null,
3413 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3415 * $download_info = $c->get_info();
3416 * if ($result === true) {
3417 * // file downloaded successfully
3419 * $error_text = $result;
3420 * $error_code = $c->get_errno();
3426 * $result = $c->download_one('http://localhost/', null,
3427 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3428 * // ... see above, no need to close handle and remove file if unsuccessful
3431 * @param string $url
3432 * @param array|null $params key-value pairs to be added to $url as query string
3433 * @param array $options request options. Must include either 'file' or 'filepath'
3434 * @return bool|string true on success or error string on failure
3436 public function download_one($url, $params, $options = array()) {
3437 $options['CURLOPT_HTTPGET'] = 1;
3438 if (!empty($params)) {
3439 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
3440 $url .= http_build_query($params, '', '&');
3442 if (!empty($options['filepath']) && empty($options['file'])) {
3444 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3446 return get_string('cannotwritefile', 'error', $options['filepath']);
3448 $filepath = $options['filepath'];
3450 unset($options['filepath']);
3451 $result = $this->request($url, $options);
3452 if (isset($filepath)) {
3453 fclose($options['file']);
3454 if ($result !== true) {
3464 * @param string $url
3465 * @param array $params
3466 * @param array $options
3469 public function put($url, $params = array(), $options = array()) {
3470 $file = $params['file'];
3471 if (!is_file($file)) {
3474 $fp = fopen($file, 'r');
3475 $size = filesize($file);
3476 $options['CURLOPT_PUT'] = 1;
3477 $options['CURLOPT_INFILESIZE'] = $size;
3478 $options['CURLOPT_INFILE'] = $fp;
3479 if (!isset($this->options
['CURLOPT_USERPWD'])) {
3480 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3482 $ret = $this->request($url, $options);
3488 * HTTP DELETE method
3490 * @param string $url
3491 * @param array $param
3492 * @param array $options
3495 public function delete($url, $param = array(), $options = array()) {
3496 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3497 if (!isset($options['CURLOPT_USERPWD'])) {
3498 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3500 $ret = $this->request($url, $options);
3507 * @param string $url
3508 * @param array $options
3511 public function trace($url, $options = array()) {
3512 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3513 $ret = $this->request($url, $options);
3518 * HTTP OPTIONS method
3520 * @param string $url
3521 * @param array $options
3524 public function options($url, $options = array()) {
3525 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3526 $ret = $this->request($url, $options);
3531 * Get curl information
3535 public function get_info() {
3540 * Get curl error code
3544 public function get_errno() {
3545 return $this->errno
;
3549 * When using a proxy, an additional HTTP response code may appear at
3550 * the start of the header. For example, when using https over a proxy
3551 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3552 * also possible and some may come with their own headers.
3554 * If using the return value containing all headers, this function can be
3555 * called to remove unwanted doubles.
3557 * Note that it is not possible to distinguish this situation from valid
3558 * data unless you know the actual response part (below the headers)
3559 * will not be included in this string, or else will not 'look like' HTTP
3560 * headers. As a result it is not safe to call this function for general
3563 * @param string $input Input HTTP response
3564 * @return string HTTP response with additional headers stripped if any
3566 public static function strip_double_headers($input) {
3567 // I have tried to make this regular expression as specific as possible
3568 // to avoid any case where it does weird stuff if you happen to put
3569 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3570 // also make it faster because it can abandon regex processing as soon
3571 // as it hits something that doesn't look like an http header. The
3572 // header definition is taken from RFC 822, except I didn't support
3573 // folding which is never used in practice.
3575 return preg_replace(
3576 // HTTP version and status code (ignore value of code).
3577 '~^HTTP/1\..*' . $crlf .
3578 // Header name: character between 33 and 126 decimal, except colon.
3579 // Colon. Header value: any character except \r and \n. CRLF.
3580 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3581 // Headers are terminated by another CRLF (blank line).
3583 // Second HTTP status code, this time must be 200.
3584 '(HTTP/1.[01] 200 )~', '$1', $input);
3589 * This class is used by cURL class, use case:
3592 * $CFG->repositorycacheexpire = 120;
3593 * $CFG->curlcache = 120;
3595 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3596 * $ret = $c->get('http://www.google.com');
3599 * @package core_files
3600 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3604 /** @var string Path to cache directory */
3610 * @global stdClass $CFG
3611 * @param string $module which module is using curl_cache
3613 public function __construct($module = 'repository') {
3615 if (!empty($module)) {
3616 $this->dir
= $CFG->cachedir
.'/'.$module.'/';
3618 $this->dir
= $CFG->cachedir
.'/misc/';
3620 if (!file_exists($this->dir
)) {
3621 mkdir($this->dir
, $CFG->directorypermissions
, true);
3623 if ($module == 'repository') {
3624 if (empty($CFG->repositorycacheexpire
)) {
3625 $CFG->repositorycacheexpire
= 120;
3627 $this->ttl
= $CFG->repositorycacheexpire
;
3629 if (empty($CFG->curlcache
)) {
3630 $CFG->curlcache
= 120;
3632 $this->ttl
= $CFG->curlcache
;
3639 * @global stdClass $CFG
3640 * @global stdClass $USER
3641 * @param mixed $param
3642 * @return bool|string
3644 public function get($param) {
3646 $this->cleanup($this->ttl
);
3647 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
3648 if(file_exists($this->dir
.$filename)) {
3649 $lasttime = filemtime($this->dir
.$filename);
3650 if (time()-$lasttime > $this->ttl
) {
3653 $fp = fopen($this->dir
.$filename, 'r');
3654 $size = filesize($this->dir
.$filename);
3655 $content = fread($fp, $size);
3656 return unserialize($content);
3665 * @global object $CFG
3666 * @global object $USER
3667 * @param mixed $param
3670 public function set($param, $val) {
3672 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
3673 $fp = fopen($this->dir
.$filename, 'w');
3674 fwrite($fp, serialize($val));
3676 @chmod
($this->dir
.$filename, $CFG->filepermissions
);
3680 * Remove cache files
3682 * @param int $expire The number of seconds before expiry
3684 public function cleanup($expire) {
3685 if ($dir = opendir($this->dir
)) {
3686 while (false !== ($file = readdir($dir))) {
3687 if(!is_dir($file) && $file != '.' && $file != '..') {
3688 $lasttime = @filemtime
($this->dir
.$file);
3689 if (time() - $lasttime > $expire) {
3690 @unlink
($this->dir
.$file);
3698 * delete current user's cache file
3700 * @global object $CFG
3701 * @global object $USER
3703 public function refresh() {
3705 if ($dir = opendir($this->dir
)) {
3706 while (false !== ($file = readdir($dir))) {
3707 if (!is_dir($file) && $file != '.' && $file != '..') {
3708 if (strpos($file, 'u'.$USER->id
.'_') !== false) {
3709 @unlink
($this->dir
.$file);
3718 * This function delegates file serving to individual plugins
3720 * @param string $relativepath
3721 * @param bool $forcedownload
3722 * @param null|string $preview the preview mode, defaults to serving the original file
3723 * @todo MDL-31088 file serving improments
3725 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3726 global $DB, $CFG, $USER;
3727 // relative path must start with '/'
3728 if (!$relativepath) {
3729 print_error('invalidargorconf');
3730 } else if ($relativepath[0] != '/') {
3731 print_error('pathdoesnotstartslash');
3734 // extract relative path components
3735 $args = explode('/', ltrim($relativepath, '/'));
3737 if (count($args) < 3) { // always at least context, component and filearea
3738 print_error('invalidarguments');
3741 $contextid = (int)array_shift($args);
3742 $component = clean_param(array_shift($args), PARAM_COMPONENT
);
3743 $filearea = clean_param(array_shift($args), PARAM_AREA
);
3745 list($context, $course, $cm) = get_context_info_array($contextid);
3747 $fs = get_file_storage();
3749 // ========================================================================================================================
3750 if ($component === 'blog') {
3751 // Blog file serving
3752 if ($context->contextlevel
!= CONTEXT_SYSTEM
) {
3753 send_file_not_found();
3755 if ($filearea !== 'attachment' and $filearea !== 'post') {
3756 send_file_not_found();
3759 if (empty($CFG->enableblogs
)) {
3760 print_error('siteblogdisable', 'blog');
3763 $entryid = (int)array_shift($args);
3764 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3765 send_file_not_found();
3767 if ($CFG->bloglevel
< BLOG_GLOBAL_LEVEL
) {
3769 if (isguestuser()) {
3770 print_error('noguest');
3772 if ($CFG->bloglevel
== BLOG_USER_LEVEL
) {
3773 if ($USER->id
!= $entry->userid
) {
3774 send_file_not_found();
3779 if ($entry->publishstate
=== 'public') {
3780 if ($CFG->forcelogin
) {
3784 } else if ($entry->publishstate
=== 'site') {
3787 } else if ($entry->publishstate
=== 'draft') {
3789 if ($USER->id
!= $entry->userid
) {
3790 send_file_not_found();
3794 $filename = array_pop($args);
3795 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
3797 if (!$file = $fs->get_file($context->id
, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3798 send_file_not_found();
3801 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3803 // ========================================================================================================================
3804 } else if ($component === 'grade') {
3805 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel
== CONTEXT_SYSTEM
) {
3806 // Global gradebook files
3807 if ($CFG->forcelogin
) {
3811 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3813 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3814 send_file_not_found();
3817 \core\session\manager
::write_close(); // Unlock session during file serving.
3818 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3820 } else if ($filearea === 'feedback' and $context->contextlevel
== CONTEXT_COURSE
) {
3821 //TODO: nobody implemented this yet in grade edit form!!
3822 send_file_not_found();
3824 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
3825 require_login($course);
3828 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3830 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3831 send_file_not_found();
3834 \core\session\manager
::write_close(); // Unlock session during file serving.
3835 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3837 send_file_not_found();
3840 // ========================================================================================================================
3841 } else if ($component === 'tag') {
3842 if ($filearea === 'description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
3844 // All tag descriptions are going to be public but we still need to respect forcelogin
3845 if ($CFG->forcelogin
) {
3849 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3851 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3852 send_file_not_found();
3855 \core\session\manager
::write_close(); // Unlock session during file serving.
3856 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3859 send_file_not_found();
3861 // ========================================================================================================================
3862 } else if ($component === 'badges') {
3863 require_once($CFG->libdir
. '/badgeslib.php');
3865 $badgeid = (int)array_shift($args);
3866 $badge = new badge($badgeid);
3867 $filename = array_pop($args);
3869 if ($filearea === 'badgeimage') {
3870 if ($filename !== 'f1' && $filename !== 'f2') {
3871 send_file_not_found();
3873 if (!$file = $fs->get_file($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $filename.'.png')) {
3874 send_file_not_found();
3877 \core\session\manager
::write_close();
3878 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3879 } else if ($filearea === 'userbadge' and $context->contextlevel
== CONTEXT_USER
) {
3880 if (!$file = $fs->get_file($context->id
, 'badges', 'userbadge', $badge->id
, '/', $filename.'.png')) {
3881 send_file_not_found();
3884 \core\session\manager
::write_close();
3885 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3887 // ========================================================================================================================
3888 } else if ($component === 'calendar') {
3889 if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_SYSTEM
) {
3891 // All events here are public the one requirement is that we respect forcelogin
3892 if ($CFG->forcelogin
) {
3896 // Get the event if from the args array
3897 $eventid = array_shift($args);
3899 // Load the event from the database
3900 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3901 send_file_not_found();
3904 // Get the file and serve if successful
3905 $filename = array_pop($args);
3906 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
3907 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3908 send_file_not_found();
3911 \core\session\manager
::write_close(); // Unlock session during file serving.
3912 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3914 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_USER
) {
3916 // Must be logged in, if they are not then they obviously can't be this user
3919 // Don't want guests here, potentially saves a DB call
3920 if (isguestuser()) {
3921 send_file_not_found();
3924 // Get the event if from the args array
3925 $eventid = array_shift($args);
3927 // Load the event from the database - user id must match
3928 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id
, 'eventtype'=>'user'))) {
3929 send_file_not_found();
3932 // Get the file and serve if successful
3933 $filename = array_pop($args);
3934 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
3935 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3936 send_file_not_found();
3939 \core\session\manager
::write_close(); // Unlock session during file serving.
3940 send_stored_file($file, 0, 0, true, array('preview' => $preview));
3942 } else if ($filearea === 'event_description' and $context->contextlevel
== CONTEXT_COURSE
) {
3944 // Respect forcelogin and require login unless this is the site.... it probably
3945 // should NEVER be the site
3946 if ($CFG->forcelogin ||
$course->id
!= SITEID
) {
3947 require_login($course);
3950 // Must be able to at least view the course. This does not apply to the front page.
3951 if ($course->id
!= SITEID
&& (!is_enrolled($context)) && (!is_viewing($context))) {
3952 //TODO: hmm, do we really want to block guests here?
3953 send_file_not_found();
3957 $eventid = array_shift($args);
3959 // Load the event from the database we need to check whether it is
3960 // a) valid course event
3962 // Group events use the course context (there is no group context)
3963 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id
))) {
3964 send_file_not_found();
3967 // If its a group event require either membership of view all groups capability
3968 if ($event->eventtype
=== 'group') {
3969 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid
, $USER->id
)) {
3970 send_file_not_found();
3972 } else if ($event->eventtype
=== 'course' ||
$event->eventtype
=== 'site') {
3973 // Ok. Please note that the event type 'site' still uses a course context.
3976 send_file_not_found();
3979 // If we get this far we can serve the file
3980 $filename = array_pop($args);
3981 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
3982 if (!$file = $fs->get_file($context->id
, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3983 send_file_not_found();
3986 \core\session\manager
::write_close(); // Unlock session during file serving.
3987 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3990 send_file_not_found();
3993 // ========================================================================================================================
3994 } else if ($component === 'user') {
3995 if ($filearea === 'icon' and $context->contextlevel
== CONTEXT_USER
) {
3996 if (count($args) == 1) {
3997 $themename = theme_config
::DEFAULT_THEME
;
3998 $filename = array_shift($args);
4000 $themename = array_shift($args);
4001 $filename = array_shift($args);
4004 // fix file name automatically
4005 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4009 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
4010 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
4011 // protect images if login required and not logged in;
4012 // also if login is required for profile images and is not logged in or guest
4013 // do not use require_login() because it is expensive and not suitable here anyway
4014 $theme = theme_config
::load($themename);
4015 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
4018 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.png')) {
4019 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4020 if ($filename === 'f3') {
4021 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4022 if (!$file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.png')) {
4023 $file = $fs->get_file($context->id
, 'user', 'icon', 0, '/', 'f1.jpg');
4029 // bad reference - try to prevent future retries as hard as possible!
4030 if ($user = $DB->get_record('user', array('id'=>$context->instanceid
), 'id, picture')) {
4031 if ($user->picture
> 0) {
4032 $DB->set_field('user', 'picture', 0, array('id'=>$user->id
));
4035 // no redirect here because it is not cached
4036 $theme = theme_config
::load($themename);
4037 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4038 send_file($imagefile, basename($imagefile), 60*60*24*14);
4041 $options = array('preview' => $preview);
4042 if (empty($CFG->forcelogin
) && empty($CFG->forceloginforprofileimage
)) {
4043 // Profile images should be cache-able by both browsers and proxies according
4044 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4045 $options['cacheability'] = 'public';
4047 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4049 } else if ($filearea === 'private' and $context->contextlevel
== CONTEXT_USER
) {
4052 if (isguestuser()) {
4053 send_file_not_found();
4056 if ($USER->id
!== $context->instanceid
) {
4057 send_file_not_found();
4060 $filename = array_pop($args);
4061 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4062 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4063 send_file_not_found();
4066 \core\session\manager
::write_close(); // Unlock session during file serving.
4067 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4069 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_USER
) {
4071 if ($CFG->forcelogin
) {
4075 $userid = $context->instanceid
;
4077 if ($USER->id
== $userid) {
4078 // always can access own
4080 } else if (!empty($CFG->forceloginforprofiles
)) {
4083 if (isguestuser()) {
4084 send_file_not_found();
4087 // we allow access to site profile of all course contacts (usually teachers)
4088 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4089 send_file_not_found();
4093 if (has_capability('moodle/user:viewdetails', $context)) {
4096 $courses = enrol_get_my_courses();
4099 while (!$canview && count($courses) > 0) {
4100 $course = array_shift($courses);
4101 if (has_capability('moodle/user:viewdetails', context_course
::instance($course->id
))) {
4107 $filename = array_pop($args);
4108 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4109 if (!$file = $fs->get_file($context->id
, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4110 send_file_not_found();
4113 \core\session\manager
::write_close(); // Unlock session during file serving.
4114 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4116 } else if ($filearea === 'profile' and $context->contextlevel
== CONTEXT_COURSE
) {
4117 $userid = (int)array_shift($args);
4118 $usercontext = context_user
::instance($userid);
4120 if ($CFG->forcelogin
) {
4124 if (!empty($CFG->forceloginforprofiles
)) {
4126 if (isguestuser()) {
4127 print_error('noguest');
4130 //TODO: review this logic of user profile access prevention
4131 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4132 print_error('usernotavailable');
4134 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4135 print_error('cannotviewprofile');
4137 if (!is_enrolled($context, $userid)) {
4138 print_error('notenrolledprofile');
4140 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
4141 print_error('groupnotamember');
4145 $filename = array_pop($args);
4146 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4147 if (!$file = $fs->get_file($usercontext->id
, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4148 send_file_not_found();
4151 \core\session\manager
::write_close(); // Unlock session during file serving.
4152 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4154 } else if ($filearea === 'backup' and $context->contextlevel
== CONTEXT_USER
) {
4157 if (isguestuser()) {
4158 send_file_not_found();
4160 $userid = $context->instanceid
;
4162 if ($USER->id
!= $userid) {
4163 send_file_not_found();
4166 $filename = array_pop($args);
4167 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4168 if (!$file = $fs->get_file($context->id
, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4169 send_file_not_found();
4172 \core\session\manager
::write_close(); // Unlock session during file serving.
4173 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4176 send_file_not_found();
4179 // ========================================================================================================================
4180 } else if ($component === 'coursecat') {
4181 if ($context->contextlevel
!= CONTEXT_COURSECAT
) {
4182 send_file_not_found();
4185 if ($filearea === 'description') {
4186 if ($CFG->forcelogin
) {
4187 // no login necessary - unless login forced everywhere
4191 $filename = array_pop($args);
4192 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4193 if (!$file = $fs->get_file($context->id
, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4194 send_file_not_found();
4197 \core\session\manager
::write_close(); // Unlock session during file serving.
4198 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4200 send_file_not_found();
4203 // ========================================================================================================================
4204 } else if ($component === 'course') {
4205 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4206 send_file_not_found();
4209 if ($filearea === 'summary' ||
$filearea === 'overviewfiles') {
4210 if ($CFG->forcelogin
) {
4214 $filename = array_pop($args);
4215 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4216 if (!$file = $fs->get_file($context->id
, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4217 send_file_not_found();
4220 \core\session\manager
::write_close(); // Unlock session during file serving.
4221 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4223 } else if ($filearea === 'section') {
4224 if ($CFG->forcelogin
) {
4225 require_login($course);
4226 } else if ($course->id
!= SITEID
) {
4227 require_login($course);
4230 $sectionid = (int)array_shift($args);
4232 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id
))) {
4233 send_file_not_found();
4236 $filename = array_pop($args);
4237 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4238 if (!$file = $fs->get_file($context->id
, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4239 send_file_not_found();
4242 \core\session\manager
::write_close(); // Unlock session during file serving.
4243 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4246 send_file_not_found();
4249 } else if ($component === 'cohort') {
4251 $cohortid = (int)array_shift($args);
4252 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST
);
4253 $cohortcontext = context
::instance_by_id($cohort->contextid
);
4255 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4256 if ($context->id
!= $cohort->contextid
&&
4257 ($context->contextlevel
!= CONTEXT_COURSE ||
!in_array($cohort->contextid
, $context->get_parent_context_ids()))) {
4258 send_file_not_found();
4261 // User is able to access cohort if they have view cap on cohort level or
4262 // the cohort is visible and they have view cap on course level.
4263 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4264 ($cohort->visible
&& has_capability('moodle/cohort:view', $context));
4266 if ($filearea === 'description' && $canview) {
4267 $filename = array_pop($args);
4268 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4269 if (($file = $fs->get_file($cohortcontext->id
, 'cohort', 'description', $cohort->id
, $filepath, $filename))
4270 && !$file->is_directory()) {
4271 \core\session\manager
::write_close(); // Unlock session during file serving.
4272 send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
4276 send_file_not_found();
4278 } else if ($component === 'group') {
4279 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4280 send_file_not_found();
4283 require_course_login($course, true, null, false);
4285 $groupid = (int)array_shift($args);
4287 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id
), '*', MUST_EXIST
);
4288 if (($course->groupmodeforce
and $course->groupmode
== SEPARATEGROUPS
) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id
, $USER->id
)) {
4289 // do not allow access to separate group info if not member or teacher
4290 send_file_not_found();
4293 if ($filearea === 'description') {
4295 require_login($course);
4297 $filename = array_pop($args);
4298 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4299 if (!$file = $fs->get_file($context->id
, 'group', 'description', $group->id
, $filepath, $filename) or $file->is_directory()) {
4300 send_file_not_found();
4303 \core\session\manager
::write_close(); // Unlock session during file serving.
4304 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4306 } else if ($filearea === 'icon') {
4307 $filename = array_pop($args);
4309 if ($filename !== 'f1' and $filename !== 'f2') {
4310 send_file_not_found();
4312 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.png')) {
4313 if (!$file = $fs->get_file($context->id
, 'group', 'icon', $group->id
, '/', $filename.'.jpg')) {
4314 send_file_not_found();
4318 \core\session\manager
::write_close(); // Unlock session during file serving.
4319 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4322 send_file_not_found();
4325 } else if ($component === 'grouping') {
4326 if ($context->contextlevel
!= CONTEXT_COURSE
) {
4327 send_file_not_found();
4330 require_login($course);
4332 $groupingid = (int)array_shift($args);
4334 // note: everybody has access to grouping desc images for now
4335 if ($filearea === 'description') {
4337 $filename = array_pop($args);
4338 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4339 if (!$file = $fs->get_file($context->id
, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4340 send_file_not_found();
4343 \core\session\manager
::write_close(); // Unlock session during file serving.
4344 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4347 send_file_not_found();
4350 // ========================================================================================================================
4351 } else if ($component === 'backup') {
4352 if ($filearea === 'course' and $context->contextlevel
== CONTEXT_COURSE
) {
4353 require_login($course);
4354 require_capability('moodle/backup:downloadfile', $context);
4356 $filename = array_pop($args);
4357 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4358 if (!$file = $fs->get_file($context->id
, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4359 send_file_not_found();
4362 \core\session\manager
::write_close(); // Unlock session during file serving.
4363 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4365 } else if ($filearea === 'section' and $context->contextlevel
== CONTEXT_COURSE
) {
4366 require_login($course);
4367 require_capability('moodle/backup:downloadfile', $context);
4369 $sectionid = (int)array_shift($args);
4371 $filename = array_pop($args);
4372 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4373 if (!$file = $fs->get_file($context->id
, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4374 send_file_not_found();
4377 \core\session\manager
::write_close();
4378 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4380 } else if ($filearea === 'activity' and $context->contextlevel
== CONTEXT_MODULE
) {
4381 require_login($course, false, $cm);
4382 require_capability('moodle/backup:downloadfile', $context);
4384 $filename = array_pop($args);
4385 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4386 if (!$file = $fs->get_file($context->id
, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4387 send_file_not_found();
4390 \core\session\manager
::write_close();
4391 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4393 } else if ($filearea === 'automated' and $context->contextlevel
== CONTEXT_COURSE
) {
4394 // Backup files that were generated by the automated backup systems.
4396 require_login($course);
4397 require_capability('moodle/site:config', $context);
4399 $filename = array_pop($args);
4400 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4401 if (!$file = $fs->get_file($context->id
, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4402 send_file_not_found();
4405 \core\session\manager
::write_close(); // Unlock session during file serving.
4406 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4409 send_file_not_found();
4412 // ========================================================================================================================
4413 } else if ($component === 'question') {
4414 require_once($CFG->libdir
. '/questionlib.php');
4415 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4416 send_file_not_found();
4418 // ========================================================================================================================
4419 } else if ($component === 'grading') {
4420 if ($filearea === 'description') {
4421 // files embedded into the form definition description
4423 if ($context->contextlevel
== CONTEXT_SYSTEM
) {
4426 } else if ($context->contextlevel
>= CONTEXT_COURSE
) {
4427 require_login($course, false, $cm);
4430 send_file_not_found();
4433 $formid = (int)array_shift($args);
4435 $sql = "SELECT ga.id
4436 FROM {grading_areas} ga
4437 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4438 WHERE gd.id = ? AND ga.contextid = ?";
4439 $areaid = $DB->get_field_sql($sql, array($formid, $context->id
), IGNORE_MISSING
);
4442 send_file_not_found();
4445 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4447 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4448 send_file_not_found();
4451 \core\session\manager
::write_close(); // Unlock session during file serving.
4452 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4455 // ========================================================================================================================
4456 } else if (strpos($component, 'mod_') === 0) {
4457 $modname = substr($component, 4);
4458 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4459 send_file_not_found();
4461 require_once("$CFG->dirroot/mod/$modname/lib.php");
4463 if ($context->contextlevel
== CONTEXT_MODULE
) {
4464 if ($cm->modname
!== $modname) {
4465 // somebody tries to gain illegal access, cm type must match the component!
4466 send_file_not_found();
4470 if ($filearea === 'intro') {
4471 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO
, true)) {
4472 send_file_not_found();
4474 require_course_login($course, true, $cm);
4476 // all users may access it
4477 $filename = array_pop($args);
4478 $filepath = $args ?
'/'.implode('/', $args).'/' : '/';
4479 if (!$file = $fs->get_file($context->id
, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4480 send_file_not_found();
4483 // finally send the file
4484 send_stored_file($file, null, 0, false, array('preview' => $preview));
4487 $filefunction = $component.'_pluginfile';
4488 $filefunctionold = $modname.'_pluginfile';
4489 if (function_exists($filefunction)) {
4490 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4491 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4492 } else if (function_exists($filefunctionold)) {
4493 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4494 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4497 send_file_not_found();
4499 // ========================================================================================================================
4500 } else if (strpos($component, 'block_') === 0) {
4501 $blockname = substr($component, 6);
4502 // note: no more class methods in blocks please, that is ....
4503 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4504 send_file_not_found();
4506 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4508 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4509 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid
), '*',MUST_EXIST
);
4510 if ($birecord->blockname
!== $blockname) {
4511 // somebody tries to gain illegal access, cm type must match the component!
4512 send_file_not_found();
4515 if ($context->get_course_context(false)) {
4516 // If block is in course context, then check if user has capability to access course.
4517 require_course_login($course);
4518 } else if ($CFG->forcelogin
) {
4519 // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
4523 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id
, 'blockinstanceid' => $context->instanceid
));
4524 // User can't access file, if block is hidden or doesn't have block:view capability
4525 if (($bprecord && !$bprecord->visible
) ||
!has_capability('moodle/block:view', $context)) {
4526 send_file_not_found();
4532 $filefunction = $component.'_pluginfile';
4533 if (function_exists($filefunction)) {
4534 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4535 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4538 send_file_not_found();
4540 // ========================================================================================================================
4541 } else if (strpos($component, '_') === false) {
4542 // all core subsystems have to be specified above, no more guessing here!
4543 send_file_not_found();
4546 // try to serve general plugin file in arbitrary context
4547 $dir = core_component
::get_component_directory($component);
4548 if (!file_exists("$dir/lib.php")) {
4549 send_file_not_found();
4551 include_once("$dir/lib.php");
4553 $filefunction = $component.'_pluginfile';
4554 if (function_exists($filefunction)) {
4555 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4556 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4559 send_file_not_found();