MDL-35991 - use PARAM_LOCALURL for local urls
[moodle.git] / lib / filelib.php
blobab120b3959369a977c834e6525773058e72fdf29
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 * @return array with the following entries:
467 * 'filecount' => number of files in the draft area.
468 * (more information will be added as needed).
470 function file_get_draft_area_info($draftitemid) {
471 global $CFG, $USER;
473 $usercontext = context_user::instance($USER->id);
474 $fs = get_file_storage();
476 $results = array();
478 // The number of files
479 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
480 $results['filecount'] = count($draftfiles);
481 $results['filesize'] = 0;
482 foreach ($draftfiles as $file) {
483 $results['filesize'] += $file->get_filesize();
486 return $results;
490 * Returns whether a draft area has exceeded/will exceed its size limit.
492 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
494 * @param int $draftitemid the draft area item id.
495 * @param int $areamaxbytes the maximum size allowed in this draft area.
496 * @param int $newfilesize the size that would be added to the current area.
497 * @return bool true if the area will/has exceeded its limit.
498 * @since 2.4
500 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0) {
501 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
502 $draftinfo = file_get_draft_area_info($draftitemid);
503 if ($draftinfo['filesize'] + $newfilesize > $areamaxbytes) {
504 return true;
507 return false;
511 * Get used space of files
512 * @global moodle_database $DB
513 * @global stdClass $USER
514 * @return int total bytes
516 function file_get_user_used_space() {
517 global $DB, $USER;
519 $usercontext = context_user::instance($USER->id);
520 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
521 JOIN (SELECT contenthash, filename, MAX(id) AS id
522 FROM {files}
523 WHERE contextid = ? AND component = ? AND filearea != ?
524 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
525 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
526 $record = $DB->get_record_sql($sql, $params);
527 return (int)$record->totalbytes;
531 * Convert any string to a valid filepath
532 * @todo review this function
533 * @param string $str
534 * @return string path
536 function file_correct_filepath($str) { //TODO: what is this? (skodak)
537 if ($str == '/' or empty($str)) {
538 return '/';
539 } else {
540 return '/'.trim($str, './@#$ ').'/';
545 * Generate a folder tree of draft area of current USER recursively
547 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
548 * @param int $draftitemid
549 * @param string $filepath
550 * @param mixed $data
552 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
553 global $USER, $OUTPUT, $CFG;
554 $data->children = array();
555 $context = context_user::instance($USER->id);
556 $fs = get_file_storage();
557 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
558 foreach ($files as $file) {
559 if ($file->is_directory()) {
560 $item = new stdClass();
561 $item->sortorder = $file->get_sortorder();
562 $item->filepath = $file->get_filepath();
564 $foldername = explode('/', trim($item->filepath, '/'));
565 $item->fullname = trim(array_pop($foldername), '/');
567 $item->id = uniqid();
568 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
569 $data->children[] = $item;
570 } else {
571 continue;
578 * Listing all files (including folders) in current path (draft area)
579 * used by file manager
580 * @param int $draftitemid
581 * @param string $filepath
582 * @return stdClass
584 function file_get_drafarea_files($draftitemid, $filepath = '/') {
585 global $USER, $OUTPUT, $CFG;
587 $context = context_user::instance($USER->id);
588 $fs = get_file_storage();
590 $data = new stdClass();
591 $data->path = array();
592 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
594 // will be used to build breadcrumb
595 $trail = '/';
596 if ($filepath !== '/') {
597 $filepath = file_correct_filepath($filepath);
598 $parts = explode('/', $filepath);
599 foreach ($parts as $part) {
600 if ($part != '' && $part != null) {
601 $trail .= ($part.'/');
602 $data->path[] = array('name'=>$part, 'path'=>$trail);
607 $list = array();
608 $maxlength = 12;
609 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
610 foreach ($files as $file) {
611 $item = new stdClass();
612 $item->filename = $file->get_filename();
613 $item->filepath = $file->get_filepath();
614 $item->fullname = trim($item->filename, '/');
615 $filesize = $file->get_filesize();
616 $item->size = $filesize ? $filesize : null;
617 $item->filesize = $filesize ? display_size($filesize) : '';
619 $item->sortorder = $file->get_sortorder();
620 $item->author = $file->get_author();
621 $item->license = $file->get_license();
622 $item->datemodified = $file->get_timemodified();
623 $item->datecreated = $file->get_timecreated();
624 $item->isref = $file->is_external_file();
625 if ($item->isref && $file->get_status() == 666) {
626 $item->originalmissing = true;
628 // find the file this draft file was created from and count all references in local
629 // system pointing to that file
630 $source = @unserialize($file->get_source());
631 if (isset($source->original)) {
632 $item->refcount = $fs->search_references_count($source->original);
635 if ($file->is_directory()) {
636 $item->filesize = 0;
637 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
638 $item->type = 'folder';
639 $foldername = explode('/', trim($item->filepath, '/'));
640 $item->fullname = trim(array_pop($foldername), '/');
641 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
642 } else {
643 // do NOT use file browser here!
644 $item->mimetype = get_mimetype_description($file);
645 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
646 $item->type = 'zip';
647 } else {
648 $item->type = 'file';
650 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
651 $item->url = $itemurl->out();
652 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
653 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
654 if ($imageinfo = $file->get_imageinfo()) {
655 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
656 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
657 $item->image_width = $imageinfo['width'];
658 $item->image_height = $imageinfo['height'];
661 $list[] = $item;
664 $data->itemid = $draftitemid;
665 $data->list = $list;
666 return $data;
670 * Returns draft area itemid for a given element.
672 * @category files
673 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
674 * @return int the itemid, or 0 if there is not one yet.
676 function file_get_submitted_draft_itemid($elname) {
677 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
678 if (!isset($_REQUEST[$elname])) {
679 return 0;
681 if (is_array($_REQUEST[$elname])) {
682 $param = optional_param_array($elname, 0, PARAM_INT);
683 if (!empty($param['itemid'])) {
684 $param = $param['itemid'];
685 } else {
686 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
687 return false;
690 } else {
691 $param = optional_param($elname, 0, PARAM_INT);
694 if ($param) {
695 require_sesskey();
698 return $param;
702 * Restore the original source field from draft files
704 * @param stored_file $storedfile This only works with draft files
705 * @return stored_file
707 function file_restore_source_field_from_draft_file($storedfile) {
708 $source = @unserialize($storedfile->get_source());
709 if (!empty($source)) {
710 if (is_object($source)) {
711 $restoredsource = $source->source;
712 $storedfile->set_source($restoredsource);
713 } else {
714 throw new moodle_exception('invalidsourcefield', 'error');
717 return $storedfile;
720 * Saves files from a draft file area to a real one (merging the list of files).
721 * Can rewrite URLs in some content at the same time if desired.
723 * @category files
724 * @global stdClass $USER
725 * @param int $draftitemid the id of the draft area to use. Normally obtained
726 * from file_get_submitted_draft_itemid('elementname') or similar.
727 * @param int $contextid This parameter and the next two identify the file area to save to.
728 * @param string $component
729 * @param string $filearea indentifies the file area.
730 * @param int $itemid helps identifies the file area.
731 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
732 * @param string $text some html content that needs to have embedded links rewritten
733 * to the @@PLUGINFILE@@ form for saving in the database.
734 * @param bool $forcehttps force https urls.
735 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
737 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
738 global $USER;
740 $usercontext = context_user::instance($USER->id);
741 $fs = get_file_storage();
743 $options = (array)$options;
744 if (!isset($options['subdirs'])) {
745 $options['subdirs'] = false;
747 if (!isset($options['maxfiles'])) {
748 $options['maxfiles'] = -1; // unlimited
750 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
751 $options['maxbytes'] = 0; // unlimited
753 if (!isset($options['areamaxbytes'])) {
754 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
756 $allowreferences = true;
757 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
758 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
759 // this is not exactly right. BUT there are many places in code where filemanager options
760 // are not passed to file_save_draft_area_files()
761 $allowreferences = false;
764 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
765 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
766 // anything at all in the next area.
767 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
768 return null;
771 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
772 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
774 if (count($draftfiles) < 2) {
775 // means there are no files - one file means root dir only ;-)
776 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
778 } else if (count($oldfiles) < 2) {
779 $filecount = 0;
780 // there were no files before - one file means root dir only ;-)
781 foreach ($draftfiles as $file) {
782 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
783 if (!$options['subdirs']) {
784 if ($file->get_filepath() !== '/' or $file->is_directory()) {
785 continue;
788 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
789 // oversized file - should not get here at all
790 continue;
792 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
793 // more files - should not get here at all
794 break;
796 if (!$file->is_directory()) {
797 $filecount++;
800 if ($file->is_external_file()) {
801 if (!$allowreferences) {
802 continue;
804 $repoid = $file->get_repository_id();
805 if (!empty($repoid)) {
806 $file_record['repositoryid'] = $repoid;
807 $file_record['reference'] = $file->get_reference();
810 file_restore_source_field_from_draft_file($file);
812 $fs->create_file_from_storedfile($file_record, $file);
815 } else {
816 // we have to merge old and new files - we want to keep file ids for files that were not changed
817 // we change time modified for all new and changed files, we keep time created as is
819 $newhashes = array();
820 foreach ($draftfiles as $file) {
821 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
822 file_restore_source_field_from_draft_file($file);
823 $newhashes[$newhash] = $file;
825 $filecount = 0;
826 foreach ($oldfiles as $oldfile) {
827 $oldhash = $oldfile->get_pathnamehash();
828 if (!isset($newhashes[$oldhash])) {
829 // delete files not needed any more - deleted by user
830 $oldfile->delete();
831 continue;
834 $newfile = $newhashes[$oldhash];
835 // status changed, we delete old file, and create a new one
836 if ($oldfile->get_status() != $newfile->get_status()) {
837 // file was changed, use updated with new timemodified data
838 $oldfile->delete();
839 // This file will be added later
840 continue;
843 // Updated author
844 if ($oldfile->get_author() != $newfile->get_author()) {
845 $oldfile->set_author($newfile->get_author());
847 // Updated license
848 if ($oldfile->get_license() != $newfile->get_license()) {
849 $oldfile->set_license($newfile->get_license());
852 // Updated file source
853 if ($oldfile->get_source() != $newfile->get_source()) {
854 $oldfile->set_source($newfile->get_source());
857 // Updated sort order
858 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
859 $oldfile->set_sortorder($newfile->get_sortorder());
862 // Update file timemodified
863 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
864 $oldfile->set_timemodified($newfile->get_timemodified());
867 // Replaced file content
868 if ($oldfile->get_contenthash() != $newfile->get_contenthash() || $oldfile->get_filesize() != $newfile->get_filesize()) {
869 $oldfile->replace_content_with($newfile);
870 // push changes to all local files that are referencing this file
871 $fs->update_references_to_storedfile($oldfile);
874 // unchanged file or directory - we keep it as is
875 unset($newhashes[$oldhash]);
876 if (!$oldfile->is_directory()) {
877 $filecount++;
881 // Add fresh file or the file which has changed status
882 // the size and subdirectory tests are extra safety only, the UI should prevent it
883 foreach ($newhashes as $file) {
884 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
885 if (!$options['subdirs']) {
886 if ($file->get_filepath() !== '/' or $file->is_directory()) {
887 continue;
890 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
891 // oversized file - should not get here at all
892 continue;
894 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
895 // more files - should not get here at all
896 break;
898 if (!$file->is_directory()) {
899 $filecount++;
902 if ($file->is_external_file()) {
903 if (!$allowreferences) {
904 continue;
906 $repoid = $file->get_repository_id();
907 if (!empty($repoid)) {
908 $file_record['repositoryid'] = $repoid;
909 $file_record['reference'] = $file->get_reference();
913 $fs->create_file_from_storedfile($file_record, $file);
917 // note: do not purge the draft area - we clean up areas later in cron,
918 // the reason is that user might press submit twice and they would loose the files,
919 // also sometimes we might want to use hacks that save files into two different areas
921 if (is_null($text)) {
922 return null;
923 } else {
924 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
929 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
930 * ready to be saved in the database. Normally, this is done automatically by
931 * {@link file_save_draft_area_files()}.
933 * @category files
934 * @param string $text the content to process.
935 * @param int $draftitemid the draft file area the content was using.
936 * @param bool $forcehttps whether the content contains https URLs. Default false.
937 * @return string the processed content.
939 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
940 global $CFG, $USER;
942 $usercontext = context_user::instance($USER->id);
944 $wwwroot = $CFG->wwwroot;
945 if ($forcehttps) {
946 $wwwroot = str_replace('http://', 'https://', $wwwroot);
949 // relink embedded files if text submitted - no absolute links allowed in database!
950 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
952 if (strpos($text, 'draftfile.php?file=') !== false) {
953 $matches = array();
954 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
955 if ($matches) {
956 foreach ($matches[0] as $match) {
957 $replace = str_ireplace('%2F', '/', $match);
958 $text = str_replace($match, $replace, $text);
961 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
964 return $text;
968 * Set file sort order
970 * @global moodle_database $DB
971 * @param int $contextid the context id
972 * @param string $component file component
973 * @param string $filearea file area.
974 * @param int $itemid itemid.
975 * @param string $filepath file path.
976 * @param string $filename file name.
977 * @param int $sortorder the sort order of file.
978 * @return bool
980 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
981 global $DB;
982 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
983 if ($file_record = $DB->get_record('files', $conditions)) {
984 $sortorder = (int)$sortorder;
985 $file_record->sortorder = $sortorder;
986 $DB->update_record('files', $file_record);
987 return true;
989 return false;
993 * reset file sort order number to 0
994 * @global moodle_database $DB
995 * @param int $contextid the context id
996 * @param string $component
997 * @param string $filearea file area.
998 * @param int|bool $itemid itemid.
999 * @return bool
1001 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1002 global $DB;
1004 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1005 if ($itemid !== false) {
1006 $conditions['itemid'] = $itemid;
1009 $file_records = $DB->get_records('files', $conditions);
1010 foreach ($file_records as $file_record) {
1011 $file_record->sortorder = 0;
1012 $DB->update_record('files', $file_record);
1014 return true;
1018 * Returns description of upload error
1020 * @param int $errorcode found in $_FILES['filename.ext']['error']
1021 * @return string error description string, '' if ok
1023 function file_get_upload_error($errorcode) {
1025 switch ($errorcode) {
1026 case 0: // UPLOAD_ERR_OK - no error
1027 $errmessage = '';
1028 break;
1030 case 1: // UPLOAD_ERR_INI_SIZE
1031 $errmessage = get_string('uploadserverlimit');
1032 break;
1034 case 2: // UPLOAD_ERR_FORM_SIZE
1035 $errmessage = get_string('uploadformlimit');
1036 break;
1038 case 3: // UPLOAD_ERR_PARTIAL
1039 $errmessage = get_string('uploadpartialfile');
1040 break;
1042 case 4: // UPLOAD_ERR_NO_FILE
1043 $errmessage = get_string('uploadnofilefound');
1044 break;
1046 // Note: there is no error with a value of 5
1048 case 6: // UPLOAD_ERR_NO_TMP_DIR
1049 $errmessage = get_string('uploadnotempdir');
1050 break;
1052 case 7: // UPLOAD_ERR_CANT_WRITE
1053 $errmessage = get_string('uploadcantwrite');
1054 break;
1056 case 8: // UPLOAD_ERR_EXTENSION
1057 $errmessage = get_string('uploadextension');
1058 break;
1060 default:
1061 $errmessage = get_string('uploadproblem');
1064 return $errmessage;
1068 * Recursive function formating an array in POST parameter
1069 * @param array $arraydata - the array that we are going to format and add into &$data array
1070 * @param string $currentdata - a row of the final postdata array at instant T
1071 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1072 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1074 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1075 foreach ($arraydata as $k=>$v) {
1076 $newcurrentdata = $currentdata;
1077 if (is_array($v)) { //the value is an array, call the function recursively
1078 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1079 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1080 } else { //add the POST parameter to the $data array
1081 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1087 * Transform a PHP array into POST parameter
1088 * (see the recursive function format_array_postdata_for_curlcall)
1089 * @param array $postdata
1090 * @return array containing all POST parameters (1 row = 1 POST parameter)
1092 function format_postdata_for_curlcall($postdata) {
1093 $data = array();
1094 foreach ($postdata as $k=>$v) {
1095 if (is_array($v)) {
1096 $currentdata = urlencode($k);
1097 format_array_postdata_for_curlcall($v, $currentdata, $data);
1098 } else {
1099 $data[] = urlencode($k).'='.urlencode($v);
1102 $convertedpostdata = implode('&', $data);
1103 return $convertedpostdata;
1107 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1108 * Due to security concerns only downloads from http(s) sources are supported.
1110 * @todo MDL-31073 add version test for '7.10.5'
1111 * @category files
1112 * @param string $url file url starting with http(s)://
1113 * @param array $headers http headers, null if none. If set, should be an
1114 * associative array of header name => value pairs.
1115 * @param array $postdata array means use POST request with given parameters
1116 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1117 * (if false, just returns content)
1118 * @param int $timeout timeout for complete download process including all file transfer
1119 * (default 5 minutes)
1120 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1121 * usually happens if the remote server is completely down (default 20 seconds);
1122 * may not work when using proxy
1123 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1124 * Only use this when already in a trusted location.
1125 * @param string $tofile store the downloaded content to file instead of returning it.
1126 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1127 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1128 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1130 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1131 global $CFG;
1133 // some extra security
1134 $newlines = array("\r", "\n");
1135 if (is_array($headers) ) {
1136 foreach ($headers as $key => $value) {
1137 $headers[$key] = str_replace($newlines, '', $value);
1140 $url = str_replace($newlines, '', $url);
1141 if (!preg_match('|^https?://|i', $url)) {
1142 if ($fullresponse) {
1143 $response = new stdClass();
1144 $response->status = 0;
1145 $response->headers = array();
1146 $response->response_code = 'Invalid protocol specified in url';
1147 $response->results = '';
1148 $response->error = 'Invalid protocol specified in url';
1149 return $response;
1150 } else {
1151 return false;
1155 // check if proxy (if used) should be bypassed for this url
1156 $proxybypass = is_proxybypass($url);
1158 if (!$ch = curl_init($url)) {
1159 debugging('Can not init curl.');
1160 return false;
1163 // set extra headers
1164 if (is_array($headers) ) {
1165 $headers2 = array();
1166 foreach ($headers as $key => $value) {
1167 $headers2[] = "$key: $value";
1169 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1172 if ($skipcertverify) {
1173 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1176 // use POST if requested
1177 if (is_array($postdata)) {
1178 $postdata = format_postdata_for_curlcall($postdata);
1179 curl_setopt($ch, CURLOPT_POST, true);
1180 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1183 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1184 curl_setopt($ch, CURLOPT_HEADER, false);
1185 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1187 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1188 // TODO: add version test for '7.10.5'
1189 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1190 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1193 if (!empty($CFG->proxyhost) and !$proxybypass) {
1194 // SOCKS supported in PHP5 only
1195 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1196 if (defined('CURLPROXY_SOCKS5')) {
1197 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1198 } else {
1199 curl_close($ch);
1200 if ($fullresponse) {
1201 $response = new stdClass();
1202 $response->status = '0';
1203 $response->headers = array();
1204 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1205 $response->results = '';
1206 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1207 return $response;
1208 } else {
1209 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1210 return false;
1215 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1217 if (empty($CFG->proxyport)) {
1218 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1219 } else {
1220 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1223 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1224 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1225 if (defined('CURLOPT_PROXYAUTH')) {
1226 // any proxy authentication if PHP 5.1
1227 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1232 // set up header and content handlers
1233 $received = new stdClass();
1234 $received->headers = array(); // received headers array
1235 $received->tofile = $tofile;
1236 $received->fh = null;
1237 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1238 if ($tofile) {
1239 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1242 if (!isset($CFG->curltimeoutkbitrate)) {
1243 //use very slow rate of 56kbps as a timeout speed when not set
1244 $bitrate = 56;
1245 } else {
1246 $bitrate = $CFG->curltimeoutkbitrate;
1249 // try to calculate the proper amount for timeout from remote file size.
1250 // if disabled or zero, we won't do any checks nor head requests.
1251 if ($calctimeout && $bitrate > 0) {
1252 //setup header request only options
1253 curl_setopt_array ($ch, array(
1254 CURLOPT_RETURNTRANSFER => false,
1255 CURLOPT_NOBODY => true)
1258 curl_exec($ch);
1259 $info = curl_getinfo($ch);
1260 $err = curl_error($ch);
1262 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1263 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1265 //reinstate affected curl options
1266 curl_setopt_array ($ch, array(
1267 CURLOPT_RETURNTRANSFER => true,
1268 CURLOPT_NOBODY => false)
1272 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1273 $result = curl_exec($ch);
1275 // try to detect encoding problems
1276 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1277 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1278 $result = curl_exec($ch);
1281 if ($received->fh) {
1282 fclose($received->fh);
1285 if (curl_errno($ch)) {
1286 $error = curl_error($ch);
1287 $error_no = curl_errno($ch);
1288 curl_close($ch);
1290 if ($fullresponse) {
1291 $response = new stdClass();
1292 if ($error_no == 28) {
1293 $response->status = '-100'; // mimic snoopy
1294 } else {
1295 $response->status = '0';
1297 $response->headers = array();
1298 $response->response_code = $error;
1299 $response->results = false;
1300 $response->error = $error;
1301 return $response;
1302 } else {
1303 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1304 return false;
1307 } else {
1308 $info = curl_getinfo($ch);
1309 curl_close($ch);
1311 if (empty($info['http_code'])) {
1312 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1313 $response = new stdClass();
1314 $response->status = '0';
1315 $response->headers = array();
1316 $response->response_code = 'Unknown cURL error';
1317 $response->results = false; // do NOT change this, we really want to ignore the result!
1318 $response->error = 'Unknown cURL error';
1320 } else {
1321 $response = new stdClass();;
1322 $response->status = (string)$info['http_code'];
1323 $response->headers = $received->headers;
1324 $response->response_code = $received->headers[0];
1325 $response->results = $result;
1326 $response->error = '';
1329 if ($fullresponse) {
1330 return $response;
1331 } else if ($info['http_code'] != 200) {
1332 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1333 return false;
1334 } else {
1335 return $response->results;
1341 * internal implementation
1342 * @param stdClass $received
1343 * @param resource $ch
1344 * @param mixed $header
1345 * @return int header length
1347 function download_file_content_header_handler($received, $ch, $header) {
1348 $received->headers[] = $header;
1349 return strlen($header);
1353 * internal implementation
1354 * @param stdClass $received
1355 * @param resource $ch
1356 * @param mixed $data
1358 function download_file_content_write_handler($received, $ch, $data) {
1359 if (!$received->fh) {
1360 $received->fh = fopen($received->tofile, 'w');
1361 if ($received->fh === false) {
1362 // bad luck, file creation or overriding failed
1363 return 0;
1366 if (fwrite($received->fh, $data) === false) {
1367 // bad luck, write failed, let's abort completely
1368 return 0;
1370 return strlen($data);
1374 * Returns a list of information about file types based on extensions.
1376 * The following elements expected in value array for each extension:
1377 * 'type' - mimetype
1378 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1379 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1380 * also files with bigger sizes under names
1381 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1382 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1383 * commonly used in moodle the following groups:
1384 * - web_image - image that can be included as <img> in HTML
1385 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1386 * - video - file that can be imported as video in text editor
1387 * - audio - file that can be imported as audio in text editor
1388 * - archive - we can extract files from this archive
1389 * - spreadsheet - used for portfolio format
1390 * - document - used for portfolio format
1391 * - presentation - used for portfolio format
1392 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1393 * human-readable description for this filetype;
1394 * Function {@link get_mimetype_description()} first looks at the presence of string for
1395 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1396 * attribute, if not found returns the value of 'type';
1397 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1398 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1399 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1401 * @category files
1402 * @return array List of information about file types based on extensions.
1403 * Associative array of extension (lower-case) to associative array
1404 * from 'element name' to data. Current element names are 'type' and 'icon'.
1405 * Unknown types should use the 'xxx' entry which includes defaults.
1407 function &get_mimetypes_array() {
1408 static $mimearray = array (
1409 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1410 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1411 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1412 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1413 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1414 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1415 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1416 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1417 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1418 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1419 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1420 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1421 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1422 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1423 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1424 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1425 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1426 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1427 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1428 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1429 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1430 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1432 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1433 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1434 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1435 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1436 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1438 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1439 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1440 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1441 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1442 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1443 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1444 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1445 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1446 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1447 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1448 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1449 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1450 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1451 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1452 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1453 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1454 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1455 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1456 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1457 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1458 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1459 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1460 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1461 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1462 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1463 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1464 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1465 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1466 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1467 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1468 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1469 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1470 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1471 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1472 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1473 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1474 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1475 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1476 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1477 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1478 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1479 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1480 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1481 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1482 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1483 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1484 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1485 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1486 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1487 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1489 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1490 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1491 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1492 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1493 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1494 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1495 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1496 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1497 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1498 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1499 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1500 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1501 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1502 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1503 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1504 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1505 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1507 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1508 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1509 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1510 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1511 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1512 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1514 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1515 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1516 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1517 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1518 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1519 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1520 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1521 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1522 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1524 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1525 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1526 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1527 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1528 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1529 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1530 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1531 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1532 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1533 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1534 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1535 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1536 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1537 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1538 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1539 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1540 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1541 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1542 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1543 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1545 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1546 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1547 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1548 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1549 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1550 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1551 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1552 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1553 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1554 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1556 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1557 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1558 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1559 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1560 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1561 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1562 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1563 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1564 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1565 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1566 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1567 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1568 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1569 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1570 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1572 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1573 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1574 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1575 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1576 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1577 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1578 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1580 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1581 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1582 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1584 return $mimearray;
1588 * Obtains information about a filetype based on its extension. Will
1589 * use a default if no information is present about that particular
1590 * extension.
1592 * @category files
1593 * @param string $element Desired information (usually 'icon'
1594 * for icon filename or 'type' for MIME type. Can also be
1595 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1596 * @param string $filename Filename we're looking up
1597 * @return string Requested piece of information from array
1599 function mimeinfo($element, $filename) {
1600 global $CFG;
1601 $mimeinfo = & get_mimetypes_array();
1602 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1604 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1605 if (empty($filetype)) {
1606 $filetype = 'xxx'; // file without extension
1608 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1609 $iconsize = max(array(16, (int)$iconsizematch[1]));
1610 $filenames = array($mimeinfo['xxx']['icon']);
1611 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1612 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1614 // find the file with the closest size, first search for specific icon then for default icon
1615 foreach ($filenames as $filename) {
1616 foreach ($iconpostfixes as $size => $postfix) {
1617 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1618 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1619 return $filename.$postfix;
1623 } else if (isset($mimeinfo[$filetype][$element])) {
1624 return $mimeinfo[$filetype][$element];
1625 } else if (isset($mimeinfo['xxx'][$element])) {
1626 return $mimeinfo['xxx'][$element]; // By default
1627 } else {
1628 return null;
1633 * Obtains information about a filetype based on the MIME type rather than
1634 * the other way around.
1636 * @category files
1637 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1638 * @param string $mimetype MIME type we're looking up
1639 * @return string Requested piece of information from array
1641 function mimeinfo_from_type($element, $mimetype) {
1642 /* array of cached mimetype->extension associations */
1643 static $cached = array();
1644 $mimeinfo = & get_mimetypes_array();
1646 if (!array_key_exists($mimetype, $cached)) {
1647 $cached[$mimetype] = null;
1648 foreach($mimeinfo as $filetype => $values) {
1649 if ($values['type'] == $mimetype) {
1650 if ($cached[$mimetype] === null) {
1651 $cached[$mimetype] = '.'.$filetype;
1653 if (!empty($values['defaulticon'])) {
1654 $cached[$mimetype] = '.'.$filetype;
1655 break;
1659 if (empty($cached[$mimetype])) {
1660 $cached[$mimetype] = '.xxx';
1663 if ($element === 'extension') {
1664 return $cached[$mimetype];
1665 } else {
1666 return mimeinfo($element, $cached[$mimetype]);
1671 * Return the relative icon path for a given file
1673 * Usage:
1674 * <code>
1675 * // $file - instance of stored_file or file_info
1676 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1677 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1678 * </code>
1679 * or
1680 * <code>
1681 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1682 * </code>
1684 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1685 * and $file->mimetype are expected)
1686 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1687 * @return string
1689 function file_file_icon($file, $size = null) {
1690 if (!is_object($file)) {
1691 $file = (object)$file;
1693 if (isset($file->filename)) {
1694 $filename = $file->filename;
1695 } else if (method_exists($file, 'get_filename')) {
1696 $filename = $file->get_filename();
1697 } else if (method_exists($file, 'get_visible_name')) {
1698 $filename = $file->get_visible_name();
1699 } else {
1700 $filename = '';
1702 if (isset($file->mimetype)) {
1703 $mimetype = $file->mimetype;
1704 } else if (method_exists($file, 'get_mimetype')) {
1705 $mimetype = $file->get_mimetype();
1706 } else {
1707 $mimetype = '';
1709 $mimetypes = &get_mimetypes_array();
1710 if ($filename) {
1711 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1712 if ($extension && !empty($mimetypes[$extension])) {
1713 // if file name has known extension, return icon for this extension
1714 return file_extension_icon($filename, $size);
1717 return file_mimetype_icon($mimetype, $size);
1721 * Return the relative icon path for a folder image
1723 * Usage:
1724 * <code>
1725 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1726 * echo html_writer::empty_tag('img', array('src' => $icon));
1727 * </code>
1728 * or
1729 * <code>
1730 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1731 * </code>
1733 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1734 * @return string
1736 function file_folder_icon($iconsize = null) {
1737 global $CFG;
1738 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1739 static $cached = array();
1740 $iconsize = max(array(16, (int)$iconsize));
1741 if (!array_key_exists($iconsize, $cached)) {
1742 foreach ($iconpostfixes as $size => $postfix) {
1743 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1744 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1745 $cached[$iconsize] = 'f/folder'.$postfix;
1746 break;
1750 return $cached[$iconsize];
1754 * Returns the relative icon path for a given mime type
1756 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1757 * a return the full path to an icon.
1759 * <code>
1760 * $mimetype = 'image/jpg';
1761 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1762 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1763 * </code>
1765 * @category files
1766 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1767 * to conform with that.
1768 * @param string $mimetype The mimetype to fetch an icon for
1769 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1770 * @return string The relative path to the icon
1772 function file_mimetype_icon($mimetype, $size = NULL) {
1773 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1777 * Returns the relative icon path for a given file name
1779 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1780 * a return the full path to an icon.
1782 * <code>
1783 * $filename = '.jpg';
1784 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1785 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1786 * </code>
1788 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1789 * to conform with that.
1790 * @todo MDL-31074 Implement $size
1791 * @category files
1792 * @param string $filename The filename to get the icon for
1793 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1794 * @return string
1796 function file_extension_icon($filename, $size = NULL) {
1797 return 'f/'.mimeinfo('icon'.$size, $filename);
1801 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1802 * mimetypes.php language file.
1804 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1805 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1806 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1807 * @param bool $capitalise If true, capitalises first character of result
1808 * @return string Text description
1810 function get_mimetype_description($obj, $capitalise=false) {
1811 $filename = $mimetype = '';
1812 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1813 // this is an instance of stored_file
1814 $mimetype = $obj->get_mimetype();
1815 $filename = $obj->get_filename();
1816 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1817 // this is an instance of file_info
1818 $mimetype = $obj->get_mimetype();
1819 $filename = $obj->get_visible_name();
1820 } else if (is_array($obj) || is_object ($obj)) {
1821 $obj = (array)$obj;
1822 if (!empty($obj['filename'])) {
1823 $filename = $obj['filename'];
1825 if (!empty($obj['mimetype'])) {
1826 $mimetype = $obj['mimetype'];
1828 } else {
1829 $mimetype = $obj;
1831 $mimetypefromext = mimeinfo('type', $filename);
1832 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1833 // if file has a known extension, overwrite the specified mimetype
1834 $mimetype = $mimetypefromext;
1836 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1837 if (empty($extension)) {
1838 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1839 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1840 } else {
1841 $mimetypestr = mimeinfo('string', $filename);
1843 $chunks = explode('/', $mimetype, 2);
1844 $chunks[] = '';
1845 $attr = array(
1846 'mimetype' => $mimetype,
1847 'ext' => $extension,
1848 'mimetype1' => $chunks[0],
1849 'mimetype2' => $chunks[1],
1851 $a = array();
1852 foreach ($attr as $key => $value) {
1853 $a[$key] = $value;
1854 $a[strtoupper($key)] = strtoupper($value);
1855 $a[ucfirst($key)] = ucfirst($value);
1858 // MIME types may include + symbol but this is not permitted in string ids.
1859 $safemimetype = str_replace('+', '_', $mimetype);
1860 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1861 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1862 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1863 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1864 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1865 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1866 $result = get_string('default', 'mimetypes', (object)$a);
1867 } else {
1868 $result = $mimetype;
1870 if ($capitalise) {
1871 $result=ucfirst($result);
1873 return $result;
1877 * Returns array of elements of type $element in type group(s)
1879 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1880 * @param string|array $groups one group or array of groups/extensions/mimetypes
1881 * @return array
1883 function file_get_typegroup($element, $groups) {
1884 static $cached = array();
1885 if (!is_array($groups)) {
1886 $groups = array($groups);
1888 if (!array_key_exists($element, $cached)) {
1889 $cached[$element] = array();
1891 $result = array();
1892 foreach ($groups as $group) {
1893 if (!array_key_exists($group, $cached[$element])) {
1894 // retrieive and cache all elements of type $element for group $group
1895 $mimeinfo = & get_mimetypes_array();
1896 $cached[$element][$group] = array();
1897 foreach ($mimeinfo as $extension => $value) {
1898 $value['extension'] = '.'.$extension;
1899 if (empty($value[$element])) {
1900 continue;
1902 if (($group === '.'.$extension || $group === $value['type'] ||
1903 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1904 !in_array($value[$element], $cached[$element][$group])) {
1905 $cached[$element][$group][] = $value[$element];
1909 $result = array_merge($result, $cached[$element][$group]);
1911 return array_unique($result);
1915 * Checks if file with name $filename has one of the extensions in groups $groups
1917 * @see get_mimetypes_array()
1918 * @param string $filename name of the file to check
1919 * @param string|array $groups one group or array of groups to check
1920 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1921 * file mimetype is in mimetypes in groups $groups
1922 * @return bool
1924 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1925 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1926 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1927 return true;
1929 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1933 * Checks if mimetype $mimetype belongs to one of the groups $groups
1935 * @see get_mimetypes_array()
1936 * @param string $mimetype
1937 * @param string|array $groups one group or array of groups to check
1938 * @return bool
1940 function file_mimetype_in_typegroup($mimetype, $groups) {
1941 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1945 * Requested file is not found or not accessible, does not return, terminates script
1947 * @global stdClass $CFG
1948 * @global stdClass $COURSE
1950 function send_file_not_found() {
1951 global $CFG, $COURSE;
1952 send_header_404();
1953 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1956 * Helper function to send correct 404 for server.
1958 function send_header_404() {
1959 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1960 header("Status: 404 Not Found");
1961 } else {
1962 header('HTTP/1.0 404 not found');
1967 * Enhanced readfile() with optional acceleration.
1968 * @param string|stored_file $file
1969 * @param string $mimetype
1970 * @param bool $accelerate
1971 * @return void
1973 function readfile_accel($file, $mimetype, $accelerate) {
1974 global $CFG;
1976 if ($mimetype === 'text/plain') {
1977 // there is no encoding specified in text files, we need something consistent
1978 header('Content-Type: text/plain; charset=utf-8');
1979 } else {
1980 header('Content-Type: '.$mimetype);
1983 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1984 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1986 if (is_object($file)) {
1987 header('ETag: ' . $file->get_contenthash());
1988 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1989 header('HTTP/1.1 304 Not Modified');
1990 return;
1994 // if etag present for stored file rely on it exclusively
1995 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1996 // get unixtime of request header; clip extra junk off first
1997 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1998 if ($since && $since >= $lastmodified) {
1999 header('HTTP/1.1 304 Not Modified');
2000 return;
2004 if ($accelerate and !empty($CFG->xsendfile)) {
2005 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2006 header('Accept-Ranges: bytes');
2007 } else {
2008 header('Accept-Ranges: none');
2011 if (is_object($file)) {
2012 $fs = get_file_storage();
2013 if ($fs->xsendfile($file->get_contenthash())) {
2014 return;
2017 } else {
2018 require_once("$CFG->libdir/xsendfilelib.php");
2019 if (xsendfile($file)) {
2020 return;
2025 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2027 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2029 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2030 header('Accept-Ranges: bytes');
2032 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2033 // byteserving stuff - for acrobat reader and download accelerators
2034 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2035 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2036 $ranges = false;
2037 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2038 foreach ($ranges as $key=>$value) {
2039 if ($ranges[$key][1] == '') {
2040 //suffix case
2041 $ranges[$key][1] = $filesize - $ranges[$key][2];
2042 $ranges[$key][2] = $filesize - 1;
2043 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2044 //fix range length
2045 $ranges[$key][2] = $filesize - 1;
2047 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2048 //invalid byte-range ==> ignore header
2049 $ranges = false;
2050 break;
2052 //prepare multipart header
2053 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2054 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2056 } else {
2057 $ranges = false;
2059 if ($ranges) {
2060 if (is_object($file)) {
2061 $handle = $file->get_content_file_handle();
2062 } else {
2063 $handle = fopen($file, 'rb');
2065 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2068 } else {
2069 // Do not byteserve
2070 header('Accept-Ranges: none');
2073 header('Content-Length: '.$filesize);
2075 if ($filesize > 10000000) {
2076 // for large files try to flush and close all buffers to conserve memory
2077 while(@ob_get_level()) {
2078 if (!@ob_end_flush()) {
2079 break;
2084 // send the whole file content
2085 if (is_object($file)) {
2086 $file->readfile();
2087 } else {
2088 readfile($file);
2093 * Similar to readfile_accel() but designed for strings.
2094 * @param string $string
2095 * @param string $mimetype
2096 * @param bool $accelerate
2097 * @return void
2099 function readstring_accel($string, $mimetype, $accelerate) {
2100 global $CFG;
2102 if ($mimetype === 'text/plain') {
2103 // there is no encoding specified in text files, we need something consistent
2104 header('Content-Type: text/plain; charset=utf-8');
2105 } else {
2106 header('Content-Type: '.$mimetype);
2108 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2109 header('Accept-Ranges: none');
2111 if ($accelerate and !empty($CFG->xsendfile)) {
2112 $fs = get_file_storage();
2113 if ($fs->xsendfile(sha1($string))) {
2114 return;
2118 header('Content-Length: '.strlen($string));
2119 echo $string;
2123 * Handles the sending of temporary file to user, download is forced.
2124 * File is deleted after abort or successful sending, does not return, script terminated
2126 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2127 * @param string $filename proposed file name when saving file
2128 * @param bool $pathisstring If the path is string
2130 function send_temp_file($path, $filename, $pathisstring=false) {
2131 global $CFG;
2133 if (check_browser_version('Firefox', '1.5')) {
2134 // only FF is known to correctly save to disk before opening...
2135 $mimetype = mimeinfo('type', $filename);
2136 } else {
2137 $mimetype = 'application/x-forcedownload';
2140 // close session - not needed anymore
2141 session_get_instance()->write_close();
2143 if (!$pathisstring) {
2144 if (!file_exists($path)) {
2145 send_header_404();
2146 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2148 // executed after normal finish or abort
2149 @register_shutdown_function('send_temp_file_finished', $path);
2152 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2153 if (check_browser_version('MSIE')) {
2154 $filename = urlencode($filename);
2157 header('Content-Disposition: attachment; filename="'.$filename.'"');
2158 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2159 header('Cache-Control: max-age=10');
2160 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2161 header('Pragma: ');
2162 } else { //normal http - prevent caching at all cost
2163 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2164 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2165 header('Pragma: no-cache');
2168 // send the contents - we can not accelerate this because the file will be deleted asap
2169 if ($pathisstring) {
2170 readstring_accel($path, $mimetype, false);
2171 } else {
2172 readfile_accel($path, $mimetype, false);
2173 @unlink($path);
2176 die; //no more chars to output
2180 * Internal callback function used by send_temp_file()
2182 * @param string $path
2184 function send_temp_file_finished($path) {
2185 if (file_exists($path)) {
2186 @unlink($path);
2191 * Handles the sending of file data to the user's browser, including support for
2192 * byteranges etc.
2194 * @category files
2195 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2196 * @param string $filename Filename to send
2197 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2198 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2199 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2200 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2201 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2202 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2203 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2204 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2205 * and should not be reopened.
2206 * @return null script execution stopped unless $dontdie is true
2208 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2209 global $CFG, $COURSE;
2211 if ($dontdie) {
2212 ignore_user_abort(true);
2215 // MDL-11789, apply $CFG->filelifetime here
2216 if ($lifetime === 'default') {
2217 if (!empty($CFG->filelifetime)) {
2218 $lifetime = $CFG->filelifetime;
2219 } else {
2220 $lifetime = 86400;
2224 session_get_instance()->write_close(); // unlock session during fileserving
2226 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2227 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2228 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2229 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2230 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2231 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2233 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2234 if (check_browser_version('MSIE')) {
2235 $filename = rawurlencode($filename);
2238 if ($forcedownload) {
2239 header('Content-Disposition: attachment; filename="'.$filename.'"');
2240 } else {
2241 header('Content-Disposition: inline; filename="'.$filename.'"');
2244 if ($lifetime > 0) {
2245 $nobyteserving = false;
2246 header('Cache-Control: max-age='.$lifetime);
2247 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2248 header('Pragma: ');
2250 } else { // Do not cache files in proxies and browsers
2251 $nobyteserving = true;
2252 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2253 header('Cache-Control: max-age=10');
2254 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2255 header('Pragma: ');
2256 } else { //normal http - prevent caching at all cost
2257 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2258 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2259 header('Pragma: no-cache');
2263 if (empty($filter)) {
2264 // send the contents
2265 if ($pathisstring) {
2266 readstring_accel($path, $mimetype, !$dontdie);
2267 } else {
2268 readfile_accel($path, $mimetype, !$dontdie);
2271 } else {
2272 // Try to put the file through filters
2273 if ($mimetype == 'text/html') {
2274 $options = new stdClass();
2275 $options->noclean = true;
2276 $options->nocache = true; // temporary workaround for MDL-5136
2277 $text = $pathisstring ? $path : implode('', file($path));
2279 $text = file_modify_html_header($text);
2280 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2282 readstring_accel($output, $mimetype, false);
2284 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2285 // only filter text if filter all files is selected
2286 $options = new stdClass();
2287 $options->newlines = false;
2288 $options->noclean = true;
2289 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2290 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2292 readstring_accel($output, $mimetype, false);
2294 } else {
2295 // send the contents
2296 if ($pathisstring) {
2297 readstring_accel($path, $mimetype, !$dontdie);
2298 } else {
2299 readfile_accel($path, $mimetype, !$dontdie);
2303 if ($dontdie) {
2304 return;
2306 die; //no more chars to output!!!
2310 * Handles the sending of file data to the user's browser, including support for
2311 * byteranges etc.
2313 * The $options parameter supports the following keys:
2314 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2315 * (string|null) filename - overrides the implicit filename
2316 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2317 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2318 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2319 * and should not be reopened.
2321 * @category files
2322 * @param stored_file $stored_file local file object
2323 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2324 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2325 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2326 * @param array $options additional options affecting the file serving
2327 * @return null script execution stopped unless $options['dontdie'] is true
2329 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2330 global $CFG, $COURSE;
2332 if (empty($options['filename'])) {
2333 $filename = null;
2334 } else {
2335 $filename = $options['filename'];
2338 if (empty($options['dontdie'])) {
2339 $dontdie = false;
2340 } else {
2341 $dontdie = true;
2344 if (!empty($options['preview'])) {
2345 // replace the file with its preview
2346 $fs = get_file_storage();
2347 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2348 if (!$preview_file) {
2349 // unable to create a preview of the file, send its default mime icon instead
2350 if ($options['preview'] === 'tinyicon') {
2351 $size = 24;
2352 } else if ($options['preview'] === 'thumb') {
2353 $size = 90;
2354 } else {
2355 $size = 256;
2357 $fileicon = file_file_icon($stored_file, $size);
2358 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2359 } else {
2360 // preview images have fixed cache lifetime and they ignore forced download
2361 // (they are generated by GD and therefore they are considered reasonably safe).
2362 $stored_file = $preview_file;
2363 $lifetime = DAYSECS;
2364 $filter = 0;
2365 $forcedownload = false;
2369 // handle external resource
2370 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2371 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2372 die;
2375 if (!$stored_file or $stored_file->is_directory()) {
2376 // nothing to serve
2377 if ($dontdie) {
2378 return;
2380 die;
2383 if ($dontdie) {
2384 ignore_user_abort(true);
2387 session_get_instance()->write_close(); // unlock session during fileserving
2389 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2390 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2391 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2392 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2393 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2394 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2395 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2397 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2398 if (check_browser_version('MSIE')) {
2399 $filename = rawurlencode($filename);
2402 if ($forcedownload) {
2403 header('Content-Disposition: attachment; filename="'.$filename.'"');
2404 } else {
2405 header('Content-Disposition: inline; filename="'.$filename.'"');
2408 if ($lifetime > 0) {
2409 header('Cache-Control: max-age='.$lifetime);
2410 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2411 header('Pragma: ');
2413 } else { // Do not cache files in proxies and browsers
2414 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2415 header('Cache-Control: max-age=10');
2416 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2417 header('Pragma: ');
2418 } else { //normal http - prevent caching at all cost
2419 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2420 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2421 header('Pragma: no-cache');
2425 if (empty($filter)) {
2426 // send the contents
2427 readfile_accel($stored_file, $mimetype, !$dontdie);
2429 } else { // Try to put the file through filters
2430 if ($mimetype == 'text/html') {
2431 $options = new stdClass();
2432 $options->noclean = true;
2433 $options->nocache = true; // temporary workaround for MDL-5136
2434 $text = $stored_file->get_content();
2435 $text = file_modify_html_header($text);
2436 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2438 readstring_accel($output, $mimetype, false);
2440 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2441 // only filter text if filter all files is selected
2442 $options = new stdClass();
2443 $options->newlines = false;
2444 $options->noclean = true;
2445 $text = $stored_file->get_content();
2446 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2448 readstring_accel($output, $mimetype, false);
2450 } else { // Just send it out raw
2451 readfile_accel($stored_file, $mimetype, !$dontdie);
2454 if ($dontdie) {
2455 return;
2457 die; //no more chars to output!!!
2461 * Retrieves an array of records from a CSV file and places
2462 * them into a given table structure
2464 * @global stdClass $CFG
2465 * @global moodle_database $DB
2466 * @param string $file The path to a CSV file
2467 * @param string $table The table to retrieve columns from
2468 * @return bool|array Returns an array of CSV records or false
2470 function get_records_csv($file, $table) {
2471 global $CFG, $DB;
2473 if (!$metacolumns = $DB->get_columns($table)) {
2474 return false;
2477 if(!($handle = @fopen($file, 'r'))) {
2478 print_error('get_records_csv failed to open '.$file);
2481 $fieldnames = fgetcsv($handle, 4096);
2482 if(empty($fieldnames)) {
2483 fclose($handle);
2484 return false;
2487 $columns = array();
2489 foreach($metacolumns as $metacolumn) {
2490 $ord = array_search($metacolumn->name, $fieldnames);
2491 if(is_int($ord)) {
2492 $columns[$metacolumn->name] = $ord;
2496 $rows = array();
2498 while (($data = fgetcsv($handle, 4096)) !== false) {
2499 $item = new stdClass;
2500 foreach($columns as $name => $ord) {
2501 $item->$name = $data[$ord];
2503 $rows[] = $item;
2506 fclose($handle);
2507 return $rows;
2511 * Create a file with CSV contents
2513 * @global stdClass $CFG
2514 * @global moodle_database $DB
2515 * @param string $file The file to put the CSV content into
2516 * @param array $records An array of records to write to a CSV file
2517 * @param string $table The table to get columns from
2518 * @return bool success
2520 function put_records_csv($file, $records, $table = NULL) {
2521 global $CFG, $DB;
2523 if (empty($records)) {
2524 return true;
2527 $metacolumns = NULL;
2528 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2529 return false;
2532 echo "x";
2534 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2535 print_error('put_records_csv failed to open '.$file);
2538 $proto = reset($records);
2539 if(is_object($proto)) {
2540 $fields_records = array_keys(get_object_vars($proto));
2542 else if(is_array($proto)) {
2543 $fields_records = array_keys($proto);
2545 else {
2546 return false;
2548 echo "x";
2550 if(!empty($metacolumns)) {
2551 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2552 $fields = array_intersect($fields_records, $fields_table);
2554 else {
2555 $fields = $fields_records;
2558 fwrite($fp, implode(',', $fields));
2559 fwrite($fp, "\r\n");
2561 foreach($records as $record) {
2562 $array = (array)$record;
2563 $values = array();
2564 foreach($fields as $field) {
2565 if(strpos($array[$field], ',')) {
2566 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2568 else {
2569 $values[] = $array[$field];
2572 fwrite($fp, implode(',', $values)."\r\n");
2575 fclose($fp);
2576 return true;
2581 * Recursively delete the file or folder with path $location. That is,
2582 * if it is a file delete it. If it is a folder, delete all its content
2583 * then delete it. If $location does not exist to start, that is not
2584 * considered an error.
2586 * @param string $location the path to remove.
2587 * @return bool
2589 function fulldelete($location) {
2590 if (empty($location)) {
2591 // extra safety against wrong param
2592 return false;
2594 if (is_dir($location)) {
2595 if (!$currdir = opendir($location)) {
2596 return false;
2598 while (false !== ($file = readdir($currdir))) {
2599 if ($file <> ".." && $file <> ".") {
2600 $fullfile = $location."/".$file;
2601 if (is_dir($fullfile)) {
2602 if (!fulldelete($fullfile)) {
2603 return false;
2605 } else {
2606 if (!unlink($fullfile)) {
2607 return false;
2612 closedir($currdir);
2613 if (! rmdir($location)) {
2614 return false;
2617 } else if (file_exists($location)) {
2618 if (!unlink($location)) {
2619 return false;
2622 return true;
2626 * Send requested byterange of file.
2628 * @param resource $handle A file handle
2629 * @param string $mimetype The mimetype for the output
2630 * @param array $ranges An array of ranges to send
2631 * @param string $filesize The size of the content if only one range is used
2633 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2634 // better turn off any kind of compression and buffering
2635 @ini_set('zlib.output_compression', 'Off');
2637 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2638 if ($handle === false) {
2639 die;
2641 if (count($ranges) == 1) { //only one range requested
2642 $length = $ranges[0][2] - $ranges[0][1] + 1;
2643 header('HTTP/1.1 206 Partial content');
2644 header('Content-Length: '.$length);
2645 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2646 header('Content-Type: '.$mimetype);
2648 while(@ob_get_level()) {
2649 if (!@ob_end_flush()) {
2650 break;
2654 fseek($handle, $ranges[0][1]);
2655 while (!feof($handle) && $length > 0) {
2656 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2657 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2658 echo $buffer;
2659 flush();
2660 $length -= strlen($buffer);
2662 fclose($handle);
2663 die;
2664 } else { // multiple ranges requested - not tested much
2665 $totallength = 0;
2666 foreach($ranges as $range) {
2667 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2669 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2670 header('HTTP/1.1 206 Partial content');
2671 header('Content-Length: '.$totallength);
2672 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2674 while(@ob_get_level()) {
2675 if (!@ob_end_flush()) {
2676 break;
2680 foreach($ranges as $range) {
2681 $length = $range[2] - $range[1] + 1;
2682 echo $range[0];
2683 fseek($handle, $range[1]);
2684 while (!feof($handle) && $length > 0) {
2685 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2686 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2687 echo $buffer;
2688 flush();
2689 $length -= strlen($buffer);
2692 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2693 fclose($handle);
2694 die;
2699 * add includes (js and css) into uploaded files
2700 * before returning them, useful for themes and utf.js includes
2702 * @global stdClass $CFG
2703 * @param string $text text to search and replace
2704 * @return string text with added head includes
2705 * @todo MDL-21120
2707 function file_modify_html_header($text) {
2708 // first look for <head> tag
2709 global $CFG;
2711 $stylesheetshtml = '';
2712 /* foreach ($CFG->stylesheets as $stylesheet) {
2713 //TODO: MDL-21120
2714 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2717 $ufo = '';
2718 if (filter_is_enabled('filter/mediaplugin')) {
2719 // this script is needed by most media filter plugins.
2720 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2721 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2724 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2725 if ($matches) {
2726 $replacement = '<head>'.$ufo.$stylesheetshtml;
2727 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2728 return $text;
2731 // if not, look for <html> tag, and stick <head> right after
2732 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2733 if ($matches) {
2734 // replace <html> tag with <html><head>includes</head>
2735 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2736 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2737 return $text;
2740 // if not, look for <body> tag, and stick <head> before body
2741 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2742 if ($matches) {
2743 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2744 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2745 return $text;
2748 // if not, just stick a <head> tag at the beginning
2749 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2750 return $text;
2754 * RESTful cURL class
2756 * This is a wrapper class for curl, it is quite easy to use:
2757 * <code>
2758 * $c = new curl;
2759 * // enable cache
2760 * $c = new curl(array('cache'=>true));
2761 * // enable cookie
2762 * $c = new curl(array('cookie'=>true));
2763 * // enable proxy
2764 * $c = new curl(array('proxy'=>true));
2766 * // HTTP GET Method
2767 * $html = $c->get('http://example.com');
2768 * // HTTP POST Method
2769 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2770 * // HTTP PUT Method
2771 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2772 * </code>
2774 * @package core_files
2775 * @category files
2776 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2777 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2779 class curl {
2780 /** @var bool Caches http request contents */
2781 public $cache = false;
2782 /** @var bool Uses proxy */
2783 public $proxy = false;
2784 /** @var string library version */
2785 public $version = '0.4 dev';
2786 /** @var array http's response */
2787 public $response = array();
2788 /** @var array http header */
2789 public $header = array();
2790 /** @var string cURL information */
2791 public $info;
2792 /** @var string error */
2793 public $error;
2794 /** @var int error code */
2795 public $errno;
2797 /** @var array cURL options */
2798 private $options;
2799 /** @var string Proxy host */
2800 private $proxy_host = '';
2801 /** @var string Proxy auth */
2802 private $proxy_auth = '';
2803 /** @var string Proxy type */
2804 private $proxy_type = '';
2805 /** @var bool Debug mode on */
2806 private $debug = false;
2807 /** @var bool|string Path to cookie file */
2808 private $cookie = false;
2811 * Constructor
2813 * @global stdClass $CFG
2814 * @param array $options
2816 public function __construct($options = array()){
2817 global $CFG;
2818 if (!function_exists('curl_init')) {
2819 $this->error = 'cURL module must be enabled!';
2820 trigger_error($this->error, E_USER_ERROR);
2821 return false;
2823 // the options of curl should be init here.
2824 $this->resetopt();
2825 if (!empty($options['debug'])) {
2826 $this->debug = true;
2828 if(!empty($options['cookie'])) {
2829 if($options['cookie'] === true) {
2830 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2831 } else {
2832 $this->cookie = $options['cookie'];
2835 if (!empty($options['cache'])) {
2836 if (class_exists('curl_cache')) {
2837 if (!empty($options['module_cache'])) {
2838 $this->cache = new curl_cache($options['module_cache']);
2839 } else {
2840 $this->cache = new curl_cache('misc');
2844 if (!empty($CFG->proxyhost)) {
2845 if (empty($CFG->proxyport)) {
2846 $this->proxy_host = $CFG->proxyhost;
2847 } else {
2848 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2850 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2851 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2852 $this->setopt(array(
2853 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2854 'proxyuserpwd'=>$this->proxy_auth));
2856 if (!empty($CFG->proxytype)) {
2857 if ($CFG->proxytype == 'SOCKS5') {
2858 $this->proxy_type = CURLPROXY_SOCKS5;
2859 } else {
2860 $this->proxy_type = CURLPROXY_HTTP;
2861 $this->setopt(array('httpproxytunnel'=>false));
2863 $this->setopt(array('proxytype'=>$this->proxy_type));
2866 if (!empty($this->proxy_host)) {
2867 $this->proxy = array('proxy'=>$this->proxy_host);
2871 * Resets the CURL options that have already been set
2873 public function resetopt(){
2874 $this->options = array();
2875 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2876 // True to include the header in the output
2877 $this->options['CURLOPT_HEADER'] = 0;
2878 // True to Exclude the body from the output
2879 $this->options['CURLOPT_NOBODY'] = 0;
2880 // TRUE to follow any "Location: " header that the server
2881 // sends as part of the HTTP header (note this is recursive,
2882 // PHP will follow as many "Location: " headers that it is sent,
2883 // unless CURLOPT_MAXREDIRS is set).
2884 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2885 $this->options['CURLOPT_MAXREDIRS'] = 10;
2886 $this->options['CURLOPT_ENCODING'] = '';
2887 // TRUE to return the transfer as a string of the return
2888 // value of curl_exec() instead of outputting it out directly.
2889 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2890 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2891 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2892 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2893 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2897 * Reset Cookie
2899 public function resetcookie() {
2900 if (!empty($this->cookie)) {
2901 if (is_file($this->cookie)) {
2902 $fp = fopen($this->cookie, 'w');
2903 if (!empty($fp)) {
2904 fwrite($fp, '');
2905 fclose($fp);
2912 * Set curl options
2914 * @param array $options If array is null, this function will
2915 * reset the options to default value.
2917 public function setopt($options = array()) {
2918 if (is_array($options)) {
2919 foreach($options as $name => $val){
2920 if (stripos($name, 'CURLOPT_') === false) {
2921 $name = strtoupper('CURLOPT_'.$name);
2923 $this->options[$name] = $val;
2929 * Reset http method
2931 public function cleanopt(){
2932 unset($this->options['CURLOPT_HTTPGET']);
2933 unset($this->options['CURLOPT_POST']);
2934 unset($this->options['CURLOPT_POSTFIELDS']);
2935 unset($this->options['CURLOPT_PUT']);
2936 unset($this->options['CURLOPT_INFILE']);
2937 unset($this->options['CURLOPT_INFILESIZE']);
2938 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2939 unset($this->options['CURLOPT_FILE']);
2943 * Resets the HTTP Request headers (to prepare for the new request)
2945 public function resetHeader() {
2946 $this->header = array();
2950 * Set HTTP Request Header
2952 * @param array $header
2954 public function setHeader($header) {
2955 if (is_array($header)){
2956 foreach ($header as $v) {
2957 $this->setHeader($v);
2959 } else {
2960 $this->header[] = $header;
2965 * Set HTTP Response Header
2968 public function getResponse(){
2969 return $this->response;
2973 * private callback function
2974 * Formatting HTTP Response Header
2976 * @param resource $ch Apparently not used
2977 * @param string $header
2978 * @return int The strlen of the header
2980 private function formatHeader($ch, $header)
2982 $this->count++;
2983 if (strlen($header) > 2) {
2984 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2985 $key = rtrim($key, ':');
2986 if (!empty($this->response[$key])) {
2987 if (is_array($this->response[$key])){
2988 $this->response[$key][] = $value;
2989 } else {
2990 $tmp = $this->response[$key];
2991 $this->response[$key] = array();
2992 $this->response[$key][] = $tmp;
2993 $this->response[$key][] = $value;
2996 } else {
2997 $this->response[$key] = $value;
3000 return strlen($header);
3004 * Set options for individual curl instance
3006 * @param resource $curl A curl handle
3007 * @param array $options
3008 * @return resource The curl handle
3010 private function apply_opt($curl, $options) {
3011 // Clean up
3012 $this->cleanopt();
3013 // set cookie
3014 if (!empty($this->cookie) || !empty($options['cookie'])) {
3015 $this->setopt(array('cookiejar'=>$this->cookie,
3016 'cookiefile'=>$this->cookie
3020 // set proxy
3021 if (!empty($this->proxy) || !empty($options['proxy'])) {
3022 $this->setopt($this->proxy);
3024 $this->setopt($options);
3025 // reset before set options
3026 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3027 // set headers
3028 if (empty($this->header)){
3029 $this->setHeader(array(
3030 'User-Agent: MoodleBot/1.0',
3031 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3032 'Connection: keep-alive'
3035 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3037 if ($this->debug){
3038 echo '<h1>Options</h1>';
3039 var_dump($this->options);
3040 echo '<h1>Header</h1>';
3041 var_dump($this->header);
3044 // set options
3045 foreach($this->options as $name => $val) {
3046 if (is_string($name)) {
3047 $name = constant(strtoupper($name));
3049 curl_setopt($curl, $name, $val);
3051 return $curl;
3055 * Download multiple files in parallel
3057 * Calls {@link multi()} with specific download headers
3059 * <code>
3060 * $c = new curl();
3061 * $file1 = fopen('a', 'wb');
3062 * $file2 = fopen('b', 'wb');
3063 * $c->download(array(
3064 * array('url'=>'http://localhost/', 'file'=>$file1),
3065 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3066 * ));
3067 * fclose($file1);
3068 * fclose($file2);
3069 * </code>
3071 * or
3073 * <code>
3074 * $c = new curl();
3075 * $c->download(array(
3076 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3077 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3078 * ));
3079 * </code>
3081 * @param array $requests An array of files to request {
3082 * url => url to download the file [required]
3083 * file => file handler, or
3084 * filepath => file path
3086 * If 'file' and 'filepath' parameters are both specified in one request, the
3087 * open file handle in the 'file' parameter will take precedence and 'filepath'
3088 * will be ignored.
3090 * @param array $options An array of options to set
3091 * @return array An array of results
3093 public function download($requests, $options = array()) {
3094 $options['CURLOPT_BINARYTRANSFER'] = 1;
3095 $options['RETURNTRANSFER'] = false;
3096 return $this->multi($requests, $options);
3100 * Mulit HTTP Requests
3101 * This function could run multi-requests in parallel.
3103 * @param array $requests An array of files to request
3104 * @param array $options An array of options to set
3105 * @return array An array of results
3107 protected function multi($requests, $options = array()) {
3108 $count = count($requests);
3109 $handles = array();
3110 $results = array();
3111 $main = curl_multi_init();
3112 for ($i = 0; $i < $count; $i++) {
3113 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3114 // open file
3115 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3116 $requests[$i]['auto-handle'] = true;
3118 foreach($requests[$i] as $n=>$v){
3119 $options[$n] = $v;
3121 $handles[$i] = curl_init($requests[$i]['url']);
3122 $this->apply_opt($handles[$i], $options);
3123 curl_multi_add_handle($main, $handles[$i]);
3125 $running = 0;
3126 do {
3127 curl_multi_exec($main, $running);
3128 } while($running > 0);
3129 for ($i = 0; $i < $count; $i++) {
3130 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3131 $results[] = true;
3132 } else {
3133 $results[] = curl_multi_getcontent($handles[$i]);
3135 curl_multi_remove_handle($main, $handles[$i]);
3137 curl_multi_close($main);
3139 for ($i = 0; $i < $count; $i++) {
3140 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3141 // close file handler if file is opened in this function
3142 fclose($requests[$i]['file']);
3145 return $results;
3149 * Single HTTP Request
3151 * @param string $url The URL to request
3152 * @param array $options
3153 * @return bool
3155 protected function request($url, $options = array()){
3156 // create curl instance
3157 $curl = curl_init($url);
3158 $options['url'] = $url;
3159 $this->apply_opt($curl, $options);
3160 if ($this->cache && $ret = $this->cache->get($this->options)) {
3161 return $ret;
3162 } else {
3163 $ret = curl_exec($curl);
3164 if ($this->cache) {
3165 $this->cache->set($this->options, $ret);
3169 $this->info = curl_getinfo($curl);
3170 $this->error = curl_error($curl);
3171 $this->errno = curl_errno($curl);
3173 if ($this->debug){
3174 echo '<h1>Return Data</h1>';
3175 var_dump($ret);
3176 echo '<h1>Info</h1>';
3177 var_dump($this->info);
3178 echo '<h1>Error</h1>';
3179 var_dump($this->error);
3182 curl_close($curl);
3184 if (empty($this->error)){
3185 return $ret;
3186 } else {
3187 return $this->error;
3188 // exception is not ajax friendly
3189 //throw new moodle_exception($this->error, 'curl');
3194 * HTTP HEAD method
3196 * @see request()
3198 * @param string $url
3199 * @param array $options
3200 * @return bool
3202 public function head($url, $options = array()){
3203 $options['CURLOPT_HTTPGET'] = 0;
3204 $options['CURLOPT_HEADER'] = 1;
3205 $options['CURLOPT_NOBODY'] = 1;
3206 return $this->request($url, $options);
3210 * HTTP POST method
3212 * @param string $url
3213 * @param array|string $params
3214 * @param array $options
3215 * @return bool
3217 public function post($url, $params = '', $options = array()){
3218 $options['CURLOPT_POST'] = 1;
3219 if (is_array($params)) {
3220 $this->_tmp_file_post_params = array();
3221 foreach ($params as $key => $value) {
3222 if ($value instanceof stored_file) {
3223 $value->add_to_curl_request($this, $key);
3224 } else {
3225 $this->_tmp_file_post_params[$key] = $value;
3228 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3229 unset($this->_tmp_file_post_params);
3230 } else {
3231 // $params is the raw post data
3232 $options['CURLOPT_POSTFIELDS'] = $params;
3234 return $this->request($url, $options);
3238 * HTTP GET method
3240 * @param string $url
3241 * @param array $params
3242 * @param array $options
3243 * @return bool
3245 public function get($url, $params = array(), $options = array()){
3246 $options['CURLOPT_HTTPGET'] = 1;
3248 if (!empty($params)){
3249 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3250 $url .= http_build_query($params, '', '&');
3252 return $this->request($url, $options);
3256 * Downloads one file and writes it to the specified file handler
3258 * <code>
3259 * $c = new curl();
3260 * $file = fopen('savepath', 'w');
3261 * $result = $c->download_one('http://localhost/', null,
3262 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3263 * fclose($file);
3264 * $download_info = $c->get_info();
3265 * if ($result === true) {
3266 * // file downloaded successfully
3267 * } else {
3268 * $error_text = $result;
3269 * $error_code = $c->get_errno();
3271 * </code>
3273 * <code>
3274 * $c = new curl();
3275 * $result = $c->download_one('http://localhost/', null,
3276 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3277 * // ... see above, no need to close handle and remove file if unsuccessful
3278 * </code>
3280 * @param string $url
3281 * @param array|null $params key-value pairs to be added to $url as query string
3282 * @param array $options request options. Must include either 'file' or 'filepath'
3283 * @return bool|string true on success or error string on failure
3285 public function download_one($url, $params, $options = array()) {
3286 $options['CURLOPT_HTTPGET'] = 1;
3287 $options['CURLOPT_BINARYTRANSFER'] = true;
3288 if (!empty($params)){
3289 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3290 $url .= http_build_query($params, '', '&');
3292 if (!empty($options['filepath']) && empty($options['file'])) {
3293 // open file
3294 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3295 $this->errno = 100;
3296 return get_string('cannotwritefile', 'error', $options['filepath']);
3298 $filepath = $options['filepath'];
3300 unset($options['filepath']);
3301 $result = $this->request($url, $options);
3302 if (isset($filepath)) {
3303 fclose($options['file']);
3304 if ($result !== true) {
3305 unlink($filepath);
3308 return $result;
3312 * HTTP PUT method
3314 * @param string $url
3315 * @param array $params
3316 * @param array $options
3317 * @return bool
3319 public function put($url, $params = array(), $options = array()){
3320 $file = $params['file'];
3321 if (!is_file($file)){
3322 return null;
3324 $fp = fopen($file, 'r');
3325 $size = filesize($file);
3326 $options['CURLOPT_PUT'] = 1;
3327 $options['CURLOPT_INFILESIZE'] = $size;
3328 $options['CURLOPT_INFILE'] = $fp;
3329 if (!isset($this->options['CURLOPT_USERPWD'])){
3330 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3332 $ret = $this->request($url, $options);
3333 fclose($fp);
3334 return $ret;
3338 * HTTP DELETE method
3340 * @param string $url
3341 * @param array $param
3342 * @param array $options
3343 * @return bool
3345 public function delete($url, $param = array(), $options = array()){
3346 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3347 if (!isset($options['CURLOPT_USERPWD'])) {
3348 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3350 $ret = $this->request($url, $options);
3351 return $ret;
3355 * HTTP TRACE method
3357 * @param string $url
3358 * @param array $options
3359 * @return bool
3361 public function trace($url, $options = array()){
3362 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3363 $ret = $this->request($url, $options);
3364 return $ret;
3368 * HTTP OPTIONS method
3370 * @param string $url
3371 * @param array $options
3372 * @return bool
3374 public function options($url, $options = array()){
3375 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3376 $ret = $this->request($url, $options);
3377 return $ret;
3381 * Get curl information
3383 * @return string
3385 public function get_info() {
3386 return $this->info;
3390 * Get curl error code
3392 * @return int
3394 public function get_errno() {
3395 return $this->errno;
3400 * This class is used by cURL class, use case:
3402 * <code>
3403 * $CFG->repositorycacheexpire = 120;
3404 * $CFG->curlcache = 120;
3406 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3407 * $ret = $c->get('http://www.google.com');
3408 * </code>
3410 * @package core_files
3411 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3414 class curl_cache {
3415 /** @var string Path to cache directory */
3416 public $dir = '';
3419 * Constructor
3421 * @global stdClass $CFG
3422 * @param string $module which module is using curl_cache
3424 public function __construct($module = 'repository') {
3425 global $CFG;
3426 if (!empty($module)) {
3427 $this->dir = $CFG->cachedir.'/'.$module.'/';
3428 } else {
3429 $this->dir = $CFG->cachedir.'/misc/';
3431 if (!file_exists($this->dir)) {
3432 mkdir($this->dir, $CFG->directorypermissions, true);
3434 if ($module == 'repository') {
3435 if (empty($CFG->repositorycacheexpire)) {
3436 $CFG->repositorycacheexpire = 120;
3438 $this->ttl = $CFG->repositorycacheexpire;
3439 } else {
3440 if (empty($CFG->curlcache)) {
3441 $CFG->curlcache = 120;
3443 $this->ttl = $CFG->curlcache;
3448 * Get cached value
3450 * @global stdClass $CFG
3451 * @global stdClass $USER
3452 * @param mixed $param
3453 * @return bool|string
3455 public function get($param) {
3456 global $CFG, $USER;
3457 $this->cleanup($this->ttl);
3458 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3459 if(file_exists($this->dir.$filename)) {
3460 $lasttime = filemtime($this->dir.$filename);
3461 if (time()-$lasttime > $this->ttl) {
3462 return false;
3463 } else {
3464 $fp = fopen($this->dir.$filename, 'r');
3465 $size = filesize($this->dir.$filename);
3466 $content = fread($fp, $size);
3467 return unserialize($content);
3470 return false;
3474 * Set cache value
3476 * @global object $CFG
3477 * @global object $USER
3478 * @param mixed $param
3479 * @param mixed $val
3481 public function set($param, $val) {
3482 global $CFG, $USER;
3483 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3484 $fp = fopen($this->dir.$filename, 'w');
3485 fwrite($fp, serialize($val));
3486 fclose($fp);
3490 * Remove cache files
3492 * @param int $expire The number of seconds before expiry
3494 public function cleanup($expire) {
3495 if ($dir = opendir($this->dir)) {
3496 while (false !== ($file = readdir($dir))) {
3497 if(!is_dir($file) && $file != '.' && $file != '..') {
3498 $lasttime = @filemtime($this->dir.$file);
3499 if (time() - $lasttime > $expire) {
3500 @unlink($this->dir.$file);
3504 closedir($dir);
3508 * delete current user's cache file
3510 * @global object $CFG
3511 * @global object $USER
3513 public function refresh() {
3514 global $CFG, $USER;
3515 if ($dir = opendir($this->dir)) {
3516 while (false !== ($file = readdir($dir))) {
3517 if (!is_dir($file) && $file != '.' && $file != '..') {
3518 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3519 @unlink($this->dir.$file);
3528 * This function delegates file serving to individual plugins
3530 * @param string $relativepath
3531 * @param bool $forcedownload
3532 * @param null|string $preview the preview mode, defaults to serving the original file
3533 * @todo MDL-31088 file serving improments
3535 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3536 global $DB, $CFG, $USER;
3537 // relative path must start with '/'
3538 if (!$relativepath) {
3539 print_error('invalidargorconf');
3540 } else if ($relativepath[0] != '/') {
3541 print_error('pathdoesnotstartslash');
3544 // extract relative path components
3545 $args = explode('/', ltrim($relativepath, '/'));
3547 if (count($args) < 3) { // always at least context, component and filearea
3548 print_error('invalidarguments');
3551 $contextid = (int)array_shift($args);
3552 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3553 $filearea = clean_param(array_shift($args), PARAM_AREA);
3555 list($context, $course, $cm) = get_context_info_array($contextid);
3557 $fs = get_file_storage();
3559 // ========================================================================================================================
3560 if ($component === 'blog') {
3561 // Blog file serving
3562 if ($context->contextlevel != CONTEXT_SYSTEM) {
3563 send_file_not_found();
3565 if ($filearea !== 'attachment' and $filearea !== 'post') {
3566 send_file_not_found();
3569 if (empty($CFG->enableblogs)) {
3570 print_error('siteblogdisable', 'blog');
3573 $entryid = (int)array_shift($args);
3574 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3575 send_file_not_found();
3577 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3578 require_login();
3579 if (isguestuser()) {
3580 print_error('noguest');
3582 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3583 if ($USER->id != $entry->userid) {
3584 send_file_not_found();
3589 if ($entry->publishstate === 'public') {
3590 if ($CFG->forcelogin) {
3591 require_login();
3594 } else if ($entry->publishstate === 'site') {
3595 require_login();
3596 //ok
3597 } else if ($entry->publishstate === 'draft') {
3598 require_login();
3599 if ($USER->id != $entry->userid) {
3600 send_file_not_found();
3604 $filename = array_pop($args);
3605 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3607 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3608 send_file_not_found();
3611 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3613 // ========================================================================================================================
3614 } else if ($component === 'grade') {
3615 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3616 // Global gradebook files
3617 if ($CFG->forcelogin) {
3618 require_login();
3621 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3623 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3624 send_file_not_found();
3627 session_get_instance()->write_close(); // unlock session during fileserving
3628 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3630 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3631 //TODO: nobody implemented this yet in grade edit form!!
3632 send_file_not_found();
3634 if ($CFG->forcelogin || $course->id != SITEID) {
3635 require_login($course);
3638 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3640 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3641 send_file_not_found();
3644 session_get_instance()->write_close(); // unlock session during fileserving
3645 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3646 } else {
3647 send_file_not_found();
3650 // ========================================================================================================================
3651 } else if ($component === 'tag') {
3652 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3654 // All tag descriptions are going to be public but we still need to respect forcelogin
3655 if ($CFG->forcelogin) {
3656 require_login();
3659 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3661 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3662 send_file_not_found();
3665 session_get_instance()->write_close(); // unlock session during fileserving
3666 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3668 } else {
3669 send_file_not_found();
3672 // ========================================================================================================================
3673 } else if ($component === 'calendar') {
3674 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3676 // All events here are public the one requirement is that we respect forcelogin
3677 if ($CFG->forcelogin) {
3678 require_login();
3681 // Get the event if from the args array
3682 $eventid = array_shift($args);
3684 // Load the event from the database
3685 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3686 send_file_not_found();
3689 // Get the file and serve if successful
3690 $filename = array_pop($args);
3691 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3692 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3693 send_file_not_found();
3696 session_get_instance()->write_close(); // unlock session during fileserving
3697 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3699 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3701 // Must be logged in, if they are not then they obviously can't be this user
3702 require_login();
3704 // Don't want guests here, potentially saves a DB call
3705 if (isguestuser()) {
3706 send_file_not_found();
3709 // Get the event if from the args array
3710 $eventid = array_shift($args);
3712 // Load the event from the database - user id must match
3713 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3714 send_file_not_found();
3717 // Get the file and serve if successful
3718 $filename = array_pop($args);
3719 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3720 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3721 send_file_not_found();
3724 session_get_instance()->write_close(); // unlock session during fileserving
3725 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3727 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3729 // Respect forcelogin and require login unless this is the site.... it probably
3730 // should NEVER be the site
3731 if ($CFG->forcelogin || $course->id != SITEID) {
3732 require_login($course);
3735 // Must be able to at least view the course. This does not apply to the front page.
3736 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
3737 //TODO: hmm, do we really want to block guests here?
3738 send_file_not_found();
3741 // Get the event id
3742 $eventid = array_shift($args);
3744 // Load the event from the database we need to check whether it is
3745 // a) valid course event
3746 // b) a group event
3747 // Group events use the course context (there is no group context)
3748 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3749 send_file_not_found();
3752 // If its a group event require either membership of view all groups capability
3753 if ($event->eventtype === 'group') {
3754 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3755 send_file_not_found();
3757 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
3758 // Ok. Please note that the event type 'site' still uses a course context.
3759 } else {
3760 // Some other type.
3761 send_file_not_found();
3764 // If we get this far we can serve the file
3765 $filename = array_pop($args);
3766 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3767 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3768 send_file_not_found();
3771 session_get_instance()->write_close(); // unlock session during fileserving
3772 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3774 } else {
3775 send_file_not_found();
3778 // ========================================================================================================================
3779 } else if ($component === 'user') {
3780 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3781 if (count($args) == 1) {
3782 $themename = theme_config::DEFAULT_THEME;
3783 $filename = array_shift($args);
3784 } else {
3785 $themename = array_shift($args);
3786 $filename = array_shift($args);
3789 // fix file name automatically
3790 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3791 $filename = 'f1';
3794 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3795 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3796 // protect images if login required and not logged in;
3797 // also if login is required for profile images and is not logged in or guest
3798 // do not use require_login() because it is expensive and not suitable here anyway
3799 $theme = theme_config::load($themename);
3800 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3803 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3804 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3805 if ($filename === 'f3') {
3806 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3807 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3808 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3813 if (!$file) {
3814 // bad reference - try to prevent future retries as hard as possible!
3815 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3816 if ($user->picture > 0) {
3817 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3820 // no redirect here because it is not cached
3821 $theme = theme_config::load($themename);
3822 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
3823 send_file($imagefile, basename($imagefile), 60*60*24*14);
3826 send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3828 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3829 require_login();
3831 if (isguestuser()) {
3832 send_file_not_found();
3835 if ($USER->id !== $context->instanceid) {
3836 send_file_not_found();
3839 $filename = array_pop($args);
3840 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3841 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3842 send_file_not_found();
3845 session_get_instance()->write_close(); // unlock session during fileserving
3846 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3848 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3850 if ($CFG->forcelogin) {
3851 require_login();
3854 $userid = $context->instanceid;
3856 if ($USER->id == $userid) {
3857 // always can access own
3859 } else if (!empty($CFG->forceloginforprofiles)) {
3860 require_login();
3862 if (isguestuser()) {
3863 send_file_not_found();
3866 // we allow access to site profile of all course contacts (usually teachers)
3867 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3868 send_file_not_found();
3871 $canview = false;
3872 if (has_capability('moodle/user:viewdetails', $context)) {
3873 $canview = true;
3874 } else {
3875 $courses = enrol_get_my_courses();
3878 while (!$canview && count($courses) > 0) {
3879 $course = array_shift($courses);
3880 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
3881 $canview = true;
3886 $filename = array_pop($args);
3887 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3888 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3889 send_file_not_found();
3892 session_get_instance()->write_close(); // unlock session during fileserving
3893 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3895 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3896 $userid = (int)array_shift($args);
3897 $usercontext = context_user::instance($userid);
3899 if ($CFG->forcelogin) {
3900 require_login();
3903 if (!empty($CFG->forceloginforprofiles)) {
3904 require_login();
3905 if (isguestuser()) {
3906 print_error('noguest');
3909 //TODO: review this logic of user profile access prevention
3910 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3911 print_error('usernotavailable');
3913 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3914 print_error('cannotviewprofile');
3916 if (!is_enrolled($context, $userid)) {
3917 print_error('notenrolledprofile');
3919 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3920 print_error('groupnotamember');
3924 $filename = array_pop($args);
3925 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3926 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3927 send_file_not_found();
3930 session_get_instance()->write_close(); // unlock session during fileserving
3931 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3933 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3934 require_login();
3936 if (isguestuser()) {
3937 send_file_not_found();
3939 $userid = $context->instanceid;
3941 if ($USER->id != $userid) {
3942 send_file_not_found();
3945 $filename = array_pop($args);
3946 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3947 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3948 send_file_not_found();
3951 session_get_instance()->write_close(); // unlock session during fileserving
3952 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3954 } else {
3955 send_file_not_found();
3958 // ========================================================================================================================
3959 } else if ($component === 'coursecat') {
3960 if ($context->contextlevel != CONTEXT_COURSECAT) {
3961 send_file_not_found();
3964 if ($filearea === 'description') {
3965 if ($CFG->forcelogin) {
3966 // no login necessary - unless login forced everywhere
3967 require_login();
3970 $filename = array_pop($args);
3971 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3972 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3973 send_file_not_found();
3976 session_get_instance()->write_close(); // unlock session during fileserving
3977 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3978 } else {
3979 send_file_not_found();
3982 // ========================================================================================================================
3983 } else if ($component === 'course') {
3984 if ($context->contextlevel != CONTEXT_COURSE) {
3985 send_file_not_found();
3988 if ($filearea === 'summary') {
3989 if ($CFG->forcelogin) {
3990 require_login();
3993 $filename = array_pop($args);
3994 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3995 if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
3996 send_file_not_found();
3999 session_get_instance()->write_close(); // unlock session during fileserving
4000 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4002 } else if ($filearea === 'section') {
4003 if ($CFG->forcelogin) {
4004 require_login($course);
4005 } else if ($course->id != SITEID) {
4006 require_login($course);
4009 $sectionid = (int)array_shift($args);
4011 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4012 send_file_not_found();
4015 $filename = array_pop($args);
4016 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4017 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4018 send_file_not_found();
4021 session_get_instance()->write_close(); // unlock session during fileserving
4022 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4024 } else {
4025 send_file_not_found();
4028 } else if ($component === 'group') {
4029 if ($context->contextlevel != CONTEXT_COURSE) {
4030 send_file_not_found();
4033 require_course_login($course, true, null, false);
4035 $groupid = (int)array_shift($args);
4037 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4038 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4039 // do not allow access to separate group info if not member or teacher
4040 send_file_not_found();
4043 if ($filearea === 'description') {
4045 require_login($course);
4047 $filename = array_pop($args);
4048 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4049 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4050 send_file_not_found();
4053 session_get_instance()->write_close(); // unlock session during fileserving
4054 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4056 } else if ($filearea === 'icon') {
4057 $filename = array_pop($args);
4059 if ($filename !== 'f1' and $filename !== 'f2') {
4060 send_file_not_found();
4062 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4063 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4064 send_file_not_found();
4068 session_get_instance()->write_close(); // unlock session during fileserving
4069 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4071 } else {
4072 send_file_not_found();
4075 } else if ($component === 'grouping') {
4076 if ($context->contextlevel != CONTEXT_COURSE) {
4077 send_file_not_found();
4080 require_login($course);
4082 $groupingid = (int)array_shift($args);
4084 // note: everybody has access to grouping desc images for now
4085 if ($filearea === 'description') {
4087 $filename = array_pop($args);
4088 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4089 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4090 send_file_not_found();
4093 session_get_instance()->write_close(); // unlock session during fileserving
4094 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4096 } else {
4097 send_file_not_found();
4100 // ========================================================================================================================
4101 } else if ($component === 'backup') {
4102 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4103 require_login($course);
4104 require_capability('moodle/backup:downloadfile', $context);
4106 $filename = array_pop($args);
4107 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4108 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4109 send_file_not_found();
4112 session_get_instance()->write_close(); // unlock session during fileserving
4113 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4115 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4116 require_login($course);
4117 require_capability('moodle/backup:downloadfile', $context);
4119 $sectionid = (int)array_shift($args);
4121 $filename = array_pop($args);
4122 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4123 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4124 send_file_not_found();
4127 session_get_instance()->write_close();
4128 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4130 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4131 require_login($course, false, $cm);
4132 require_capability('moodle/backup:downloadfile', $context);
4134 $filename = array_pop($args);
4135 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4136 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4137 send_file_not_found();
4140 session_get_instance()->write_close();
4141 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4143 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4144 // Backup files that were generated by the automated backup systems.
4146 require_login($course);
4147 require_capability('moodle/site:config', $context);
4149 $filename = array_pop($args);
4150 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4151 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4152 send_file_not_found();
4155 session_get_instance()->write_close(); // unlock session during fileserving
4156 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4158 } else {
4159 send_file_not_found();
4162 // ========================================================================================================================
4163 } else if ($component === 'question') {
4164 require_once($CFG->libdir . '/questionlib.php');
4165 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4166 send_file_not_found();
4168 // ========================================================================================================================
4169 } else if ($component === 'grading') {
4170 if ($filearea === 'description') {
4171 // files embedded into the form definition description
4173 if ($context->contextlevel == CONTEXT_SYSTEM) {
4174 require_login();
4176 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4177 require_login($course, false, $cm);
4179 } else {
4180 send_file_not_found();
4183 $formid = (int)array_shift($args);
4185 $sql = "SELECT ga.id
4186 FROM {grading_areas} ga
4187 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4188 WHERE gd.id = ? AND ga.contextid = ?";
4189 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4191 if (!$areaid) {
4192 send_file_not_found();
4195 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4197 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4198 send_file_not_found();
4201 session_get_instance()->write_close(); // unlock session during fileserving
4202 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4205 // ========================================================================================================================
4206 } else if (strpos($component, 'mod_') === 0) {
4207 $modname = substr($component, 4);
4208 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4209 send_file_not_found();
4211 require_once("$CFG->dirroot/mod/$modname/lib.php");
4213 if ($context->contextlevel == CONTEXT_MODULE) {
4214 if ($cm->modname !== $modname) {
4215 // somebody tries to gain illegal access, cm type must match the component!
4216 send_file_not_found();
4220 if ($filearea === 'intro') {
4221 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4222 send_file_not_found();
4224 require_course_login($course, true, $cm);
4226 // all users may access it
4227 $filename = array_pop($args);
4228 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4229 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4230 send_file_not_found();
4233 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4235 // finally send the file
4236 send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4239 $filefunction = $component.'_pluginfile';
4240 $filefunctionold = $modname.'_pluginfile';
4241 if (function_exists($filefunction)) {
4242 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4243 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4244 } else if (function_exists($filefunctionold)) {
4245 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4246 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4249 send_file_not_found();
4251 // ========================================================================================================================
4252 } else if (strpos($component, 'block_') === 0) {
4253 $blockname = substr($component, 6);
4254 // note: no more class methods in blocks please, that is ....
4255 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4256 send_file_not_found();
4258 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4260 if ($context->contextlevel == CONTEXT_BLOCK) {
4261 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4262 if ($birecord->blockname !== $blockname) {
4263 // somebody tries to gain illegal access, cm type must match the component!
4264 send_file_not_found();
4267 $bprecord = $DB->get_record('block_positions', array('blockinstanceid' => $context->instanceid), 'visible');
4268 // User can't access file, if block is hidden or doesn't have block:view capability
4269 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4270 send_file_not_found();
4272 } else {
4273 $birecord = null;
4276 $filefunction = $component.'_pluginfile';
4277 if (function_exists($filefunction)) {
4278 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4279 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4282 send_file_not_found();
4284 // ========================================================================================================================
4285 } else if (strpos($component, '_') === false) {
4286 // all core subsystems have to be specified above, no more guessing here!
4287 send_file_not_found();
4289 } else {
4290 // try to serve general plugin file in arbitrary context
4291 $dir = get_component_directory($component);
4292 if (!file_exists("$dir/lib.php")) {
4293 send_file_not_found();
4295 include_once("$dir/lib.php");
4297 $filefunction = $component.'_pluginfile';
4298 if (function_exists($filefunction)) {
4299 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4300 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4303 send_file_not_found();