MDL-36206 - Unit Test - Create unit test for pagination bar
[moodle.git] / lib / filelib.php
blob013f6c509dfec06b1c1e3466989d0470e8f5a471
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 * Prepares 'editor' formslib element from data in database
86 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
87 * function then copies the embedded files into draft area (assigning itemids automatically),
88 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
89 * displayed.
90 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
91 * your mform's set_data() supplying the object returned by this function.
93 * @category files
94 * @param stdClass $data database field that holds the html text with embedded media
95 * @param string $field the name of the database field that holds the html text with embedded media
96 * @param array $options editor options (like maxifiles, maxbytes etc.)
97 * @param stdClass $context context of the editor
98 * @param string $component
99 * @param string $filearea file area name
100 * @param int $itemid item id, required if item exists
101 * @return stdClass modified data object
103 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
104 $options = (array)$options;
105 if (!isset($options['trusttext'])) {
106 $options['trusttext'] = false;
108 if (!isset($options['forcehttps'])) {
109 $options['forcehttps'] = false;
111 if (!isset($options['subdirs'])) {
112 $options['subdirs'] = false;
114 if (!isset($options['maxfiles'])) {
115 $options['maxfiles'] = 0; // no files by default
117 if (!isset($options['noclean'])) {
118 $options['noclean'] = false;
121 //sanity check for passed context. This function doesn't expect $option['context'] to be set
122 //But this function is called before creating editor hence, this is one of the best places to check
123 //if context is used properly. This check notify developer that they missed passing context to editor.
124 if (isset($context) && !isset($options['context'])) {
125 //if $context is not null then make sure $option['context'] is also set.
126 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
127 } else if (isset($options['context']) && isset($context)) {
128 //If both are passed then they should be equal.
129 if ($options['context']->id != $context->id) {
130 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
131 throw new coding_exception($exceptionmsg);
135 if (is_null($itemid) or is_null($context)) {
136 $contextid = null;
137 $itemid = null;
138 if (!isset($data)) {
139 $data = new stdClass();
141 if (!isset($data->{$field})) {
142 $data->{$field} = '';
144 if (!isset($data->{$field.'format'})) {
145 $data->{$field.'format'} = editors_get_preferred_format();
147 if (!$options['noclean']) {
148 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
151 } else {
152 if ($options['trusttext']) {
153 // noclean ignored if trusttext enabled
154 if (!isset($data->{$field.'trust'})) {
155 $data->{$field.'trust'} = 0;
157 $data = trusttext_pre_edit($data, $field, $context);
158 } else {
159 if (!$options['noclean']) {
160 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
163 $contextid = $context->id;
166 if ($options['maxfiles'] != 0) {
167 $draftid_editor = file_get_submitted_draft_itemid($field);
168 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
169 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
170 } else {
171 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
174 return $data;
178 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
180 * This function moves files from draft area to the destination area and
181 * encodes URLs to the draft files so they can be safely saved into DB. The
182 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
183 * is the name of the database field to hold the wysiwyg editor content. The
184 * editor data comes as an array with text, format and itemid properties. This
185 * function automatically adds $data properties foobar, foobarformat and
186 * foobartrust, where foobar has URL to embedded files encoded.
188 * @category files
189 * @param stdClass $data raw data submitted by the form
190 * @param string $field name of the database field containing the html with embedded media files
191 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
192 * @param stdClass $context context, required for existing data
193 * @param string $component file component
194 * @param string $filearea file area name
195 * @param int $itemid item id, required if item exists
196 * @return stdClass modified data object
198 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
199 $options = (array)$options;
200 if (!isset($options['trusttext'])) {
201 $options['trusttext'] = false;
203 if (!isset($options['forcehttps'])) {
204 $options['forcehttps'] = false;
206 if (!isset($options['subdirs'])) {
207 $options['subdirs'] = false;
209 if (!isset($options['maxfiles'])) {
210 $options['maxfiles'] = 0; // no files by default
212 if (!isset($options['maxbytes'])) {
213 $options['maxbytes'] = 0; // unlimited
216 if ($options['trusttext']) {
217 $data->{$field.'trust'} = trusttext_trusted($context);
218 } else {
219 $data->{$field.'trust'} = 0;
222 $editor = $data->{$field.'_editor'};
224 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
225 $data->{$field} = $editor['text'];
226 } else {
227 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
229 $data->{$field.'format'} = $editor['format'];
231 return $data;
235 * Saves text and files modified by Editor formslib element
237 * @category files
238 * @param stdClass $data $database entry field
239 * @param string $field name of data field
240 * @param array $options various options
241 * @param stdClass $context context - must already exist
242 * @param string $component
243 * @param string $filearea file area name
244 * @param int $itemid must already exist, usually means data is in db
245 * @return stdClass modified data obejct
247 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
248 $options = (array)$options;
249 if (!isset($options['subdirs'])) {
250 $options['subdirs'] = false;
252 if (is_null($itemid) or is_null($context)) {
253 $itemid = null;
254 $contextid = null;
255 } else {
256 $contextid = $context->id;
259 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
260 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
261 $data->{$field.'_filemanager'} = $draftid_editor;
263 return $data;
267 * Saves files modified by File manager formslib element
269 * @todo MDL-31073 review this function
270 * @category files
271 * @param stdClass $data $database entry field
272 * @param string $field name of data field
273 * @param array $options various options
274 * @param stdClass $context context - must already exist
275 * @param string $component
276 * @param string $filearea file area name
277 * @param int $itemid must already exist, usually means data is in db
278 * @return stdClass modified data obejct
280 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
281 $options = (array)$options;
282 if (!isset($options['subdirs'])) {
283 $options['subdirs'] = false;
285 if (!isset($options['maxfiles'])) {
286 $options['maxfiles'] = -1; // unlimited
288 if (!isset($options['maxbytes'])) {
289 $options['maxbytes'] = 0; // unlimited
292 if (empty($data->{$field.'_filemanager'})) {
293 $data->$field = '';
295 } else {
296 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
297 $fs = get_file_storage();
299 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
300 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
301 } else {
302 $data->$field = '';
306 return $data;
310 * Generate a draft itemid
312 * @category files
313 * @global moodle_database $DB
314 * @global stdClass $USER
315 * @return int a random but available draft itemid that can be used to create a new draft
316 * file area.
318 function file_get_unused_draft_itemid() {
319 global $DB, $USER;
321 if (isguestuser() or !isloggedin()) {
322 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
323 print_error('noguest');
326 $contextid = context_user::instance($USER->id)->id;
328 $fs = get_file_storage();
329 $draftitemid = rand(1, 999999999);
330 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
331 $draftitemid = rand(1, 999999999);
334 return $draftitemid;
338 * Initialise a draft file area from a real one by copying the files. A draft
339 * area will be created if one does not already exist. Normally you should
340 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
342 * @category files
343 * @global stdClass $CFG
344 * @global stdClass $USER
345 * @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.
346 * @param int $contextid This parameter and the next two identify the file area to copy files from.
347 * @param string $component
348 * @param string $filearea helps indentify the file area.
349 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
350 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
351 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
352 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
354 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
355 global $CFG, $USER, $CFG;
357 $options = (array)$options;
358 if (!isset($options['subdirs'])) {
359 $options['subdirs'] = false;
361 if (!isset($options['forcehttps'])) {
362 $options['forcehttps'] = false;
365 $usercontext = context_user::instance($USER->id);
366 $fs = get_file_storage();
368 if (empty($draftitemid)) {
369 // create a new area and copy existing files into
370 $draftitemid = file_get_unused_draft_itemid();
371 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
372 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
373 foreach ($files as $file) {
374 if ($file->is_directory() and $file->get_filepath() === '/') {
375 // we need a way to mark the age of each draft area,
376 // by not copying the root dir we force it to be created automatically with current timestamp
377 continue;
379 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
380 continue;
382 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
383 // XXX: This is a hack for file manager (MDL-28666)
384 // File manager needs to know the original file information before copying
385 // to draft area, so we append these information in mdl_files.source field
386 // {@link file_storage::search_references()}
387 // {@link file_storage::search_references_count()}
388 $sourcefield = $file->get_source();
389 $newsourcefield = new stdClass;
390 $newsourcefield->source = $sourcefield;
391 $original = new stdClass;
392 $original->contextid = $contextid;
393 $original->component = $component;
394 $original->filearea = $filearea;
395 $original->itemid = $itemid;
396 $original->filename = $file->get_filename();
397 $original->filepath = $file->get_filepath();
398 $newsourcefield->original = file_storage::pack_reference($original);
399 $draftfile->set_source(serialize($newsourcefield));
400 // End of file manager hack
403 if (!is_null($text)) {
404 // at this point there should not be any draftfile links yet,
405 // because this is a new text from database that should still contain the @@pluginfile@@ links
406 // this happens when developers forget to post process the text
407 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
409 } else {
410 // nothing to do
413 if (is_null($text)) {
414 return null;
417 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
418 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
422 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
424 * @category files
425 * @global stdClass $CFG
426 * @param string $text The content that may contain ULRs in need of rewriting.
427 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
428 * @param int $contextid This parameter and the next two identify the file area to use.
429 * @param string $component
430 * @param string $filearea helps identify the file area.
431 * @param int $itemid helps identify the file area.
432 * @param array $options text and file options ('forcehttps'=>false)
433 * @return string the processed text.
435 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
436 global $CFG;
438 $options = (array)$options;
439 if (!isset($options['forcehttps'])) {
440 $options['forcehttps'] = false;
443 if (!$CFG->slasharguments) {
444 $file = $file . '?file=';
447 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
449 if ($itemid !== null) {
450 $baseurl .= "$itemid/";
453 if ($options['forcehttps']) {
454 $baseurl = str_replace('http://', 'https://', $baseurl);
457 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
461 * Returns information about files in a draft area.
463 * @global stdClass $CFG
464 * @global stdClass $USER
465 * @param int $draftitemid the draft area item id.
466 * @param string $filepath path to the directory from which the information have to be retrieved.
467 * @return array with the following entries:
468 * 'filecount' => number of files in the draft area.
469 * 'filesize' => total size of the files in the draft area.
470 * 'foldercount' => number of folders in the draft area.
471 * 'filesize_without_references' => total size of the area excluding file references.
472 * (more information will be added as needed).
474 function file_get_draft_area_info($draftitemid, $filepath = '/') {
475 global $CFG, $USER;
477 $usercontext = context_user::instance($USER->id);
478 $fs = get_file_storage();
480 $results = array(
481 'filecount' => 0,
482 'foldercount' => 0,
483 'filesize' => 0,
484 'filesize_without_references' => 0
487 if ($filepath != '/') {
488 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
489 } else {
490 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
492 foreach ($draftfiles as $file) {
493 if ($file->is_directory()) {
494 $results['foldercount'] += 1;
495 } else {
496 $results['filecount'] += 1;
499 $filesize = $file->get_filesize();
500 $results['filesize'] += $filesize;
501 if (!$file->is_external_file()) {
502 $results['filesize_without_references'] += $filesize;
506 return $results;
510 * Returns whether a draft area has exceeded/will exceed its size limit.
512 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
514 * @param int $draftitemid the draft area item id.
515 * @param int $areamaxbytes the maximum size allowed in this draft area.
516 * @param int $newfilesize the size that would be added to the current area.
517 * @param bool $includereferences true to include the size of the references in the area size.
518 * @return bool true if the area will/has exceeded its limit.
519 * @since 2.4
521 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
522 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
523 $draftinfo = file_get_draft_area_info($draftitemid);
524 $areasize = $draftinfo['filesize_without_references'];
525 if ($includereferences) {
526 $areasize = $draftinfo['filesize'];
528 if ($areasize + $newfilesize > $areamaxbytes) {
529 return true;
532 return false;
536 * Get used space of files
537 * @global moodle_database $DB
538 * @global stdClass $USER
539 * @return int total bytes
541 function file_get_user_used_space() {
542 global $DB, $USER;
544 $usercontext = context_user::instance($USER->id);
545 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
546 JOIN (SELECT contenthash, filename, MAX(id) AS id
547 FROM {files}
548 WHERE contextid = ? AND component = ? AND filearea != ?
549 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
550 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
551 $record = $DB->get_record_sql($sql, $params);
552 return (int)$record->totalbytes;
556 * Convert any string to a valid filepath
557 * @todo review this function
558 * @param string $str
559 * @return string path
561 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
562 if ($str == '/' or empty($str)) {
563 return '/';
564 } else {
565 return '/'.trim($str, '/').'/';
570 * Generate a folder tree of draft area of current USER recursively
572 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
573 * @param int $draftitemid
574 * @param string $filepath
575 * @param mixed $data
577 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
578 global $USER, $OUTPUT, $CFG;
579 $data->children = array();
580 $context = context_user::instance($USER->id);
581 $fs = get_file_storage();
582 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
583 foreach ($files as $file) {
584 if ($file->is_directory()) {
585 $item = new stdClass();
586 $item->sortorder = $file->get_sortorder();
587 $item->filepath = $file->get_filepath();
589 $foldername = explode('/', trim($item->filepath, '/'));
590 $item->fullname = trim(array_pop($foldername), '/');
592 $item->id = uniqid();
593 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
594 $data->children[] = $item;
595 } else {
596 continue;
603 * Listing all files (including folders) in current path (draft area)
604 * used by file manager
605 * @param int $draftitemid
606 * @param string $filepath
607 * @return stdClass
609 function file_get_drafarea_files($draftitemid, $filepath = '/') {
610 global $USER, $OUTPUT, $CFG;
612 $context = context_user::instance($USER->id);
613 $fs = get_file_storage();
615 $data = new stdClass();
616 $data->path = array();
617 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
619 // will be used to build breadcrumb
620 $trail = '/';
621 if ($filepath !== '/') {
622 $filepath = file_correct_filepath($filepath);
623 $parts = explode('/', $filepath);
624 foreach ($parts as $part) {
625 if ($part != '' && $part != null) {
626 $trail .= ($part.'/');
627 $data->path[] = array('name'=>$part, 'path'=>$trail);
632 $list = array();
633 $maxlength = 12;
634 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
635 foreach ($files as $file) {
636 $item = new stdClass();
637 $item->filename = $file->get_filename();
638 $item->filepath = $file->get_filepath();
639 $item->fullname = trim($item->filename, '/');
640 $filesize = $file->get_filesize();
641 $item->size = $filesize ? $filesize : null;
642 $item->filesize = $filesize ? display_size($filesize) : '';
644 $item->sortorder = $file->get_sortorder();
645 $item->author = $file->get_author();
646 $item->license = $file->get_license();
647 $item->datemodified = $file->get_timemodified();
648 $item->datecreated = $file->get_timecreated();
649 $item->isref = $file->is_external_file();
650 if ($item->isref && $file->get_status() == 666) {
651 $item->originalmissing = true;
653 // find the file this draft file was created from and count all references in local
654 // system pointing to that file
655 $source = @unserialize($file->get_source());
656 if (isset($source->original)) {
657 $item->refcount = $fs->search_references_count($source->original);
660 if ($file->is_directory()) {
661 $item->filesize = 0;
662 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
663 $item->type = 'folder';
664 $foldername = explode('/', trim($item->filepath, '/'));
665 $item->fullname = trim(array_pop($foldername), '/');
666 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
667 } else {
668 // do NOT use file browser here!
669 $item->mimetype = get_mimetype_description($file);
670 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
671 $item->type = 'zip';
672 } else {
673 $item->type = 'file';
675 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
676 $item->url = $itemurl->out();
677 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
678 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
679 if ($imageinfo = $file->get_imageinfo()) {
680 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
681 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
682 $item->image_width = $imageinfo['width'];
683 $item->image_height = $imageinfo['height'];
686 $list[] = $item;
689 $data->itemid = $draftitemid;
690 $data->list = $list;
691 return $data;
695 * Returns draft area itemid for a given element.
697 * @category files
698 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
699 * @return int the itemid, or 0 if there is not one yet.
701 function file_get_submitted_draft_itemid($elname) {
702 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
703 if (!isset($_REQUEST[$elname])) {
704 return 0;
706 if (is_array($_REQUEST[$elname])) {
707 $param = optional_param_array($elname, 0, PARAM_INT);
708 if (!empty($param['itemid'])) {
709 $param = $param['itemid'];
710 } else {
711 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
712 return false;
715 } else {
716 $param = optional_param($elname, 0, PARAM_INT);
719 if ($param) {
720 require_sesskey();
723 return $param;
727 * Restore the original source field from draft files
729 * @param stored_file $storedfile This only works with draft files
730 * @return stored_file
732 function file_restore_source_field_from_draft_file($storedfile) {
733 $source = @unserialize($storedfile->get_source());
734 if (!empty($source)) {
735 if (is_object($source)) {
736 $restoredsource = $source->source;
737 $storedfile->set_source($restoredsource);
738 } else {
739 throw new moodle_exception('invalidsourcefield', 'error');
742 return $storedfile;
745 * Saves files from a draft file area to a real one (merging the list of files).
746 * Can rewrite URLs in some content at the same time if desired.
748 * @category files
749 * @global stdClass $USER
750 * @param int $draftitemid the id of the draft area to use. Normally obtained
751 * from file_get_submitted_draft_itemid('elementname') or similar.
752 * @param int $contextid This parameter and the next two identify the file area to save to.
753 * @param string $component
754 * @param string $filearea indentifies the file area.
755 * @param int $itemid helps identifies the file area.
756 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
757 * @param string $text some html content that needs to have embedded links rewritten
758 * to the @@PLUGINFILE@@ form for saving in the database.
759 * @param bool $forcehttps force https urls.
760 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
762 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
763 global $USER;
765 $usercontext = context_user::instance($USER->id);
766 $fs = get_file_storage();
768 $options = (array)$options;
769 if (!isset($options['subdirs'])) {
770 $options['subdirs'] = false;
772 if (!isset($options['maxfiles'])) {
773 $options['maxfiles'] = -1; // unlimited
775 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
776 $options['maxbytes'] = 0; // unlimited
778 if (!isset($options['areamaxbytes'])) {
779 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
781 $allowreferences = true;
782 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
783 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
784 // this is not exactly right. BUT there are many places in code where filemanager options
785 // are not passed to file_save_draft_area_files()
786 $allowreferences = false;
789 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
790 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
791 // anything at all in the next area.
792 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
793 return null;
796 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
797 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
799 if (count($draftfiles) < 2) {
800 // means there are no files - one file means root dir only ;-)
801 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
803 } else if (count($oldfiles) < 2) {
804 $filecount = 0;
805 // there were no files before - one file means root dir only ;-)
806 foreach ($draftfiles as $file) {
807 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
808 if (!$options['subdirs']) {
809 if ($file->get_filepath() !== '/' or $file->is_directory()) {
810 continue;
813 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
814 // oversized file - should not get here at all
815 continue;
817 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
818 // more files - should not get here at all
819 break;
821 if (!$file->is_directory()) {
822 $filecount++;
825 if ($file->is_external_file()) {
826 if (!$allowreferences) {
827 continue;
829 $repoid = $file->get_repository_id();
830 if (!empty($repoid)) {
831 $file_record['repositoryid'] = $repoid;
832 $file_record['reference'] = $file->get_reference();
835 file_restore_source_field_from_draft_file($file);
837 $fs->create_file_from_storedfile($file_record, $file);
840 } else {
841 // we have to merge old and new files - we want to keep file ids for files that were not changed
842 // we change time modified for all new and changed files, we keep time created as is
844 $newhashes = array();
845 foreach ($draftfiles as $file) {
846 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
847 file_restore_source_field_from_draft_file($file);
848 $newhashes[$newhash] = $file;
850 $filecount = 0;
851 foreach ($oldfiles as $oldfile) {
852 $oldhash = $oldfile->get_pathnamehash();
853 if (!isset($newhashes[$oldhash])) {
854 // delete files not needed any more - deleted by user
855 $oldfile->delete();
856 continue;
859 $newfile = $newhashes[$oldhash];
860 // status changed, we delete old file, and create a new one
861 if ($oldfile->get_status() != $newfile->get_status()) {
862 // file was changed, use updated with new timemodified data
863 $oldfile->delete();
864 // This file will be added later
865 continue;
868 // Updated author
869 if ($oldfile->get_author() != $newfile->get_author()) {
870 $oldfile->set_author($newfile->get_author());
872 // Updated license
873 if ($oldfile->get_license() != $newfile->get_license()) {
874 $oldfile->set_license($newfile->get_license());
877 // Updated file source
878 if ($oldfile->get_source() != $newfile->get_source()) {
879 $oldfile->set_source($newfile->get_source());
882 // Updated sort order
883 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
884 $oldfile->set_sortorder($newfile->get_sortorder());
887 // Update file timemodified
888 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
889 $oldfile->set_timemodified($newfile->get_timemodified());
892 // Replaced file content
893 if ($oldfile->get_contenthash() != $newfile->get_contenthash() || $oldfile->get_filesize() != $newfile->get_filesize()) {
894 $oldfile->replace_content_with($newfile);
895 // push changes to all local files that are referencing this file
896 $fs->update_references_to_storedfile($oldfile);
899 // unchanged file or directory - we keep it as is
900 unset($newhashes[$oldhash]);
901 if (!$oldfile->is_directory()) {
902 $filecount++;
906 // Add fresh file or the file which has changed status
907 // the size and subdirectory tests are extra safety only, the UI should prevent it
908 foreach ($newhashes as $file) {
909 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
910 if (!$options['subdirs']) {
911 if ($file->get_filepath() !== '/' or $file->is_directory()) {
912 continue;
915 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
916 // oversized file - should not get here at all
917 continue;
919 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
920 // more files - should not get here at all
921 break;
923 if (!$file->is_directory()) {
924 $filecount++;
927 if ($file->is_external_file()) {
928 if (!$allowreferences) {
929 continue;
931 $repoid = $file->get_repository_id();
932 if (!empty($repoid)) {
933 $file_record['repositoryid'] = $repoid;
934 $file_record['reference'] = $file->get_reference();
938 $fs->create_file_from_storedfile($file_record, $file);
942 // note: do not purge the draft area - we clean up areas later in cron,
943 // the reason is that user might press submit twice and they would loose the files,
944 // also sometimes we might want to use hacks that save files into two different areas
946 if (is_null($text)) {
947 return null;
948 } else {
949 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
954 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
955 * ready to be saved in the database. Normally, this is done automatically by
956 * {@link file_save_draft_area_files()}.
958 * @category files
959 * @param string $text the content to process.
960 * @param int $draftitemid the draft file area the content was using.
961 * @param bool $forcehttps whether the content contains https URLs. Default false.
962 * @return string the processed content.
964 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
965 global $CFG, $USER;
967 $usercontext = context_user::instance($USER->id);
969 $wwwroot = $CFG->wwwroot;
970 if ($forcehttps) {
971 $wwwroot = str_replace('http://', 'https://', $wwwroot);
974 // relink embedded files if text submitted - no absolute links allowed in database!
975 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
977 if (strpos($text, 'draftfile.php?file=') !== false) {
978 $matches = array();
979 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
980 if ($matches) {
981 foreach ($matches[0] as $match) {
982 $replace = str_ireplace('%2F', '/', $match);
983 $text = str_replace($match, $replace, $text);
986 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
989 return $text;
993 * Set file sort order
995 * @global moodle_database $DB
996 * @param int $contextid the context id
997 * @param string $component file component
998 * @param string $filearea file area.
999 * @param int $itemid itemid.
1000 * @param string $filepath file path.
1001 * @param string $filename file name.
1002 * @param int $sortorder the sort order of file.
1003 * @return bool
1005 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1006 global $DB;
1007 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1008 if ($file_record = $DB->get_record('files', $conditions)) {
1009 $sortorder = (int)$sortorder;
1010 $file_record->sortorder = $sortorder;
1011 $DB->update_record('files', $file_record);
1012 return true;
1014 return false;
1018 * reset file sort order number to 0
1019 * @global moodle_database $DB
1020 * @param int $contextid the context id
1021 * @param string $component
1022 * @param string $filearea file area.
1023 * @param int|bool $itemid itemid.
1024 * @return bool
1026 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1027 global $DB;
1029 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1030 if ($itemid !== false) {
1031 $conditions['itemid'] = $itemid;
1034 $file_records = $DB->get_records('files', $conditions);
1035 foreach ($file_records as $file_record) {
1036 $file_record->sortorder = 0;
1037 $DB->update_record('files', $file_record);
1039 return true;
1043 * Returns description of upload error
1045 * @param int $errorcode found in $_FILES['filename.ext']['error']
1046 * @return string error description string, '' if ok
1048 function file_get_upload_error($errorcode) {
1050 switch ($errorcode) {
1051 case 0: // UPLOAD_ERR_OK - no error
1052 $errmessage = '';
1053 break;
1055 case 1: // UPLOAD_ERR_INI_SIZE
1056 $errmessage = get_string('uploadserverlimit');
1057 break;
1059 case 2: // UPLOAD_ERR_FORM_SIZE
1060 $errmessage = get_string('uploadformlimit');
1061 break;
1063 case 3: // UPLOAD_ERR_PARTIAL
1064 $errmessage = get_string('uploadpartialfile');
1065 break;
1067 case 4: // UPLOAD_ERR_NO_FILE
1068 $errmessage = get_string('uploadnofilefound');
1069 break;
1071 // Note: there is no error with a value of 5
1073 case 6: // UPLOAD_ERR_NO_TMP_DIR
1074 $errmessage = get_string('uploadnotempdir');
1075 break;
1077 case 7: // UPLOAD_ERR_CANT_WRITE
1078 $errmessage = get_string('uploadcantwrite');
1079 break;
1081 case 8: // UPLOAD_ERR_EXTENSION
1082 $errmessage = get_string('uploadextension');
1083 break;
1085 default:
1086 $errmessage = get_string('uploadproblem');
1089 return $errmessage;
1093 * Recursive function formating an array in POST parameter
1094 * @param array $arraydata - the array that we are going to format and add into &$data array
1095 * @param string $currentdata - a row of the final postdata array at instant T
1096 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1097 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1099 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1100 foreach ($arraydata as $k=>$v) {
1101 $newcurrentdata = $currentdata;
1102 if (is_array($v)) { //the value is an array, call the function recursively
1103 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1104 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1105 } else { //add the POST parameter to the $data array
1106 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1112 * Transform a PHP array into POST parameter
1113 * (see the recursive function format_array_postdata_for_curlcall)
1114 * @param array $postdata
1115 * @return array containing all POST parameters (1 row = 1 POST parameter)
1117 function format_postdata_for_curlcall($postdata) {
1118 $data = array();
1119 foreach ($postdata as $k=>$v) {
1120 if (is_array($v)) {
1121 $currentdata = urlencode($k);
1122 format_array_postdata_for_curlcall($v, $currentdata, $data);
1123 } else {
1124 $data[] = urlencode($k).'='.urlencode($v);
1127 $convertedpostdata = implode('&', $data);
1128 return $convertedpostdata;
1132 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1133 * Due to security concerns only downloads from http(s) sources are supported.
1135 * @todo MDL-31073 add version test for '7.10.5'
1136 * @category files
1137 * @param string $url file url starting with http(s)://
1138 * @param array $headers http headers, null if none. If set, should be an
1139 * associative array of header name => value pairs.
1140 * @param array $postdata array means use POST request with given parameters
1141 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1142 * (if false, just returns content)
1143 * @param int $timeout timeout for complete download process including all file transfer
1144 * (default 5 minutes)
1145 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1146 * usually happens if the remote server is completely down (default 20 seconds);
1147 * may not work when using proxy
1148 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1149 * Only use this when already in a trusted location.
1150 * @param string $tofile store the downloaded content to file instead of returning it.
1151 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1152 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1153 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1155 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1156 global $CFG;
1158 // some extra security
1159 $newlines = array("\r", "\n");
1160 if (is_array($headers) ) {
1161 foreach ($headers as $key => $value) {
1162 $headers[$key] = str_replace($newlines, '', $value);
1165 $url = str_replace($newlines, '', $url);
1166 if (!preg_match('|^https?://|i', $url)) {
1167 if ($fullresponse) {
1168 $response = new stdClass();
1169 $response->status = 0;
1170 $response->headers = array();
1171 $response->response_code = 'Invalid protocol specified in url';
1172 $response->results = '';
1173 $response->error = 'Invalid protocol specified in url';
1174 return $response;
1175 } else {
1176 return false;
1180 // check if proxy (if used) should be bypassed for this url
1181 $proxybypass = is_proxybypass($url);
1183 if (!$ch = curl_init($url)) {
1184 debugging('Can not init curl.');
1185 return false;
1188 // set extra headers
1189 if (is_array($headers) ) {
1190 $headers2 = array();
1191 foreach ($headers as $key => $value) {
1192 $headers2[] = "$key: $value";
1194 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1197 if ($skipcertverify) {
1198 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1201 // use POST if requested
1202 if (is_array($postdata)) {
1203 $postdata = format_postdata_for_curlcall($postdata);
1204 curl_setopt($ch, CURLOPT_POST, true);
1205 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1208 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1209 curl_setopt($ch, CURLOPT_HEADER, false);
1210 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1212 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1213 // TODO: add version test for '7.10.5'
1214 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1215 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1218 if (!empty($CFG->proxyhost) and !$proxybypass) {
1219 // SOCKS supported in PHP5 only
1220 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1221 if (defined('CURLPROXY_SOCKS5')) {
1222 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1223 } else {
1224 curl_close($ch);
1225 if ($fullresponse) {
1226 $response = new stdClass();
1227 $response->status = '0';
1228 $response->headers = array();
1229 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1230 $response->results = '';
1231 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1232 return $response;
1233 } else {
1234 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1235 return false;
1240 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1242 if (empty($CFG->proxyport)) {
1243 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1244 } else {
1245 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1248 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1249 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1250 if (defined('CURLOPT_PROXYAUTH')) {
1251 // any proxy authentication if PHP 5.1
1252 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1257 // set up header and content handlers
1258 $received = new stdClass();
1259 $received->headers = array(); // received headers array
1260 $received->tofile = $tofile;
1261 $received->fh = null;
1262 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1263 if ($tofile) {
1264 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1267 if (!isset($CFG->curltimeoutkbitrate)) {
1268 //use very slow rate of 56kbps as a timeout speed when not set
1269 $bitrate = 56;
1270 } else {
1271 $bitrate = $CFG->curltimeoutkbitrate;
1274 // try to calculate the proper amount for timeout from remote file size.
1275 // if disabled or zero, we won't do any checks nor head requests.
1276 if ($calctimeout && $bitrate > 0) {
1277 //setup header request only options
1278 curl_setopt_array ($ch, array(
1279 CURLOPT_RETURNTRANSFER => false,
1280 CURLOPT_NOBODY => true)
1283 curl_exec($ch);
1284 $info = curl_getinfo($ch);
1285 $err = curl_error($ch);
1287 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1288 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1290 //reinstate affected curl options
1291 curl_setopt_array ($ch, array(
1292 CURLOPT_RETURNTRANSFER => true,
1293 CURLOPT_NOBODY => false)
1297 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1298 $result = curl_exec($ch);
1300 // try to detect encoding problems
1301 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1302 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1303 $result = curl_exec($ch);
1306 if ($received->fh) {
1307 fclose($received->fh);
1310 if (curl_errno($ch)) {
1311 $error = curl_error($ch);
1312 $error_no = curl_errno($ch);
1313 curl_close($ch);
1315 if ($fullresponse) {
1316 $response = new stdClass();
1317 if ($error_no == 28) {
1318 $response->status = '-100'; // mimic snoopy
1319 } else {
1320 $response->status = '0';
1322 $response->headers = array();
1323 $response->response_code = $error;
1324 $response->results = false;
1325 $response->error = $error;
1326 return $response;
1327 } else {
1328 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1329 return false;
1332 } else {
1333 $info = curl_getinfo($ch);
1334 curl_close($ch);
1336 if (empty($info['http_code'])) {
1337 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1338 $response = new stdClass();
1339 $response->status = '0';
1340 $response->headers = array();
1341 $response->response_code = 'Unknown cURL error';
1342 $response->results = false; // do NOT change this, we really want to ignore the result!
1343 $response->error = 'Unknown cURL error';
1345 } else {
1346 $response = new stdClass();
1347 $response->status = (string)$info['http_code'];
1348 $response->headers = $received->headers;
1349 $response->response_code = $received->headers[0];
1350 $response->results = $result;
1351 $response->error = '';
1354 if ($fullresponse) {
1355 return $response;
1356 } else if ($info['http_code'] != 200) {
1357 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1358 return false;
1359 } else {
1360 return $response->results;
1366 * internal implementation
1367 * @param stdClass $received
1368 * @param resource $ch
1369 * @param mixed $header
1370 * @return int header length
1372 function download_file_content_header_handler($received, $ch, $header) {
1373 $received->headers[] = $header;
1374 return strlen($header);
1378 * internal implementation
1379 * @param stdClass $received
1380 * @param resource $ch
1381 * @param mixed $data
1383 function download_file_content_write_handler($received, $ch, $data) {
1384 if (!$received->fh) {
1385 $received->fh = fopen($received->tofile, 'w');
1386 if ($received->fh === false) {
1387 // bad luck, file creation or overriding failed
1388 return 0;
1391 if (fwrite($received->fh, $data) === false) {
1392 // bad luck, write failed, let's abort completely
1393 return 0;
1395 return strlen($data);
1399 * Returns a list of information about file types based on extensions.
1401 * The following elements expected in value array for each extension:
1402 * 'type' - mimetype
1403 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1404 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1405 * also files with bigger sizes under names
1406 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1407 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1408 * commonly used in moodle the following groups:
1409 * - web_image - image that can be included as <img> in HTML
1410 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1411 * - video - file that can be imported as video in text editor
1412 * - audio - file that can be imported as audio in text editor
1413 * - archive - we can extract files from this archive
1414 * - spreadsheet - used for portfolio format
1415 * - document - used for portfolio format
1416 * - presentation - used for portfolio format
1417 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1418 * human-readable description for this filetype;
1419 * Function {@link get_mimetype_description()} first looks at the presence of string for
1420 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1421 * attribute, if not found returns the value of 'type';
1422 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1423 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1424 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1426 * @category files
1427 * @return array List of information about file types based on extensions.
1428 * Associative array of extension (lower-case) to associative array
1429 * from 'element name' to data. Current element names are 'type' and 'icon'.
1430 * Unknown types should use the 'xxx' entry which includes defaults.
1432 function &get_mimetypes_array() {
1433 static $mimearray = array (
1434 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1435 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1436 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1437 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1438 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1439 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1440 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1441 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1442 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1443 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1444 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1445 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1446 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1447 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1448 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1449 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1450 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1451 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1452 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1453 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1454 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1455 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1457 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1458 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1459 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1460 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1461 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1463 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1464 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1465 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1466 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1467 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1468 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1469 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1470 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1471 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1472 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1473 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1474 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1475 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1476 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1477 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1478 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1479 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1480 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1481 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1482 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1483 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1484 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1485 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1486 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1487 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1488 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1489 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1490 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1491 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1492 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1493 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1494 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1495 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1496 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1497 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1498 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1499 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1500 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1501 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1502 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1503 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1504 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1505 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1506 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1507 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1508 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1509 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1510 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1511 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1512 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1513 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1515 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1516 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1517 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1518 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1519 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1520 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1521 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1522 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1523 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1524 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1525 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1526 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1527 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1528 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1529 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1530 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1531 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1533 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1534 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1535 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1536 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1537 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1538 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1540 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1541 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1542 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1543 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1544 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1545 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1546 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1547 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1548 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1550 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1551 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1552 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1553 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1554 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1555 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1556 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1557 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1558 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1559 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1560 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1561 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1562 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1563 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1564 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1565 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1566 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1567 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1568 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1569 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1571 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1572 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1573 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1574 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1575 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1576 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1577 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1578 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1579 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1580 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1582 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1583 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1584 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1585 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1586 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1587 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1588 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1589 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1590 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1591 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1592 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1593 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1594 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1595 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1596 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1598 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1599 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1600 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1601 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1602 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1603 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1604 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1606 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1607 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1608 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1610 return $mimearray;
1614 * Obtains information about a filetype based on its extension. Will
1615 * use a default if no information is present about that particular
1616 * extension.
1618 * @category files
1619 * @param string $element Desired information (usually 'icon'
1620 * for icon filename or 'type' for MIME type. Can also be
1621 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1622 * @param string $filename Filename we're looking up
1623 * @return string Requested piece of information from array
1625 function mimeinfo($element, $filename) {
1626 global $CFG;
1627 $mimeinfo = & get_mimetypes_array();
1628 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1630 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1631 if (empty($filetype)) {
1632 $filetype = 'xxx'; // file without extension
1634 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1635 $iconsize = max(array(16, (int)$iconsizematch[1]));
1636 $filenames = array($mimeinfo['xxx']['icon']);
1637 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1638 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1640 // find the file with the closest size, first search for specific icon then for default icon
1641 foreach ($filenames as $filename) {
1642 foreach ($iconpostfixes as $size => $postfix) {
1643 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1644 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1645 return $filename.$postfix;
1649 } else if (isset($mimeinfo[$filetype][$element])) {
1650 return $mimeinfo[$filetype][$element];
1651 } else if (isset($mimeinfo['xxx'][$element])) {
1652 return $mimeinfo['xxx'][$element]; // By default
1653 } else {
1654 return null;
1659 * Obtains information about a filetype based on the MIME type rather than
1660 * the other way around.
1662 * @category files
1663 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1664 * @param string $mimetype MIME type we're looking up
1665 * @return string Requested piece of information from array
1667 function mimeinfo_from_type($element, $mimetype) {
1668 /* array of cached mimetype->extension associations */
1669 static $cached = array();
1670 $mimeinfo = & get_mimetypes_array();
1672 if (!array_key_exists($mimetype, $cached)) {
1673 $cached[$mimetype] = null;
1674 foreach($mimeinfo as $filetype => $values) {
1675 if ($values['type'] == $mimetype) {
1676 if ($cached[$mimetype] === null) {
1677 $cached[$mimetype] = '.'.$filetype;
1679 if (!empty($values['defaulticon'])) {
1680 $cached[$mimetype] = '.'.$filetype;
1681 break;
1685 if (empty($cached[$mimetype])) {
1686 $cached[$mimetype] = '.xxx';
1689 if ($element === 'extension') {
1690 return $cached[$mimetype];
1691 } else {
1692 return mimeinfo($element, $cached[$mimetype]);
1697 * Return the relative icon path for a given file
1699 * Usage:
1700 * <code>
1701 * // $file - instance of stored_file or file_info
1702 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1703 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1704 * </code>
1705 * or
1706 * <code>
1707 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1708 * </code>
1710 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1711 * and $file->mimetype are expected)
1712 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1713 * @return string
1715 function file_file_icon($file, $size = null) {
1716 if (!is_object($file)) {
1717 $file = (object)$file;
1719 if (isset($file->filename)) {
1720 $filename = $file->filename;
1721 } else if (method_exists($file, 'get_filename')) {
1722 $filename = $file->get_filename();
1723 } else if (method_exists($file, 'get_visible_name')) {
1724 $filename = $file->get_visible_name();
1725 } else {
1726 $filename = '';
1728 if (isset($file->mimetype)) {
1729 $mimetype = $file->mimetype;
1730 } else if (method_exists($file, 'get_mimetype')) {
1731 $mimetype = $file->get_mimetype();
1732 } else {
1733 $mimetype = '';
1735 $mimetypes = &get_mimetypes_array();
1736 if ($filename) {
1737 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1738 if ($extension && !empty($mimetypes[$extension])) {
1739 // if file name has known extension, return icon for this extension
1740 return file_extension_icon($filename, $size);
1743 return file_mimetype_icon($mimetype, $size);
1747 * Return the relative icon path for a folder image
1749 * Usage:
1750 * <code>
1751 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1752 * echo html_writer::empty_tag('img', array('src' => $icon));
1753 * </code>
1754 * or
1755 * <code>
1756 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1757 * </code>
1759 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1760 * @return string
1762 function file_folder_icon($iconsize = null) {
1763 global $CFG;
1764 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1765 static $cached = array();
1766 $iconsize = max(array(16, (int)$iconsize));
1767 if (!array_key_exists($iconsize, $cached)) {
1768 foreach ($iconpostfixes as $size => $postfix) {
1769 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1770 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1771 $cached[$iconsize] = 'f/folder'.$postfix;
1772 break;
1776 return $cached[$iconsize];
1780 * Returns the relative icon path for a given mime type
1782 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1783 * a return the full path to an icon.
1785 * <code>
1786 * $mimetype = 'image/jpg';
1787 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1788 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1789 * </code>
1791 * @category files
1792 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1793 * to conform with that.
1794 * @param string $mimetype The mimetype to fetch an icon for
1795 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1796 * @return string The relative path to the icon
1798 function file_mimetype_icon($mimetype, $size = NULL) {
1799 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1803 * Returns the relative icon path for a given file name
1805 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1806 * a return the full path to an icon.
1808 * <code>
1809 * $filename = '.jpg';
1810 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1811 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1812 * </code>
1814 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1815 * to conform with that.
1816 * @todo MDL-31074 Implement $size
1817 * @category files
1818 * @param string $filename The filename to get the icon for
1819 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1820 * @return string
1822 function file_extension_icon($filename, $size = NULL) {
1823 return 'f/'.mimeinfo('icon'.$size, $filename);
1827 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1828 * mimetypes.php language file.
1830 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1831 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1832 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1833 * @param bool $capitalise If true, capitalises first character of result
1834 * @return string Text description
1836 function get_mimetype_description($obj, $capitalise=false) {
1837 $filename = $mimetype = '';
1838 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1839 // this is an instance of stored_file
1840 $mimetype = $obj->get_mimetype();
1841 $filename = $obj->get_filename();
1842 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1843 // this is an instance of file_info
1844 $mimetype = $obj->get_mimetype();
1845 $filename = $obj->get_visible_name();
1846 } else if (is_array($obj) || is_object ($obj)) {
1847 $obj = (array)$obj;
1848 if (!empty($obj['filename'])) {
1849 $filename = $obj['filename'];
1851 if (!empty($obj['mimetype'])) {
1852 $mimetype = $obj['mimetype'];
1854 } else {
1855 $mimetype = $obj;
1857 $mimetypefromext = mimeinfo('type', $filename);
1858 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1859 // if file has a known extension, overwrite the specified mimetype
1860 $mimetype = $mimetypefromext;
1862 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1863 if (empty($extension)) {
1864 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1865 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1866 } else {
1867 $mimetypestr = mimeinfo('string', $filename);
1869 $chunks = explode('/', $mimetype, 2);
1870 $chunks[] = '';
1871 $attr = array(
1872 'mimetype' => $mimetype,
1873 'ext' => $extension,
1874 'mimetype1' => $chunks[0],
1875 'mimetype2' => $chunks[1],
1877 $a = array();
1878 foreach ($attr as $key => $value) {
1879 $a[$key] = $value;
1880 $a[strtoupper($key)] = strtoupper($value);
1881 $a[ucfirst($key)] = ucfirst($value);
1884 // MIME types may include + symbol but this is not permitted in string ids.
1885 $safemimetype = str_replace('+', '_', $mimetype);
1886 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1887 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1888 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1889 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1890 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1891 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1892 $result = get_string('default', 'mimetypes', (object)$a);
1893 } else {
1894 $result = $mimetype;
1896 if ($capitalise) {
1897 $result=ucfirst($result);
1899 return $result;
1903 * Returns array of elements of type $element in type group(s)
1905 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1906 * @param string|array $groups one group or array of groups/extensions/mimetypes
1907 * @return array
1909 function file_get_typegroup($element, $groups) {
1910 static $cached = array();
1911 if (!is_array($groups)) {
1912 $groups = array($groups);
1914 if (!array_key_exists($element, $cached)) {
1915 $cached[$element] = array();
1917 $result = array();
1918 foreach ($groups as $group) {
1919 if (!array_key_exists($group, $cached[$element])) {
1920 // retrieive and cache all elements of type $element for group $group
1921 $mimeinfo = & get_mimetypes_array();
1922 $cached[$element][$group] = array();
1923 foreach ($mimeinfo as $extension => $value) {
1924 $value['extension'] = '.'.$extension;
1925 if (empty($value[$element])) {
1926 continue;
1928 if (($group === '.'.$extension || $group === $value['type'] ||
1929 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1930 !in_array($value[$element], $cached[$element][$group])) {
1931 $cached[$element][$group][] = $value[$element];
1935 $result = array_merge($result, $cached[$element][$group]);
1937 return array_unique($result);
1941 * Checks if file with name $filename has one of the extensions in groups $groups
1943 * @see get_mimetypes_array()
1944 * @param string $filename name of the file to check
1945 * @param string|array $groups one group or array of groups to check
1946 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1947 * file mimetype is in mimetypes in groups $groups
1948 * @return bool
1950 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1951 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1952 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1953 return true;
1955 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1959 * Checks if mimetype $mimetype belongs to one of the groups $groups
1961 * @see get_mimetypes_array()
1962 * @param string $mimetype
1963 * @param string|array $groups one group or array of groups to check
1964 * @return bool
1966 function file_mimetype_in_typegroup($mimetype, $groups) {
1967 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1971 * Requested file is not found or not accessible, does not return, terminates script
1973 * @global stdClass $CFG
1974 * @global stdClass $COURSE
1976 function send_file_not_found() {
1977 global $CFG, $COURSE;
1978 send_header_404();
1979 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1982 * Helper function to send correct 404 for server.
1984 function send_header_404() {
1985 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1986 header("Status: 404 Not Found");
1987 } else {
1988 header('HTTP/1.0 404 not found');
1993 * Enhanced readfile() with optional acceleration.
1994 * @param string|stored_file $file
1995 * @param string $mimetype
1996 * @param bool $accelerate
1997 * @return void
1999 function readfile_accel($file, $mimetype, $accelerate) {
2000 global $CFG;
2002 if ($mimetype === 'text/plain') {
2003 // there is no encoding specified in text files, we need something consistent
2004 header('Content-Type: text/plain; charset=utf-8');
2005 } else {
2006 header('Content-Type: '.$mimetype);
2009 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2010 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2012 if (is_object($file)) {
2013 header('ETag: ' . $file->get_contenthash());
2014 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
2015 header('HTTP/1.1 304 Not Modified');
2016 return;
2020 // if etag present for stored file rely on it exclusively
2021 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2022 // get unixtime of request header; clip extra junk off first
2023 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2024 if ($since && $since >= $lastmodified) {
2025 header('HTTP/1.1 304 Not Modified');
2026 return;
2030 if ($accelerate and !empty($CFG->xsendfile)) {
2031 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2032 header('Accept-Ranges: bytes');
2033 } else {
2034 header('Accept-Ranges: none');
2037 if (is_object($file)) {
2038 $fs = get_file_storage();
2039 if ($fs->xsendfile($file->get_contenthash())) {
2040 return;
2043 } else {
2044 require_once("$CFG->libdir/xsendfilelib.php");
2045 if (xsendfile($file)) {
2046 return;
2051 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2053 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2055 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2056 header('Accept-Ranges: bytes');
2058 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2059 // byteserving stuff - for acrobat reader and download accelerators
2060 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2061 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2062 $ranges = false;
2063 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2064 foreach ($ranges as $key=>$value) {
2065 if ($ranges[$key][1] == '') {
2066 //suffix case
2067 $ranges[$key][1] = $filesize - $ranges[$key][2];
2068 $ranges[$key][2] = $filesize - 1;
2069 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2070 //fix range length
2071 $ranges[$key][2] = $filesize - 1;
2073 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2074 //invalid byte-range ==> ignore header
2075 $ranges = false;
2076 break;
2078 //prepare multipart header
2079 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2080 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2082 } else {
2083 $ranges = false;
2085 if ($ranges) {
2086 if (is_object($file)) {
2087 $handle = $file->get_content_file_handle();
2088 } else {
2089 $handle = fopen($file, 'rb');
2091 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2094 } else {
2095 // Do not byteserve
2096 header('Accept-Ranges: none');
2099 header('Content-Length: '.$filesize);
2101 if ($filesize > 10000000) {
2102 // for large files try to flush and close all buffers to conserve memory
2103 while(@ob_get_level()) {
2104 if (!@ob_end_flush()) {
2105 break;
2110 // send the whole file content
2111 if (is_object($file)) {
2112 $file->readfile();
2113 } else {
2114 readfile($file);
2119 * Similar to readfile_accel() but designed for strings.
2120 * @param string $string
2121 * @param string $mimetype
2122 * @param bool $accelerate
2123 * @return void
2125 function readstring_accel($string, $mimetype, $accelerate) {
2126 global $CFG;
2128 if ($mimetype === 'text/plain') {
2129 // there is no encoding specified in text files, we need something consistent
2130 header('Content-Type: text/plain; charset=utf-8');
2131 } else {
2132 header('Content-Type: '.$mimetype);
2134 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2135 header('Accept-Ranges: none');
2137 if ($accelerate and !empty($CFG->xsendfile)) {
2138 $fs = get_file_storage();
2139 if ($fs->xsendfile(sha1($string))) {
2140 return;
2144 header('Content-Length: '.strlen($string));
2145 echo $string;
2149 * Handles the sending of temporary file to user, download is forced.
2150 * File is deleted after abort or successful sending, does not return, script terminated
2152 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2153 * @param string $filename proposed file name when saving file
2154 * @param bool $pathisstring If the path is string
2156 function send_temp_file($path, $filename, $pathisstring=false) {
2157 global $CFG;
2159 if (check_browser_version('Firefox', '1.5')) {
2160 // only FF is known to correctly save to disk before opening...
2161 $mimetype = mimeinfo('type', $filename);
2162 } else {
2163 $mimetype = 'application/x-forcedownload';
2166 // close session - not needed anymore
2167 session_get_instance()->write_close();
2169 if (!$pathisstring) {
2170 if (!file_exists($path)) {
2171 send_header_404();
2172 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2174 // executed after normal finish or abort
2175 @register_shutdown_function('send_temp_file_finished', $path);
2178 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2179 if (check_browser_version('MSIE')) {
2180 $filename = urlencode($filename);
2183 header('Content-Disposition: attachment; filename="'.$filename.'"');
2184 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2185 header('Cache-Control: max-age=10');
2186 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2187 header('Pragma: ');
2188 } else { //normal http - prevent caching at all cost
2189 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2190 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2191 header('Pragma: no-cache');
2194 // send the contents - we can not accelerate this because the file will be deleted asap
2195 if ($pathisstring) {
2196 readstring_accel($path, $mimetype, false);
2197 } else {
2198 readfile_accel($path, $mimetype, false);
2199 @unlink($path);
2202 die; //no more chars to output
2206 * Internal callback function used by send_temp_file()
2208 * @param string $path
2210 function send_temp_file_finished($path) {
2211 if (file_exists($path)) {
2212 @unlink($path);
2217 * Handles the sending of file data to the user's browser, including support for
2218 * byteranges etc.
2220 * @category files
2221 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2222 * @param string $filename Filename to send
2223 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2224 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2225 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2226 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2227 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2228 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2229 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2230 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2231 * and should not be reopened.
2232 * @return null script execution stopped unless $dontdie is true
2234 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2235 global $CFG, $COURSE;
2237 if ($dontdie) {
2238 ignore_user_abort(true);
2241 // MDL-11789, apply $CFG->filelifetime here
2242 if ($lifetime === 'default') {
2243 if (!empty($CFG->filelifetime)) {
2244 $lifetime = $CFG->filelifetime;
2245 } else {
2246 $lifetime = 86400;
2250 session_get_instance()->write_close(); // unlock session during fileserving
2252 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2253 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2254 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2255 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2256 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2257 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2259 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2260 if (check_browser_version('MSIE')) {
2261 $filename = rawurlencode($filename);
2264 if ($forcedownload) {
2265 header('Content-Disposition: attachment; filename="'.$filename.'"');
2266 } else {
2267 header('Content-Disposition: inline; filename="'.$filename.'"');
2270 if ($lifetime > 0) {
2271 $nobyteserving = false;
2272 header('Cache-Control: max-age='.$lifetime);
2273 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2274 header('Pragma: ');
2276 } else { // Do not cache files in proxies and browsers
2277 $nobyteserving = true;
2278 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2279 header('Cache-Control: max-age=10');
2280 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2281 header('Pragma: ');
2282 } else { //normal http - prevent caching at all cost
2283 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2284 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2285 header('Pragma: no-cache');
2289 if (empty($filter)) {
2290 // send the contents
2291 if ($pathisstring) {
2292 readstring_accel($path, $mimetype, !$dontdie);
2293 } else {
2294 readfile_accel($path, $mimetype, !$dontdie);
2297 } else {
2298 // Try to put the file through filters
2299 if ($mimetype == 'text/html') {
2300 $options = new stdClass();
2301 $options->noclean = true;
2302 $options->nocache = true; // temporary workaround for MDL-5136
2303 $text = $pathisstring ? $path : implode('', file($path));
2305 $text = file_modify_html_header($text);
2306 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2308 readstring_accel($output, $mimetype, false);
2310 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2311 // only filter text if filter all files is selected
2312 $options = new stdClass();
2313 $options->newlines = false;
2314 $options->noclean = true;
2315 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2316 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2318 readstring_accel($output, $mimetype, false);
2320 } else {
2321 // send the contents
2322 if ($pathisstring) {
2323 readstring_accel($path, $mimetype, !$dontdie);
2324 } else {
2325 readfile_accel($path, $mimetype, !$dontdie);
2329 if ($dontdie) {
2330 return;
2332 die; //no more chars to output!!!
2336 * Handles the sending of file data to the user's browser, including support for
2337 * byteranges etc.
2339 * The $options parameter supports the following keys:
2340 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2341 * (string|null) filename - overrides the implicit filename
2342 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2343 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2344 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2345 * and should not be reopened.
2347 * @category files
2348 * @param stored_file $stored_file local file object
2349 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2350 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2351 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2352 * @param array $options additional options affecting the file serving
2353 * @return null script execution stopped unless $options['dontdie'] is true
2355 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2356 global $CFG, $COURSE;
2358 if (empty($options['filename'])) {
2359 $filename = null;
2360 } else {
2361 $filename = $options['filename'];
2364 if (empty($options['dontdie'])) {
2365 $dontdie = false;
2366 } else {
2367 $dontdie = true;
2370 if (!empty($options['preview'])) {
2371 // replace the file with its preview
2372 $fs = get_file_storage();
2373 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2374 if (!$preview_file) {
2375 // unable to create a preview of the file, send its default mime icon instead
2376 if ($options['preview'] === 'tinyicon') {
2377 $size = 24;
2378 } else if ($options['preview'] === 'thumb') {
2379 $size = 90;
2380 } else {
2381 $size = 256;
2383 $fileicon = file_file_icon($stored_file, $size);
2384 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2385 } else {
2386 // preview images have fixed cache lifetime and they ignore forced download
2387 // (they are generated by GD and therefore they are considered reasonably safe).
2388 $stored_file = $preview_file;
2389 $lifetime = DAYSECS;
2390 $filter = 0;
2391 $forcedownload = false;
2395 // handle external resource
2396 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2397 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2398 die;
2401 if (!$stored_file or $stored_file->is_directory()) {
2402 // nothing to serve
2403 if ($dontdie) {
2404 return;
2406 die;
2409 if ($dontdie) {
2410 ignore_user_abort(true);
2413 session_get_instance()->write_close(); // unlock session during fileserving
2415 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2416 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2417 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2418 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2419 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2420 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2421 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2423 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2424 if (check_browser_version('MSIE')) {
2425 $filename = rawurlencode($filename);
2428 if ($forcedownload) {
2429 header('Content-Disposition: attachment; filename="'.$filename.'"');
2430 } else {
2431 header('Content-Disposition: inline; filename="'.$filename.'"');
2434 if ($lifetime > 0) {
2435 header('Cache-Control: max-age='.$lifetime);
2436 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2437 header('Pragma: ');
2439 } else { // Do not cache files in proxies and browsers
2440 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2441 header('Cache-Control: max-age=10');
2442 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2443 header('Pragma: ');
2444 } else { //normal http - prevent caching at all cost
2445 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2446 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2447 header('Pragma: no-cache');
2451 if (empty($filter)) {
2452 // send the contents
2453 readfile_accel($stored_file, $mimetype, !$dontdie);
2455 } else { // Try to put the file through filters
2456 if ($mimetype == 'text/html') {
2457 $options = new stdClass();
2458 $options->noclean = true;
2459 $options->nocache = true; // temporary workaround for MDL-5136
2460 $text = $stored_file->get_content();
2461 $text = file_modify_html_header($text);
2462 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2464 readstring_accel($output, $mimetype, false);
2466 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2467 // only filter text if filter all files is selected
2468 $options = new stdClass();
2469 $options->newlines = false;
2470 $options->noclean = true;
2471 $text = $stored_file->get_content();
2472 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2474 readstring_accel($output, $mimetype, false);
2476 } else { // Just send it out raw
2477 readfile_accel($stored_file, $mimetype, !$dontdie);
2480 if ($dontdie) {
2481 return;
2483 die; //no more chars to output!!!
2487 * Retrieves an array of records from a CSV file and places
2488 * them into a given table structure
2490 * @global stdClass $CFG
2491 * @global moodle_database $DB
2492 * @param string $file The path to a CSV file
2493 * @param string $table The table to retrieve columns from
2494 * @return bool|array Returns an array of CSV records or false
2496 function get_records_csv($file, $table) {
2497 global $CFG, $DB;
2499 if (!$metacolumns = $DB->get_columns($table)) {
2500 return false;
2503 if(!($handle = @fopen($file, 'r'))) {
2504 print_error('get_records_csv failed to open '.$file);
2507 $fieldnames = fgetcsv($handle, 4096);
2508 if(empty($fieldnames)) {
2509 fclose($handle);
2510 return false;
2513 $columns = array();
2515 foreach($metacolumns as $metacolumn) {
2516 $ord = array_search($metacolumn->name, $fieldnames);
2517 if(is_int($ord)) {
2518 $columns[$metacolumn->name] = $ord;
2522 $rows = array();
2524 while (($data = fgetcsv($handle, 4096)) !== false) {
2525 $item = new stdClass;
2526 foreach($columns as $name => $ord) {
2527 $item->$name = $data[$ord];
2529 $rows[] = $item;
2532 fclose($handle);
2533 return $rows;
2537 * Create a file with CSV contents
2539 * @global stdClass $CFG
2540 * @global moodle_database $DB
2541 * @param string $file The file to put the CSV content into
2542 * @param array $records An array of records to write to a CSV file
2543 * @param string $table The table to get columns from
2544 * @return bool success
2546 function put_records_csv($file, $records, $table = NULL) {
2547 global $CFG, $DB;
2549 if (empty($records)) {
2550 return true;
2553 $metacolumns = NULL;
2554 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2555 return false;
2558 echo "x";
2560 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2561 print_error('put_records_csv failed to open '.$file);
2564 $proto = reset($records);
2565 if(is_object($proto)) {
2566 $fields_records = array_keys(get_object_vars($proto));
2568 else if(is_array($proto)) {
2569 $fields_records = array_keys($proto);
2571 else {
2572 return false;
2574 echo "x";
2576 if(!empty($metacolumns)) {
2577 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2578 $fields = array_intersect($fields_records, $fields_table);
2580 else {
2581 $fields = $fields_records;
2584 fwrite($fp, implode(',', $fields));
2585 fwrite($fp, "\r\n");
2587 foreach($records as $record) {
2588 $array = (array)$record;
2589 $values = array();
2590 foreach($fields as $field) {
2591 if(strpos($array[$field], ',')) {
2592 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2594 else {
2595 $values[] = $array[$field];
2598 fwrite($fp, implode(',', $values)."\r\n");
2601 fclose($fp);
2602 return true;
2607 * Recursively delete the file or folder with path $location. That is,
2608 * if it is a file delete it. If it is a folder, delete all its content
2609 * then delete it. If $location does not exist to start, that is not
2610 * considered an error.
2612 * @param string $location the path to remove.
2613 * @return bool
2615 function fulldelete($location) {
2616 if (empty($location)) {
2617 // extra safety against wrong param
2618 return false;
2620 if (is_dir($location)) {
2621 if (!$currdir = opendir($location)) {
2622 return false;
2624 while (false !== ($file = readdir($currdir))) {
2625 if ($file <> ".." && $file <> ".") {
2626 $fullfile = $location."/".$file;
2627 if (is_dir($fullfile)) {
2628 if (!fulldelete($fullfile)) {
2629 return false;
2631 } else {
2632 if (!unlink($fullfile)) {
2633 return false;
2638 closedir($currdir);
2639 if (! rmdir($location)) {
2640 return false;
2643 } else if (file_exists($location)) {
2644 if (!unlink($location)) {
2645 return false;
2648 return true;
2652 * Send requested byterange of file.
2654 * @param resource $handle A file handle
2655 * @param string $mimetype The mimetype for the output
2656 * @param array $ranges An array of ranges to send
2657 * @param string $filesize The size of the content if only one range is used
2659 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2660 // better turn off any kind of compression and buffering
2661 @ini_set('zlib.output_compression', 'Off');
2663 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2664 if ($handle === false) {
2665 die;
2667 if (count($ranges) == 1) { //only one range requested
2668 $length = $ranges[0][2] - $ranges[0][1] + 1;
2669 header('HTTP/1.1 206 Partial content');
2670 header('Content-Length: '.$length);
2671 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2672 header('Content-Type: '.$mimetype);
2674 while(@ob_get_level()) {
2675 if (!@ob_end_flush()) {
2676 break;
2680 fseek($handle, $ranges[0][1]);
2681 while (!feof($handle) && $length > 0) {
2682 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2683 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2684 echo $buffer;
2685 flush();
2686 $length -= strlen($buffer);
2688 fclose($handle);
2689 die;
2690 } else { // multiple ranges requested - not tested much
2691 $totallength = 0;
2692 foreach($ranges as $range) {
2693 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2695 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2696 header('HTTP/1.1 206 Partial content');
2697 header('Content-Length: '.$totallength);
2698 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2700 while(@ob_get_level()) {
2701 if (!@ob_end_flush()) {
2702 break;
2706 foreach($ranges as $range) {
2707 $length = $range[2] - $range[1] + 1;
2708 echo $range[0];
2709 fseek($handle, $range[1]);
2710 while (!feof($handle) && $length > 0) {
2711 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2712 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2713 echo $buffer;
2714 flush();
2715 $length -= strlen($buffer);
2718 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2719 fclose($handle);
2720 die;
2725 * add includes (js and css) into uploaded files
2726 * before returning them, useful for themes and utf.js includes
2728 * @global stdClass $CFG
2729 * @param string $text text to search and replace
2730 * @return string text with added head includes
2731 * @todo MDL-21120
2733 function file_modify_html_header($text) {
2734 // first look for <head> tag
2735 global $CFG;
2737 $stylesheetshtml = '';
2738 /* foreach ($CFG->stylesheets as $stylesheet) {
2739 //TODO: MDL-21120
2740 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2743 $ufo = '';
2744 if (filter_is_enabled('mediaplugin')) {
2745 // this script is needed by most media filter plugins.
2746 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2747 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2750 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2751 if ($matches) {
2752 $replacement = '<head>'.$ufo.$stylesheetshtml;
2753 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2754 return $text;
2757 // if not, look for <html> tag, and stick <head> right after
2758 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2759 if ($matches) {
2760 // replace <html> tag with <html><head>includes</head>
2761 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2762 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2763 return $text;
2766 // if not, look for <body> tag, and stick <head> before body
2767 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2768 if ($matches) {
2769 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2770 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2771 return $text;
2774 // if not, just stick a <head> tag at the beginning
2775 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2776 return $text;
2780 * RESTful cURL class
2782 * This is a wrapper class for curl, it is quite easy to use:
2783 * <code>
2784 * $c = new curl;
2785 * // enable cache
2786 * $c = new curl(array('cache'=>true));
2787 * // enable cookie
2788 * $c = new curl(array('cookie'=>true));
2789 * // enable proxy
2790 * $c = new curl(array('proxy'=>true));
2792 * // HTTP GET Method
2793 * $html = $c->get('http://example.com');
2794 * // HTTP POST Method
2795 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2796 * // HTTP PUT Method
2797 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2798 * </code>
2800 * @package core_files
2801 * @category files
2802 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2803 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2805 class curl {
2806 /** @var bool Caches http request contents */
2807 public $cache = false;
2808 /** @var bool Uses proxy */
2809 public $proxy = false;
2810 /** @var string library version */
2811 public $version = '0.4 dev';
2812 /** @var array http's response */
2813 public $response = array();
2814 /** @var array http header */
2815 public $header = array();
2816 /** @var string cURL information */
2817 public $info;
2818 /** @var string error */
2819 public $error;
2820 /** @var int error code */
2821 public $errno;
2823 /** @var array cURL options */
2824 private $options;
2825 /** @var string Proxy host */
2826 private $proxy_host = '';
2827 /** @var string Proxy auth */
2828 private $proxy_auth = '';
2829 /** @var string Proxy type */
2830 private $proxy_type = '';
2831 /** @var bool Debug mode on */
2832 private $debug = false;
2833 /** @var bool|string Path to cookie file */
2834 private $cookie = false;
2837 * Constructor
2839 * @global stdClass $CFG
2840 * @param array $options
2842 public function __construct($options = array()){
2843 global $CFG;
2844 if (!function_exists('curl_init')) {
2845 $this->error = 'cURL module must be enabled!';
2846 trigger_error($this->error, E_USER_ERROR);
2847 return false;
2849 // the options of curl should be init here.
2850 $this->resetopt();
2851 if (!empty($options['debug'])) {
2852 $this->debug = true;
2854 if(!empty($options['cookie'])) {
2855 if($options['cookie'] === true) {
2856 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2857 } else {
2858 $this->cookie = $options['cookie'];
2861 if (!empty($options['cache'])) {
2862 if (class_exists('curl_cache')) {
2863 if (!empty($options['module_cache'])) {
2864 $this->cache = new curl_cache($options['module_cache']);
2865 } else {
2866 $this->cache = new curl_cache('misc');
2870 if (!empty($CFG->proxyhost)) {
2871 if (empty($CFG->proxyport)) {
2872 $this->proxy_host = $CFG->proxyhost;
2873 } else {
2874 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2876 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2877 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2878 $this->setopt(array(
2879 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2880 'proxyuserpwd'=>$this->proxy_auth));
2882 if (!empty($CFG->proxytype)) {
2883 if ($CFG->proxytype == 'SOCKS5') {
2884 $this->proxy_type = CURLPROXY_SOCKS5;
2885 } else {
2886 $this->proxy_type = CURLPROXY_HTTP;
2887 $this->setopt(array('httpproxytunnel'=>false));
2889 $this->setopt(array('proxytype'=>$this->proxy_type));
2892 if (!empty($this->proxy_host)) {
2893 $this->proxy = array('proxy'=>$this->proxy_host);
2897 * Resets the CURL options that have already been set
2899 public function resetopt(){
2900 $this->options = array();
2901 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2902 // True to include the header in the output
2903 $this->options['CURLOPT_HEADER'] = 0;
2904 // True to Exclude the body from the output
2905 $this->options['CURLOPT_NOBODY'] = 0;
2906 // TRUE to follow any "Location: " header that the server
2907 // sends as part of the HTTP header (note this is recursive,
2908 // PHP will follow as many "Location: " headers that it is sent,
2909 // unless CURLOPT_MAXREDIRS is set).
2910 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2911 $this->options['CURLOPT_MAXREDIRS'] = 10;
2912 $this->options['CURLOPT_ENCODING'] = '';
2913 // TRUE to return the transfer as a string of the return
2914 // value of curl_exec() instead of outputting it out directly.
2915 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2916 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2917 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2918 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2919 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2923 * Reset Cookie
2925 public function resetcookie() {
2926 if (!empty($this->cookie)) {
2927 if (is_file($this->cookie)) {
2928 $fp = fopen($this->cookie, 'w');
2929 if (!empty($fp)) {
2930 fwrite($fp, '');
2931 fclose($fp);
2938 * Set curl options
2940 * @param array $options If array is null, this function will
2941 * reset the options to default value.
2943 public function setopt($options = array()) {
2944 if (is_array($options)) {
2945 foreach($options as $name => $val){
2946 if (stripos($name, 'CURLOPT_') === false) {
2947 $name = strtoupper('CURLOPT_'.$name);
2949 $this->options[$name] = $val;
2955 * Reset http method
2957 public function cleanopt(){
2958 unset($this->options['CURLOPT_HTTPGET']);
2959 unset($this->options['CURLOPT_POST']);
2960 unset($this->options['CURLOPT_POSTFIELDS']);
2961 unset($this->options['CURLOPT_PUT']);
2962 unset($this->options['CURLOPT_INFILE']);
2963 unset($this->options['CURLOPT_INFILESIZE']);
2964 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2965 unset($this->options['CURLOPT_FILE']);
2969 * Resets the HTTP Request headers (to prepare for the new request)
2971 public function resetHeader() {
2972 $this->header = array();
2976 * Set HTTP Request Header
2978 * @param array $header
2980 public function setHeader($header) {
2981 if (is_array($header)){
2982 foreach ($header as $v) {
2983 $this->setHeader($v);
2985 } else {
2986 $this->header[] = $header;
2991 * Set HTTP Response Header
2994 public function getResponse(){
2995 return $this->response;
2999 * private callback function
3000 * Formatting HTTP Response Header
3002 * @param resource $ch Apparently not used
3003 * @param string $header
3004 * @return int The strlen of the header
3006 private function formatHeader($ch, $header)
3008 $this->count++;
3009 if (strlen($header) > 2) {
3010 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3011 $key = rtrim($key, ':');
3012 if (!empty($this->response[$key])) {
3013 if (is_array($this->response[$key])){
3014 $this->response[$key][] = $value;
3015 } else {
3016 $tmp = $this->response[$key];
3017 $this->response[$key] = array();
3018 $this->response[$key][] = $tmp;
3019 $this->response[$key][] = $value;
3022 } else {
3023 $this->response[$key] = $value;
3026 return strlen($header);
3030 * Set options for individual curl instance
3032 * @param resource $curl A curl handle
3033 * @param array $options
3034 * @return resource The curl handle
3036 private function apply_opt($curl, $options) {
3037 // Clean up
3038 $this->cleanopt();
3039 // set cookie
3040 if (!empty($this->cookie) || !empty($options['cookie'])) {
3041 $this->setopt(array('cookiejar'=>$this->cookie,
3042 'cookiefile'=>$this->cookie
3046 // set proxy
3047 if (!empty($this->proxy) || !empty($options['proxy'])) {
3048 $this->setopt($this->proxy);
3050 $this->setopt($options);
3051 // reset before set options
3052 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3053 // set headers
3054 if (empty($this->header)){
3055 $this->setHeader(array(
3056 'User-Agent: MoodleBot/1.0',
3057 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3058 'Connection: keep-alive'
3061 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3063 if ($this->debug){
3064 echo '<h1>Options</h1>';
3065 var_dump($this->options);
3066 echo '<h1>Header</h1>';
3067 var_dump($this->header);
3070 // set options
3071 foreach($this->options as $name => $val) {
3072 if (is_string($name)) {
3073 $name = constant(strtoupper($name));
3075 curl_setopt($curl, $name, $val);
3077 return $curl;
3081 * Download multiple files in parallel
3083 * Calls {@link multi()} with specific download headers
3085 * <code>
3086 * $c = new curl();
3087 * $file1 = fopen('a', 'wb');
3088 * $file2 = fopen('b', 'wb');
3089 * $c->download(array(
3090 * array('url'=>'http://localhost/', 'file'=>$file1),
3091 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3092 * ));
3093 * fclose($file1);
3094 * fclose($file2);
3095 * </code>
3097 * or
3099 * <code>
3100 * $c = new curl();
3101 * $c->download(array(
3102 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3103 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3104 * ));
3105 * </code>
3107 * @param array $requests An array of files to request {
3108 * url => url to download the file [required]
3109 * file => file handler, or
3110 * filepath => file path
3112 * If 'file' and 'filepath' parameters are both specified in one request, the
3113 * open file handle in the 'file' parameter will take precedence and 'filepath'
3114 * will be ignored.
3116 * @param array $options An array of options to set
3117 * @return array An array of results
3119 public function download($requests, $options = array()) {
3120 $options['CURLOPT_BINARYTRANSFER'] = 1;
3121 $options['RETURNTRANSFER'] = false;
3122 return $this->multi($requests, $options);
3126 * Mulit HTTP Requests
3127 * This function could run multi-requests in parallel.
3129 * @param array $requests An array of files to request
3130 * @param array $options An array of options to set
3131 * @return array An array of results
3133 protected function multi($requests, $options = array()) {
3134 $count = count($requests);
3135 $handles = array();
3136 $results = array();
3137 $main = curl_multi_init();
3138 for ($i = 0; $i < $count; $i++) {
3139 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3140 // open file
3141 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3142 $requests[$i]['auto-handle'] = true;
3144 foreach($requests[$i] as $n=>$v){
3145 $options[$n] = $v;
3147 $handles[$i] = curl_init($requests[$i]['url']);
3148 $this->apply_opt($handles[$i], $options);
3149 curl_multi_add_handle($main, $handles[$i]);
3151 $running = 0;
3152 do {
3153 curl_multi_exec($main, $running);
3154 } while($running > 0);
3155 for ($i = 0; $i < $count; $i++) {
3156 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3157 $results[] = true;
3158 } else {
3159 $results[] = curl_multi_getcontent($handles[$i]);
3161 curl_multi_remove_handle($main, $handles[$i]);
3163 curl_multi_close($main);
3165 for ($i = 0; $i < $count; $i++) {
3166 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3167 // close file handler if file is opened in this function
3168 fclose($requests[$i]['file']);
3171 return $results;
3175 * Single HTTP Request
3177 * @param string $url The URL to request
3178 * @param array $options
3179 * @return bool
3181 protected function request($url, $options = array()){
3182 // create curl instance
3183 $curl = curl_init($url);
3184 $options['url'] = $url;
3185 $this->apply_opt($curl, $options);
3186 if ($this->cache && $ret = $this->cache->get($this->options)) {
3187 return $ret;
3188 } else {
3189 $ret = curl_exec($curl);
3190 if ($this->cache) {
3191 $this->cache->set($this->options, $ret);
3195 $this->info = curl_getinfo($curl);
3196 $this->error = curl_error($curl);
3197 $this->errno = curl_errno($curl);
3199 if ($this->debug){
3200 echo '<h1>Return Data</h1>';
3201 var_dump($ret);
3202 echo '<h1>Info</h1>';
3203 var_dump($this->info);
3204 echo '<h1>Error</h1>';
3205 var_dump($this->error);
3208 curl_close($curl);
3210 if (empty($this->error)){
3211 return $ret;
3212 } else {
3213 return $this->error;
3214 // exception is not ajax friendly
3215 //throw new moodle_exception($this->error, 'curl');
3220 * HTTP HEAD method
3222 * @see request()
3224 * @param string $url
3225 * @param array $options
3226 * @return bool
3228 public function head($url, $options = array()){
3229 $options['CURLOPT_HTTPGET'] = 0;
3230 $options['CURLOPT_HEADER'] = 1;
3231 $options['CURLOPT_NOBODY'] = 1;
3232 return $this->request($url, $options);
3236 * HTTP POST method
3238 * @param string $url
3239 * @param array|string $params
3240 * @param array $options
3241 * @return bool
3243 public function post($url, $params = '', $options = array()){
3244 $options['CURLOPT_POST'] = 1;
3245 if (is_array($params)) {
3246 $this->_tmp_file_post_params = array();
3247 foreach ($params as $key => $value) {
3248 if ($value instanceof stored_file) {
3249 $value->add_to_curl_request($this, $key);
3250 } else {
3251 $this->_tmp_file_post_params[$key] = $value;
3254 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3255 unset($this->_tmp_file_post_params);
3256 } else {
3257 // $params is the raw post data
3258 $options['CURLOPT_POSTFIELDS'] = $params;
3260 return $this->request($url, $options);
3264 * HTTP GET method
3266 * @param string $url
3267 * @param array $params
3268 * @param array $options
3269 * @return bool
3271 public function get($url, $params = array(), $options = array()){
3272 $options['CURLOPT_HTTPGET'] = 1;
3274 if (!empty($params)){
3275 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3276 $url .= http_build_query($params, '', '&');
3278 return $this->request($url, $options);
3282 * Downloads one file and writes it to the specified file handler
3284 * <code>
3285 * $c = new curl();
3286 * $file = fopen('savepath', 'w');
3287 * $result = $c->download_one('http://localhost/', null,
3288 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3289 * fclose($file);
3290 * $download_info = $c->get_info();
3291 * if ($result === true) {
3292 * // file downloaded successfully
3293 * } else {
3294 * $error_text = $result;
3295 * $error_code = $c->get_errno();
3297 * </code>
3299 * <code>
3300 * $c = new curl();
3301 * $result = $c->download_one('http://localhost/', null,
3302 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3303 * // ... see above, no need to close handle and remove file if unsuccessful
3304 * </code>
3306 * @param string $url
3307 * @param array|null $params key-value pairs to be added to $url as query string
3308 * @param array $options request options. Must include either 'file' or 'filepath'
3309 * @return bool|string true on success or error string on failure
3311 public function download_one($url, $params, $options = array()) {
3312 $options['CURLOPT_HTTPGET'] = 1;
3313 $options['CURLOPT_BINARYTRANSFER'] = true;
3314 if (!empty($params)){
3315 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3316 $url .= http_build_query($params, '', '&');
3318 if (!empty($options['filepath']) && empty($options['file'])) {
3319 // open file
3320 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3321 $this->errno = 100;
3322 return get_string('cannotwritefile', 'error', $options['filepath']);
3324 $filepath = $options['filepath'];
3326 unset($options['filepath']);
3327 $result = $this->request($url, $options);
3328 if (isset($filepath)) {
3329 fclose($options['file']);
3330 if ($result !== true) {
3331 unlink($filepath);
3334 return $result;
3338 * HTTP PUT method
3340 * @param string $url
3341 * @param array $params
3342 * @param array $options
3343 * @return bool
3345 public function put($url, $params = array(), $options = array()){
3346 $file = $params['file'];
3347 if (!is_file($file)){
3348 return null;
3350 $fp = fopen($file, 'r');
3351 $size = filesize($file);
3352 $options['CURLOPT_PUT'] = 1;
3353 $options['CURLOPT_INFILESIZE'] = $size;
3354 $options['CURLOPT_INFILE'] = $fp;
3355 if (!isset($this->options['CURLOPT_USERPWD'])){
3356 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3358 $ret = $this->request($url, $options);
3359 fclose($fp);
3360 return $ret;
3364 * HTTP DELETE method
3366 * @param string $url
3367 * @param array $param
3368 * @param array $options
3369 * @return bool
3371 public function delete($url, $param = array(), $options = array()){
3372 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3373 if (!isset($options['CURLOPT_USERPWD'])) {
3374 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3376 $ret = $this->request($url, $options);
3377 return $ret;
3381 * HTTP TRACE method
3383 * @param string $url
3384 * @param array $options
3385 * @return bool
3387 public function trace($url, $options = array()){
3388 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3389 $ret = $this->request($url, $options);
3390 return $ret;
3394 * HTTP OPTIONS method
3396 * @param string $url
3397 * @param array $options
3398 * @return bool
3400 public function options($url, $options = array()){
3401 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3402 $ret = $this->request($url, $options);
3403 return $ret;
3407 * Get curl information
3409 * @return string
3411 public function get_info() {
3412 return $this->info;
3416 * Get curl error code
3418 * @return int
3420 public function get_errno() {
3421 return $this->errno;
3426 * This class is used by cURL class, use case:
3428 * <code>
3429 * $CFG->repositorycacheexpire = 120;
3430 * $CFG->curlcache = 120;
3432 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3433 * $ret = $c->get('http://www.google.com');
3434 * </code>
3436 * @package core_files
3437 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3440 class curl_cache {
3441 /** @var string Path to cache directory */
3442 public $dir = '';
3445 * Constructor
3447 * @global stdClass $CFG
3448 * @param string $module which module is using curl_cache
3450 public function __construct($module = 'repository') {
3451 global $CFG;
3452 if (!empty($module)) {
3453 $this->dir = $CFG->cachedir.'/'.$module.'/';
3454 } else {
3455 $this->dir = $CFG->cachedir.'/misc/';
3457 if (!file_exists($this->dir)) {
3458 mkdir($this->dir, $CFG->directorypermissions, true);
3460 if ($module == 'repository') {
3461 if (empty($CFG->repositorycacheexpire)) {
3462 $CFG->repositorycacheexpire = 120;
3464 $this->ttl = $CFG->repositorycacheexpire;
3465 } else {
3466 if (empty($CFG->curlcache)) {
3467 $CFG->curlcache = 120;
3469 $this->ttl = $CFG->curlcache;
3474 * Get cached value
3476 * @global stdClass $CFG
3477 * @global stdClass $USER
3478 * @param mixed $param
3479 * @return bool|string
3481 public function get($param) {
3482 global $CFG, $USER;
3483 $this->cleanup($this->ttl);
3484 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3485 if(file_exists($this->dir.$filename)) {
3486 $lasttime = filemtime($this->dir.$filename);
3487 if (time()-$lasttime > $this->ttl) {
3488 return false;
3489 } else {
3490 $fp = fopen($this->dir.$filename, 'r');
3491 $size = filesize($this->dir.$filename);
3492 $content = fread($fp, $size);
3493 return unserialize($content);
3496 return false;
3500 * Set cache value
3502 * @global object $CFG
3503 * @global object $USER
3504 * @param mixed $param
3505 * @param mixed $val
3507 public function set($param, $val) {
3508 global $CFG, $USER;
3509 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3510 $fp = fopen($this->dir.$filename, 'w');
3511 fwrite($fp, serialize($val));
3512 fclose($fp);
3516 * Remove cache files
3518 * @param int $expire The number of seconds before expiry
3520 public function cleanup($expire) {
3521 if ($dir = opendir($this->dir)) {
3522 while (false !== ($file = readdir($dir))) {
3523 if(!is_dir($file) && $file != '.' && $file != '..') {
3524 $lasttime = @filemtime($this->dir.$file);
3525 if (time() - $lasttime > $expire) {
3526 @unlink($this->dir.$file);
3530 closedir($dir);
3534 * delete current user's cache file
3536 * @global object $CFG
3537 * @global object $USER
3539 public function refresh() {
3540 global $CFG, $USER;
3541 if ($dir = opendir($this->dir)) {
3542 while (false !== ($file = readdir($dir))) {
3543 if (!is_dir($file) && $file != '.' && $file != '..') {
3544 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3545 @unlink($this->dir.$file);
3554 * This function delegates file serving to individual plugins
3556 * @param string $relativepath
3557 * @param bool $forcedownload
3558 * @param null|string $preview the preview mode, defaults to serving the original file
3559 * @todo MDL-31088 file serving improments
3561 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3562 global $DB, $CFG, $USER;
3563 // relative path must start with '/'
3564 if (!$relativepath) {
3565 print_error('invalidargorconf');
3566 } else if ($relativepath[0] != '/') {
3567 print_error('pathdoesnotstartslash');
3570 // extract relative path components
3571 $args = explode('/', ltrim($relativepath, '/'));
3573 if (count($args) < 3) { // always at least context, component and filearea
3574 print_error('invalidarguments');
3577 $contextid = (int)array_shift($args);
3578 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3579 $filearea = clean_param(array_shift($args), PARAM_AREA);
3581 list($context, $course, $cm) = get_context_info_array($contextid);
3583 $fs = get_file_storage();
3585 // ========================================================================================================================
3586 if ($component === 'blog') {
3587 // Blog file serving
3588 if ($context->contextlevel != CONTEXT_SYSTEM) {
3589 send_file_not_found();
3591 if ($filearea !== 'attachment' and $filearea !== 'post') {
3592 send_file_not_found();
3595 if (empty($CFG->enableblogs)) {
3596 print_error('siteblogdisable', 'blog');
3599 $entryid = (int)array_shift($args);
3600 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3601 send_file_not_found();
3603 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3604 require_login();
3605 if (isguestuser()) {
3606 print_error('noguest');
3608 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3609 if ($USER->id != $entry->userid) {
3610 send_file_not_found();
3615 if ($entry->publishstate === 'public') {
3616 if ($CFG->forcelogin) {
3617 require_login();
3620 } else if ($entry->publishstate === 'site') {
3621 require_login();
3622 //ok
3623 } else if ($entry->publishstate === 'draft') {
3624 require_login();
3625 if ($USER->id != $entry->userid) {
3626 send_file_not_found();
3630 $filename = array_pop($args);
3631 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3633 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3634 send_file_not_found();
3637 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3639 // ========================================================================================================================
3640 } else if ($component === 'grade') {
3641 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3642 // Global gradebook files
3643 if ($CFG->forcelogin) {
3644 require_login();
3647 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3649 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3650 send_file_not_found();
3653 session_get_instance()->write_close(); // unlock session during fileserving
3654 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3656 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3657 //TODO: nobody implemented this yet in grade edit form!!
3658 send_file_not_found();
3660 if ($CFG->forcelogin || $course->id != SITEID) {
3661 require_login($course);
3664 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3666 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3667 send_file_not_found();
3670 session_get_instance()->write_close(); // unlock session during fileserving
3671 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3672 } else {
3673 send_file_not_found();
3676 // ========================================================================================================================
3677 } else if ($component === 'tag') {
3678 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3680 // All tag descriptions are going to be public but we still need to respect forcelogin
3681 if ($CFG->forcelogin) {
3682 require_login();
3685 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3687 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3688 send_file_not_found();
3691 session_get_instance()->write_close(); // unlock session during fileserving
3692 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3694 } else {
3695 send_file_not_found();
3698 // ========================================================================================================================
3699 } else if ($component === 'calendar') {
3700 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3702 // All events here are public the one requirement is that we respect forcelogin
3703 if ($CFG->forcelogin) {
3704 require_login();
3707 // Get the event if from the args array
3708 $eventid = array_shift($args);
3710 // Load the event from the database
3711 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3712 send_file_not_found();
3715 // Get the file and serve if successful
3716 $filename = array_pop($args);
3717 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3718 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3719 send_file_not_found();
3722 session_get_instance()->write_close(); // unlock session during fileserving
3723 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3725 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3727 // Must be logged in, if they are not then they obviously can't be this user
3728 require_login();
3730 // Don't want guests here, potentially saves a DB call
3731 if (isguestuser()) {
3732 send_file_not_found();
3735 // Get the event if from the args array
3736 $eventid = array_shift($args);
3738 // Load the event from the database - user id must match
3739 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3740 send_file_not_found();
3743 // Get the file and serve if successful
3744 $filename = array_pop($args);
3745 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3746 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3747 send_file_not_found();
3750 session_get_instance()->write_close(); // unlock session during fileserving
3751 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3753 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3755 // Respect forcelogin and require login unless this is the site.... it probably
3756 // should NEVER be the site
3757 if ($CFG->forcelogin || $course->id != SITEID) {
3758 require_login($course);
3761 // Must be able to at least view the course. This does not apply to the front page.
3762 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
3763 //TODO: hmm, do we really want to block guests here?
3764 send_file_not_found();
3767 // Get the event id
3768 $eventid = array_shift($args);
3770 // Load the event from the database we need to check whether it is
3771 // a) valid course event
3772 // b) a group event
3773 // Group events use the course context (there is no group context)
3774 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3775 send_file_not_found();
3778 // If its a group event require either membership of view all groups capability
3779 if ($event->eventtype === 'group') {
3780 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3781 send_file_not_found();
3783 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
3784 // Ok. Please note that the event type 'site' still uses a course context.
3785 } else {
3786 // Some other type.
3787 send_file_not_found();
3790 // If we get this far we can serve the file
3791 $filename = array_pop($args);
3792 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3793 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3794 send_file_not_found();
3797 session_get_instance()->write_close(); // unlock session during fileserving
3798 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3800 } else {
3801 send_file_not_found();
3804 // ========================================================================================================================
3805 } else if ($component === 'user') {
3806 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3807 if (count($args) == 1) {
3808 $themename = theme_config::DEFAULT_THEME;
3809 $filename = array_shift($args);
3810 } else {
3811 $themename = array_shift($args);
3812 $filename = array_shift($args);
3815 // fix file name automatically
3816 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3817 $filename = 'f1';
3820 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3821 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3822 // protect images if login required and not logged in;
3823 // also if login is required for profile images and is not logged in or guest
3824 // do not use require_login() because it is expensive and not suitable here anyway
3825 $theme = theme_config::load($themename);
3826 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3829 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3830 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3831 if ($filename === 'f3') {
3832 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3833 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3834 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3839 if (!$file) {
3840 // bad reference - try to prevent future retries as hard as possible!
3841 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3842 if ($user->picture > 0) {
3843 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3846 // no redirect here because it is not cached
3847 $theme = theme_config::load($themename);
3848 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
3849 send_file($imagefile, basename($imagefile), 60*60*24*14);
3852 send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3854 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3855 require_login();
3857 if (isguestuser()) {
3858 send_file_not_found();
3861 if ($USER->id !== $context->instanceid) {
3862 send_file_not_found();
3865 $filename = array_pop($args);
3866 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3867 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3868 send_file_not_found();
3871 session_get_instance()->write_close(); // unlock session during fileserving
3872 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3874 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3876 if ($CFG->forcelogin) {
3877 require_login();
3880 $userid = $context->instanceid;
3882 if ($USER->id == $userid) {
3883 // always can access own
3885 } else if (!empty($CFG->forceloginforprofiles)) {
3886 require_login();
3888 if (isguestuser()) {
3889 send_file_not_found();
3892 // we allow access to site profile of all course contacts (usually teachers)
3893 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3894 send_file_not_found();
3897 $canview = false;
3898 if (has_capability('moodle/user:viewdetails', $context)) {
3899 $canview = true;
3900 } else {
3901 $courses = enrol_get_my_courses();
3904 while (!$canview && count($courses) > 0) {
3905 $course = array_shift($courses);
3906 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
3907 $canview = true;
3912 $filename = array_pop($args);
3913 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3914 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3915 send_file_not_found();
3918 session_get_instance()->write_close(); // unlock session during fileserving
3919 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3921 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3922 $userid = (int)array_shift($args);
3923 $usercontext = context_user::instance($userid);
3925 if ($CFG->forcelogin) {
3926 require_login();
3929 if (!empty($CFG->forceloginforprofiles)) {
3930 require_login();
3931 if (isguestuser()) {
3932 print_error('noguest');
3935 //TODO: review this logic of user profile access prevention
3936 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3937 print_error('usernotavailable');
3939 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3940 print_error('cannotviewprofile');
3942 if (!is_enrolled($context, $userid)) {
3943 print_error('notenrolledprofile');
3945 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3946 print_error('groupnotamember');
3950 $filename = array_pop($args);
3951 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3952 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3953 send_file_not_found();
3956 session_get_instance()->write_close(); // unlock session during fileserving
3957 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3959 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3960 require_login();
3962 if (isguestuser()) {
3963 send_file_not_found();
3965 $userid = $context->instanceid;
3967 if ($USER->id != $userid) {
3968 send_file_not_found();
3971 $filename = array_pop($args);
3972 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3973 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3974 send_file_not_found();
3977 session_get_instance()->write_close(); // unlock session during fileserving
3978 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3980 } else {
3981 send_file_not_found();
3984 // ========================================================================================================================
3985 } else if ($component === 'coursecat') {
3986 if ($context->contextlevel != CONTEXT_COURSECAT) {
3987 send_file_not_found();
3990 if ($filearea === 'description') {
3991 if ($CFG->forcelogin) {
3992 // no login necessary - unless login forced everywhere
3993 require_login();
3996 $filename = array_pop($args);
3997 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3998 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3999 send_file_not_found();
4002 session_get_instance()->write_close(); // unlock session during fileserving
4003 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4004 } else {
4005 send_file_not_found();
4008 // ========================================================================================================================
4009 } else if ($component === 'course') {
4010 if ($context->contextlevel != CONTEXT_COURSE) {
4011 send_file_not_found();
4014 if ($filearea === 'summary') {
4015 if ($CFG->forcelogin) {
4016 require_login();
4019 $filename = array_pop($args);
4020 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4021 if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
4022 send_file_not_found();
4025 session_get_instance()->write_close(); // unlock session during fileserving
4026 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4028 } else if ($filearea === 'section') {
4029 if ($CFG->forcelogin) {
4030 require_login($course);
4031 } else if ($course->id != SITEID) {
4032 require_login($course);
4035 $sectionid = (int)array_shift($args);
4037 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4038 send_file_not_found();
4041 $filename = array_pop($args);
4042 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4043 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4044 send_file_not_found();
4047 session_get_instance()->write_close(); // unlock session during fileserving
4048 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4050 } else {
4051 send_file_not_found();
4054 } else if ($component === 'group') {
4055 if ($context->contextlevel != CONTEXT_COURSE) {
4056 send_file_not_found();
4059 require_course_login($course, true, null, false);
4061 $groupid = (int)array_shift($args);
4063 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4064 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4065 // do not allow access to separate group info if not member or teacher
4066 send_file_not_found();
4069 if ($filearea === 'description') {
4071 require_login($course);
4073 $filename = array_pop($args);
4074 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4075 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4076 send_file_not_found();
4079 session_get_instance()->write_close(); // unlock session during fileserving
4080 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4082 } else if ($filearea === 'icon') {
4083 $filename = array_pop($args);
4085 if ($filename !== 'f1' and $filename !== 'f2') {
4086 send_file_not_found();
4088 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4089 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4090 send_file_not_found();
4094 session_get_instance()->write_close(); // unlock session during fileserving
4095 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4097 } else {
4098 send_file_not_found();
4101 } else if ($component === 'grouping') {
4102 if ($context->contextlevel != CONTEXT_COURSE) {
4103 send_file_not_found();
4106 require_login($course);
4108 $groupingid = (int)array_shift($args);
4110 // note: everybody has access to grouping desc images for now
4111 if ($filearea === 'description') {
4113 $filename = array_pop($args);
4114 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4115 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4116 send_file_not_found();
4119 session_get_instance()->write_close(); // unlock session during fileserving
4120 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4122 } else {
4123 send_file_not_found();
4126 // ========================================================================================================================
4127 } else if ($component === 'backup') {
4128 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4129 require_login($course);
4130 require_capability('moodle/backup:downloadfile', $context);
4132 $filename = array_pop($args);
4133 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4134 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4135 send_file_not_found();
4138 session_get_instance()->write_close(); // unlock session during fileserving
4139 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4141 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4142 require_login($course);
4143 require_capability('moodle/backup:downloadfile', $context);
4145 $sectionid = (int)array_shift($args);
4147 $filename = array_pop($args);
4148 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4149 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4150 send_file_not_found();
4153 session_get_instance()->write_close();
4154 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4156 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4157 require_login($course, false, $cm);
4158 require_capability('moodle/backup:downloadfile', $context);
4160 $filename = array_pop($args);
4161 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4162 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4163 send_file_not_found();
4166 session_get_instance()->write_close();
4167 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4169 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4170 // Backup files that were generated by the automated backup systems.
4172 require_login($course);
4173 require_capability('moodle/site:config', $context);
4175 $filename = array_pop($args);
4176 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4177 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4178 send_file_not_found();
4181 session_get_instance()->write_close(); // unlock session during fileserving
4182 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4184 } else {
4185 send_file_not_found();
4188 // ========================================================================================================================
4189 } else if ($component === 'question') {
4190 require_once($CFG->libdir . '/questionlib.php');
4191 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4192 send_file_not_found();
4194 // ========================================================================================================================
4195 } else if ($component === 'grading') {
4196 if ($filearea === 'description') {
4197 // files embedded into the form definition description
4199 if ($context->contextlevel == CONTEXT_SYSTEM) {
4200 require_login();
4202 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4203 require_login($course, false, $cm);
4205 } else {
4206 send_file_not_found();
4209 $formid = (int)array_shift($args);
4211 $sql = "SELECT ga.id
4212 FROM {grading_areas} ga
4213 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4214 WHERE gd.id = ? AND ga.contextid = ?";
4215 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4217 if (!$areaid) {
4218 send_file_not_found();
4221 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4223 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4224 send_file_not_found();
4227 session_get_instance()->write_close(); // unlock session during fileserving
4228 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4231 // ========================================================================================================================
4232 } else if (strpos($component, 'mod_') === 0) {
4233 $modname = substr($component, 4);
4234 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4235 send_file_not_found();
4237 require_once("$CFG->dirroot/mod/$modname/lib.php");
4239 if ($context->contextlevel == CONTEXT_MODULE) {
4240 if ($cm->modname !== $modname) {
4241 // somebody tries to gain illegal access, cm type must match the component!
4242 send_file_not_found();
4246 if ($filearea === 'intro') {
4247 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4248 send_file_not_found();
4250 require_course_login($course, true, $cm);
4252 // all users may access it
4253 $filename = array_pop($args);
4254 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4255 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4256 send_file_not_found();
4259 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4261 // finally send the file
4262 send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4265 $filefunction = $component.'_pluginfile';
4266 $filefunctionold = $modname.'_pluginfile';
4267 if (function_exists($filefunction)) {
4268 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4269 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4270 } else if (function_exists($filefunctionold)) {
4271 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4272 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4275 send_file_not_found();
4277 // ========================================================================================================================
4278 } else if (strpos($component, 'block_') === 0) {
4279 $blockname = substr($component, 6);
4280 // note: no more class methods in blocks please, that is ....
4281 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4282 send_file_not_found();
4284 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4286 if ($context->contextlevel == CONTEXT_BLOCK) {
4287 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4288 if ($birecord->blockname !== $blockname) {
4289 // somebody tries to gain illegal access, cm type must match the component!
4290 send_file_not_found();
4293 $bprecord = $DB->get_record('block_positions', array('blockinstanceid' => $context->instanceid), 'visible');
4294 // User can't access file, if block is hidden or doesn't have block:view capability
4295 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4296 send_file_not_found();
4298 } else {
4299 $birecord = null;
4302 $filefunction = $component.'_pluginfile';
4303 if (function_exists($filefunction)) {
4304 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4305 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4308 send_file_not_found();
4310 // ========================================================================================================================
4311 } else if (strpos($component, '_') === false) {
4312 // all core subsystems have to be specified above, no more guessing here!
4313 send_file_not_found();
4315 } else {
4316 // try to serve general plugin file in arbitrary context
4317 $dir = get_component_directory($component);
4318 if (!file_exists("$dir/lib.php")) {
4319 send_file_not_found();
4321 include_once("$dir/lib.php");
4323 $filefunction = $component.'_pluginfile';
4324 if (function_exists($filefunction)) {
4325 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4326 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4329 send_file_not_found();