Merge branch 'wip-mdl-48190-m27' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / filelib.php
blobdda080b6273142e6b3778069d8a12cb10c0bd582
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for file handling.
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 /**
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
42 /**
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56 global $CFG;
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
65 if ($forcedownload) {
66 $return .= '?forcedownload=1';
68 } else {
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
71 if ($forcedownload) {
72 $return .= '&amp;forcedownload=1';
76 if ($https) {
77 $return = str_replace('http://', 'https://', $return);
80 return $return;
83 /**
84 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
92 * @return bool
94 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
95 global $DB;
97 if (!isset($itemid)) {
98 // Not initialised yet.
99 return false;
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
114 * displayed.
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
118 * @category files
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id != $context->id) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
161 $contextid = null;
162 $itemid = null;
163 if (!isset($data)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
176 } else {
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
183 } else {
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
195 } else {
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
199 return $data;
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
213 * @category files
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
241 if ($options['trusttext']) {
242 $data->{$field.'trust'} = trusttext_trusted($context);
243 } else {
244 $data->{$field.'trust'} = 0;
247 $editor = $data->{$field.'_editor'};
249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
250 $data->{$field} = $editor['text'];
251 } else {
252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
254 $data->{$field.'format'} = $editor['format'];
256 return $data;
260 * Saves text and files modified by Editor formslib element
262 * @category files
263 * @param stdClass $data $database entry field
264 * @param string $field name of data field
265 * @param array $options various options
266 * @param stdClass $context context - must already exist
267 * @param string $component
268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
270 * @return stdClass modified data obejct
272 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
277 if (is_null($itemid) or is_null($context)) {
278 $itemid = null;
279 $contextid = null;
280 } else {
281 $contextid = $context->id;
284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
286 $data->{$field.'_filemanager'} = $draftid_editor;
288 return $data;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
295 * @category files
296 * @param stdClass $data $database entry field
297 * @param string $field name of data field
298 * @param array $options various options
299 * @param stdClass $context context - must already exist
300 * @param string $component
301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
303 * @return stdClass modified data obejct
305 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
317 if (empty($data->{$field.'_filemanager'})) {
318 $data->$field = '';
320 } else {
321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
322 $fs = get_file_storage();
324 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
326 } else {
327 $data->$field = '';
331 return $data;
335 * Generate a draft itemid
337 * @category files
338 * @global moodle_database $DB
339 * @global stdClass $USER
340 * @return int a random but available draft itemid that can be used to create a new draft
341 * file area.
343 function file_get_unused_draft_itemid() {
344 global $DB, $USER;
346 if (isguestuser() or !isloggedin()) {
347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
348 print_error('noguest');
351 $contextid = context_user::instance($USER->id)->id;
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
356 $draftitemid = rand(1, 999999999);
359 return $draftitemid;
363 * Initialise a draft file area from a real one by copying the files. A draft
364 * area will be created if one does not already exist. Normally you should
365 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
367 * @category files
368 * @global stdClass $CFG
369 * @global stdClass $USER
370 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
371 * @param int $contextid This parameter and the next two identify the file area to copy files from.
372 * @param string $component
373 * @param string $filearea helps indentify the file area.
374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
379 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
380 global $CFG, $USER, $CFG;
382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
386 if (!isset($options['forcehttps'])) {
387 $options['forcehttps'] = false;
390 $usercontext = context_user::instance($USER->id);
391 $fs = get_file_storage();
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
395 $draftitemid = file_get_unused_draft_itemid();
396 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
397 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
398 foreach ($files as $file) {
399 if ($file->is_directory() and $file->get_filepath() === '/') {
400 // we need a way to mark the age of each draft area,
401 // by not copying the root dir we force it to be created automatically with current timestamp
402 continue;
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
405 continue;
407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
408 // XXX: This is a hack for file manager (MDL-28666)
409 // File manager needs to know the original file information before copying
410 // to draft area, so we append these information in mdl_files.source field
411 // {@link file_storage::search_references()}
412 // {@link file_storage::search_references_count()}
413 $sourcefield = $file->get_source();
414 $newsourcefield = new stdClass;
415 $newsourcefield->source = $sourcefield;
416 $original = new stdClass;
417 $original->contextid = $contextid;
418 $original->component = $component;
419 $original->filearea = $filearea;
420 $original->itemid = $itemid;
421 $original->filename = $file->get_filename();
422 $original->filepath = $file->get_filepath();
423 $newsourcefield->original = file_storage::pack_reference($original);
424 $draftfile->set_source(serialize($newsourcefield));
425 // End of file manager hack
428 if (!is_null($text)) {
429 // at this point there should not be any draftfile links yet,
430 // because this is a new text from database that should still contain the @@pluginfile@@ links
431 // this happens when developers forget to post process the text
432 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
434 } else {
435 // nothing to do
438 if (is_null($text)) {
439 return null;
442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
449 * @category files
450 * @global stdClass $CFG
451 * @param string $text The content that may contain ULRs in need of rewriting.
452 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
453 * @param int $contextid This parameter and the next two identify the file area to use.
454 * @param string $component
455 * @param string $filearea helps identify the file area.
456 * @param int $itemid helps identify the file area.
457 * @param array $options text and file options ('forcehttps'=>false)
458 * @return string the processed text.
460 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
461 global $CFG;
463 $options = (array)$options;
464 if (!isset($options['forcehttps'])) {
465 $options['forcehttps'] = false;
468 if (!$CFG->slasharguments) {
469 $file = $file . '?file=';
472 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
474 if ($itemid !== null) {
475 $baseurl .= "$itemid/";
478 if ($options['forcehttps']) {
479 $baseurl = str_replace('http://', 'https://', $baseurl);
482 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
486 * Returns information about files in a draft area.
488 * @global stdClass $CFG
489 * @global stdClass $USER
490 * @param int $draftitemid the draft area item id.
491 * @param string $filepath path to the directory from which the information have to be retrieved.
492 * @return array with the following entries:
493 * 'filecount' => number of files in the draft area.
494 * 'filesize' => total size of the files in the draft area.
495 * 'foldercount' => number of folders in the draft area.
496 * 'filesize_without_references' => total size of the area excluding file references.
497 * (more information will be added as needed).
499 function file_get_draft_area_info($draftitemid, $filepath = '/') {
500 global $CFG, $USER;
502 $usercontext = context_user::instance($USER->id);
503 $fs = get_file_storage();
505 $results = array(
506 'filecount' => 0,
507 'foldercount' => 0,
508 'filesize' => 0,
509 'filesize_without_references' => 0
512 if ($filepath != '/') {
513 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
514 } else {
515 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
517 foreach ($draftfiles as $file) {
518 if ($file->is_directory()) {
519 $results['foldercount'] += 1;
520 } else {
521 $results['filecount'] += 1;
524 $filesize = $file->get_filesize();
525 $results['filesize'] += $filesize;
526 if (!$file->is_external_file()) {
527 $results['filesize_without_references'] += $filesize;
531 return $results;
535 * Returns whether a draft area has exceeded/will exceed its size limit.
537 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
539 * @param int $draftitemid the draft area item id.
540 * @param int $areamaxbytes the maximum size allowed in this draft area.
541 * @param int $newfilesize the size that would be added to the current area.
542 * @param bool $includereferences true to include the size of the references in the area size.
543 * @return bool true if the area will/has exceeded its limit.
544 * @since Moodle 2.4
546 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
547 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
548 $draftinfo = file_get_draft_area_info($draftitemid);
549 $areasize = $draftinfo['filesize_without_references'];
550 if ($includereferences) {
551 $areasize = $draftinfo['filesize'];
553 if ($areasize + $newfilesize > $areamaxbytes) {
554 return true;
557 return false;
561 * Get used space of files
562 * @global moodle_database $DB
563 * @global stdClass $USER
564 * @return int total bytes
566 function file_get_user_used_space() {
567 global $DB, $USER;
569 $usercontext = context_user::instance($USER->id);
570 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
571 JOIN (SELECT contenthash, filename, MAX(id) AS id
572 FROM {files}
573 WHERE contextid = ? AND component = ? AND filearea != ?
574 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
575 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
576 $record = $DB->get_record_sql($sql, $params);
577 return (int)$record->totalbytes;
581 * Convert any string to a valid filepath
582 * @todo review this function
583 * @param string $str
584 * @return string path
586 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
587 if ($str == '/' or empty($str)) {
588 return '/';
589 } else {
590 return '/'.trim($str, '/').'/';
595 * Generate a folder tree of draft area of current USER recursively
597 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
598 * @param int $draftitemid
599 * @param string $filepath
600 * @param mixed $data
602 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
603 global $USER, $OUTPUT, $CFG;
604 $data->children = array();
605 $context = context_user::instance($USER->id);
606 $fs = get_file_storage();
607 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
608 foreach ($files as $file) {
609 if ($file->is_directory()) {
610 $item = new stdClass();
611 $item->sortorder = $file->get_sortorder();
612 $item->filepath = $file->get_filepath();
614 $foldername = explode('/', trim($item->filepath, '/'));
615 $item->fullname = trim(array_pop($foldername), '/');
617 $item->id = uniqid();
618 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
619 $data->children[] = $item;
620 } else {
621 continue;
628 * Listing all files (including folders) in current path (draft area)
629 * used by file manager
630 * @param int $draftitemid
631 * @param string $filepath
632 * @return stdClass
634 function file_get_drafarea_files($draftitemid, $filepath = '/') {
635 global $USER, $OUTPUT, $CFG;
637 $context = context_user::instance($USER->id);
638 $fs = get_file_storage();
640 $data = new stdClass();
641 $data->path = array();
642 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
644 // will be used to build breadcrumb
645 $trail = '/';
646 if ($filepath !== '/') {
647 $filepath = file_correct_filepath($filepath);
648 $parts = explode('/', $filepath);
649 foreach ($parts as $part) {
650 if ($part != '' && $part != null) {
651 $trail .= ($part.'/');
652 $data->path[] = array('name'=>$part, 'path'=>$trail);
657 $list = array();
658 $maxlength = 12;
659 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
660 foreach ($files as $file) {
661 $item = new stdClass();
662 $item->filename = $file->get_filename();
663 $item->filepath = $file->get_filepath();
664 $item->fullname = trim($item->filename, '/');
665 $filesize = $file->get_filesize();
666 $item->size = $filesize ? $filesize : null;
667 $item->filesize = $filesize ? display_size($filesize) : '';
669 $item->sortorder = $file->get_sortorder();
670 $item->author = $file->get_author();
671 $item->license = $file->get_license();
672 $item->datemodified = $file->get_timemodified();
673 $item->datecreated = $file->get_timecreated();
674 $item->isref = $file->is_external_file();
675 if ($item->isref && $file->get_status() == 666) {
676 $item->originalmissing = true;
678 // find the file this draft file was created from and count all references in local
679 // system pointing to that file
680 $source = @unserialize($file->get_source());
681 if (isset($source->original)) {
682 $item->refcount = $fs->search_references_count($source->original);
685 if ($file->is_directory()) {
686 $item->filesize = 0;
687 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
688 $item->type = 'folder';
689 $foldername = explode('/', trim($item->filepath, '/'));
690 $item->fullname = trim(array_pop($foldername), '/');
691 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
692 } else {
693 // do NOT use file browser here!
694 $item->mimetype = get_mimetype_description($file);
695 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
696 $item->type = 'zip';
697 } else {
698 $item->type = 'file';
700 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
701 $item->url = $itemurl->out();
702 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
703 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
704 if ($imageinfo = $file->get_imageinfo()) {
705 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
706 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
707 $item->image_width = $imageinfo['width'];
708 $item->image_height = $imageinfo['height'];
711 $list[] = $item;
714 $data->itemid = $draftitemid;
715 $data->list = $list;
716 return $data;
720 * Returns draft area itemid for a given element.
722 * @category files
723 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
724 * @return int the itemid, or 0 if there is not one yet.
726 function file_get_submitted_draft_itemid($elname) {
727 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
728 if (!isset($_REQUEST[$elname])) {
729 return 0;
731 if (is_array($_REQUEST[$elname])) {
732 $param = optional_param_array($elname, 0, PARAM_INT);
733 if (!empty($param['itemid'])) {
734 $param = $param['itemid'];
735 } else {
736 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
737 return false;
740 } else {
741 $param = optional_param($elname, 0, PARAM_INT);
744 if ($param) {
745 require_sesskey();
748 return $param;
752 * Restore the original source field from draft files
754 * Do not use this function because it makes field files.source inconsistent
755 * for draft area files. This function will be deprecated in 2.6
757 * @param stored_file $storedfile This only works with draft files
758 * @return stored_file
760 function file_restore_source_field_from_draft_file($storedfile) {
761 $source = @unserialize($storedfile->get_source());
762 if (!empty($source)) {
763 if (is_object($source)) {
764 $restoredsource = $source->source;
765 $storedfile->set_source($restoredsource);
766 } else {
767 throw new moodle_exception('invalidsourcefield', 'error');
770 return $storedfile;
773 * Saves files from a draft file area to a real one (merging the list of files).
774 * Can rewrite URLs in some content at the same time if desired.
776 * @category files
777 * @global stdClass $USER
778 * @param int $draftitemid the id of the draft area to use. Normally obtained
779 * from file_get_submitted_draft_itemid('elementname') or similar.
780 * @param int $contextid This parameter and the next two identify the file area to save to.
781 * @param string $component
782 * @param string $filearea indentifies the file area.
783 * @param int $itemid helps identifies the file area.
784 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
785 * @param string $text some html content that needs to have embedded links rewritten
786 * to the @@PLUGINFILE@@ form for saving in the database.
787 * @param bool $forcehttps force https urls.
788 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
790 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
791 global $USER;
793 $usercontext = context_user::instance($USER->id);
794 $fs = get_file_storage();
796 $options = (array)$options;
797 if (!isset($options['subdirs'])) {
798 $options['subdirs'] = false;
800 if (!isset($options['maxfiles'])) {
801 $options['maxfiles'] = -1; // unlimited
803 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
804 $options['maxbytes'] = 0; // unlimited
806 if (!isset($options['areamaxbytes'])) {
807 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
809 $allowreferences = true;
810 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
811 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
812 // this is not exactly right. BUT there are many places in code where filemanager options
813 // are not passed to file_save_draft_area_files()
814 $allowreferences = false;
817 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
818 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
819 // anything at all in the next area.
820 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
821 return null;
824 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
825 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
827 // One file in filearea means it is empty (it has only top-level directory '.').
828 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
829 // we have to merge old and new files - we want to keep file ids for files that were not changed
830 // we change time modified for all new and changed files, we keep time created as is
832 $newhashes = array();
833 $filecount = 0;
834 foreach ($draftfiles as $file) {
835 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
836 continue;
838 if (!$allowreferences && $file->is_external_file()) {
839 continue;
841 if (!$file->is_directory()) {
842 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
843 // oversized file - should not get here at all
844 continue;
846 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
847 // more files - should not get here at all
848 continue;
850 $filecount++;
852 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
853 $newhashes[$newhash] = $file;
856 // Loop through oldfiles and decide which we need to delete and which to update.
857 // After this cycle the array $newhashes will only contain the files that need to be added.
858 foreach ($oldfiles as $oldfile) {
859 $oldhash = $oldfile->get_pathnamehash();
860 if (!isset($newhashes[$oldhash])) {
861 // delete files not needed any more - deleted by user
862 $oldfile->delete();
863 continue;
866 $newfile = $newhashes[$oldhash];
867 // Now we know that we have $oldfile and $newfile for the same path.
868 // Let's check if we can update this file or we need to delete and create.
869 if ($newfile->is_directory()) {
870 // Directories are always ok to just update.
871 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
872 // File has the 'original' - we need to update the file (it may even have not been changed at all).
873 $original = file_storage::unpack_reference($source->original);
874 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
875 // Very odd, original points to another file. Delete and create file.
876 $oldfile->delete();
877 continue;
879 } else {
880 // The same file name but absence of 'original' means that file was deteled and uploaded again.
881 // By deleting and creating new file we properly manage all existing references.
882 $oldfile->delete();
883 continue;
886 // status changed, we delete old file, and create a new one
887 if ($oldfile->get_status() != $newfile->get_status()) {
888 // file was changed, use updated with new timemodified data
889 $oldfile->delete();
890 // This file will be added later
891 continue;
894 // Updated author
895 if ($oldfile->get_author() != $newfile->get_author()) {
896 $oldfile->set_author($newfile->get_author());
898 // Updated license
899 if ($oldfile->get_license() != $newfile->get_license()) {
900 $oldfile->set_license($newfile->get_license());
903 // Updated file source
904 // Field files.source for draftarea files contains serialised object with source and original information.
905 // We only store the source part of it for non-draft file area.
906 $newsource = $newfile->get_source();
907 if ($source = @unserialize($newfile->get_source())) {
908 $newsource = $source->source;
910 if ($oldfile->get_source() !== $newsource) {
911 $oldfile->set_source($newsource);
914 // Updated sort order
915 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
916 $oldfile->set_sortorder($newfile->get_sortorder());
919 // Update file timemodified
920 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
921 $oldfile->set_timemodified($newfile->get_timemodified());
924 // Replaced file content
925 if (!$oldfile->is_directory() &&
926 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
927 $oldfile->get_filesize() != $newfile->get_filesize() ||
928 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
929 $oldfile->get_userid() != $newfile->get_userid())) {
930 $oldfile->replace_file_with($newfile);
933 // unchanged file or directory - we keep it as is
934 unset($newhashes[$oldhash]);
937 // Add fresh file or the file which has changed status
938 // the size and subdirectory tests are extra safety only, the UI should prevent it
939 foreach ($newhashes as $file) {
940 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
941 if ($source = @unserialize($file->get_source())) {
942 // Field files.source for draftarea files contains serialised object with source and original information.
943 // We only store the source part of it for non-draft file area.
944 $file_record['source'] = $source->source;
947 if ($file->is_external_file()) {
948 $repoid = $file->get_repository_id();
949 if (!empty($repoid)) {
950 $file_record['repositoryid'] = $repoid;
951 $file_record['reference'] = $file->get_reference();
955 $fs->create_file_from_storedfile($file_record, $file);
959 // note: do not purge the draft area - we clean up areas later in cron,
960 // the reason is that user might press submit twice and they would loose the files,
961 // also sometimes we might want to use hacks that save files into two different areas
963 if (is_null($text)) {
964 return null;
965 } else {
966 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
971 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
972 * ready to be saved in the database. Normally, this is done automatically by
973 * {@link file_save_draft_area_files()}.
975 * @category files
976 * @param string $text the content to process.
977 * @param int $draftitemid the draft file area the content was using.
978 * @param bool $forcehttps whether the content contains https URLs. Default false.
979 * @return string the processed content.
981 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
982 global $CFG, $USER;
984 $usercontext = context_user::instance($USER->id);
986 $wwwroot = $CFG->wwwroot;
987 if ($forcehttps) {
988 $wwwroot = str_replace('http://', 'https://', $wwwroot);
991 // relink embedded files if text submitted - no absolute links allowed in database!
992 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
994 if (strpos($text, 'draftfile.php?file=') !== false) {
995 $matches = array();
996 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
997 if ($matches) {
998 foreach ($matches[0] as $match) {
999 $replace = str_ireplace('%2F', '/', $match);
1000 $text = str_replace($match, $replace, $text);
1003 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1006 return $text;
1010 * Set file sort order
1012 * @global moodle_database $DB
1013 * @param int $contextid the context id
1014 * @param string $component file component
1015 * @param string $filearea file area.
1016 * @param int $itemid itemid.
1017 * @param string $filepath file path.
1018 * @param string $filename file name.
1019 * @param int $sortorder the sort order of file.
1020 * @return bool
1022 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1023 global $DB;
1024 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1025 if ($file_record = $DB->get_record('files', $conditions)) {
1026 $sortorder = (int)$sortorder;
1027 $file_record->sortorder = $sortorder;
1028 $DB->update_record('files', $file_record);
1029 return true;
1031 return false;
1035 * reset file sort order number to 0
1036 * @global moodle_database $DB
1037 * @param int $contextid the context id
1038 * @param string $component
1039 * @param string $filearea file area.
1040 * @param int|bool $itemid itemid.
1041 * @return bool
1043 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1044 global $DB;
1046 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1047 if ($itemid !== false) {
1048 $conditions['itemid'] = $itemid;
1051 $file_records = $DB->get_records('files', $conditions);
1052 foreach ($file_records as $file_record) {
1053 $file_record->sortorder = 0;
1054 $DB->update_record('files', $file_record);
1056 return true;
1060 * Returns description of upload error
1062 * @param int $errorcode found in $_FILES['filename.ext']['error']
1063 * @return string error description string, '' if ok
1065 function file_get_upload_error($errorcode) {
1067 switch ($errorcode) {
1068 case 0: // UPLOAD_ERR_OK - no error
1069 $errmessage = '';
1070 break;
1072 case 1: // UPLOAD_ERR_INI_SIZE
1073 $errmessage = get_string('uploadserverlimit');
1074 break;
1076 case 2: // UPLOAD_ERR_FORM_SIZE
1077 $errmessage = get_string('uploadformlimit');
1078 break;
1080 case 3: // UPLOAD_ERR_PARTIAL
1081 $errmessage = get_string('uploadpartialfile');
1082 break;
1084 case 4: // UPLOAD_ERR_NO_FILE
1085 $errmessage = get_string('uploadnofilefound');
1086 break;
1088 // Note: there is no error with a value of 5
1090 case 6: // UPLOAD_ERR_NO_TMP_DIR
1091 $errmessage = get_string('uploadnotempdir');
1092 break;
1094 case 7: // UPLOAD_ERR_CANT_WRITE
1095 $errmessage = get_string('uploadcantwrite');
1096 break;
1098 case 8: // UPLOAD_ERR_EXTENSION
1099 $errmessage = get_string('uploadextension');
1100 break;
1102 default:
1103 $errmessage = get_string('uploadproblem');
1106 return $errmessage;
1110 * Recursive function formating an array in POST parameter
1111 * @param array $arraydata - the array that we are going to format and add into &$data array
1112 * @param string $currentdata - a row of the final postdata array at instant T
1113 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1114 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1116 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1117 foreach ($arraydata as $k=>$v) {
1118 $newcurrentdata = $currentdata;
1119 if (is_array($v)) { //the value is an array, call the function recursively
1120 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1121 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1122 } else { //add the POST parameter to the $data array
1123 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1129 * Transform a PHP array into POST parameter
1130 * (see the recursive function format_array_postdata_for_curlcall)
1131 * @param array $postdata
1132 * @return array containing all POST parameters (1 row = 1 POST parameter)
1134 function format_postdata_for_curlcall($postdata) {
1135 $data = array();
1136 foreach ($postdata as $k=>$v) {
1137 if (is_array($v)) {
1138 $currentdata = urlencode($k);
1139 format_array_postdata_for_curlcall($v, $currentdata, $data);
1140 } else {
1141 $data[] = urlencode($k).'='.urlencode($v);
1144 $convertedpostdata = implode('&', $data);
1145 return $convertedpostdata;
1149 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1150 * Due to security concerns only downloads from http(s) sources are supported.
1152 * @category files
1153 * @param string $url file url starting with http(s)://
1154 * @param array $headers http headers, null if none. If set, should be an
1155 * associative array of header name => value pairs.
1156 * @param array $postdata array means use POST request with given parameters
1157 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1158 * (if false, just returns content)
1159 * @param int $timeout timeout for complete download process including all file transfer
1160 * (default 5 minutes)
1161 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1162 * usually happens if the remote server is completely down (default 20 seconds);
1163 * may not work when using proxy
1164 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1165 * Only use this when already in a trusted location.
1166 * @param string $tofile store the downloaded content to file instead of returning it.
1167 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1168 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1169 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1170 * if file downloaded into $tofile successfully or the file content as a string.
1172 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1173 global $CFG;
1175 // Only http and https links supported.
1176 if (!preg_match('|^https?://|i', $url)) {
1177 if ($fullresponse) {
1178 $response = new stdClass();
1179 $response->status = 0;
1180 $response->headers = array();
1181 $response->response_code = 'Invalid protocol specified in url';
1182 $response->results = '';
1183 $response->error = 'Invalid protocol specified in url';
1184 return $response;
1185 } else {
1186 return false;
1190 $options = array();
1192 $headers2 = array();
1193 if (is_array($headers)) {
1194 foreach ($headers as $key => $value) {
1195 if (is_numeric($key)) {
1196 $headers2[] = $value;
1197 } else {
1198 $headers2[] = "$key: $value";
1203 if ($skipcertverify) {
1204 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1205 } else {
1206 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1209 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1211 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1212 $options['CURLOPT_MAXREDIRS'] = 5;
1214 // Use POST if requested.
1215 if (is_array($postdata)) {
1216 $postdata = format_postdata_for_curlcall($postdata);
1217 } else if (empty($postdata)) {
1218 $postdata = null;
1221 // Optionally attempt to get more correct timeout by fetching the file size.
1222 if (!isset($CFG->curltimeoutkbitrate)) {
1223 // Use very slow rate of 56kbps as a timeout speed when not set.
1224 $bitrate = 56;
1225 } else {
1226 $bitrate = $CFG->curltimeoutkbitrate;
1228 if ($calctimeout and !isset($postdata)) {
1229 $curl = new curl();
1230 $curl->setHeader($headers2);
1232 $curl->head($url, $postdata, $options);
1234 $info = $curl->get_info();
1235 $error_no = $curl->get_errno();
1236 if (!$error_no && $info['download_content_length'] > 0) {
1237 // No curl errors - adjust for large files only - take max timeout.
1238 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1242 $curl = new curl();
1243 $curl->setHeader($headers2);
1245 $options['CURLOPT_RETURNTRANSFER'] = true;
1246 $options['CURLOPT_NOBODY'] = false;
1247 $options['CURLOPT_TIMEOUT'] = $timeout;
1249 if ($tofile) {
1250 $fh = fopen($tofile, 'w');
1251 if (!$fh) {
1252 if ($fullresponse) {
1253 $response = new stdClass();
1254 $response->status = 0;
1255 $response->headers = array();
1256 $response->response_code = 'Can not write to file';
1257 $response->results = false;
1258 $response->error = 'Can not write to file';
1259 return $response;
1260 } else {
1261 return false;
1264 $options['CURLOPT_FILE'] = $fh;
1267 if (isset($postdata)) {
1268 $content = $curl->post($url, $postdata, $options);
1269 } else {
1270 $content = $curl->get($url, null, $options);
1273 if ($tofile) {
1274 fclose($fh);
1275 @chmod($tofile, $CFG->filepermissions);
1279 // Try to detect encoding problems.
1280 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1281 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1282 $result = curl_exec($ch);
1286 $info = $curl->get_info();
1287 $error_no = $curl->get_errno();
1288 $rawheaders = $curl->get_raw_response();
1290 if ($error_no) {
1291 $error = $content;
1292 if (!$fullresponse) {
1293 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1294 return false;
1297 $response = new stdClass();
1298 if ($error_no == 28) {
1299 $response->status = '-100'; // Mimic snoopy.
1300 } else {
1301 $response->status = '0';
1303 $response->headers = array();
1304 $response->response_code = $error;
1305 $response->results = false;
1306 $response->error = $error;
1307 return $response;
1310 if ($tofile) {
1311 $content = true;
1314 if (empty($info['http_code'])) {
1315 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1316 $response = new stdClass();
1317 $response->status = '0';
1318 $response->headers = array();
1319 $response->response_code = 'Unknown cURL error';
1320 $response->results = false; // do NOT change this, we really want to ignore the result!
1321 $response->error = 'Unknown cURL error';
1323 } else {
1324 $response = new stdClass();
1325 $response->status = (string)$info['http_code'];
1326 $response->headers = $rawheaders;
1327 $response->results = $content;
1328 $response->error = '';
1330 // There might be multiple headers on redirect, find the status of the last one.
1331 $firstline = true;
1332 foreach ($rawheaders as $line) {
1333 if ($firstline) {
1334 $response->response_code = $line;
1335 $firstline = false;
1337 if (trim($line, "\r\n") === '') {
1338 $firstline = true;
1343 if ($fullresponse) {
1344 return $response;
1347 if ($info['http_code'] != 200) {
1348 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1349 return false;
1351 return $response->results;
1355 * Returns a list of information about file types based on extensions.
1357 * The following elements expected in value array for each extension:
1358 * 'type' - mimetype
1359 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1360 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1361 * also files with bigger sizes under names
1362 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1363 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1364 * commonly used in moodle the following groups:
1365 * - web_image - image that can be included as <img> in HTML
1366 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1367 * - video - file that can be imported as video in text editor
1368 * - audio - file that can be imported as audio in text editor
1369 * - archive - we can extract files from this archive
1370 * - spreadsheet - used for portfolio format
1371 * - document - used for portfolio format
1372 * - presentation - used for portfolio format
1373 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1374 * human-readable description for this filetype;
1375 * Function {@link get_mimetype_description()} first looks at the presence of string for
1376 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1377 * attribute, if not found returns the value of 'type';
1378 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1379 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1380 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1382 * @category files
1383 * @return array List of information about file types based on extensions.
1384 * Associative array of extension (lower-case) to associative array
1385 * from 'element name' to data. Current element names are 'type' and 'icon'.
1386 * Unknown types should use the 'xxx' entry which includes defaults.
1388 function &get_mimetypes_array() {
1389 static $mimearray = array (
1390 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1391 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1392 '7z' => array ('type'=>'application/x-7z-compressed', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1393 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1394 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1395 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1396 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1397 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1398 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1399 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1400 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1401 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1402 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1403 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1404 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1405 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1406 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1407 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1408 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1409 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1410 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1411 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1412 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1414 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1415 'bdoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
1416 'cdoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
1417 'ddoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
1418 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1419 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1420 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1421 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1423 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1424 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1425 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1426 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1427 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1428 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1429 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1430 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1431 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1433 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1434 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1435 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1436 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1437 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1438 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1439 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1440 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1441 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1442 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1443 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1444 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1445 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1446 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1447 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1448 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1449 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1450 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1451 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1452 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1453 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1454 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1455 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1456 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1457 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1458 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1459 'jnlp' => array ('type'=>'application/x-java-jnlp-file', 'icon'=>'markup'),
1460 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1461 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1462 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1463 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1464 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1465 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1466 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1467 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1468 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1469 'mht' => array ('type'=>'message/rfc822', 'icon'=>'archive'),
1470 'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
1471 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1472 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1473 'mw' => array ('type'=>'application/maple', 'icon'=>'math'),
1474 'mws' => array ('type'=>'application/maple', 'icon'=>'math'),
1475 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1476 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1477 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1478 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1479 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1480 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1481 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1482 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1483 'mpr' => array ('type'=>'application/vnd.moodle.profiling', 'icon'=>'moodle'),
1485 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1486 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1488 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1489 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1490 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1491 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1492 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1493 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1494 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1495 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1496 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1497 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1498 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1499 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1500 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1501 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1502 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1503 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1504 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1506 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1507 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1508 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1509 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1510 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1511 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1512 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1513 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1514 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1515 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1516 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1517 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1518 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1519 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1520 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1521 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1522 'pub' => array ('type'=>'application/x-mspublisher', 'icon'=>'publisher', 'groups'=>array('presentation')),
1524 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1525 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1526 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1527 'rar' => array ('type'=>'application/x-rar-compressed', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1528 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1529 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1530 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1531 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1532 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1533 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1534 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1535 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1536 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1537 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1538 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1539 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1540 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1541 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1542 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1543 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1545 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1546 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1547 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1548 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1549 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1550 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1551 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1552 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1553 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1554 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1556 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1557 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1558 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1559 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1560 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1561 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1562 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1563 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1564 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1565 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1566 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1567 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1568 'wma' => array ('type'=>'audio/x-ms-wma', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1570 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1571 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1572 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1573 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1575 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1576 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1577 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1578 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1579 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1580 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1581 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1583 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1584 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1586 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1588 return $mimearray;
1592 * Obtains information about a filetype based on its extension. Will
1593 * use a default if no information is present about that particular
1594 * extension.
1596 * @category files
1597 * @param string $element Desired information (usually 'icon'
1598 * for icon filename or 'type' for MIME type. Can also be
1599 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1600 * @param string $filename Filename we're looking up
1601 * @return string Requested piece of information from array
1603 function mimeinfo($element, $filename) {
1604 global $CFG;
1605 $mimeinfo = & get_mimetypes_array();
1606 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1608 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1609 if (empty($filetype)) {
1610 $filetype = 'xxx'; // file without extension
1612 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1613 $iconsize = max(array(16, (int)$iconsizematch[1]));
1614 $filenames = array($mimeinfo['xxx']['icon']);
1615 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1616 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1618 // find the file with the closest size, first search for specific icon then for default icon
1619 foreach ($filenames as $filename) {
1620 foreach ($iconpostfixes as $size => $postfix) {
1621 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1622 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1623 return $filename.$postfix;
1627 } else if (isset($mimeinfo[$filetype][$element])) {
1628 return $mimeinfo[$filetype][$element];
1629 } else if (isset($mimeinfo['xxx'][$element])) {
1630 return $mimeinfo['xxx'][$element]; // By default
1631 } else {
1632 return null;
1637 * Obtains information about a filetype based on the MIME type rather than
1638 * the other way around.
1640 * @category files
1641 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1642 * @param string $mimetype MIME type we're looking up
1643 * @return string Requested piece of information from array
1645 function mimeinfo_from_type($element, $mimetype) {
1646 /* array of cached mimetype->extension associations */
1647 static $cached = array();
1648 $mimeinfo = & get_mimetypes_array();
1650 if (!array_key_exists($mimetype, $cached)) {
1651 $cached[$mimetype] = null;
1652 foreach($mimeinfo as $filetype => $values) {
1653 if ($values['type'] == $mimetype) {
1654 if ($cached[$mimetype] === null) {
1655 $cached[$mimetype] = '.'.$filetype;
1657 if (!empty($values['defaulticon'])) {
1658 $cached[$mimetype] = '.'.$filetype;
1659 break;
1663 if (empty($cached[$mimetype])) {
1664 $cached[$mimetype] = '.xxx';
1667 if ($element === 'extension') {
1668 return $cached[$mimetype];
1669 } else {
1670 return mimeinfo($element, $cached[$mimetype]);
1675 * Return the relative icon path for a given file
1677 * Usage:
1678 * <code>
1679 * // $file - instance of stored_file or file_info
1680 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1681 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1682 * </code>
1683 * or
1684 * <code>
1685 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1686 * </code>
1688 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1689 * and $file->mimetype are expected)
1690 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1691 * @return string
1693 function file_file_icon($file, $size = null) {
1694 if (!is_object($file)) {
1695 $file = (object)$file;
1697 if (isset($file->filename)) {
1698 $filename = $file->filename;
1699 } else if (method_exists($file, 'get_filename')) {
1700 $filename = $file->get_filename();
1701 } else if (method_exists($file, 'get_visible_name')) {
1702 $filename = $file->get_visible_name();
1703 } else {
1704 $filename = '';
1706 if (isset($file->mimetype)) {
1707 $mimetype = $file->mimetype;
1708 } else if (method_exists($file, 'get_mimetype')) {
1709 $mimetype = $file->get_mimetype();
1710 } else {
1711 $mimetype = '';
1713 $mimetypes = &get_mimetypes_array();
1714 if ($filename) {
1715 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1716 if ($extension && !empty($mimetypes[$extension])) {
1717 // if file name has known extension, return icon for this extension
1718 return file_extension_icon($filename, $size);
1721 return file_mimetype_icon($mimetype, $size);
1725 * Return the relative icon path for a folder image
1727 * Usage:
1728 * <code>
1729 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1730 * echo html_writer::empty_tag('img', array('src' => $icon));
1731 * </code>
1732 * or
1733 * <code>
1734 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1735 * </code>
1737 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1738 * @return string
1740 function file_folder_icon($iconsize = null) {
1741 global $CFG;
1742 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1743 static $cached = array();
1744 $iconsize = max(array(16, (int)$iconsize));
1745 if (!array_key_exists($iconsize, $cached)) {
1746 foreach ($iconpostfixes as $size => $postfix) {
1747 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1748 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1749 $cached[$iconsize] = 'f/folder'.$postfix;
1750 break;
1754 return $cached[$iconsize];
1758 * Returns the relative icon path for a given mime type
1760 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1761 * a return the full path to an icon.
1763 * <code>
1764 * $mimetype = 'image/jpg';
1765 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1766 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1767 * </code>
1769 * @category files
1770 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1771 * to conform with that.
1772 * @param string $mimetype The mimetype to fetch an icon for
1773 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1774 * @return string The relative path to the icon
1776 function file_mimetype_icon($mimetype, $size = NULL) {
1777 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1781 * Returns the relative icon path for a given file name
1783 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1784 * a return the full path to an icon.
1786 * <code>
1787 * $filename = '.jpg';
1788 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1789 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1790 * </code>
1792 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1793 * to conform with that.
1794 * @todo MDL-31074 Implement $size
1795 * @category files
1796 * @param string $filename The filename to get the icon for
1797 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1798 * @return string
1800 function file_extension_icon($filename, $size = NULL) {
1801 return 'f/'.mimeinfo('icon'.$size, $filename);
1805 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1806 * mimetypes.php language file.
1808 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1809 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1810 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1811 * @param bool $capitalise If true, capitalises first character of result
1812 * @return string Text description
1814 function get_mimetype_description($obj, $capitalise=false) {
1815 $filename = $mimetype = '';
1816 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1817 // this is an instance of stored_file
1818 $mimetype = $obj->get_mimetype();
1819 $filename = $obj->get_filename();
1820 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1821 // this is an instance of file_info
1822 $mimetype = $obj->get_mimetype();
1823 $filename = $obj->get_visible_name();
1824 } else if (is_array($obj) || is_object ($obj)) {
1825 $obj = (array)$obj;
1826 if (!empty($obj['filename'])) {
1827 $filename = $obj['filename'];
1829 if (!empty($obj['mimetype'])) {
1830 $mimetype = $obj['mimetype'];
1832 } else {
1833 $mimetype = $obj;
1835 $mimetypefromext = mimeinfo('type', $filename);
1836 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1837 // if file has a known extension, overwrite the specified mimetype
1838 $mimetype = $mimetypefromext;
1840 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1841 if (empty($extension)) {
1842 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1843 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1844 } else {
1845 $mimetypestr = mimeinfo('string', $filename);
1847 $chunks = explode('/', $mimetype, 2);
1848 $chunks[] = '';
1849 $attr = array(
1850 'mimetype' => $mimetype,
1851 'ext' => $extension,
1852 'mimetype1' => $chunks[0],
1853 'mimetype2' => $chunks[1],
1855 $a = array();
1856 foreach ($attr as $key => $value) {
1857 $a[$key] = $value;
1858 $a[strtoupper($key)] = strtoupper($value);
1859 $a[ucfirst($key)] = ucfirst($value);
1862 // MIME types may include + symbol but this is not permitted in string ids.
1863 $safemimetype = str_replace('+', '_', $mimetype);
1864 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1865 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1866 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1867 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1868 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1869 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1870 $result = get_string('default', 'mimetypes', (object)$a);
1871 } else {
1872 $result = $mimetype;
1874 if ($capitalise) {
1875 $result=ucfirst($result);
1877 return $result;
1881 * Returns array of elements of type $element in type group(s)
1883 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1884 * @param string|array $groups one group or array of groups/extensions/mimetypes
1885 * @return array
1887 function file_get_typegroup($element, $groups) {
1888 static $cached = array();
1889 if (!is_array($groups)) {
1890 $groups = array($groups);
1892 if (!array_key_exists($element, $cached)) {
1893 $cached[$element] = array();
1895 $result = array();
1896 foreach ($groups as $group) {
1897 if (!array_key_exists($group, $cached[$element])) {
1898 // retrieive and cache all elements of type $element for group $group
1899 $mimeinfo = & get_mimetypes_array();
1900 $cached[$element][$group] = array();
1901 foreach ($mimeinfo as $extension => $value) {
1902 $value['extension'] = '.'.$extension;
1903 if (empty($value[$element])) {
1904 continue;
1906 if (($group === '.'.$extension || $group === $value['type'] ||
1907 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1908 !in_array($value[$element], $cached[$element][$group])) {
1909 $cached[$element][$group][] = $value[$element];
1913 $result = array_merge($result, $cached[$element][$group]);
1915 return array_values(array_unique($result));
1919 * Checks if file with name $filename has one of the extensions in groups $groups
1921 * @see get_mimetypes_array()
1922 * @param string $filename name of the file to check
1923 * @param string|array $groups one group or array of groups to check
1924 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1925 * file mimetype is in mimetypes in groups $groups
1926 * @return bool
1928 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1929 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1930 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1931 return true;
1933 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1937 * Checks if mimetype $mimetype belongs to one of the groups $groups
1939 * @see get_mimetypes_array()
1940 * @param string $mimetype
1941 * @param string|array $groups one group or array of groups to check
1942 * @return bool
1944 function file_mimetype_in_typegroup($mimetype, $groups) {
1945 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1949 * Requested file is not found or not accessible, does not return, terminates script
1951 * @global stdClass $CFG
1952 * @global stdClass $COURSE
1954 function send_file_not_found() {
1955 global $CFG, $COURSE;
1956 send_header_404();
1957 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1960 * Helper function to send correct 404 for server.
1962 function send_header_404() {
1963 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1964 header("Status: 404 Not Found");
1965 } else {
1966 header('HTTP/1.0 404 not found');
1971 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1972 * platforms). This wrapper uses readfile for small files and custom code for
1973 * large ones.
1975 * @param string $path Path to file
1976 * @param int $filesize Size of file (if left out, will get it automatically)
1977 * @return int|bool Size read (will always be $filesize) or false if failed
1979 function readfile_allow_large($path, $filesize = -1) {
1980 // Automatically get size if not specified.
1981 if ($filesize === -1) {
1982 $filesize = filesize($path);
1984 if ($filesize <= 2147483647) {
1985 // If the file is up to 2^31 - 1, send it normally using readfile.
1986 return readfile($path);
1987 } else {
1988 // For large files, read and output in 64KB chunks.
1989 $handle = fopen($path, 'r');
1990 if ($handle === false) {
1991 return false;
1993 $left = $filesize;
1994 while ($left > 0) {
1995 $size = min($left, 65536);
1996 $buffer = fread($handle, $size);
1997 if ($buffer === false) {
1998 return false;
2000 echo $buffer;
2001 $left -= $size;
2003 return $filesize;
2008 * Enhanced readfile() with optional acceleration.
2009 * @param string|stored_file $file
2010 * @param string $mimetype
2011 * @param bool $accelerate
2012 * @return void
2014 function readfile_accel($file, $mimetype, $accelerate) {
2015 global $CFG;
2017 if ($mimetype === 'text/plain') {
2018 // there is no encoding specified in text files, we need something consistent
2019 header('Content-Type: text/plain; charset=utf-8');
2020 } else {
2021 header('Content-Type: '.$mimetype);
2024 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2025 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2027 if (is_object($file)) {
2028 header('Etag: "' . $file->get_contenthash() . '"');
2029 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2030 header('HTTP/1.1 304 Not Modified');
2031 return;
2035 // if etag present for stored file rely on it exclusively
2036 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2037 // get unixtime of request header; clip extra junk off first
2038 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2039 if ($since && $since >= $lastmodified) {
2040 header('HTTP/1.1 304 Not Modified');
2041 return;
2045 if ($accelerate and !empty($CFG->xsendfile)) {
2046 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2047 header('Accept-Ranges: bytes');
2048 } else {
2049 header('Accept-Ranges: none');
2052 if (is_object($file)) {
2053 $fs = get_file_storage();
2054 if ($fs->xsendfile($file->get_contenthash())) {
2055 return;
2058 } else {
2059 require_once("$CFG->libdir/xsendfilelib.php");
2060 if (xsendfile($file)) {
2061 return;
2066 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2068 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2070 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2071 header('Accept-Ranges: bytes');
2073 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2074 // byteserving stuff - for acrobat reader and download accelerators
2075 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2076 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2077 $ranges = false;
2078 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2079 foreach ($ranges as $key=>$value) {
2080 if ($ranges[$key][1] == '') {
2081 //suffix case
2082 $ranges[$key][1] = $filesize - $ranges[$key][2];
2083 $ranges[$key][2] = $filesize - 1;
2084 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2085 //fix range length
2086 $ranges[$key][2] = $filesize - 1;
2088 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2089 //invalid byte-range ==> ignore header
2090 $ranges = false;
2091 break;
2093 //prepare multipart header
2094 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2095 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2097 } else {
2098 $ranges = false;
2100 if ($ranges) {
2101 if (is_object($file)) {
2102 $handle = $file->get_content_file_handle();
2103 } else {
2104 $handle = fopen($file, 'rb');
2106 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2109 } else {
2110 // Do not byteserve
2111 header('Accept-Ranges: none');
2114 header('Content-Length: '.$filesize);
2116 if ($filesize > 10000000) {
2117 // for large files try to flush and close all buffers to conserve memory
2118 while(@ob_get_level()) {
2119 if (!@ob_end_flush()) {
2120 break;
2125 // send the whole file content
2126 if (is_object($file)) {
2127 $file->readfile();
2128 } else {
2129 readfile_allow_large($file, $filesize);
2134 * Similar to readfile_accel() but designed for strings.
2135 * @param string $string
2136 * @param string $mimetype
2137 * @param bool $accelerate
2138 * @return void
2140 function readstring_accel($string, $mimetype, $accelerate) {
2141 global $CFG;
2143 if ($mimetype === 'text/plain') {
2144 // there is no encoding specified in text files, we need something consistent
2145 header('Content-Type: text/plain; charset=utf-8');
2146 } else {
2147 header('Content-Type: '.$mimetype);
2149 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2150 header('Accept-Ranges: none');
2152 if ($accelerate and !empty($CFG->xsendfile)) {
2153 $fs = get_file_storage();
2154 if ($fs->xsendfile(sha1($string))) {
2155 return;
2159 header('Content-Length: '.strlen($string));
2160 echo $string;
2164 * Handles the sending of temporary file to user, download is forced.
2165 * File is deleted after abort or successful sending, does not return, script terminated
2167 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2168 * @param string $filename proposed file name when saving file
2169 * @param bool $pathisstring If the path is string
2171 function send_temp_file($path, $filename, $pathisstring=false) {
2172 global $CFG;
2174 if (core_useragent::is_firefox()) {
2175 // only FF is known to correctly save to disk before opening...
2176 $mimetype = mimeinfo('type', $filename);
2177 } else {
2178 $mimetype = 'application/x-forcedownload';
2181 // close session - not needed anymore
2182 \core\session\manager::write_close();
2184 if (!$pathisstring) {
2185 if (!file_exists($path)) {
2186 send_header_404();
2187 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2189 // executed after normal finish or abort
2190 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2193 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2194 if (core_useragent::is_ie()) {
2195 $filename = urlencode($filename);
2198 header('Content-Disposition: attachment; filename="'.$filename.'"');
2199 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2200 header('Cache-Control: private, max-age=10, no-transform');
2201 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2202 header('Pragma: ');
2203 } else { //normal http - prevent caching at all cost
2204 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2205 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2206 header('Pragma: no-cache');
2209 // send the contents - we can not accelerate this because the file will be deleted asap
2210 if ($pathisstring) {
2211 readstring_accel($path, $mimetype, false);
2212 } else {
2213 readfile_accel($path, $mimetype, false);
2214 @unlink($path);
2217 die; //no more chars to output
2221 * Internal callback function used by send_temp_file()
2223 * @param string $path
2225 function send_temp_file_finished($path) {
2226 if (file_exists($path)) {
2227 @unlink($path);
2232 * Handles the sending of file data to the user's browser, including support for
2233 * byteranges etc.
2235 * @category files
2236 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2237 * @param string $filename Filename to send
2238 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2239 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2240 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2241 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2242 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2243 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2244 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2245 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2246 * and should not be reopened.
2247 * @return null script execution stopped unless $dontdie is true
2249 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2250 global $CFG, $COURSE;
2252 if ($dontdie) {
2253 ignore_user_abort(true);
2256 if ($lifetime === 'default' or is_null($lifetime)) {
2257 $lifetime = $CFG->filelifetime;
2260 \core\session\manager::write_close(); // Unlock session during file serving.
2262 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2263 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2264 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2265 $isFF = core_useragent::is_firefox(); // only FF properly tested
2266 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2267 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2269 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2270 if (core_useragent::is_ie()) {
2271 $filename = rawurlencode($filename);
2274 if ($forcedownload) {
2275 header('Content-Disposition: attachment; filename="'.$filename.'"');
2276 } else if ($mimetype !== 'application/x-shockwave-flash') {
2277 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2278 // as an upload and enforces security that may prevent the file from being loaded.
2280 header('Content-Disposition: inline; filename="'.$filename.'"');
2283 if ($lifetime > 0) {
2284 $cacheability = ' public,';
2285 if (isloggedin() and !isguestuser()) {
2286 // By default, under the conditions above, this file must be cache-able only by browsers.
2287 $cacheability = ' private,';
2289 $nobyteserving = false;
2290 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2291 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2292 header('Pragma: ');
2294 } else { // Do not cache files in proxies and browsers
2295 $nobyteserving = true;
2296 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2297 header('Cache-Control: private, max-age=10, no-transform');
2298 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2299 header('Pragma: ');
2300 } else { //normal http - prevent caching at all cost
2301 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2302 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2303 header('Pragma: no-cache');
2307 if (empty($filter)) {
2308 // send the contents
2309 if ($pathisstring) {
2310 readstring_accel($path, $mimetype, !$dontdie);
2311 } else {
2312 readfile_accel($path, $mimetype, !$dontdie);
2315 } else {
2316 // Try to put the file through filters
2317 if ($mimetype == 'text/html') {
2318 $options = new stdClass();
2319 $options->noclean = true;
2320 $options->nocache = true; // temporary workaround for MDL-5136
2321 $text = $pathisstring ? $path : implode('', file($path));
2323 $text = file_modify_html_header($text);
2324 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2326 readstring_accel($output, $mimetype, false);
2328 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2329 // only filter text if filter all files is selected
2330 $options = new stdClass();
2331 $options->newlines = false;
2332 $options->noclean = true;
2333 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2334 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2336 readstring_accel($output, $mimetype, false);
2338 } else {
2339 // send the contents
2340 if ($pathisstring) {
2341 readstring_accel($path, $mimetype, !$dontdie);
2342 } else {
2343 readfile_accel($path, $mimetype, !$dontdie);
2347 if ($dontdie) {
2348 return;
2350 die; //no more chars to output!!!
2354 * Handles the sending of file data to the user's browser, including support for
2355 * byteranges etc.
2357 * The $options parameter supports the following keys:
2358 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2359 * (string|null) filename - overrides the implicit filename
2360 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2361 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2362 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2363 * and should not be reopened
2364 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2365 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2366 * defaults to "public".
2368 * @category files
2369 * @param stored_file $stored_file local file object
2370 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2371 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2372 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2373 * @param array $options additional options affecting the file serving
2374 * @return null script execution stopped unless $options['dontdie'] is true
2376 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2377 global $CFG, $COURSE;
2379 if (empty($options['filename'])) {
2380 $filename = null;
2381 } else {
2382 $filename = $options['filename'];
2385 if (empty($options['dontdie'])) {
2386 $dontdie = false;
2387 } else {
2388 $dontdie = true;
2391 if ($lifetime === 'default' or is_null($lifetime)) {
2392 $lifetime = $CFG->filelifetime;
2395 if (!empty($options['preview'])) {
2396 // replace the file with its preview
2397 $fs = get_file_storage();
2398 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2399 if (!$preview_file) {
2400 // unable to create a preview of the file, send its default mime icon instead
2401 if ($options['preview'] === 'tinyicon') {
2402 $size = 24;
2403 } else if ($options['preview'] === 'thumb') {
2404 $size = 90;
2405 } else {
2406 $size = 256;
2408 $fileicon = file_file_icon($stored_file, $size);
2409 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2410 } else {
2411 // preview images have fixed cache lifetime and they ignore forced download
2412 // (they are generated by GD and therefore they are considered reasonably safe).
2413 $stored_file = $preview_file;
2414 $lifetime = DAYSECS;
2415 $filter = 0;
2416 $forcedownload = false;
2420 // handle external resource
2421 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2422 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2423 die;
2426 if (!$stored_file or $stored_file->is_directory()) {
2427 // nothing to serve
2428 if ($dontdie) {
2429 return;
2431 die;
2434 if ($dontdie) {
2435 ignore_user_abort(true);
2438 \core\session\manager::write_close(); // Unlock session during file serving.
2440 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2441 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2442 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2443 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2444 $isFF = core_useragent::is_firefox(); // only FF properly tested
2445 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2446 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2448 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2449 if (core_useragent::is_ie()) {
2450 $filename = rawurlencode($filename);
2453 if ($forcedownload) {
2454 header('Content-Disposition: attachment; filename="'.$filename.'"');
2455 } else if ($mimetype !== 'application/x-shockwave-flash') {
2456 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2457 // as an upload and enforces security that may prevent the file from being loaded.
2459 header('Content-Disposition: inline; filename="'.$filename.'"');
2462 if ($lifetime > 0) {
2463 $cacheability = ' public,';
2464 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2465 // This file must be cache-able by both browsers and proxies.
2466 $cacheability = ' public,';
2467 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2468 // This file must be cache-able only by browsers.
2469 $cacheability = ' private,';
2470 } else if (isloggedin() and !isguestuser()) {
2471 $cacheability = ' private,';
2473 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2474 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2475 header('Pragma: ');
2477 } else { // Do not cache files in proxies and browsers
2478 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2479 header('Cache-Control: private, max-age=10, no-transform');
2480 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2481 header('Pragma: ');
2482 } else { //normal http - prevent caching at all cost
2483 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2484 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2485 header('Pragma: no-cache');
2489 if (empty($filter)) {
2490 // send the contents
2491 readfile_accel($stored_file, $mimetype, !$dontdie);
2493 } else { // Try to put the file through filters
2494 if ($mimetype == 'text/html') {
2495 $options = new stdClass();
2496 $options->noclean = true;
2497 $options->nocache = true; // temporary workaround for MDL-5136
2498 $text = $stored_file->get_content();
2499 $text = file_modify_html_header($text);
2500 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2502 readstring_accel($output, $mimetype, false);
2504 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2505 // only filter text if filter all files is selected
2506 $options = new stdClass();
2507 $options->newlines = false;
2508 $options->noclean = true;
2509 $text = $stored_file->get_content();
2510 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2512 readstring_accel($output, $mimetype, false);
2514 } else { // Just send it out raw
2515 readfile_accel($stored_file, $mimetype, !$dontdie);
2518 if ($dontdie) {
2519 return;
2521 die; //no more chars to output!!!
2525 * Retrieves an array of records from a CSV file and places
2526 * them into a given table structure
2528 * @global stdClass $CFG
2529 * @global moodle_database $DB
2530 * @param string $file The path to a CSV file
2531 * @param string $table The table to retrieve columns from
2532 * @return bool|array Returns an array of CSV records or false
2534 function get_records_csv($file, $table) {
2535 global $CFG, $DB;
2537 if (!$metacolumns = $DB->get_columns($table)) {
2538 return false;
2541 if(!($handle = @fopen($file, 'r'))) {
2542 print_error('get_records_csv failed to open '.$file);
2545 $fieldnames = fgetcsv($handle, 4096);
2546 if(empty($fieldnames)) {
2547 fclose($handle);
2548 return false;
2551 $columns = array();
2553 foreach($metacolumns as $metacolumn) {
2554 $ord = array_search($metacolumn->name, $fieldnames);
2555 if(is_int($ord)) {
2556 $columns[$metacolumn->name] = $ord;
2560 $rows = array();
2562 while (($data = fgetcsv($handle, 4096)) !== false) {
2563 $item = new stdClass;
2564 foreach($columns as $name => $ord) {
2565 $item->$name = $data[$ord];
2567 $rows[] = $item;
2570 fclose($handle);
2571 return $rows;
2575 * Create a file with CSV contents
2577 * @global stdClass $CFG
2578 * @global moodle_database $DB
2579 * @param string $file The file to put the CSV content into
2580 * @param array $records An array of records to write to a CSV file
2581 * @param string $table The table to get columns from
2582 * @return bool success
2584 function put_records_csv($file, $records, $table = NULL) {
2585 global $CFG, $DB;
2587 if (empty($records)) {
2588 return true;
2591 $metacolumns = NULL;
2592 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2593 return false;
2596 echo "x";
2598 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2599 print_error('put_records_csv failed to open '.$file);
2602 $proto = reset($records);
2603 if(is_object($proto)) {
2604 $fields_records = array_keys(get_object_vars($proto));
2606 else if(is_array($proto)) {
2607 $fields_records = array_keys($proto);
2609 else {
2610 return false;
2612 echo "x";
2614 if(!empty($metacolumns)) {
2615 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2616 $fields = array_intersect($fields_records, $fields_table);
2618 else {
2619 $fields = $fields_records;
2622 fwrite($fp, implode(',', $fields));
2623 fwrite($fp, "\r\n");
2625 foreach($records as $record) {
2626 $array = (array)$record;
2627 $values = array();
2628 foreach($fields as $field) {
2629 if(strpos($array[$field], ',')) {
2630 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2632 else {
2633 $values[] = $array[$field];
2636 fwrite($fp, implode(',', $values)."\r\n");
2639 fclose($fp);
2640 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
2641 return true;
2646 * Recursively delete the file or folder with path $location. That is,
2647 * if it is a file delete it. If it is a folder, delete all its content
2648 * then delete it. If $location does not exist to start, that is not
2649 * considered an error.
2651 * @param string $location the path to remove.
2652 * @return bool
2654 function fulldelete($location) {
2655 if (empty($location)) {
2656 // extra safety against wrong param
2657 return false;
2659 if (is_dir($location)) {
2660 if (!$currdir = opendir($location)) {
2661 return false;
2663 while (false !== ($file = readdir($currdir))) {
2664 if ($file <> ".." && $file <> ".") {
2665 $fullfile = $location."/".$file;
2666 if (is_dir($fullfile)) {
2667 if (!fulldelete($fullfile)) {
2668 return false;
2670 } else {
2671 if (!unlink($fullfile)) {
2672 return false;
2677 closedir($currdir);
2678 if (! rmdir($location)) {
2679 return false;
2682 } else if (file_exists($location)) {
2683 if (!unlink($location)) {
2684 return false;
2687 return true;
2691 * Send requested byterange of file.
2693 * @param resource $handle A file handle
2694 * @param string $mimetype The mimetype for the output
2695 * @param array $ranges An array of ranges to send
2696 * @param string $filesize The size of the content if only one range is used
2698 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2699 // better turn off any kind of compression and buffering
2700 ini_set('zlib.output_compression', 'Off');
2702 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2703 if ($handle === false) {
2704 die;
2706 if (count($ranges) == 1) { //only one range requested
2707 $length = $ranges[0][2] - $ranges[0][1] + 1;
2708 header('HTTP/1.1 206 Partial content');
2709 header('Content-Length: '.$length);
2710 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2711 header('Content-Type: '.$mimetype);
2713 while(@ob_get_level()) {
2714 if (!@ob_end_flush()) {
2715 break;
2719 fseek($handle, $ranges[0][1]);
2720 while (!feof($handle) && $length > 0) {
2721 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2722 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2723 echo $buffer;
2724 flush();
2725 $length -= strlen($buffer);
2727 fclose($handle);
2728 die;
2729 } else { // multiple ranges requested - not tested much
2730 $totallength = 0;
2731 foreach($ranges as $range) {
2732 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2734 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2735 header('HTTP/1.1 206 Partial content');
2736 header('Content-Length: '.$totallength);
2737 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2739 while(@ob_get_level()) {
2740 if (!@ob_end_flush()) {
2741 break;
2745 foreach($ranges as $range) {
2746 $length = $range[2] - $range[1] + 1;
2747 echo $range[0];
2748 fseek($handle, $range[1]);
2749 while (!feof($handle) && $length > 0) {
2750 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2751 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2752 echo $buffer;
2753 flush();
2754 $length -= strlen($buffer);
2757 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2758 fclose($handle);
2759 die;
2764 * add includes (js and css) into uploaded files
2765 * before returning them, useful for themes and utf.js includes
2767 * @global stdClass $CFG
2768 * @param string $text text to search and replace
2769 * @return string text with added head includes
2770 * @todo MDL-21120
2772 function file_modify_html_header($text) {
2773 // first look for <head> tag
2774 global $CFG;
2776 $stylesheetshtml = '';
2778 foreach ($CFG->stylesheets as $stylesheet) {
2779 //TODO: MDL-21120
2780 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2783 // TODO The code below is actually a waste of CPU. When MDL-29738 will be implemented it should be re-evaluated too.
2785 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2786 if ($matches) {
2787 $replacement = '<head>'.$stylesheetshtml;
2788 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2789 return $text;
2792 // if not, look for <html> tag, and stick <head> right after
2793 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2794 if ($matches) {
2795 // replace <html> tag with <html><head>includes</head>
2796 $replacement = '<html>'."\n".'<head>'.$stylesheetshtml.'</head>';
2797 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2798 return $text;
2801 // if not, look for <body> tag, and stick <head> before body
2802 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2803 if ($matches) {
2804 $replacement = '<head>'.$stylesheetshtml.'</head>'."\n".'<body>';
2805 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2806 return $text;
2809 // if not, just stick a <head> tag at the beginning
2810 $text = '<head>'.$stylesheetshtml.'</head>'."\n".$text;
2811 return $text;
2815 * RESTful cURL class
2817 * This is a wrapper class for curl, it is quite easy to use:
2818 * <code>
2819 * $c = new curl;
2820 * // enable cache
2821 * $c = new curl(array('cache'=>true));
2822 * // enable cookie
2823 * $c = new curl(array('cookie'=>true));
2824 * // enable proxy
2825 * $c = new curl(array('proxy'=>true));
2827 * // HTTP GET Method
2828 * $html = $c->get('http://example.com');
2829 * // HTTP POST Method
2830 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2831 * // HTTP PUT Method
2832 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2833 * </code>
2835 * @package core_files
2836 * @category files
2837 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2838 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2840 class curl {
2841 /** @var bool Caches http request contents */
2842 public $cache = false;
2843 /** @var bool Uses proxy, null means automatic based on URL */
2844 public $proxy = null;
2845 /** @var string library version */
2846 public $version = '0.4 dev';
2847 /** @var array http's response */
2848 public $response = array();
2849 /** @var array Raw response headers, needed for BC in download_file_content(). */
2850 public $rawresponse = array();
2851 /** @var array http header */
2852 public $header = array();
2853 /** @var string cURL information */
2854 public $info;
2855 /** @var string error */
2856 public $error;
2857 /** @var int error code */
2858 public $errno;
2859 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2860 public $emulateredirects = null;
2862 /** @var array cURL options */
2863 private $options;
2864 /** @var string Proxy host */
2865 private $proxy_host = '';
2866 /** @var string Proxy auth */
2867 private $proxy_auth = '';
2868 /** @var string Proxy type */
2869 private $proxy_type = '';
2870 /** @var bool Debug mode on */
2871 private $debug = false;
2872 /** @var bool|string Path to cookie file */
2873 private $cookie = false;
2874 /** @var bool tracks multiple headers in response - redirect detection */
2875 private $responsefinished = false;
2878 * Curl constructor.
2880 * Allowed settings are:
2881 * proxy: (bool) use proxy server, null means autodetect non-local from url
2882 * debug: (bool) use debug output
2883 * cookie: (string) path to cookie file, false if none
2884 * cache: (bool) use cache
2885 * module_cache: (string) type of cache
2887 * @param array $settings
2889 public function __construct($settings = array()) {
2890 global $CFG;
2891 if (!function_exists('curl_init')) {
2892 $this->error = 'cURL module must be enabled!';
2893 trigger_error($this->error, E_USER_ERROR);
2894 return false;
2897 // All settings of this class should be init here.
2898 $this->resetopt();
2899 if (!empty($settings['debug'])) {
2900 $this->debug = true;
2902 if (!empty($settings['cookie'])) {
2903 if($settings['cookie'] === true) {
2904 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2905 } else {
2906 $this->cookie = $settings['cookie'];
2909 if (!empty($settings['cache'])) {
2910 if (class_exists('curl_cache')) {
2911 if (!empty($settings['module_cache'])) {
2912 $this->cache = new curl_cache($settings['module_cache']);
2913 } else {
2914 $this->cache = new curl_cache('misc');
2918 if (!empty($CFG->proxyhost)) {
2919 if (empty($CFG->proxyport)) {
2920 $this->proxy_host = $CFG->proxyhost;
2921 } else {
2922 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2924 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2925 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2926 $this->setopt(array(
2927 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2928 'proxyuserpwd'=>$this->proxy_auth));
2930 if (!empty($CFG->proxytype)) {
2931 if ($CFG->proxytype == 'SOCKS5') {
2932 $this->proxy_type = CURLPROXY_SOCKS5;
2933 } else {
2934 $this->proxy_type = CURLPROXY_HTTP;
2935 $this->setopt(array('httpproxytunnel'=>false));
2937 $this->setopt(array('proxytype'=>$this->proxy_type));
2940 if (isset($settings['proxy'])) {
2941 $this->proxy = $settings['proxy'];
2943 } else {
2944 $this->proxy = false;
2947 if (!isset($this->emulateredirects)) {
2948 $this->emulateredirects = ini_get('open_basedir');
2953 * Resets the CURL options that have already been set
2955 public function resetopt() {
2956 $this->options = array();
2957 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2958 // True to include the header in the output
2959 $this->options['CURLOPT_HEADER'] = 0;
2960 // True to Exclude the body from the output
2961 $this->options['CURLOPT_NOBODY'] = 0;
2962 // Redirect ny default.
2963 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2964 $this->options['CURLOPT_MAXREDIRS'] = 10;
2965 $this->options['CURLOPT_ENCODING'] = '';
2966 // TRUE to return the transfer as a string of the return
2967 // value of curl_exec() instead of outputting it out directly.
2968 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2969 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2970 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2971 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2973 if ($cacert = self::get_cacert()) {
2974 $this->options['CURLOPT_CAINFO'] = $cacert;
2979 * Get the location of ca certificates.
2980 * @return string absolute file path or empty if default used
2982 public static function get_cacert() {
2983 global $CFG;
2985 // Bundle in dataroot always wins.
2986 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2987 return realpath("$CFG->dataroot/moodleorgca.crt");
2990 // Next comes the default from php.ini
2991 $cacert = ini_get('curl.cainfo');
2992 if (!empty($cacert) and is_readable($cacert)) {
2993 return realpath($cacert);
2996 // Windows PHP does not have any certs, we need to use something.
2997 if ($CFG->ostype === 'WINDOWS') {
2998 if (is_readable("$CFG->libdir/cacert.pem")) {
2999 return realpath("$CFG->libdir/cacert.pem");
3003 // Use default, this should work fine on all properly configured *nix systems.
3004 return null;
3008 * Reset Cookie
3010 public function resetcookie() {
3011 if (!empty($this->cookie)) {
3012 if (is_file($this->cookie)) {
3013 $fp = fopen($this->cookie, 'w');
3014 if (!empty($fp)) {
3015 fwrite($fp, '');
3016 fclose($fp);
3023 * Set curl options.
3025 * Do not use the curl constants to define the options, pass a string
3026 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3027 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3029 * @param array $options If array is null, this function will reset the options to default value.
3030 * @return void
3031 * @throws coding_exception If an option uses constant value instead of option name.
3033 public function setopt($options = array()) {
3034 if (is_array($options)) {
3035 foreach ($options as $name => $val) {
3036 if (!is_string($name)) {
3037 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3039 if (stripos($name, 'CURLOPT_') === false) {
3040 $name = strtoupper('CURLOPT_'.$name);
3041 } else {
3042 $name = strtoupper($name);
3044 $this->options[$name] = $val;
3050 * Reset http method
3052 public function cleanopt() {
3053 unset($this->options['CURLOPT_HTTPGET']);
3054 unset($this->options['CURLOPT_POST']);
3055 unset($this->options['CURLOPT_POSTFIELDS']);
3056 unset($this->options['CURLOPT_PUT']);
3057 unset($this->options['CURLOPT_INFILE']);
3058 unset($this->options['CURLOPT_INFILESIZE']);
3059 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3060 unset($this->options['CURLOPT_FILE']);
3064 * Resets the HTTP Request headers (to prepare for the new request)
3066 public function resetHeader() {
3067 $this->header = array();
3071 * Set HTTP Request Header
3073 * @param array $header
3075 public function setHeader($header) {
3076 if (is_array($header)) {
3077 foreach ($header as $v) {
3078 $this->setHeader($v);
3080 } else {
3081 // Remove newlines, they are not allowed in headers.
3082 $this->header[] = preg_replace('/[\r\n]/', '', $header);
3087 * Get HTTP Response Headers
3088 * @return array of arrays
3090 public function getResponse() {
3091 return $this->response;
3095 * Get raw HTTP Response Headers
3096 * @return array of strings
3098 public function get_raw_response() {
3099 return $this->rawresponse;
3103 * private callback function
3104 * Formatting HTTP Response Header
3106 * We only keep the last headers returned. For example during a redirect the
3107 * redirect headers will not appear in {@link self::getResponse()}, if you need
3108 * to use those headers, refer to {@link self::get_raw_response()}.
3110 * @param resource $ch Apparently not used
3111 * @param string $header
3112 * @return int The strlen of the header
3114 private function formatHeader($ch, $header) {
3115 $this->rawresponse[] = $header;
3117 if (trim($header, "\r\n") === '') {
3118 // This must be the last header.
3119 $this->responsefinished = true;
3122 if (strlen($header) > 2) {
3123 if ($this->responsefinished) {
3124 // We still have headers after the supposedly last header, we must be
3125 // in a redirect so let's empty the response to keep the last headers.
3126 $this->responsefinished = false;
3127 $this->response = array();
3129 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3130 $key = rtrim($key, ':');
3131 if (!empty($this->response[$key])) {
3132 if (is_array($this->response[$key])) {
3133 $this->response[$key][] = $value;
3134 } else {
3135 $tmp = $this->response[$key];
3136 $this->response[$key] = array();
3137 $this->response[$key][] = $tmp;
3138 $this->response[$key][] = $value;
3141 } else {
3142 $this->response[$key] = $value;
3145 return strlen($header);
3149 * Set options for individual curl instance
3151 * @param resource $curl A curl handle
3152 * @param array $options
3153 * @return resource The curl handle
3155 private function apply_opt($curl, $options) {
3156 // Some more security first.
3157 if (defined('CURLOPT_PROTOCOLS')) {
3158 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3160 if (defined('CURLOPT_REDIR_PROTOCOLS')) {
3161 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3164 // Clean up
3165 $this->cleanopt();
3166 // set cookie
3167 if (!empty($this->cookie) || !empty($options['cookie'])) {
3168 $this->setopt(array('cookiejar'=>$this->cookie,
3169 'cookiefile'=>$this->cookie
3173 // Bypass proxy if required.
3174 if ($this->proxy === null) {
3175 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3176 $proxy = false;
3177 } else {
3178 $proxy = true;
3180 } else {
3181 $proxy = (bool)$this->proxy;
3184 // Set proxy.
3185 if ($proxy) {
3186 $options['CURLOPT_PROXY'] = $this->proxy_host;
3187 } else {
3188 unset($this->options['CURLOPT_PROXY']);
3191 $this->setopt($options);
3192 // reset before set options
3193 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3194 // set headers
3195 if (empty($this->header)) {
3196 $this->setHeader(array(
3197 'User-Agent: MoodleBot/1.0',
3198 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3199 'Connection: keep-alive'
3202 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3204 if ($this->debug) {
3205 echo '<h1>Options</h1>';
3206 var_dump($this->options);
3207 echo '<h1>Header</h1>';
3208 var_dump($this->header);
3211 // Do not allow infinite redirects.
3212 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3213 $this->options['CURLOPT_MAXREDIRS'] = 0;
3214 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3215 $this->options['CURLOPT_MAXREDIRS'] = 100;
3216 } else {
3217 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3220 // Make sure we always know if redirects expected.
3221 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3222 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3225 // Set options.
3226 foreach($this->options as $name => $val) {
3227 if ($name === 'CURLOPT_PROTOCOLS' or $name === 'CURLOPT_REDIR_PROTOCOLS') {
3228 // These can not be changed, sorry.
3229 continue;
3231 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3232 // The redirects are emulated elsewhere.
3233 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3234 continue;
3236 $name = constant($name);
3237 curl_setopt($curl, $name, $val);
3240 return $curl;
3244 * Download multiple files in parallel
3246 * Calls {@link multi()} with specific download headers
3248 * <code>
3249 * $c = new curl();
3250 * $file1 = fopen('a', 'wb');
3251 * $file2 = fopen('b', 'wb');
3252 * $c->download(array(
3253 * array('url'=>'http://localhost/', 'file'=>$file1),
3254 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3255 * ));
3256 * fclose($file1);
3257 * fclose($file2);
3258 * </code>
3260 * or
3262 * <code>
3263 * $c = new curl();
3264 * $c->download(array(
3265 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3266 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3267 * ));
3268 * </code>
3270 * @param array $requests An array of files to request {
3271 * url => url to download the file [required]
3272 * file => file handler, or
3273 * filepath => file path
3275 * If 'file' and 'filepath' parameters are both specified in one request, the
3276 * open file handle in the 'file' parameter will take precedence and 'filepath'
3277 * will be ignored.
3279 * @param array $options An array of options to set
3280 * @return array An array of results
3282 public function download($requests, $options = array()) {
3283 $options['RETURNTRANSFER'] = false;
3284 return $this->multi($requests, $options);
3288 * Multi HTTP Requests
3289 * This function could run multi-requests in parallel.
3291 * @param array $requests An array of files to request
3292 * @param array $options An array of options to set
3293 * @return array An array of results
3295 protected function multi($requests, $options = array()) {
3296 $count = count($requests);
3297 $handles = array();
3298 $results = array();
3299 $main = curl_multi_init();
3300 for ($i = 0; $i < $count; $i++) {
3301 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3302 // open file
3303 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3304 $requests[$i]['auto-handle'] = true;
3306 foreach($requests[$i] as $n=>$v) {
3307 $options[$n] = $v;
3309 $handles[$i] = curl_init($requests[$i]['url']);
3310 $this->apply_opt($handles[$i], $options);
3311 curl_multi_add_handle($main, $handles[$i]);
3313 $running = 0;
3314 do {
3315 curl_multi_exec($main, $running);
3316 } while($running > 0);
3317 for ($i = 0; $i < $count; $i++) {
3318 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3319 $results[] = true;
3320 } else {
3321 $results[] = curl_multi_getcontent($handles[$i]);
3323 curl_multi_remove_handle($main, $handles[$i]);
3325 curl_multi_close($main);
3327 for ($i = 0; $i < $count; $i++) {
3328 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3329 // close file handler if file is opened in this function
3330 fclose($requests[$i]['file']);
3333 return $results;
3337 * Single HTTP Request
3339 * @param string $url The URL to request
3340 * @param array $options
3341 * @return bool
3343 protected function request($url, $options = array()) {
3344 // Set the URL as a curl option.
3345 $this->setopt(array('CURLOPT_URL' => $url));
3347 // Create curl instance.
3348 $curl = curl_init();
3350 // Reset here so that the data is valid when result returned from cache.
3351 $this->info = array();
3352 $this->error = '';
3353 $this->errno = 0;
3354 $this->response = array();
3355 $this->rawresponse = array();
3356 $this->responsefinished = false;
3358 $this->apply_opt($curl, $options);
3359 if ($this->cache && $ret = $this->cache->get($this->options)) {
3360 return $ret;
3363 $ret = curl_exec($curl);
3364 $this->info = curl_getinfo($curl);
3365 $this->error = curl_error($curl);
3366 $this->errno = curl_errno($curl);
3367 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3369 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3370 $redirects = 0;
3372 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3374 if ($this->info['http_code'] == 301) {
3375 // Moved Permanently - repeat the same request on new URL.
3377 } else if ($this->info['http_code'] == 302) {
3378 // Found - the standard redirect - repeat the same request on new URL.
3380 } else if ($this->info['http_code'] == 303) {
3381 // 303 See Other - repeat only if GET, do not bother with POSTs.
3382 if (empty($this->options['CURLOPT_HTTPGET'])) {
3383 break;
3386 } else if ($this->info['http_code'] == 307) {
3387 // Temporary Redirect - must repeat using the same request type.
3389 } else if ($this->info['http_code'] == 308) {
3390 // Permanent Redirect - must repeat using the same request type.
3392 } else {
3393 // Some other http code means do not retry!
3394 break;
3397 $redirects++;
3399 $redirecturl = null;
3400 if (isset($this->info['redirect_url'])) {
3401 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3402 $redirecturl = $this->info['redirect_url'];
3405 if (!$redirecturl) {
3406 foreach ($this->response as $k => $v) {
3407 if (strtolower($k) === 'location') {
3408 $redirecturl = $v;
3409 break;
3412 if (preg_match('|^https?://|i', $redirecturl)) {
3413 // Great, this is the correct location format!
3415 } else if ($redirecturl) {
3416 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3417 if (strpos($redirecturl, '/') === 0) {
3418 // Relative to server root - just guess.
3419 $pos = strpos('/', $current, 8);
3420 if ($pos === false) {
3421 $redirecturl = $current.$redirecturl;
3422 } else {
3423 $redirecturl = substr($current, 0, $pos).$redirecturl;
3425 } else {
3426 // Relative to current script.
3427 $redirecturl = dirname($current).'/'.$redirecturl;
3432 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3433 $ret = curl_exec($curl);
3435 $this->info = curl_getinfo($curl);
3436 $this->error = curl_error($curl);
3437 $this->errno = curl_errno($curl);
3439 $this->info['redirect_count'] = $redirects;
3441 if ($this->info['http_code'] === 200) {
3442 // Finally this is what we wanted.
3443 break;
3445 if ($this->errno != CURLE_OK) {
3446 // Something wrong is going on.
3447 break;
3450 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3451 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3452 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3456 if ($this->cache) {
3457 $this->cache->set($this->options, $ret);
3460 if ($this->debug) {
3461 echo '<h1>Return Data</h1>';
3462 var_dump($ret);
3463 echo '<h1>Info</h1>';
3464 var_dump($this->info);
3465 echo '<h1>Error</h1>';
3466 var_dump($this->error);
3469 curl_close($curl);
3471 if (empty($this->error)) {
3472 return $ret;
3473 } else {
3474 return $this->error;
3475 // exception is not ajax friendly
3476 //throw new moodle_exception($this->error, 'curl');
3481 * HTTP HEAD method
3483 * @see request()
3485 * @param string $url
3486 * @param array $options
3487 * @return bool
3489 public function head($url, $options = array()) {
3490 $options['CURLOPT_HTTPGET'] = 0;
3491 $options['CURLOPT_HEADER'] = 1;
3492 $options['CURLOPT_NOBODY'] = 1;
3493 return $this->request($url, $options);
3497 * HTTP POST method
3499 * @param string $url
3500 * @param array|string $params
3501 * @param array $options
3502 * @return bool
3504 public function post($url, $params = '', $options = array()) {
3505 $options['CURLOPT_POST'] = 1;
3506 if (is_array($params)) {
3507 $this->_tmp_file_post_params = array();
3508 foreach ($params as $key => $value) {
3509 if ($value instanceof stored_file) {
3510 $value->add_to_curl_request($this, $key);
3511 } else {
3512 $this->_tmp_file_post_params[$key] = $value;
3515 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3516 unset($this->_tmp_file_post_params);
3517 } else {
3518 // $params is the raw post data
3519 $options['CURLOPT_POSTFIELDS'] = $params;
3521 return $this->request($url, $options);
3525 * HTTP GET method
3527 * @param string $url
3528 * @param array $params
3529 * @param array $options
3530 * @return bool
3532 public function get($url, $params = array(), $options = array()) {
3533 $options['CURLOPT_HTTPGET'] = 1;
3535 if (!empty($params)) {
3536 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3537 $url .= http_build_query($params, '', '&');
3539 return $this->request($url, $options);
3543 * Downloads one file and writes it to the specified file handler
3545 * <code>
3546 * $c = new curl();
3547 * $file = fopen('savepath', 'w');
3548 * $result = $c->download_one('http://localhost/', null,
3549 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3550 * fclose($file);
3551 * $download_info = $c->get_info();
3552 * if ($result === true) {
3553 * // file downloaded successfully
3554 * } else {
3555 * $error_text = $result;
3556 * $error_code = $c->get_errno();
3558 * </code>
3560 * <code>
3561 * $c = new curl();
3562 * $result = $c->download_one('http://localhost/', null,
3563 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3564 * // ... see above, no need to close handle and remove file if unsuccessful
3565 * </code>
3567 * @param string $url
3568 * @param array|null $params key-value pairs to be added to $url as query string
3569 * @param array $options request options. Must include either 'file' or 'filepath'
3570 * @return bool|string true on success or error string on failure
3572 public function download_one($url, $params, $options = array()) {
3573 $options['CURLOPT_HTTPGET'] = 1;
3574 if (!empty($params)) {
3575 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3576 $url .= http_build_query($params, '', '&');
3578 if (!empty($options['filepath']) && empty($options['file'])) {
3579 // open file
3580 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3581 $this->errno = 100;
3582 return get_string('cannotwritefile', 'error', $options['filepath']);
3584 $filepath = $options['filepath'];
3586 unset($options['filepath']);
3587 $result = $this->request($url, $options);
3588 if (isset($filepath)) {
3589 fclose($options['file']);
3590 if ($result !== true) {
3591 unlink($filepath);
3594 return $result;
3598 * HTTP PUT method
3600 * @param string $url
3601 * @param array $params
3602 * @param array $options
3603 * @return bool
3605 public function put($url, $params = array(), $options = array()) {
3606 $file = $params['file'];
3607 if (!is_file($file)) {
3608 return null;
3610 $fp = fopen($file, 'r');
3611 $size = filesize($file);
3612 $options['CURLOPT_PUT'] = 1;
3613 $options['CURLOPT_INFILESIZE'] = $size;
3614 $options['CURLOPT_INFILE'] = $fp;
3615 if (!isset($this->options['CURLOPT_USERPWD'])) {
3616 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3618 $ret = $this->request($url, $options);
3619 fclose($fp);
3620 return $ret;
3624 * HTTP DELETE method
3626 * @param string $url
3627 * @param array $param
3628 * @param array $options
3629 * @return bool
3631 public function delete($url, $param = array(), $options = array()) {
3632 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3633 if (!isset($options['CURLOPT_USERPWD'])) {
3634 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3636 $ret = $this->request($url, $options);
3637 return $ret;
3641 * HTTP TRACE method
3643 * @param string $url
3644 * @param array $options
3645 * @return bool
3647 public function trace($url, $options = array()) {
3648 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3649 $ret = $this->request($url, $options);
3650 return $ret;
3654 * HTTP OPTIONS method
3656 * @param string $url
3657 * @param array $options
3658 * @return bool
3660 public function options($url, $options = array()) {
3661 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3662 $ret = $this->request($url, $options);
3663 return $ret;
3667 * Get curl information
3669 * @return string
3671 public function get_info() {
3672 return $this->info;
3676 * Get curl error code
3678 * @return int
3680 public function get_errno() {
3681 return $this->errno;
3685 * When using a proxy, an additional HTTP response code may appear at
3686 * the start of the header. For example, when using https over a proxy
3687 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3688 * also possible and some may come with their own headers.
3690 * If using the return value containing all headers, this function can be
3691 * called to remove unwanted doubles.
3693 * Note that it is not possible to distinguish this situation from valid
3694 * data unless you know the actual response part (below the headers)
3695 * will not be included in this string, or else will not 'look like' HTTP
3696 * headers. As a result it is not safe to call this function for general
3697 * data.
3699 * @param string $input Input HTTP response
3700 * @return string HTTP response with additional headers stripped if any
3702 public static function strip_double_headers($input) {
3703 // I have tried to make this regular expression as specific as possible
3704 // to avoid any case where it does weird stuff if you happen to put
3705 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3706 // also make it faster because it can abandon regex processing as soon
3707 // as it hits something that doesn't look like an http header. The
3708 // header definition is taken from RFC 822, except I didn't support
3709 // folding which is never used in practice.
3710 $crlf = "\r\n";
3711 return preg_replace(
3712 // HTTP version and status code (ignore value of code).
3713 '~^HTTP/1\..*' . $crlf .
3714 // Header name: character between 33 and 126 decimal, except colon.
3715 // Colon. Header value: any character except \r and \n. CRLF.
3716 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3717 // Headers are terminated by another CRLF (blank line).
3718 $crlf .
3719 // Second HTTP status code, this time must be 200.
3720 '(HTTP/1.[01] 200 )~', '$1', $input);
3725 * This class is used by cURL class, use case:
3727 * <code>
3728 * $CFG->repositorycacheexpire = 120;
3729 * $CFG->curlcache = 120;
3731 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3732 * $ret = $c->get('http://www.google.com');
3733 * </code>
3735 * @package core_files
3736 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3739 class curl_cache {
3740 /** @var string Path to cache directory */
3741 public $dir = '';
3744 * Constructor
3746 * @global stdClass $CFG
3747 * @param string $module which module is using curl_cache
3749 public function __construct($module = 'repository') {
3750 global $CFG;
3751 if (!empty($module)) {
3752 $this->dir = $CFG->cachedir.'/'.$module.'/';
3753 } else {
3754 $this->dir = $CFG->cachedir.'/misc/';
3756 if (!file_exists($this->dir)) {
3757 mkdir($this->dir, $CFG->directorypermissions, true);
3759 if ($module == 'repository') {
3760 if (empty($CFG->repositorycacheexpire)) {
3761 $CFG->repositorycacheexpire = 120;
3763 $this->ttl = $CFG->repositorycacheexpire;
3764 } else {
3765 if (empty($CFG->curlcache)) {
3766 $CFG->curlcache = 120;
3768 $this->ttl = $CFG->curlcache;
3773 * Get cached value
3775 * @global stdClass $CFG
3776 * @global stdClass $USER
3777 * @param mixed $param
3778 * @return bool|string
3780 public function get($param) {
3781 global $CFG, $USER;
3782 $this->cleanup($this->ttl);
3783 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3784 if(file_exists($this->dir.$filename)) {
3785 $lasttime = filemtime($this->dir.$filename);
3786 if (time()-$lasttime > $this->ttl) {
3787 return false;
3788 } else {
3789 $fp = fopen($this->dir.$filename, 'r');
3790 $size = filesize($this->dir.$filename);
3791 $content = fread($fp, $size);
3792 return unserialize($content);
3795 return false;
3799 * Set cache value
3801 * @global object $CFG
3802 * @global object $USER
3803 * @param mixed $param
3804 * @param mixed $val
3806 public function set($param, $val) {
3807 global $CFG, $USER;
3808 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3809 $fp = fopen($this->dir.$filename, 'w');
3810 fwrite($fp, serialize($val));
3811 fclose($fp);
3812 @chmod($this->dir.$filename, $CFG->filepermissions);
3816 * Remove cache files
3818 * @param int $expire The number of seconds before expiry
3820 public function cleanup($expire) {
3821 if ($dir = opendir($this->dir)) {
3822 while (false !== ($file = readdir($dir))) {
3823 if(!is_dir($file) && $file != '.' && $file != '..') {
3824 $lasttime = @filemtime($this->dir.$file);
3825 if (time() - $lasttime > $expire) {
3826 @unlink($this->dir.$file);
3830 closedir($dir);
3834 * delete current user's cache file
3836 * @global object $CFG
3837 * @global object $USER
3839 public function refresh() {
3840 global $CFG, $USER;
3841 if ($dir = opendir($this->dir)) {
3842 while (false !== ($file = readdir($dir))) {
3843 if (!is_dir($file) && $file != '.' && $file != '..') {
3844 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3845 @unlink($this->dir.$file);
3854 * This function delegates file serving to individual plugins
3856 * @param string $relativepath
3857 * @param bool $forcedownload
3858 * @param null|string $preview the preview mode, defaults to serving the original file
3859 * @todo MDL-31088 file serving improments
3861 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3862 global $DB, $CFG, $USER;
3863 // relative path must start with '/'
3864 if (!$relativepath) {
3865 print_error('invalidargorconf');
3866 } else if ($relativepath[0] != '/') {
3867 print_error('pathdoesnotstartslash');
3870 // extract relative path components
3871 $args = explode('/', ltrim($relativepath, '/'));
3873 if (count($args) < 3) { // always at least context, component and filearea
3874 print_error('invalidarguments');
3877 $contextid = (int)array_shift($args);
3878 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3879 $filearea = clean_param(array_shift($args), PARAM_AREA);
3881 list($context, $course, $cm) = get_context_info_array($contextid);
3883 $fs = get_file_storage();
3885 // ========================================================================================================================
3886 if ($component === 'blog') {
3887 // Blog file serving
3888 if ($context->contextlevel != CONTEXT_SYSTEM) {
3889 send_file_not_found();
3891 if ($filearea !== 'attachment' and $filearea !== 'post') {
3892 send_file_not_found();
3895 if (empty($CFG->enableblogs)) {
3896 print_error('siteblogdisable', 'blog');
3899 $entryid = (int)array_shift($args);
3900 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3901 send_file_not_found();
3903 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3904 require_login();
3905 if (isguestuser()) {
3906 print_error('noguest');
3908 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3909 if ($USER->id != $entry->userid) {
3910 send_file_not_found();
3915 if ($entry->publishstate === 'public') {
3916 if ($CFG->forcelogin) {
3917 require_login();
3920 } else if ($entry->publishstate === 'site') {
3921 require_login();
3922 //ok
3923 } else if ($entry->publishstate === 'draft') {
3924 require_login();
3925 if ($USER->id != $entry->userid) {
3926 send_file_not_found();
3930 $filename = array_pop($args);
3931 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3933 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3934 send_file_not_found();
3937 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3939 // ========================================================================================================================
3940 } else if ($component === 'grade') {
3941 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3942 // Global gradebook files
3943 if ($CFG->forcelogin) {
3944 require_login();
3947 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3949 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3950 send_file_not_found();
3953 \core\session\manager::write_close(); // Unlock session during file serving.
3954 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3956 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3957 //TODO: nobody implemented this yet in grade edit form!!
3958 send_file_not_found();
3960 if ($CFG->forcelogin || $course->id != SITEID) {
3961 require_login($course);
3964 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3966 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3967 send_file_not_found();
3970 \core\session\manager::write_close(); // Unlock session during file serving.
3971 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3972 } else {
3973 send_file_not_found();
3976 // ========================================================================================================================
3977 } else if ($component === 'tag') {
3978 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3980 // All tag descriptions are going to be public but we still need to respect forcelogin
3981 if ($CFG->forcelogin) {
3982 require_login();
3985 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3987 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3988 send_file_not_found();
3991 \core\session\manager::write_close(); // Unlock session during file serving.
3992 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3994 } else {
3995 send_file_not_found();
3997 // ========================================================================================================================
3998 } else if ($component === 'badges') {
3999 require_once($CFG->libdir . '/badgeslib.php');
4001 $badgeid = (int)array_shift($args);
4002 $badge = new badge($badgeid);
4003 $filename = array_pop($args);
4005 if ($filearea === 'badgeimage') {
4006 if ($filename !== 'f1' && $filename !== 'f2') {
4007 send_file_not_found();
4009 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4010 send_file_not_found();
4013 \core\session\manager::write_close();
4014 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4015 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
4016 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4017 send_file_not_found();
4020 \core\session\manager::write_close();
4021 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
4023 // ========================================================================================================================
4024 } else if ($component === 'calendar') {
4025 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
4027 // All events here are public the one requirement is that we respect forcelogin
4028 if ($CFG->forcelogin) {
4029 require_login();
4032 // Get the event if from the args array
4033 $eventid = array_shift($args);
4035 // Load the event from the database
4036 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4037 send_file_not_found();
4040 // Get the file and serve if successful
4041 $filename = array_pop($args);
4042 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4043 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4044 send_file_not_found();
4047 \core\session\manager::write_close(); // Unlock session during file serving.
4048 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4050 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4052 // Must be logged in, if they are not then they obviously can't be this user
4053 require_login();
4055 // Don't want guests here, potentially saves a DB call
4056 if (isguestuser()) {
4057 send_file_not_found();
4060 // Get the event if from the args array
4061 $eventid = array_shift($args);
4063 // Load the event from the database - user id must match
4064 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4065 send_file_not_found();
4068 // Get the file and serve if successful
4069 $filename = array_pop($args);
4070 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4071 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4072 send_file_not_found();
4075 \core\session\manager::write_close(); // Unlock session during file serving.
4076 send_stored_file($file, 0, 0, true, array('preview' => $preview));
4078 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4080 // Respect forcelogin and require login unless this is the site.... it probably
4081 // should NEVER be the site
4082 if ($CFG->forcelogin || $course->id != SITEID) {
4083 require_login($course);
4086 // Must be able to at least view the course. This does not apply to the front page.
4087 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4088 //TODO: hmm, do we really want to block guests here?
4089 send_file_not_found();
4092 // Get the event id
4093 $eventid = array_shift($args);
4095 // Load the event from the database we need to check whether it is
4096 // a) valid course event
4097 // b) a group event
4098 // Group events use the course context (there is no group context)
4099 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4100 send_file_not_found();
4103 // If its a group event require either membership of view all groups capability
4104 if ($event->eventtype === 'group') {
4105 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4106 send_file_not_found();
4108 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4109 // Ok. Please note that the event type 'site' still uses a course context.
4110 } else {
4111 // Some other type.
4112 send_file_not_found();
4115 // If we get this far we can serve the file
4116 $filename = array_pop($args);
4117 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4118 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4119 send_file_not_found();
4122 \core\session\manager::write_close(); // Unlock session during file serving.
4123 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4125 } else {
4126 send_file_not_found();
4129 // ========================================================================================================================
4130 } else if ($component === 'user') {
4131 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4132 if (count($args) == 1) {
4133 $themename = theme_config::DEFAULT_THEME;
4134 $filename = array_shift($args);
4135 } else {
4136 $themename = array_shift($args);
4137 $filename = array_shift($args);
4140 // fix file name automatically
4141 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4142 $filename = 'f1';
4145 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4146 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4147 // protect images if login required and not logged in;
4148 // also if login is required for profile images and is not logged in or guest
4149 // do not use require_login() because it is expensive and not suitable here anyway
4150 $theme = theme_config::load($themename);
4151 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
4154 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4155 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4156 if ($filename === 'f3') {
4157 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4158 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4159 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4164 if (!$file) {
4165 // bad reference - try to prevent future retries as hard as possible!
4166 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4167 if ($user->picture > 0) {
4168 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4171 // no redirect here because it is not cached
4172 $theme = theme_config::load($themename);
4173 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4174 send_file($imagefile, basename($imagefile), 60*60*24*14);
4177 $options = array('preview' => $preview);
4178 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4179 // Profile images should be cache-able by both browsers and proxies according
4180 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4181 $options['cacheability'] = 'public';
4183 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4185 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4186 require_login();
4188 if (isguestuser()) {
4189 send_file_not_found();
4192 if ($USER->id !== $context->instanceid) {
4193 send_file_not_found();
4196 $filename = array_pop($args);
4197 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4198 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4199 send_file_not_found();
4202 \core\session\manager::write_close(); // Unlock session during file serving.
4203 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4205 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4207 if ($CFG->forcelogin) {
4208 require_login();
4211 $userid = $context->instanceid;
4213 if ($USER->id == $userid) {
4214 // always can access own
4216 } else if (!empty($CFG->forceloginforprofiles)) {
4217 require_login();
4219 if (isguestuser()) {
4220 send_file_not_found();
4223 // we allow access to site profile of all course contacts (usually teachers)
4224 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4225 send_file_not_found();
4228 $canview = false;
4229 if (has_capability('moodle/user:viewdetails', $context)) {
4230 $canview = true;
4231 } else {
4232 $courses = enrol_get_my_courses();
4235 while (!$canview && count($courses) > 0) {
4236 $course = array_shift($courses);
4237 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4238 $canview = true;
4243 $filename = array_pop($args);
4244 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4245 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4246 send_file_not_found();
4249 \core\session\manager::write_close(); // Unlock session during file serving.
4250 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4252 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4253 $userid = (int)array_shift($args);
4254 $usercontext = context_user::instance($userid);
4256 if ($CFG->forcelogin) {
4257 require_login();
4260 if (!empty($CFG->forceloginforprofiles)) {
4261 require_login();
4262 if (isguestuser()) {
4263 print_error('noguest');
4266 //TODO: review this logic of user profile access prevention
4267 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4268 print_error('usernotavailable');
4270 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4271 print_error('cannotviewprofile');
4273 if (!is_enrolled($context, $userid)) {
4274 print_error('notenrolledprofile');
4276 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4277 print_error('groupnotamember');
4281 $filename = array_pop($args);
4282 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4283 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4284 send_file_not_found();
4287 \core\session\manager::write_close(); // Unlock session during file serving.
4288 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4290 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4291 require_login();
4293 if (isguestuser()) {
4294 send_file_not_found();
4296 $userid = $context->instanceid;
4298 if ($USER->id != $userid) {
4299 send_file_not_found();
4302 $filename = array_pop($args);
4303 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4304 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4305 send_file_not_found();
4308 \core\session\manager::write_close(); // Unlock session during file serving.
4309 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4311 } else {
4312 send_file_not_found();
4315 // ========================================================================================================================
4316 } else if ($component === 'coursecat') {
4317 if ($context->contextlevel != CONTEXT_COURSECAT) {
4318 send_file_not_found();
4321 if ($filearea === 'description') {
4322 if ($CFG->forcelogin) {
4323 // no login necessary - unless login forced everywhere
4324 require_login();
4327 $filename = array_pop($args);
4328 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4329 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4330 send_file_not_found();
4333 \core\session\manager::write_close(); // Unlock session during file serving.
4334 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4335 } else {
4336 send_file_not_found();
4339 // ========================================================================================================================
4340 } else if ($component === 'course') {
4341 if ($context->contextlevel != CONTEXT_COURSE) {
4342 send_file_not_found();
4345 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4346 if ($CFG->forcelogin) {
4347 require_login();
4350 $filename = array_pop($args);
4351 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4352 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4353 send_file_not_found();
4356 \core\session\manager::write_close(); // Unlock session during file serving.
4357 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4359 } else if ($filearea === 'section') {
4360 if ($CFG->forcelogin) {
4361 require_login($course);
4362 } else if ($course->id != SITEID) {
4363 require_login($course);
4366 $sectionid = (int)array_shift($args);
4368 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4369 send_file_not_found();
4372 $filename = array_pop($args);
4373 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4374 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4375 send_file_not_found();
4378 \core\session\manager::write_close(); // Unlock session during file serving.
4379 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4381 } else {
4382 send_file_not_found();
4385 } else if ($component === 'group') {
4386 if ($context->contextlevel != CONTEXT_COURSE) {
4387 send_file_not_found();
4390 require_course_login($course, true, null, false);
4392 $groupid = (int)array_shift($args);
4394 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4395 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4396 // do not allow access to separate group info if not member or teacher
4397 send_file_not_found();
4400 if ($filearea === 'description') {
4402 require_login($course);
4404 $filename = array_pop($args);
4405 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4406 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4407 send_file_not_found();
4410 \core\session\manager::write_close(); // Unlock session during file serving.
4411 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4413 } else if ($filearea === 'icon') {
4414 $filename = array_pop($args);
4416 if ($filename !== 'f1' and $filename !== 'f2') {
4417 send_file_not_found();
4419 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4420 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4421 send_file_not_found();
4425 \core\session\manager::write_close(); // Unlock session during file serving.
4426 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4428 } else {
4429 send_file_not_found();
4432 } else if ($component === 'grouping') {
4433 if ($context->contextlevel != CONTEXT_COURSE) {
4434 send_file_not_found();
4437 require_login($course);
4439 $groupingid = (int)array_shift($args);
4441 // note: everybody has access to grouping desc images for now
4442 if ($filearea === 'description') {
4444 $filename = array_pop($args);
4445 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4446 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4447 send_file_not_found();
4450 \core\session\manager::write_close(); // Unlock session during file serving.
4451 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4453 } else {
4454 send_file_not_found();
4457 // ========================================================================================================================
4458 } else if ($component === 'backup') {
4459 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4460 require_login($course);
4461 require_capability('moodle/backup:downloadfile', $context);
4463 $filename = array_pop($args);
4464 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4465 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4466 send_file_not_found();
4469 \core\session\manager::write_close(); // Unlock session during file serving.
4470 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4472 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4473 require_login($course);
4474 require_capability('moodle/backup:downloadfile', $context);
4476 $sectionid = (int)array_shift($args);
4478 $filename = array_pop($args);
4479 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4480 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4481 send_file_not_found();
4484 \core\session\manager::write_close();
4485 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4487 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4488 require_login($course, false, $cm);
4489 require_capability('moodle/backup:downloadfile', $context);
4491 $filename = array_pop($args);
4492 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4493 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4494 send_file_not_found();
4497 \core\session\manager::write_close();
4498 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4500 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4501 // Backup files that were generated by the automated backup systems.
4503 require_login($course);
4504 require_capability('moodle/site:config', $context);
4506 $filename = array_pop($args);
4507 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4508 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4509 send_file_not_found();
4512 \core\session\manager::write_close(); // Unlock session during file serving.
4513 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4515 } else {
4516 send_file_not_found();
4519 // ========================================================================================================================
4520 } else if ($component === 'question') {
4521 require_once($CFG->libdir . '/questionlib.php');
4522 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4523 send_file_not_found();
4525 // ========================================================================================================================
4526 } else if ($component === 'grading') {
4527 if ($filearea === 'description') {
4528 // files embedded into the form definition description
4530 if ($context->contextlevel == CONTEXT_SYSTEM) {
4531 require_login();
4533 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4534 require_login($course, false, $cm);
4536 } else {
4537 send_file_not_found();
4540 $formid = (int)array_shift($args);
4542 $sql = "SELECT ga.id
4543 FROM {grading_areas} ga
4544 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4545 WHERE gd.id = ? AND ga.contextid = ?";
4546 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4548 if (!$areaid) {
4549 send_file_not_found();
4552 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4554 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4555 send_file_not_found();
4558 \core\session\manager::write_close(); // Unlock session during file serving.
4559 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4562 // ========================================================================================================================
4563 } else if (strpos($component, 'mod_') === 0) {
4564 $modname = substr($component, 4);
4565 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4566 send_file_not_found();
4568 require_once("$CFG->dirroot/mod/$modname/lib.php");
4570 if ($context->contextlevel == CONTEXT_MODULE) {
4571 if ($cm->modname !== $modname) {
4572 // somebody tries to gain illegal access, cm type must match the component!
4573 send_file_not_found();
4577 if ($filearea === 'intro') {
4578 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4579 send_file_not_found();
4581 require_course_login($course, true, $cm);
4583 // all users may access it
4584 $filename = array_pop($args);
4585 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4586 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4587 send_file_not_found();
4590 // finally send the file
4591 send_stored_file($file, null, 0, false, array('preview' => $preview));
4594 $filefunction = $component.'_pluginfile';
4595 $filefunctionold = $modname.'_pluginfile';
4596 if (function_exists($filefunction)) {
4597 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4598 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4599 } else if (function_exists($filefunctionold)) {
4600 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4601 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4604 send_file_not_found();
4606 // ========================================================================================================================
4607 } else if (strpos($component, 'block_') === 0) {
4608 $blockname = substr($component, 6);
4609 // note: no more class methods in blocks please, that is ....
4610 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4611 send_file_not_found();
4613 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4615 if ($context->contextlevel == CONTEXT_BLOCK) {
4616 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4617 if ($birecord->blockname !== $blockname) {
4618 // somebody tries to gain illegal access, cm type must match the component!
4619 send_file_not_found();
4622 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4623 // User can't access file, if block is hidden or doesn't have block:view capability
4624 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4625 send_file_not_found();
4627 } else {
4628 $birecord = null;
4631 $filefunction = $component.'_pluginfile';
4632 if (function_exists($filefunction)) {
4633 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4634 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4637 send_file_not_found();
4639 // ========================================================================================================================
4640 } else if (strpos($component, '_') === false) {
4641 // all core subsystems have to be specified above, no more guessing here!
4642 send_file_not_found();
4644 } else {
4645 // try to serve general plugin file in arbitrary context
4646 $dir = core_component::get_component_directory($component);
4647 if (!file_exists("$dir/lib.php")) {
4648 send_file_not_found();
4650 include_once("$dir/lib.php");
4652 $filefunction = $component.'_pluginfile';
4653 if (function_exists($filefunction)) {
4654 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4655 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4658 send_file_not_found();