Merge branch 'MDL-30166-m23' of git://github.com/ankitagarwal/moodle into MOODLE_23_S...
[moodle.git] / lib / filelib.php
blobee2cfc8000e32d9d8306ffea592818349dd94d29
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 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @todo MDL-31071 deprecate this function
43 * @global stdClass $CFG
44 * @param string $urlbase
45 * @param string $path /filearea/itemid/dir/dir/file.exe
46 * @param bool $forcedownload
47 * @param bool $https https url required
48 * @return string encoded file url
50 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
51 global $CFG;
53 //TODO: deprecate this
55 if ($CFG->slasharguments) {
56 $parts = explode('/', $path);
57 $parts = array_map('rawurlencode', $parts);
58 $path = implode('/', $parts);
59 $return = $urlbase.$path;
60 if ($forcedownload) {
61 $return .= '?forcedownload=1';
63 } else {
64 $path = rawurlencode($path);
65 $return = $urlbase.'?file='.$path;
66 if ($forcedownload) {
67 $return .= '&amp;forcedownload=1';
71 if ($https) {
72 $return = str_replace('http://', 'https://', $return);
75 return $return;
78 /**
79 * Prepares 'editor' formslib element from data in database
81 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
82 * function then copies the embedded files into draft area (assigning itemids automatically),
83 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
84 * displayed.
85 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
86 * your mform's set_data() supplying the object returned by this function.
88 * @category files
89 * @param stdClass $data database field that holds the html text with embedded media
90 * @param string $field the name of the database field that holds the html text with embedded media
91 * @param array $options editor options (like maxifiles, maxbytes etc.)
92 * @param stdClass $context context of the editor
93 * @param string $component
94 * @param string $filearea file area name
95 * @param int $itemid item id, required if item exists
96 * @return stdClass modified data object
98 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
99 $options = (array)$options;
100 if (!isset($options['trusttext'])) {
101 $options['trusttext'] = false;
103 if (!isset($options['forcehttps'])) {
104 $options['forcehttps'] = false;
106 if (!isset($options['subdirs'])) {
107 $options['subdirs'] = false;
109 if (!isset($options['maxfiles'])) {
110 $options['maxfiles'] = 0; // no files by default
112 if (!isset($options['noclean'])) {
113 $options['noclean'] = false;
116 //sanity check for passed context. This function doesn't expect $option['context'] to be set
117 //But this function is called before creating editor hence, this is one of the best places to check
118 //if context is used properly. This check notify developer that they missed passing context to editor.
119 if (isset($context) && !isset($options['context'])) {
120 //if $context is not null then make sure $option['context'] is also set.
121 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
122 } else if (isset($options['context']) && isset($context)) {
123 //If both are passed then they should be equal.
124 if ($options['context']->id != $context->id) {
125 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
126 throw new coding_exception($exceptionmsg);
130 if (is_null($itemid) or is_null($context)) {
131 $contextid = null;
132 $itemid = null;
133 if (!isset($data)) {
134 $data = new stdClass();
136 if (!isset($data->{$field})) {
137 $data->{$field} = '';
139 if (!isset($data->{$field.'format'})) {
140 $data->{$field.'format'} = editors_get_preferred_format();
142 if (!$options['noclean']) {
143 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
146 } else {
147 if ($options['trusttext']) {
148 // noclean ignored if trusttext enabled
149 if (!isset($data->{$field.'trust'})) {
150 $data->{$field.'trust'} = 0;
152 $data = trusttext_pre_edit($data, $field, $context);
153 } else {
154 if (!$options['noclean']) {
155 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
158 $contextid = $context->id;
161 if ($options['maxfiles'] != 0) {
162 $draftid_editor = file_get_submitted_draft_itemid($field);
163 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
164 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
165 } else {
166 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
169 return $data;
173 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
175 * This function moves files from draft area to the destination area and
176 * encodes URLs to the draft files so they can be safely saved into DB. The
177 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
178 * is the name of the database field to hold the wysiwyg editor content. The
179 * editor data comes as an array with text, format and itemid properties. This
180 * function automatically adds $data properties foobar, foobarformat and
181 * foobartrust, where foobar has URL to embedded files encoded.
183 * @category files
184 * @param stdClass $data raw data submitted by the form
185 * @param string $field name of the database field containing the html with embedded media files
186 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
187 * @param stdClass $context context, required for existing data
188 * @param string $component file component
189 * @param string $filearea file area name
190 * @param int $itemid item id, required if item exists
191 * @return stdClass modified data object
193 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
194 $options = (array)$options;
195 if (!isset($options['trusttext'])) {
196 $options['trusttext'] = false;
198 if (!isset($options['forcehttps'])) {
199 $options['forcehttps'] = false;
201 if (!isset($options['subdirs'])) {
202 $options['subdirs'] = false;
204 if (!isset($options['maxfiles'])) {
205 $options['maxfiles'] = 0; // no files by default
207 if (!isset($options['maxbytes'])) {
208 $options['maxbytes'] = 0; // unlimited
211 if ($options['trusttext']) {
212 $data->{$field.'trust'} = trusttext_trusted($context);
213 } else {
214 $data->{$field.'trust'} = 0;
217 $editor = $data->{$field.'_editor'};
219 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
220 $data->{$field} = $editor['text'];
221 } else {
222 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
224 $data->{$field.'format'} = $editor['format'];
226 return $data;
230 * Saves text and files modified by Editor formslib element
232 * @category files
233 * @param stdClass $data $database entry field
234 * @param string $field name of data field
235 * @param array $options various options
236 * @param stdClass $context context - must already exist
237 * @param string $component
238 * @param string $filearea file area name
239 * @param int $itemid must already exist, usually means data is in db
240 * @return stdClass modified data obejct
242 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
243 $options = (array)$options;
244 if (!isset($options['subdirs'])) {
245 $options['subdirs'] = false;
247 if (is_null($itemid) or is_null($context)) {
248 $itemid = null;
249 $contextid = null;
250 } else {
251 $contextid = $context->id;
254 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
255 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
256 $data->{$field.'_filemanager'} = $draftid_editor;
258 return $data;
262 * Saves files modified by File manager formslib element
264 * @todo MDL-31073 review this function
265 * @category files
266 * @param stdClass $data $database entry field
267 * @param string $field name of data field
268 * @param array $options various options
269 * @param stdClass $context context - must already exist
270 * @param string $component
271 * @param string $filearea file area name
272 * @param int $itemid must already exist, usually means data is in db
273 * @return stdClass modified data obejct
275 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
276 $options = (array)$options;
277 if (!isset($options['subdirs'])) {
278 $options['subdirs'] = false;
280 if (!isset($options['maxfiles'])) {
281 $options['maxfiles'] = -1; // unlimited
283 if (!isset($options['maxbytes'])) {
284 $options['maxbytes'] = 0; // unlimited
287 if (empty($data->{$field.'_filemanager'})) {
288 $data->$field = '';
290 } else {
291 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
292 $fs = get_file_storage();
294 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
295 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
296 } else {
297 $data->$field = '';
301 return $data;
305 * Generate a draft itemid
307 * @category files
308 * @global moodle_database $DB
309 * @global stdClass $USER
310 * @return int a random but available draft itemid that can be used to create a new draft
311 * file area.
313 function file_get_unused_draft_itemid() {
314 global $DB, $USER;
316 if (isguestuser() or !isloggedin()) {
317 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
318 print_error('noguest');
321 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
323 $fs = get_file_storage();
324 $draftitemid = rand(1, 999999999);
325 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
326 $draftitemid = rand(1, 999999999);
329 return $draftitemid;
333 * Initialise a draft file area from a real one by copying the files. A draft
334 * area will be created if one does not already exist. Normally you should
335 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
337 * @category files
338 * @global stdClass $CFG
339 * @global stdClass $USER
340 * @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.
341 * @param int $contextid This parameter and the next two identify the file area to copy files from.
342 * @param string $component
343 * @param string $filearea helps indentify the file area.
344 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
345 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
346 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
347 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
349 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
350 global $CFG, $USER, $CFG;
352 $options = (array)$options;
353 if (!isset($options['subdirs'])) {
354 $options['subdirs'] = false;
356 if (!isset($options['forcehttps'])) {
357 $options['forcehttps'] = false;
360 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
361 $fs = get_file_storage();
363 if (empty($draftitemid)) {
364 // create a new area and copy existing files into
365 $draftitemid = file_get_unused_draft_itemid();
366 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
367 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
368 foreach ($files as $file) {
369 if ($file->is_directory() and $file->get_filepath() === '/') {
370 // we need a way to mark the age of each draft area,
371 // by not copying the root dir we force it to be created automatically with current timestamp
372 continue;
374 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
375 continue;
377 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
378 // XXX: This is a hack for file manager (MDL-28666)
379 // File manager needs to know the original file information before copying
380 // to draft area, so we append these information in mdl_files.source field
381 // {@link file_storage::search_references()}
382 // {@link file_storage::search_references_count()}
383 $sourcefield = $file->get_source();
384 $newsourcefield = new stdClass;
385 $newsourcefield->source = $sourcefield;
386 $original = new stdClass;
387 $original->contextid = $contextid;
388 $original->component = $component;
389 $original->filearea = $filearea;
390 $original->itemid = $itemid;
391 $original->filename = $file->get_filename();
392 $original->filepath = $file->get_filepath();
393 $newsourcefield->original = file_storage::pack_reference($original);
394 $draftfile->set_source(serialize($newsourcefield));
395 // End of file manager hack
398 if (!is_null($text)) {
399 // at this point there should not be any draftfile links yet,
400 // because this is a new text from database that should still contain the @@pluginfile@@ links
401 // this happens when developers forget to post process the text
402 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
404 } else {
405 // nothing to do
408 if (is_null($text)) {
409 return null;
412 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
413 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
417 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
419 * @category files
420 * @global stdClass $CFG
421 * @param string $text The content that may contain ULRs in need of rewriting.
422 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
423 * @param int $contextid This parameter and the next two identify the file area to use.
424 * @param string $component
425 * @param string $filearea helps identify the file area.
426 * @param int $itemid helps identify the file area.
427 * @param array $options text and file options ('forcehttps'=>false)
428 * @return string the processed text.
430 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
431 global $CFG;
433 $options = (array)$options;
434 if (!isset($options['forcehttps'])) {
435 $options['forcehttps'] = false;
438 if (!$CFG->slasharguments) {
439 $file = $file . '?file=';
442 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
444 if ($itemid !== null) {
445 $baseurl .= "$itemid/";
448 if ($options['forcehttps']) {
449 $baseurl = str_replace('http://', 'https://', $baseurl);
452 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
456 * Returns information about files in a draft area.
458 * @global stdClass $CFG
459 * @global stdClass $USER
460 * @param int $draftitemid the draft area item id.
461 * @return array with the following entries:
462 * 'filecount' => number of files in the draft area.
463 * (more information will be added as needed).
465 function file_get_draft_area_info($draftitemid) {
466 global $CFG, $USER;
468 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
469 $fs = get_file_storage();
471 $results = array();
473 // The number of files
474 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
475 $results['filecount'] = count($draftfiles);
476 $results['filesize'] = 0;
477 foreach ($draftfiles as $file) {
478 $results['filesize'] += $file->get_filesize();
481 return $results;
485 * Get used space of files
486 * @global moodle_database $DB
487 * @global stdClass $USER
488 * @return int total bytes
490 function file_get_user_used_space() {
491 global $DB, $USER;
493 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
494 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
495 JOIN (SELECT contenthash, filename, MAX(id) AS id
496 FROM {files}
497 WHERE contextid = ? AND component = ? AND filearea != ?
498 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
499 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
500 $record = $DB->get_record_sql($sql, $params);
501 return (int)$record->totalbytes;
505 * Convert any string to a valid filepath
506 * @todo review this function
507 * @param string $str
508 * @return string path
510 function file_correct_filepath($str) { //TODO: what is this? (skodak)
511 if ($str == '/' or empty($str)) {
512 return '/';
513 } else {
514 return '/'.trim($str, './@#$ ').'/';
519 * Generate a folder tree of draft area of current USER recursively
521 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
522 * @param int $draftitemid
523 * @param string $filepath
524 * @param mixed $data
526 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
527 global $USER, $OUTPUT, $CFG;
528 $data->children = array();
529 $context = get_context_instance(CONTEXT_USER, $USER->id);
530 $fs = get_file_storage();
531 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
532 foreach ($files as $file) {
533 if ($file->is_directory()) {
534 $item = new stdClass();
535 $item->sortorder = $file->get_sortorder();
536 $item->filepath = $file->get_filepath();
538 $foldername = explode('/', trim($item->filepath, '/'));
539 $item->fullname = trim(array_pop($foldername), '/');
541 $item->id = uniqid();
542 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
543 $data->children[] = $item;
544 } else {
545 continue;
552 * Listing all files (including folders) in current path (draft area)
553 * used by file manager
554 * @param int $draftitemid
555 * @param string $filepath
556 * @return stdClass
558 function file_get_drafarea_files($draftitemid, $filepath = '/') {
559 global $USER, $OUTPUT, $CFG;
561 $context = get_context_instance(CONTEXT_USER, $USER->id);
562 $fs = get_file_storage();
564 $data = new stdClass();
565 $data->path = array();
566 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
568 // will be used to build breadcrumb
569 $trail = '/';
570 if ($filepath !== '/') {
571 $filepath = file_correct_filepath($filepath);
572 $parts = explode('/', $filepath);
573 foreach ($parts as $part) {
574 if ($part != '' && $part != null) {
575 $trail .= ($part.'/');
576 $data->path[] = array('name'=>$part, 'path'=>$trail);
581 $list = array();
582 $maxlength = 12;
583 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
584 foreach ($files as $file) {
585 $item = new stdClass();
586 $item->filename = $file->get_filename();
587 $item->filepath = $file->get_filepath();
588 $item->fullname = trim($item->filename, '/');
589 $filesize = $file->get_filesize();
590 $item->size = $filesize ? $filesize : null;
591 $item->filesize = $filesize ? display_size($filesize) : '';
593 $item->sortorder = $file->get_sortorder();
594 $item->author = $file->get_author();
595 $item->license = $file->get_license();
596 $item->datemodified = $file->get_timemodified();
597 $item->datecreated = $file->get_timecreated();
598 $item->isref = $file->is_external_file();
599 if ($item->isref && $file->get_status() == 666) {
600 $item->originalmissing = true;
602 // find the file this draft file was created from and count all references in local
603 // system pointing to that file
604 $source = @unserialize($file->get_source());
605 if (isset($source->original)) {
606 $item->refcount = $fs->search_references_count($source->original);
609 if ($file->is_directory()) {
610 $item->filesize = 0;
611 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
612 $item->type = 'folder';
613 $foldername = explode('/', trim($item->filepath, '/'));
614 $item->fullname = trim(array_pop($foldername), '/');
615 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
616 } else {
617 // do NOT use file browser here!
618 $item->mimetype = get_mimetype_description($file);
619 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
620 $item->type = 'zip';
621 } else {
622 $item->type = 'file';
624 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
625 $item->url = $itemurl->out();
626 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
627 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
628 if ($imageinfo = $file->get_imageinfo()) {
629 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
630 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
631 $item->image_width = $imageinfo['width'];
632 $item->image_height = $imageinfo['height'];
635 $list[] = $item;
638 $data->itemid = $draftitemid;
639 $data->list = $list;
640 return $data;
644 * Returns draft area itemid for a given element.
646 * @category files
647 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
648 * @return int the itemid, or 0 if there is not one yet.
650 function file_get_submitted_draft_itemid($elname) {
651 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
652 if (!isset($_REQUEST[$elname])) {
653 return 0;
655 if (is_array($_REQUEST[$elname])) {
656 $param = optional_param_array($elname, 0, PARAM_INT);
657 if (!empty($param['itemid'])) {
658 $param = $param['itemid'];
659 } else {
660 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
661 return false;
664 } else {
665 $param = optional_param($elname, 0, PARAM_INT);
668 if ($param) {
669 require_sesskey();
672 return $param;
676 * Restore the original source field from draft files
678 * @param stored_file $storedfile This only works with draft files
679 * @return stored_file
681 function file_restore_source_field_from_draft_file($storedfile) {
682 $source = @unserialize($storedfile->get_source());
683 if (!empty($source)) {
684 if (is_object($source)) {
685 $restoredsource = $source->source;
686 $storedfile->set_source($restoredsource);
687 } else {
688 throw new moodle_exception('invalidsourcefield', 'error');
691 return $storedfile;
694 * Saves files from a draft file area to a real one (merging the list of files).
695 * Can rewrite URLs in some content at the same time if desired.
697 * @category files
698 * @global stdClass $USER
699 * @param int $draftitemid the id of the draft area to use. Normally obtained
700 * from file_get_submitted_draft_itemid('elementname') or similar.
701 * @param int $contextid This parameter and the next two identify the file area to save to.
702 * @param string $component
703 * @param string $filearea indentifies the file area.
704 * @param int $itemid helps identifies the file area.
705 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
706 * @param string $text some html content that needs to have embedded links rewritten
707 * to the @@PLUGINFILE@@ form for saving in the database.
708 * @param bool $forcehttps force https urls.
709 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
711 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
712 global $USER;
714 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
715 $fs = get_file_storage();
717 $options = (array)$options;
718 if (!isset($options['subdirs'])) {
719 $options['subdirs'] = false;
721 if (!isset($options['maxfiles'])) {
722 $options['maxfiles'] = -1; // unlimited
724 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
725 $options['maxbytes'] = 0; // unlimited
727 $allowreferences = true;
728 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
729 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
730 // this is not exactly right. BUT there are many places in code where filemanager options
731 // are not passed to file_save_draft_area_files()
732 $allowreferences = false;
735 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
736 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
738 if (count($draftfiles) < 2) {
739 // means there are no files - one file means root dir only ;-)
740 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
742 } else if (count($oldfiles) < 2) {
743 $filecount = 0;
744 // there were no files before - one file means root dir only ;-)
745 foreach ($draftfiles as $file) {
746 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
747 if (!$options['subdirs']) {
748 if ($file->get_filepath() !== '/' or $file->is_directory()) {
749 continue;
752 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
753 // oversized file - should not get here at all
754 continue;
756 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
757 // more files - should not get here at all
758 break;
760 if (!$file->is_directory()) {
761 $filecount++;
764 if ($file->is_external_file()) {
765 if (!$allowreferences) {
766 continue;
768 $repoid = $file->get_repository_id();
769 if (!empty($repoid)) {
770 $file_record['repositoryid'] = $repoid;
771 $file_record['reference'] = $file->get_reference();
774 file_restore_source_field_from_draft_file($file);
776 $fs->create_file_from_storedfile($file_record, $file);
779 } else {
780 // we have to merge old and new files - we want to keep file ids for files that were not changed
781 // we change time modified for all new and changed files, we keep time created as is
783 $newhashes = array();
784 foreach ($draftfiles as $file) {
785 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
786 file_restore_source_field_from_draft_file($file);
787 $newhashes[$newhash] = $file;
789 $filecount = 0;
790 foreach ($oldfiles as $oldfile) {
791 $oldhash = $oldfile->get_pathnamehash();
792 if (!isset($newhashes[$oldhash])) {
793 // delete files not needed any more - deleted by user
794 $oldfile->delete();
795 continue;
798 $newfile = $newhashes[$oldhash];
799 // status changed, we delete old file, and create a new one
800 if ($oldfile->get_status() != $newfile->get_status()) {
801 // file was changed, use updated with new timemodified data
802 $oldfile->delete();
803 // This file will be added later
804 continue;
807 // Updated author
808 if ($oldfile->get_author() != $newfile->get_author()) {
809 $oldfile->set_author($newfile->get_author());
811 // Updated license
812 if ($oldfile->get_license() != $newfile->get_license()) {
813 $oldfile->set_license($newfile->get_license());
816 // Updated file source
817 if ($oldfile->get_source() != $newfile->get_source()) {
818 $oldfile->set_source($newfile->get_source());
821 // Updated sort order
822 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
823 $oldfile->set_sortorder($newfile->get_sortorder());
826 // Update file timemodified
827 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
828 $oldfile->set_timemodified($newfile->get_timemodified());
831 // Replaced file content
832 if ($oldfile->get_contenthash() != $newfile->get_contenthash() || $oldfile->get_filesize() != $newfile->get_filesize()) {
833 $oldfile->replace_content_with($newfile);
834 // push changes to all local files that are referencing this file
835 $fs->update_references_to_storedfile($oldfile);
838 // unchanged file or directory - we keep it as is
839 unset($newhashes[$oldhash]);
840 if (!$oldfile->is_directory()) {
841 $filecount++;
845 // Add fresh file or the file which has changed status
846 // the size and subdirectory tests are extra safety only, the UI should prevent it
847 foreach ($newhashes as $file) {
848 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
849 if (!$options['subdirs']) {
850 if ($file->get_filepath() !== '/' or $file->is_directory()) {
851 continue;
854 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
855 // oversized file - should not get here at all
856 continue;
858 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
859 // more files - should not get here at all
860 break;
862 if (!$file->is_directory()) {
863 $filecount++;
866 if ($file->is_external_file()) {
867 if (!$allowreferences) {
868 continue;
870 $repoid = $file->get_repository_id();
871 if (!empty($repoid)) {
872 $file_record['repositoryid'] = $repoid;
873 $file_record['reference'] = $file->get_reference();
877 $fs->create_file_from_storedfile($file_record, $file);
881 // note: do not purge the draft area - we clean up areas later in cron,
882 // the reason is that user might press submit twice and they would loose the files,
883 // also sometimes we might want to use hacks that save files into two different areas
885 if (is_null($text)) {
886 return null;
887 } else {
888 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
893 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
894 * ready to be saved in the database. Normally, this is done automatically by
895 * {@link file_save_draft_area_files()}.
897 * @category files
898 * @param string $text the content to process.
899 * @param int $draftitemid the draft file area the content was using.
900 * @param bool $forcehttps whether the content contains https URLs. Default false.
901 * @return string the processed content.
903 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
904 global $CFG, $USER;
906 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
908 $wwwroot = $CFG->wwwroot;
909 if ($forcehttps) {
910 $wwwroot = str_replace('http://', 'https://', $wwwroot);
913 // relink embedded files if text submitted - no absolute links allowed in database!
914 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
916 if (strpos($text, 'draftfile.php?file=') !== false) {
917 $matches = array();
918 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
919 if ($matches) {
920 foreach ($matches[0] as $match) {
921 $replace = str_ireplace('%2F', '/', $match);
922 $text = str_replace($match, $replace, $text);
925 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
928 return $text;
932 * Set file sort order
934 * @global moodle_database $DB
935 * @param int $contextid the context id
936 * @param string $component file component
937 * @param string $filearea file area.
938 * @param int $itemid itemid.
939 * @param string $filepath file path.
940 * @param string $filename file name.
941 * @param int $sortorder the sort order of file.
942 * @return bool
944 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
945 global $DB;
946 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
947 if ($file_record = $DB->get_record('files', $conditions)) {
948 $sortorder = (int)$sortorder;
949 $file_record->sortorder = $sortorder;
950 $DB->update_record('files', $file_record);
951 return true;
953 return false;
957 * reset file sort order number to 0
958 * @global moodle_database $DB
959 * @param int $contextid the context id
960 * @param string $component
961 * @param string $filearea file area.
962 * @param int|bool $itemid itemid.
963 * @return bool
965 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
966 global $DB;
968 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
969 if ($itemid !== false) {
970 $conditions['itemid'] = $itemid;
973 $file_records = $DB->get_records('files', $conditions);
974 foreach ($file_records as $file_record) {
975 $file_record->sortorder = 0;
976 $DB->update_record('files', $file_record);
978 return true;
982 * Returns description of upload error
984 * @param int $errorcode found in $_FILES['filename.ext']['error']
985 * @return string error description string, '' if ok
987 function file_get_upload_error($errorcode) {
989 switch ($errorcode) {
990 case 0: // UPLOAD_ERR_OK - no error
991 $errmessage = '';
992 break;
994 case 1: // UPLOAD_ERR_INI_SIZE
995 $errmessage = get_string('uploadserverlimit');
996 break;
998 case 2: // UPLOAD_ERR_FORM_SIZE
999 $errmessage = get_string('uploadformlimit');
1000 break;
1002 case 3: // UPLOAD_ERR_PARTIAL
1003 $errmessage = get_string('uploadpartialfile');
1004 break;
1006 case 4: // UPLOAD_ERR_NO_FILE
1007 $errmessage = get_string('uploadnofilefound');
1008 break;
1010 // Note: there is no error with a value of 5
1012 case 6: // UPLOAD_ERR_NO_TMP_DIR
1013 $errmessage = get_string('uploadnotempdir');
1014 break;
1016 case 7: // UPLOAD_ERR_CANT_WRITE
1017 $errmessage = get_string('uploadcantwrite');
1018 break;
1020 case 8: // UPLOAD_ERR_EXTENSION
1021 $errmessage = get_string('uploadextension');
1022 break;
1024 default:
1025 $errmessage = get_string('uploadproblem');
1028 return $errmessage;
1032 * Recursive function formating an array in POST parameter
1033 * @param array $arraydata - the array that we are going to format and add into &$data array
1034 * @param string $currentdata - a row of the final postdata array at instant T
1035 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1036 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1038 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1039 foreach ($arraydata as $k=>$v) {
1040 $newcurrentdata = $currentdata;
1041 if (is_array($v)) { //the value is an array, call the function recursively
1042 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1043 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1044 } else { //add the POST parameter to the $data array
1045 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1051 * Transform a PHP array into POST parameter
1052 * (see the recursive function format_array_postdata_for_curlcall)
1053 * @param array $postdata
1054 * @return array containing all POST parameters (1 row = 1 POST parameter)
1056 function format_postdata_for_curlcall($postdata) {
1057 $data = array();
1058 foreach ($postdata as $k=>$v) {
1059 if (is_array($v)) {
1060 $currentdata = urlencode($k);
1061 format_array_postdata_for_curlcall($v, $currentdata, $data);
1062 } else {
1063 $data[] = urlencode($k).'='.urlencode($v);
1066 $convertedpostdata = implode('&', $data);
1067 return $convertedpostdata;
1071 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1072 * Due to security concerns only downloads from http(s) sources are supported.
1074 * @todo MDL-31073 add version test for '7.10.5'
1075 * @category files
1076 * @param string $url file url starting with http(s)://
1077 * @param array $headers http headers, null if none. If set, should be an
1078 * associative array of header name => value pairs.
1079 * @param array $postdata array means use POST request with given parameters
1080 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1081 * (if false, just returns content)
1082 * @param int $timeout timeout for complete download process including all file transfer
1083 * (default 5 minutes)
1084 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1085 * usually happens if the remote server is completely down (default 20 seconds);
1086 * may not work when using proxy
1087 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1088 * Only use this when already in a trusted location.
1089 * @param string $tofile store the downloaded content to file instead of returning it.
1090 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1091 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1092 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1094 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1095 global $CFG;
1097 // some extra security
1098 $newlines = array("\r", "\n");
1099 if (is_array($headers) ) {
1100 foreach ($headers as $key => $value) {
1101 $headers[$key] = str_replace($newlines, '', $value);
1104 $url = str_replace($newlines, '', $url);
1105 if (!preg_match('|^https?://|i', $url)) {
1106 if ($fullresponse) {
1107 $response = new stdClass();
1108 $response->status = 0;
1109 $response->headers = array();
1110 $response->response_code = 'Invalid protocol specified in url';
1111 $response->results = '';
1112 $response->error = 'Invalid protocol specified in url';
1113 return $response;
1114 } else {
1115 return false;
1119 // check if proxy (if used) should be bypassed for this url
1120 $proxybypass = is_proxybypass($url);
1122 if (!$ch = curl_init($url)) {
1123 debugging('Can not init curl.');
1124 return false;
1127 // set extra headers
1128 if (is_array($headers) ) {
1129 $headers2 = array();
1130 foreach ($headers as $key => $value) {
1131 $headers2[] = "$key: $value";
1133 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1136 if ($skipcertverify) {
1137 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1140 // use POST if requested
1141 if (is_array($postdata)) {
1142 $postdata = format_postdata_for_curlcall($postdata);
1143 curl_setopt($ch, CURLOPT_POST, true);
1144 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1147 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1148 curl_setopt($ch, CURLOPT_HEADER, false);
1149 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1151 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1152 // TODO: add version test for '7.10.5'
1153 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1154 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1157 if (!empty($CFG->proxyhost) and !$proxybypass) {
1158 // SOCKS supported in PHP5 only
1159 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1160 if (defined('CURLPROXY_SOCKS5')) {
1161 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1162 } else {
1163 curl_close($ch);
1164 if ($fullresponse) {
1165 $response = new stdClass();
1166 $response->status = '0';
1167 $response->headers = array();
1168 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1169 $response->results = '';
1170 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1171 return $response;
1172 } else {
1173 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1174 return false;
1179 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1181 if (empty($CFG->proxyport)) {
1182 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1183 } else {
1184 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1187 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1188 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1189 if (defined('CURLOPT_PROXYAUTH')) {
1190 // any proxy authentication if PHP 5.1
1191 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1196 // set up header and content handlers
1197 $received = new stdClass();
1198 $received->headers = array(); // received headers array
1199 $received->tofile = $tofile;
1200 $received->fh = null;
1201 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1202 if ($tofile) {
1203 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1206 if (!isset($CFG->curltimeoutkbitrate)) {
1207 //use very slow rate of 56kbps as a timeout speed when not set
1208 $bitrate = 56;
1209 } else {
1210 $bitrate = $CFG->curltimeoutkbitrate;
1213 // try to calculate the proper amount for timeout from remote file size.
1214 // if disabled or zero, we won't do any checks nor head requests.
1215 if ($calctimeout && $bitrate > 0) {
1216 //setup header request only options
1217 curl_setopt_array ($ch, array(
1218 CURLOPT_RETURNTRANSFER => false,
1219 CURLOPT_NOBODY => true)
1222 curl_exec($ch);
1223 $info = curl_getinfo($ch);
1224 $err = curl_error($ch);
1226 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1227 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1229 //reinstate affected curl options
1230 curl_setopt_array ($ch, array(
1231 CURLOPT_RETURNTRANSFER => true,
1232 CURLOPT_NOBODY => false)
1236 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1237 $result = curl_exec($ch);
1239 // try to detect encoding problems
1240 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1241 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1242 $result = curl_exec($ch);
1245 if ($received->fh) {
1246 fclose($received->fh);
1249 if (curl_errno($ch)) {
1250 $error = curl_error($ch);
1251 $error_no = curl_errno($ch);
1252 curl_close($ch);
1254 if ($fullresponse) {
1255 $response = new stdClass();
1256 if ($error_no == 28) {
1257 $response->status = '-100'; // mimic snoopy
1258 } else {
1259 $response->status = '0';
1261 $response->headers = array();
1262 $response->response_code = $error;
1263 $response->results = false;
1264 $response->error = $error;
1265 return $response;
1266 } else {
1267 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1268 return false;
1271 } else {
1272 $info = curl_getinfo($ch);
1273 curl_close($ch);
1275 if (empty($info['http_code'])) {
1276 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1277 $response = new stdClass();
1278 $response->status = '0';
1279 $response->headers = array();
1280 $response->response_code = 'Unknown cURL error';
1281 $response->results = false; // do NOT change this, we really want to ignore the result!
1282 $response->error = 'Unknown cURL error';
1284 } else {
1285 $response = new stdClass();;
1286 $response->status = (string)$info['http_code'];
1287 $response->headers = $received->headers;
1288 $response->response_code = $received->headers[0];
1289 $response->results = $result;
1290 $response->error = '';
1293 if ($fullresponse) {
1294 return $response;
1295 } else if ($info['http_code'] != 200) {
1296 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1297 return false;
1298 } else {
1299 return $response->results;
1305 * internal implementation
1306 * @param stdClass $received
1307 * @param resource $ch
1308 * @param mixed $header
1309 * @return int header length
1311 function download_file_content_header_handler($received, $ch, $header) {
1312 $received->headers[] = $header;
1313 return strlen($header);
1317 * internal implementation
1318 * @param stdClass $received
1319 * @param resource $ch
1320 * @param mixed $data
1322 function download_file_content_write_handler($received, $ch, $data) {
1323 if (!$received->fh) {
1324 $received->fh = fopen($received->tofile, 'w');
1325 if ($received->fh === false) {
1326 // bad luck, file creation or overriding failed
1327 return 0;
1330 if (fwrite($received->fh, $data) === false) {
1331 // bad luck, write failed, let's abort completely
1332 return 0;
1334 return strlen($data);
1338 * Returns a list of information about file types based on extensions.
1340 * The following elements expected in value array for each extension:
1341 * 'type' - mimetype
1342 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1343 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1344 * also files with bigger sizes under names
1345 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1346 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1347 * commonly used in moodle the following groups:
1348 * - web_image - image that can be included as <img> in HTML
1349 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1350 * - video - file that can be imported as video in text editor
1351 * - audio - file that can be imported as audio in text editor
1352 * - archive - we can extract files from this archive
1353 * - spreadsheet - used for portfolio format
1354 * - document - used for portfolio format
1355 * - presentation - used for portfolio format
1356 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1357 * human-readable description for this filetype;
1358 * Function {@link get_mimetype_description()} first looks at the presence of string for
1359 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1360 * attribute, if not found returns the value of 'type';
1361 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1362 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1363 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1365 * @category files
1366 * @return array List of information about file types based on extensions.
1367 * Associative array of extension (lower-case) to associative array
1368 * from 'element name' to data. Current element names are 'type' and 'icon'.
1369 * Unknown types should use the 'xxx' entry which includes defaults.
1371 function &get_mimetypes_array() {
1372 static $mimearray = array (
1373 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1374 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1375 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1376 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1377 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1378 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1379 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1380 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1381 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1382 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1383 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1384 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1385 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1386 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1387 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1388 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1389 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1390 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1391 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1392 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1393 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1394 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1396 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1397 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1398 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1399 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1400 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1402 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1403 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1404 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1405 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1406 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1407 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1408 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1409 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1410 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1412 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1413 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1414 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1415 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1416 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1417 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1418 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1419 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1420 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1421 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1422 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1423 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1424 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1425 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1426 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1427 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1428 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1429 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1430 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1431 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1432 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1433 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1434 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1435 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1436 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1437 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1438 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1439 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1440 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1441 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1442 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1443 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1444 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1445 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1446 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1447 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1448 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1449 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1450 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1451 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1452 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1453 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1454 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1455 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1456 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1458 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1459 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1461 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1462 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1463 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1464 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1465 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1466 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1467 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1468 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1469 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1470 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1471 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1472 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1473 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1474 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1475 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1476 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1477 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1479 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1480 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1481 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1482 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1483 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1484 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1486 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1487 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1488 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1489 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1490 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1491 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1492 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1493 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1494 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1496 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1497 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1498 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1499 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1500 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1501 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1502 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1503 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1504 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1505 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1506 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1507 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1508 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1509 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1510 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1511 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1512 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1513 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1514 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1515 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1517 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1518 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1519 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1520 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1521 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1522 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1523 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1524 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1525 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1526 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1528 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1529 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1530 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1531 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1532 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1533 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1534 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1535 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1536 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1537 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1538 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1539 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1541 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1542 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1543 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1544 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1546 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1547 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1548 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1549 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1550 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1551 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1552 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1554 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1555 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1557 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1559 return $mimearray;
1563 * Obtains information about a filetype based on its extension. Will
1564 * use a default if no information is present about that particular
1565 * extension.
1567 * @category files
1568 * @param string $element Desired information (usually 'icon'
1569 * for icon filename or 'type' for MIME type. Can also be
1570 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1571 * @param string $filename Filename we're looking up
1572 * @return string Requested piece of information from array
1574 function mimeinfo($element, $filename) {
1575 global $CFG;
1576 $mimeinfo = & get_mimetypes_array();
1577 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1579 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1580 if (empty($filetype)) {
1581 $filetype = 'xxx'; // file without extension
1583 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1584 $iconsize = max(array(16, (int)$iconsizematch[1]));
1585 $filenames = array($mimeinfo['xxx']['icon']);
1586 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1587 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1589 // find the file with the closest size, first search for specific icon then for default icon
1590 foreach ($filenames as $filename) {
1591 foreach ($iconpostfixes as $size => $postfix) {
1592 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1593 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1594 return $filename.$postfix;
1598 } else if (isset($mimeinfo[$filetype][$element])) {
1599 return $mimeinfo[$filetype][$element];
1600 } else if (isset($mimeinfo['xxx'][$element])) {
1601 return $mimeinfo['xxx'][$element]; // By default
1602 } else {
1603 return null;
1608 * Obtains information about a filetype based on the MIME type rather than
1609 * the other way around.
1611 * @category files
1612 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1613 * @param string $mimetype MIME type we're looking up
1614 * @return string Requested piece of information from array
1616 function mimeinfo_from_type($element, $mimetype) {
1617 /* array of cached mimetype->extension associations */
1618 static $cached = array();
1619 $mimeinfo = & get_mimetypes_array();
1621 if (!array_key_exists($mimetype, $cached)) {
1622 $cached[$mimetype] = null;
1623 foreach($mimeinfo as $filetype => $values) {
1624 if ($values['type'] == $mimetype) {
1625 if ($cached[$mimetype] === null) {
1626 $cached[$mimetype] = '.'.$filetype;
1628 if (!empty($values['defaulticon'])) {
1629 $cached[$mimetype] = '.'.$filetype;
1630 break;
1634 if (empty($cached[$mimetype])) {
1635 $cached[$mimetype] = '.xxx';
1638 if ($element === 'extension') {
1639 return $cached[$mimetype];
1640 } else {
1641 return mimeinfo($element, $cached[$mimetype]);
1646 * Return the relative icon path for a given file
1648 * Usage:
1649 * <code>
1650 * // $file - instance of stored_file or file_info
1651 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1652 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1653 * </code>
1654 * or
1655 * <code>
1656 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1657 * </code>
1659 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1660 * and $file->mimetype are expected)
1661 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1662 * @return string
1664 function file_file_icon($file, $size = null) {
1665 if (!is_object($file)) {
1666 $file = (object)$file;
1668 if (isset($file->filename)) {
1669 $filename = $file->filename;
1670 } else if (method_exists($file, 'get_filename')) {
1671 $filename = $file->get_filename();
1672 } else if (method_exists($file, 'get_visible_name')) {
1673 $filename = $file->get_visible_name();
1674 } else {
1675 $filename = '';
1677 if (isset($file->mimetype)) {
1678 $mimetype = $file->mimetype;
1679 } else if (method_exists($file, 'get_mimetype')) {
1680 $mimetype = $file->get_mimetype();
1681 } else {
1682 $mimetype = '';
1684 $mimetypes = &get_mimetypes_array();
1685 if ($filename) {
1686 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1687 if ($extension && !empty($mimetypes[$extension])) {
1688 // if file name has known extension, return icon for this extension
1689 return file_extension_icon($filename, $size);
1692 return file_mimetype_icon($mimetype, $size);
1696 * Return the relative icon path for a folder image
1698 * Usage:
1699 * <code>
1700 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1701 * echo html_writer::empty_tag('img', array('src' => $icon));
1702 * </code>
1703 * or
1704 * <code>
1705 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1706 * </code>
1708 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1709 * @return string
1711 function file_folder_icon($iconsize = null) {
1712 global $CFG;
1713 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1714 static $cached = array();
1715 $iconsize = max(array(16, (int)$iconsize));
1716 if (!array_key_exists($iconsize, $cached)) {
1717 foreach ($iconpostfixes as $size => $postfix) {
1718 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1719 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1720 $cached[$iconsize] = 'f/folder'.$postfix;
1721 break;
1725 return $cached[$iconsize];
1729 * Returns the relative icon path for a given mime type
1731 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1732 * a return the full path to an icon.
1734 * <code>
1735 * $mimetype = 'image/jpg';
1736 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1737 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1738 * </code>
1740 * @category files
1741 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1742 * to conform with that.
1743 * @param string $mimetype The mimetype to fetch an icon for
1744 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1745 * @return string The relative path to the icon
1747 function file_mimetype_icon($mimetype, $size = NULL) {
1748 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1752 * Returns the relative icon path for a given file name
1754 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1755 * a return the full path to an icon.
1757 * <code>
1758 * $filename = '.jpg';
1759 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1760 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1761 * </code>
1763 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1764 * to conform with that.
1765 * @todo MDL-31074 Implement $size
1766 * @category files
1767 * @param string $filename The filename to get the icon for
1768 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1769 * @return string
1771 function file_extension_icon($filename, $size = NULL) {
1772 return 'f/'.mimeinfo('icon'.$size, $filename);
1776 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1777 * mimetypes.php language file.
1779 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1780 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1781 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1782 * @param bool $capitalise If true, capitalises first character of result
1783 * @return string Text description
1785 function get_mimetype_description($obj, $capitalise=false) {
1786 $filename = $mimetype = '';
1787 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1788 // this is an instance of stored_file
1789 $mimetype = $obj->get_mimetype();
1790 $filename = $obj->get_filename();
1791 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1792 // this is an instance of file_info
1793 $mimetype = $obj->get_mimetype();
1794 $filename = $obj->get_visible_name();
1795 } else if (is_array($obj) || is_object ($obj)) {
1796 $obj = (array)$obj;
1797 if (!empty($obj['filename'])) {
1798 $filename = $obj['filename'];
1800 if (!empty($obj['mimetype'])) {
1801 $mimetype = $obj['mimetype'];
1803 } else {
1804 $mimetype = $obj;
1806 $mimetypefromext = mimeinfo('type', $filename);
1807 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1808 // if file has a known extension, overwrite the specified mimetype
1809 $mimetype = $mimetypefromext;
1811 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1812 if (empty($extension)) {
1813 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1814 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1815 } else {
1816 $mimetypestr = mimeinfo('string', $filename);
1818 $chunks = explode('/', $mimetype, 2);
1819 $chunks[] = '';
1820 $attr = array(
1821 'mimetype' => $mimetype,
1822 'ext' => $extension,
1823 'mimetype1' => $chunks[0],
1824 'mimetype2' => $chunks[1],
1826 $a = array();
1827 foreach ($attr as $key => $value) {
1828 $a[$key] = $value;
1829 $a[strtoupper($key)] = strtoupper($value);
1830 $a[ucfirst($key)] = ucfirst($value);
1833 // MIME types may include + symbol but this is not permitted in string ids.
1834 $safemimetype = str_replace('+', '_', $mimetype);
1835 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1836 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1837 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1838 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1839 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1840 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1841 $result = get_string('default', 'mimetypes', (object)$a);
1842 } else {
1843 $result = $mimetype;
1845 if ($capitalise) {
1846 $result=ucfirst($result);
1848 return $result;
1852 * Returns array of elements of type $element in type group(s)
1854 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1855 * @param string|array $groups one group or array of groups/extensions/mimetypes
1856 * @return array
1858 function file_get_typegroup($element, $groups) {
1859 static $cached = array();
1860 if (!is_array($groups)) {
1861 $groups = array($groups);
1863 if (!array_key_exists($element, $cached)) {
1864 $cached[$element] = array();
1866 $result = array();
1867 foreach ($groups as $group) {
1868 if (!array_key_exists($group, $cached[$element])) {
1869 // retrieive and cache all elements of type $element for group $group
1870 $mimeinfo = & get_mimetypes_array();
1871 $cached[$element][$group] = array();
1872 foreach ($mimeinfo as $extension => $value) {
1873 $value['extension'] = '.'.$extension;
1874 if (empty($value[$element])) {
1875 continue;
1877 if (($group === '.'.$extension || $group === $value['type'] ||
1878 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1879 !in_array($value[$element], $cached[$element][$group])) {
1880 $cached[$element][$group][] = $value[$element];
1884 $result = array_merge($result, $cached[$element][$group]);
1886 return array_unique($result);
1890 * Checks if file with name $filename has one of the extensions in groups $groups
1892 * @see get_mimetypes_array()
1893 * @param string $filename name of the file to check
1894 * @param string|array $groups one group or array of groups to check
1895 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1896 * file mimetype is in mimetypes in groups $groups
1897 * @return bool
1899 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1900 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1901 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1902 return true;
1904 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1908 * Checks if mimetype $mimetype belongs to one of the groups $groups
1910 * @see get_mimetypes_array()
1911 * @param string $mimetype
1912 * @param string|array $groups one group or array of groups to check
1913 * @return bool
1915 function file_mimetype_in_typegroup($mimetype, $groups) {
1916 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1920 * Requested file is not found or not accessible, does not return, terminates script
1922 * @global stdClass $CFG
1923 * @global stdClass $COURSE
1925 function send_file_not_found() {
1926 global $CFG, $COURSE;
1927 send_header_404();
1928 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1931 * Helper function to send correct 404 for server.
1933 function send_header_404() {
1934 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1935 header("Status: 404 Not Found");
1936 } else {
1937 header('HTTP/1.0 404 not found');
1942 * Enhanced readfile() with optional acceleration.
1943 * @param string|stored_file $file
1944 * @param string $mimetype
1945 * @param bool $accelerate
1946 * @return void
1948 function readfile_accel($file, $mimetype, $accelerate) {
1949 global $CFG;
1951 if ($mimetype === 'text/plain') {
1952 // there is no encoding specified in text files, we need something consistent
1953 header('Content-Type: text/plain; charset=utf-8');
1954 } else {
1955 header('Content-Type: '.$mimetype);
1958 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1959 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1961 if (is_object($file)) {
1962 header('ETag: ' . $file->get_contenthash());
1963 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1964 header('HTTP/1.1 304 Not Modified');
1965 return;
1969 // if etag present for stored file rely on it exclusively
1970 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1971 // get unixtime of request header; clip extra junk off first
1972 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1973 if ($since && $since >= $lastmodified) {
1974 header('HTTP/1.1 304 Not Modified');
1975 return;
1979 if ($accelerate and !empty($CFG->xsendfile)) {
1980 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1981 header('Accept-Ranges: bytes');
1982 } else {
1983 header('Accept-Ranges: none');
1986 if (is_object($file)) {
1987 $fs = get_file_storage();
1988 if ($fs->xsendfile($file->get_contenthash())) {
1989 return;
1992 } else {
1993 require_once("$CFG->libdir/xsendfilelib.php");
1994 if (xsendfile($file)) {
1995 return;
2000 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2002 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2004 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2005 header('Accept-Ranges: bytes');
2007 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2008 // byteserving stuff - for acrobat reader and download accelerators
2009 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2010 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2011 $ranges = false;
2012 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2013 foreach ($ranges as $key=>$value) {
2014 if ($ranges[$key][1] == '') {
2015 //suffix case
2016 $ranges[$key][1] = $filesize - $ranges[$key][2];
2017 $ranges[$key][2] = $filesize - 1;
2018 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2019 //fix range length
2020 $ranges[$key][2] = $filesize - 1;
2022 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2023 //invalid byte-range ==> ignore header
2024 $ranges = false;
2025 break;
2027 //prepare multipart header
2028 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2029 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2031 } else {
2032 $ranges = false;
2034 if ($ranges) {
2035 if (is_object($file)) {
2036 $handle = $file->get_content_file_handle();
2037 } else {
2038 $handle = fopen($file, 'rb');
2040 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2043 } else {
2044 // Do not byteserve
2045 header('Accept-Ranges: none');
2048 header('Content-Length: '.$filesize);
2050 if ($filesize > 10000000) {
2051 // for large files try to flush and close all buffers to conserve memory
2052 while(@ob_get_level()) {
2053 if (!@ob_end_flush()) {
2054 break;
2059 // send the whole file content
2060 if (is_object($file)) {
2061 $file->readfile();
2062 } else {
2063 readfile($file);
2068 * Similar to readfile_accel() but designed for strings.
2069 * @param string $string
2070 * @param string $mimetype
2071 * @param bool $accelerate
2072 * @return void
2074 function readstring_accel($string, $mimetype, $accelerate) {
2075 global $CFG;
2077 if ($mimetype === 'text/plain') {
2078 // there is no encoding specified in text files, we need something consistent
2079 header('Content-Type: text/plain; charset=utf-8');
2080 } else {
2081 header('Content-Type: '.$mimetype);
2083 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2084 header('Accept-Ranges: none');
2086 if ($accelerate and !empty($CFG->xsendfile)) {
2087 $fs = get_file_storage();
2088 if ($fs->xsendfile(sha1($string))) {
2089 return;
2093 header('Content-Length: '.strlen($string));
2094 echo $string;
2098 * Handles the sending of temporary file to user, download is forced.
2099 * File is deleted after abort or successful sending, does not return, script terminated
2101 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2102 * @param string $filename proposed file name when saving file
2103 * @param bool $pathisstring If the path is string
2105 function send_temp_file($path, $filename, $pathisstring=false) {
2106 global $CFG;
2108 if (check_browser_version('Firefox', '1.5')) {
2109 // only FF is known to correctly save to disk before opening...
2110 $mimetype = mimeinfo('type', $filename);
2111 } else {
2112 $mimetype = 'application/x-forcedownload';
2115 // close session - not needed anymore
2116 session_get_instance()->write_close();
2118 if (!$pathisstring) {
2119 if (!file_exists($path)) {
2120 send_header_404();
2121 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2123 // executed after normal finish or abort
2124 @register_shutdown_function('send_temp_file_finished', $path);
2127 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2128 if (check_browser_version('MSIE')) {
2129 $filename = urlencode($filename);
2132 header('Content-Disposition: attachment; filename="'.$filename.'"');
2133 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2134 header('Cache-Control: max-age=10');
2135 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2136 header('Pragma: ');
2137 } else { //normal http - prevent caching at all cost
2138 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2139 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2140 header('Pragma: no-cache');
2143 // send the contents - we can not accelerate this because the file will be deleted asap
2144 if ($pathisstring) {
2145 readstring_accel($path, $mimetype, false);
2146 } else {
2147 readfile_accel($path, $mimetype, false);
2148 @unlink($path);
2151 die; //no more chars to output
2155 * Internal callback function used by send_temp_file()
2157 * @param string $path
2159 function send_temp_file_finished($path) {
2160 if (file_exists($path)) {
2161 @unlink($path);
2166 * Handles the sending of file data to the user's browser, including support for
2167 * byteranges etc.
2169 * @category files
2170 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2171 * @param string $filename Filename to send
2172 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2173 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2174 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2175 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2176 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2177 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2178 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2179 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2180 * and should not be reopened.
2181 * @return null script execution stopped unless $dontdie is true
2183 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2184 global $CFG, $COURSE;
2186 if ($dontdie) {
2187 ignore_user_abort(true);
2190 // MDL-11789, apply $CFG->filelifetime here
2191 if ($lifetime === 'default') {
2192 if (!empty($CFG->filelifetime)) {
2193 $lifetime = $CFG->filelifetime;
2194 } else {
2195 $lifetime = 86400;
2199 session_get_instance()->write_close(); // unlock session during fileserving
2201 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2202 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2203 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2204 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2205 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2206 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2208 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2209 if (check_browser_version('MSIE')) {
2210 $filename = rawurlencode($filename);
2213 if ($forcedownload) {
2214 header('Content-Disposition: attachment; filename="'.$filename.'"');
2215 } else {
2216 header('Content-Disposition: inline; filename="'.$filename.'"');
2219 if ($lifetime > 0) {
2220 $nobyteserving = false;
2221 header('Cache-Control: max-age='.$lifetime);
2222 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2223 header('Pragma: ');
2225 } else { // Do not cache files in proxies and browsers
2226 $nobyteserving = true;
2227 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2228 header('Cache-Control: max-age=10');
2229 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2230 header('Pragma: ');
2231 } else { //normal http - prevent caching at all cost
2232 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2233 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2234 header('Pragma: no-cache');
2238 if (empty($filter)) {
2239 // send the contents
2240 if ($pathisstring) {
2241 readstring_accel($path, $mimetype, !$dontdie);
2242 } else {
2243 readfile_accel($path, $mimetype, !$dontdie);
2246 } else {
2247 // Try to put the file through filters
2248 if ($mimetype == 'text/html') {
2249 $options = new stdClass();
2250 $options->noclean = true;
2251 $options->nocache = true; // temporary workaround for MDL-5136
2252 $text = $pathisstring ? $path : implode('', file($path));
2254 $text = file_modify_html_header($text);
2255 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2257 readstring_accel($output, $mimetype, false);
2259 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2260 // only filter text if filter all files is selected
2261 $options = new stdClass();
2262 $options->newlines = false;
2263 $options->noclean = true;
2264 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2265 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2267 readstring_accel($output, $mimetype, false);
2269 } else {
2270 // send the contents
2271 if ($pathisstring) {
2272 readstring_accel($path, $mimetype, !$dontdie);
2273 } else {
2274 readfile_accel($path, $mimetype, !$dontdie);
2278 if ($dontdie) {
2279 return;
2281 die; //no more chars to output!!!
2285 * Handles the sending of file data to the user's browser, including support for
2286 * byteranges etc.
2288 * The $options parameter supports the following keys:
2289 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2290 * (string|null) filename - overrides the implicit filename
2291 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2292 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2293 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2294 * and should not be reopened.
2296 * @category files
2297 * @param stored_file $stored_file local file object
2298 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2299 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2300 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2301 * @param array $options additional options affecting the file serving
2302 * @return null script execution stopped unless $options['dontdie'] is true
2304 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2305 global $CFG, $COURSE;
2307 if (empty($options['filename'])) {
2308 $filename = null;
2309 } else {
2310 $filename = $options['filename'];
2313 if (empty($options['dontdie'])) {
2314 $dontdie = false;
2315 } else {
2316 $dontdie = true;
2319 if (!empty($options['preview'])) {
2320 // replace the file with its preview
2321 $fs = get_file_storage();
2322 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2323 if (!$preview_file) {
2324 // unable to create a preview of the file, send its default mime icon instead
2325 if ($options['preview'] === 'tinyicon') {
2326 $size = 24;
2327 } else if ($options['preview'] === 'thumb') {
2328 $size = 90;
2329 } else {
2330 $size = 256;
2332 $fileicon = file_file_icon($stored_file, $size);
2333 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2334 } else {
2335 // preview images have fixed cache lifetime and they ignore forced download
2336 // (they are generated by GD and therefore they are considered reasonably safe).
2337 $stored_file = $preview_file;
2338 $lifetime = DAYSECS;
2339 $filter = 0;
2340 $forcedownload = false;
2344 // handle external resource
2345 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2346 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2347 die;
2350 if (!$stored_file or $stored_file->is_directory()) {
2351 // nothing to serve
2352 if ($dontdie) {
2353 return;
2355 die;
2358 if ($dontdie) {
2359 ignore_user_abort(true);
2362 session_get_instance()->write_close(); // unlock session during fileserving
2364 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2365 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2366 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2367 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2368 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2369 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2370 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2372 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2373 if (check_browser_version('MSIE')) {
2374 $filename = rawurlencode($filename);
2377 if ($forcedownload) {
2378 header('Content-Disposition: attachment; filename="'.$filename.'"');
2379 } else {
2380 header('Content-Disposition: inline; filename="'.$filename.'"');
2383 if ($lifetime > 0) {
2384 header('Cache-Control: max-age='.$lifetime);
2385 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2386 header('Pragma: ');
2388 } else { // Do not cache files in proxies and browsers
2389 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2390 header('Cache-Control: max-age=10');
2391 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2392 header('Pragma: ');
2393 } else { //normal http - prevent caching at all cost
2394 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2395 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2396 header('Pragma: no-cache');
2400 if (empty($filter)) {
2401 // send the contents
2402 readfile_accel($stored_file, $mimetype, !$dontdie);
2404 } else { // Try to put the file through filters
2405 if ($mimetype == 'text/html') {
2406 $options = new stdClass();
2407 $options->noclean = true;
2408 $options->nocache = true; // temporary workaround for MDL-5136
2409 $text = $stored_file->get_content();
2410 $text = file_modify_html_header($text);
2411 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2413 readstring_accel($output, $mimetype, false);
2415 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2416 // only filter text if filter all files is selected
2417 $options = new stdClass();
2418 $options->newlines = false;
2419 $options->noclean = true;
2420 $text = $stored_file->get_content();
2421 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2423 readstring_accel($output, $mimetype, false);
2425 } else { // Just send it out raw
2426 readfile_accel($stored_file, $mimetype, !$dontdie);
2429 if ($dontdie) {
2430 return;
2432 die; //no more chars to output!!!
2436 * Retrieves an array of records from a CSV file and places
2437 * them into a given table structure
2439 * @global stdClass $CFG
2440 * @global moodle_database $DB
2441 * @param string $file The path to a CSV file
2442 * @param string $table The table to retrieve columns from
2443 * @return bool|array Returns an array of CSV records or false
2445 function get_records_csv($file, $table) {
2446 global $CFG, $DB;
2448 if (!$metacolumns = $DB->get_columns($table)) {
2449 return false;
2452 if(!($handle = @fopen($file, 'r'))) {
2453 print_error('get_records_csv failed to open '.$file);
2456 $fieldnames = fgetcsv($handle, 4096);
2457 if(empty($fieldnames)) {
2458 fclose($handle);
2459 return false;
2462 $columns = array();
2464 foreach($metacolumns as $metacolumn) {
2465 $ord = array_search($metacolumn->name, $fieldnames);
2466 if(is_int($ord)) {
2467 $columns[$metacolumn->name] = $ord;
2471 $rows = array();
2473 while (($data = fgetcsv($handle, 4096)) !== false) {
2474 $item = new stdClass;
2475 foreach($columns as $name => $ord) {
2476 $item->$name = $data[$ord];
2478 $rows[] = $item;
2481 fclose($handle);
2482 return $rows;
2486 * Create a file with CSV contents
2488 * @global stdClass $CFG
2489 * @global moodle_database $DB
2490 * @param string $file The file to put the CSV content into
2491 * @param array $records An array of records to write to a CSV file
2492 * @param string $table The table to get columns from
2493 * @return bool success
2495 function put_records_csv($file, $records, $table = NULL) {
2496 global $CFG, $DB;
2498 if (empty($records)) {
2499 return true;
2502 $metacolumns = NULL;
2503 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2504 return false;
2507 echo "x";
2509 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2510 print_error('put_records_csv failed to open '.$file);
2513 $proto = reset($records);
2514 if(is_object($proto)) {
2515 $fields_records = array_keys(get_object_vars($proto));
2517 else if(is_array($proto)) {
2518 $fields_records = array_keys($proto);
2520 else {
2521 return false;
2523 echo "x";
2525 if(!empty($metacolumns)) {
2526 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2527 $fields = array_intersect($fields_records, $fields_table);
2529 else {
2530 $fields = $fields_records;
2533 fwrite($fp, implode(',', $fields));
2534 fwrite($fp, "\r\n");
2536 foreach($records as $record) {
2537 $array = (array)$record;
2538 $values = array();
2539 foreach($fields as $field) {
2540 if(strpos($array[$field], ',')) {
2541 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2543 else {
2544 $values[] = $array[$field];
2547 fwrite($fp, implode(',', $values)."\r\n");
2550 fclose($fp);
2551 return true;
2556 * Recursively delete the file or folder with path $location. That is,
2557 * if it is a file delete it. If it is a folder, delete all its content
2558 * then delete it. If $location does not exist to start, that is not
2559 * considered an error.
2561 * @param string $location the path to remove.
2562 * @return bool
2564 function fulldelete($location) {
2565 if (empty($location)) {
2566 // extra safety against wrong param
2567 return false;
2569 if (is_dir($location)) {
2570 if (!$currdir = opendir($location)) {
2571 return false;
2573 while (false !== ($file = readdir($currdir))) {
2574 if ($file <> ".." && $file <> ".") {
2575 $fullfile = $location."/".$file;
2576 if (is_dir($fullfile)) {
2577 if (!fulldelete($fullfile)) {
2578 return false;
2580 } else {
2581 if (!unlink($fullfile)) {
2582 return false;
2587 closedir($currdir);
2588 if (! rmdir($location)) {
2589 return false;
2592 } else if (file_exists($location)) {
2593 if (!unlink($location)) {
2594 return false;
2597 return true;
2601 * Send requested byterange of file.
2603 * @param resource $handle A file handle
2604 * @param string $mimetype The mimetype for the output
2605 * @param array $ranges An array of ranges to send
2606 * @param string $filesize The size of the content if only one range is used
2608 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2609 // better turn off any kind of compression and buffering
2610 @ini_set('zlib.output_compression', 'Off');
2612 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2613 if ($handle === false) {
2614 die;
2616 if (count($ranges) == 1) { //only one range requested
2617 $length = $ranges[0][2] - $ranges[0][1] + 1;
2618 header('HTTP/1.1 206 Partial content');
2619 header('Content-Length: '.$length);
2620 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2621 header('Content-Type: '.$mimetype);
2623 while(@ob_get_level()) {
2624 if (!@ob_end_flush()) {
2625 break;
2629 fseek($handle, $ranges[0][1]);
2630 while (!feof($handle) && $length > 0) {
2631 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2632 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2633 echo $buffer;
2634 flush();
2635 $length -= strlen($buffer);
2637 fclose($handle);
2638 die;
2639 } else { // multiple ranges requested - not tested much
2640 $totallength = 0;
2641 foreach($ranges as $range) {
2642 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2644 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2645 header('HTTP/1.1 206 Partial content');
2646 header('Content-Length: '.$totallength);
2647 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2649 while(@ob_get_level()) {
2650 if (!@ob_end_flush()) {
2651 break;
2655 foreach($ranges as $range) {
2656 $length = $range[2] - $range[1] + 1;
2657 echo $range[0];
2658 fseek($handle, $range[1]);
2659 while (!feof($handle) && $length > 0) {
2660 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2661 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2662 echo $buffer;
2663 flush();
2664 $length -= strlen($buffer);
2667 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2668 fclose($handle);
2669 die;
2674 * add includes (js and css) into uploaded files
2675 * before returning them, useful for themes and utf.js includes
2677 * @global stdClass $CFG
2678 * @param string $text text to search and replace
2679 * @return string text with added head includes
2680 * @todo MDL-21120
2682 function file_modify_html_header($text) {
2683 // first look for <head> tag
2684 global $CFG;
2686 $stylesheetshtml = '';
2687 /* foreach ($CFG->stylesheets as $stylesheet) {
2688 //TODO: MDL-21120
2689 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2692 $ufo = '';
2693 if (filter_is_enabled('filter/mediaplugin')) {
2694 // this script is needed by most media filter plugins.
2695 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2696 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2699 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2700 if ($matches) {
2701 $replacement = '<head>'.$ufo.$stylesheetshtml;
2702 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2703 return $text;
2706 // if not, look for <html> tag, and stick <head> right after
2707 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2708 if ($matches) {
2709 // replace <html> tag with <html><head>includes</head>
2710 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2711 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2712 return $text;
2715 // if not, look for <body> tag, and stick <head> before body
2716 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2717 if ($matches) {
2718 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2719 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2720 return $text;
2723 // if not, just stick a <head> tag at the beginning
2724 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2725 return $text;
2729 * RESTful cURL class
2731 * This is a wrapper class for curl, it is quite easy to use:
2732 * <code>
2733 * $c = new curl;
2734 * // enable cache
2735 * $c = new curl(array('cache'=>true));
2736 * // enable cookie
2737 * $c = new curl(array('cookie'=>true));
2738 * // enable proxy
2739 * $c = new curl(array('proxy'=>true));
2741 * // HTTP GET Method
2742 * $html = $c->get('http://example.com');
2743 * // HTTP POST Method
2744 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2745 * // HTTP PUT Method
2746 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2747 * </code>
2749 * @package core_files
2750 * @category files
2751 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2752 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2754 class curl {
2755 /** @var bool Caches http request contents */
2756 public $cache = false;
2757 /** @var bool Uses proxy */
2758 public $proxy = false;
2759 /** @var string library version */
2760 public $version = '0.4 dev';
2761 /** @var array http's response */
2762 public $response = array();
2763 /** @var array http header */
2764 public $header = array();
2765 /** @var string cURL information */
2766 public $info;
2767 /** @var string error */
2768 public $error;
2769 /** @var int error code */
2770 public $errno;
2772 /** @var array cURL options */
2773 private $options;
2774 /** @var string Proxy host */
2775 private $proxy_host = '';
2776 /** @var string Proxy auth */
2777 private $proxy_auth = '';
2778 /** @var string Proxy type */
2779 private $proxy_type = '';
2780 /** @var bool Debug mode on */
2781 private $debug = false;
2782 /** @var bool|string Path to cookie file */
2783 private $cookie = false;
2786 * Constructor
2788 * @global stdClass $CFG
2789 * @param array $options
2791 public function __construct($options = array()){
2792 global $CFG;
2793 if (!function_exists('curl_init')) {
2794 $this->error = 'cURL module must be enabled!';
2795 trigger_error($this->error, E_USER_ERROR);
2796 return false;
2798 // the options of curl should be init here.
2799 $this->resetopt();
2800 if (!empty($options['debug'])) {
2801 $this->debug = true;
2803 if(!empty($options['cookie'])) {
2804 if($options['cookie'] === true) {
2805 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2806 } else {
2807 $this->cookie = $options['cookie'];
2810 if (!empty($options['cache'])) {
2811 if (class_exists('curl_cache')) {
2812 if (!empty($options['module_cache'])) {
2813 $this->cache = new curl_cache($options['module_cache']);
2814 } else {
2815 $this->cache = new curl_cache('misc');
2819 if (!empty($CFG->proxyhost)) {
2820 if (empty($CFG->proxyport)) {
2821 $this->proxy_host = $CFG->proxyhost;
2822 } else {
2823 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2825 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2826 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2827 $this->setopt(array(
2828 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2829 'proxyuserpwd'=>$this->proxy_auth));
2831 if (!empty($CFG->proxytype)) {
2832 if ($CFG->proxytype == 'SOCKS5') {
2833 $this->proxy_type = CURLPROXY_SOCKS5;
2834 } else {
2835 $this->proxy_type = CURLPROXY_HTTP;
2836 $this->setopt(array('httpproxytunnel'=>false));
2838 $this->setopt(array('proxytype'=>$this->proxy_type));
2841 if (!empty($this->proxy_host)) {
2842 $this->proxy = array('proxy'=>$this->proxy_host);
2846 * Resets the CURL options that have already been set
2848 public function resetopt(){
2849 $this->options = array();
2850 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2851 // True to include the header in the output
2852 $this->options['CURLOPT_HEADER'] = 0;
2853 // True to Exclude the body from the output
2854 $this->options['CURLOPT_NOBODY'] = 0;
2855 // TRUE to follow any "Location: " header that the server
2856 // sends as part of the HTTP header (note this is recursive,
2857 // PHP will follow as many "Location: " headers that it is sent,
2858 // unless CURLOPT_MAXREDIRS is set).
2859 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2860 $this->options['CURLOPT_MAXREDIRS'] = 10;
2861 $this->options['CURLOPT_ENCODING'] = '';
2862 // TRUE to return the transfer as a string of the return
2863 // value of curl_exec() instead of outputting it out directly.
2864 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2865 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2866 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2867 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2868 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2872 * Reset Cookie
2874 public function resetcookie() {
2875 if (!empty($this->cookie)) {
2876 if (is_file($this->cookie)) {
2877 $fp = fopen($this->cookie, 'w');
2878 if (!empty($fp)) {
2879 fwrite($fp, '');
2880 fclose($fp);
2887 * Set curl options
2889 * @param array $options If array is null, this function will
2890 * reset the options to default value.
2892 public function setopt($options = array()) {
2893 if (is_array($options)) {
2894 foreach($options as $name => $val){
2895 if (stripos($name, 'CURLOPT_') === false) {
2896 $name = strtoupper('CURLOPT_'.$name);
2898 $this->options[$name] = $val;
2904 * Reset http method
2906 public function cleanopt(){
2907 unset($this->options['CURLOPT_HTTPGET']);
2908 unset($this->options['CURLOPT_POST']);
2909 unset($this->options['CURLOPT_POSTFIELDS']);
2910 unset($this->options['CURLOPT_PUT']);
2911 unset($this->options['CURLOPT_INFILE']);
2912 unset($this->options['CURLOPT_INFILESIZE']);
2913 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2914 unset($this->options['CURLOPT_FILE']);
2918 * Resets the HTTP Request headers (to prepare for the new request)
2920 public function resetHeader() {
2921 $this->header = array();
2925 * Set HTTP Request Header
2927 * @param array $header
2929 public function setHeader($header) {
2930 if (is_array($header)){
2931 foreach ($header as $v) {
2932 $this->setHeader($v);
2934 } else {
2935 $this->header[] = $header;
2940 * Set HTTP Response Header
2943 public function getResponse(){
2944 return $this->response;
2948 * private callback function
2949 * Formatting HTTP Response Header
2951 * @param resource $ch Apparently not used
2952 * @param string $header
2953 * @return int The strlen of the header
2955 private function formatHeader($ch, $header)
2957 $this->count++;
2958 if (strlen($header) > 2) {
2959 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2960 $key = rtrim($key, ':');
2961 if (!empty($this->response[$key])) {
2962 if (is_array($this->response[$key])){
2963 $this->response[$key][] = $value;
2964 } else {
2965 $tmp = $this->response[$key];
2966 $this->response[$key] = array();
2967 $this->response[$key][] = $tmp;
2968 $this->response[$key][] = $value;
2971 } else {
2972 $this->response[$key] = $value;
2975 return strlen($header);
2979 * Set options for individual curl instance
2981 * @param resource $curl A curl handle
2982 * @param array $options
2983 * @return resource The curl handle
2985 private function apply_opt($curl, $options) {
2986 // Clean up
2987 $this->cleanopt();
2988 // set cookie
2989 if (!empty($this->cookie) || !empty($options['cookie'])) {
2990 $this->setopt(array('cookiejar'=>$this->cookie,
2991 'cookiefile'=>$this->cookie
2995 // set proxy
2996 if (!empty($this->proxy) || !empty($options['proxy'])) {
2997 $this->setopt($this->proxy);
2999 $this->setopt($options);
3000 // reset before set options
3001 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3002 // set headers
3003 if (empty($this->header)){
3004 $this->setHeader(array(
3005 'User-Agent: MoodleBot/1.0',
3006 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3007 'Connection: keep-alive'
3010 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3012 // Bypass proxy (for this request only) if required.
3013 if (!empty($this->options['CURLOPT_URL']) &&
3014 is_proxybypass($this->options['CURLOPT_URL'])) {
3015 unset($this->options['CURLOPT_PROXY']);
3018 if ($this->debug){
3019 echo '<h1>Options</h1>';
3020 var_dump($this->options);
3021 echo '<h1>Header</h1>';
3022 var_dump($this->header);
3025 // set options
3026 foreach($this->options as $name => $val) {
3027 if (is_string($name)) {
3028 $name = constant(strtoupper($name));
3030 curl_setopt($curl, $name, $val);
3032 return $curl;
3036 * Download multiple files in parallel
3038 * Calls {@link multi()} with specific download headers
3040 * <code>
3041 * $c = new curl();
3042 * $file1 = fopen('a', 'wb');
3043 * $file2 = fopen('b', 'wb');
3044 * $c->download(array(
3045 * array('url'=>'http://localhost/', 'file'=>$file1),
3046 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3047 * ));
3048 * fclose($file1);
3049 * fclose($file2);
3050 * </code>
3052 * or
3054 * <code>
3055 * $c = new curl();
3056 * $c->download(array(
3057 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3058 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3059 * ));
3060 * </code>
3062 * @param array $requests An array of files to request {
3063 * url => url to download the file [required]
3064 * file => file handler, or
3065 * filepath => file path
3067 * If 'file' and 'filepath' parameters are both specified in one request, the
3068 * open file handle in the 'file' parameter will take precedence and 'filepath'
3069 * will be ignored.
3071 * @param array $options An array of options to set
3072 * @return array An array of results
3074 public function download($requests, $options = array()) {
3075 $options['CURLOPT_BINARYTRANSFER'] = 1;
3076 $options['RETURNTRANSFER'] = false;
3077 return $this->multi($requests, $options);
3081 * Mulit HTTP Requests
3082 * This function could run multi-requests in parallel.
3084 * @param array $requests An array of files to request
3085 * @param array $options An array of options to set
3086 * @return array An array of results
3088 protected function multi($requests, $options = array()) {
3089 $count = count($requests);
3090 $handles = array();
3091 $results = array();
3092 $main = curl_multi_init();
3093 for ($i = 0; $i < $count; $i++) {
3094 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3095 // open file
3096 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3097 $requests[$i]['auto-handle'] = true;
3099 foreach($requests[$i] as $n=>$v){
3100 $options[$n] = $v;
3102 $handles[$i] = curl_init($requests[$i]['url']);
3103 $this->apply_opt($handles[$i], $options);
3104 curl_multi_add_handle($main, $handles[$i]);
3106 $running = 0;
3107 do {
3108 curl_multi_exec($main, $running);
3109 } while($running > 0);
3110 for ($i = 0; $i < $count; $i++) {
3111 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3112 $results[] = true;
3113 } else {
3114 $results[] = curl_multi_getcontent($handles[$i]);
3116 curl_multi_remove_handle($main, $handles[$i]);
3118 curl_multi_close($main);
3120 for ($i = 0; $i < $count; $i++) {
3121 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3122 // close file handler if file is opened in this function
3123 fclose($requests[$i]['file']);
3126 return $results;
3130 * Single HTTP Request
3132 * @param string $url The URL to request
3133 * @param array $options
3134 * @return bool
3136 protected function request($url, $options = array()){
3137 // create curl instance
3138 $curl = curl_init($url);
3139 $options['url'] = $url;
3140 $this->apply_opt($curl, $options);
3141 if ($this->cache && $ret = $this->cache->get($this->options)) {
3142 return $ret;
3143 } else {
3144 $ret = curl_exec($curl);
3145 if ($this->cache) {
3146 $this->cache->set($this->options, $ret);
3150 $this->info = curl_getinfo($curl);
3151 $this->error = curl_error($curl);
3152 $this->errno = curl_errno($curl);
3154 if ($this->debug){
3155 echo '<h1>Return Data</h1>';
3156 var_dump($ret);
3157 echo '<h1>Info</h1>';
3158 var_dump($this->info);
3159 echo '<h1>Error</h1>';
3160 var_dump($this->error);
3163 curl_close($curl);
3165 if (empty($this->error)){
3166 return $ret;
3167 } else {
3168 return $this->error;
3169 // exception is not ajax friendly
3170 //throw new moodle_exception($this->error, 'curl');
3175 * HTTP HEAD method
3177 * @see request()
3179 * @param string $url
3180 * @param array $options
3181 * @return bool
3183 public function head($url, $options = array()){
3184 $options['CURLOPT_HTTPGET'] = 0;
3185 $options['CURLOPT_HEADER'] = 1;
3186 $options['CURLOPT_NOBODY'] = 1;
3187 return $this->request($url, $options);
3191 * HTTP POST method
3193 * @param string $url
3194 * @param array|string $params
3195 * @param array $options
3196 * @return bool
3198 public function post($url, $params = '', $options = array()){
3199 $options['CURLOPT_POST'] = 1;
3200 if (is_array($params)) {
3201 $this->_tmp_file_post_params = array();
3202 foreach ($params as $key => $value) {
3203 if ($value instanceof stored_file) {
3204 $value->add_to_curl_request($this, $key);
3205 } else {
3206 $this->_tmp_file_post_params[$key] = $value;
3209 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3210 unset($this->_tmp_file_post_params);
3211 } else {
3212 // $params is the raw post data
3213 $options['CURLOPT_POSTFIELDS'] = $params;
3215 return $this->request($url, $options);
3219 * HTTP GET method
3221 * @param string $url
3222 * @param array $params
3223 * @param array $options
3224 * @return bool
3226 public function get($url, $params = array(), $options = array()){
3227 $options['CURLOPT_HTTPGET'] = 1;
3229 if (!empty($params)){
3230 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3231 $url .= http_build_query($params, '', '&');
3233 return $this->request($url, $options);
3237 * Downloads one file and writes it to the specified file handler
3239 * <code>
3240 * $c = new curl();
3241 * $file = fopen('savepath', 'w');
3242 * $result = $c->download_one('http://localhost/', null,
3243 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3244 * fclose($file);
3245 * $download_info = $c->get_info();
3246 * if ($result === true) {
3247 * // file downloaded successfully
3248 * } else {
3249 * $error_text = $result;
3250 * $error_code = $c->get_errno();
3252 * </code>
3254 * <code>
3255 * $c = new curl();
3256 * $result = $c->download_one('http://localhost/', null,
3257 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3258 * // ... see above, no need to close handle and remove file if unsuccessful
3259 * </code>
3261 * @param string $url
3262 * @param array|null $params key-value pairs to be added to $url as query string
3263 * @param array $options request options. Must include either 'file' or 'filepath'
3264 * @return bool|string true on success or error string on failure
3266 public function download_one($url, $params, $options = array()) {
3267 $options['CURLOPT_HTTPGET'] = 1;
3268 $options['CURLOPT_BINARYTRANSFER'] = true;
3269 if (!empty($params)){
3270 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3271 $url .= http_build_query($params, '', '&');
3273 if (!empty($options['filepath']) && empty($options['file'])) {
3274 // open file
3275 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3276 $this->errno = 100;
3277 return get_string('cannotwritefile', 'error', $options['filepath']);
3279 $filepath = $options['filepath'];
3281 unset($options['filepath']);
3282 $result = $this->request($url, $options);
3283 if (isset($filepath)) {
3284 fclose($options['file']);
3285 if ($result !== true) {
3286 unlink($filepath);
3289 return $result;
3293 * HTTP PUT method
3295 * @param string $url
3296 * @param array $params
3297 * @param array $options
3298 * @return bool
3300 public function put($url, $params = array(), $options = array()){
3301 $file = $params['file'];
3302 if (!is_file($file)){
3303 return null;
3305 $fp = fopen($file, 'r');
3306 $size = filesize($file);
3307 $options['CURLOPT_PUT'] = 1;
3308 $options['CURLOPT_INFILESIZE'] = $size;
3309 $options['CURLOPT_INFILE'] = $fp;
3310 if (!isset($this->options['CURLOPT_USERPWD'])){
3311 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3313 $ret = $this->request($url, $options);
3314 fclose($fp);
3315 return $ret;
3319 * HTTP DELETE method
3321 * @param string $url
3322 * @param array $param
3323 * @param array $options
3324 * @return bool
3326 public function delete($url, $param = array(), $options = array()){
3327 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3328 if (!isset($options['CURLOPT_USERPWD'])) {
3329 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3331 $ret = $this->request($url, $options);
3332 return $ret;
3336 * HTTP TRACE method
3338 * @param string $url
3339 * @param array $options
3340 * @return bool
3342 public function trace($url, $options = array()){
3343 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3344 $ret = $this->request($url, $options);
3345 return $ret;
3349 * HTTP OPTIONS method
3351 * @param string $url
3352 * @param array $options
3353 * @return bool
3355 public function options($url, $options = array()){
3356 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3357 $ret = $this->request($url, $options);
3358 return $ret;
3362 * Get curl information
3364 * @return string
3366 public function get_info() {
3367 return $this->info;
3371 * Get curl error code
3373 * @return int
3375 public function get_errno() {
3376 return $this->errno;
3380 * When using a proxy, an additional HTTP response code may appear at
3381 * the start of the header. For example, when using https over a proxy
3382 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3383 * also possible and some may come with their own headers.
3385 * If using the return value containing all headers, this function can be
3386 * called to remove unwanted doubles.
3388 * Note that it is not possible to distinguish this situation from valid
3389 * data unless you know the actual response part (below the headers)
3390 * will not be included in this string, or else will not 'look like' HTTP
3391 * headers. As a result it is not safe to call this function for general
3392 * data.
3394 * @param string $input Input HTTP response
3395 * @return string HTTP response with additional headers stripped if any
3397 public static function strip_double_headers($input) {
3398 // I have tried to make this regular expression as specific as possible
3399 // to avoid any case where it does weird stuff if you happen to put
3400 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3401 // also make it faster because it can abandon regex processing as soon
3402 // as it hits something that doesn't look like an http header. The
3403 // header definition is taken from RFC 822, except I didn't support
3404 // folding which is never used in practice.
3405 $crlf = "\r\n";
3406 return preg_replace(
3407 // HTTP version and status code (ignore value of code).
3408 '~^HTTP/1\..*' . $crlf .
3409 // Header name: character between 33 and 126 decimal, except colon.
3410 // Colon. Header value: any character except \r and \n. CRLF.
3411 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3412 // Headers are terminated by another CRLF (blank line).
3413 $crlf .
3414 // Second HTTP status code, this time must be 200.
3415 '(HTTP/1.[01] 200 )~', '$1', $input);
3420 * This class is used by cURL class, use case:
3422 * <code>
3423 * $CFG->repositorycacheexpire = 120;
3424 * $CFG->curlcache = 120;
3426 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3427 * $ret = $c->get('http://www.google.com');
3428 * </code>
3430 * @package core_files
3431 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3434 class curl_cache {
3435 /** @var string Path to cache directory */
3436 public $dir = '';
3439 * Constructor
3441 * @global stdClass $CFG
3442 * @param string $module which module is using curl_cache
3444 public function __construct($module = 'repository') {
3445 global $CFG;
3446 if (!empty($module)) {
3447 $this->dir = $CFG->cachedir.'/'.$module.'/';
3448 } else {
3449 $this->dir = $CFG->cachedir.'/misc/';
3451 if (!file_exists($this->dir)) {
3452 mkdir($this->dir, $CFG->directorypermissions, true);
3454 if ($module == 'repository') {
3455 if (empty($CFG->repositorycacheexpire)) {
3456 $CFG->repositorycacheexpire = 120;
3458 $this->ttl = $CFG->repositorycacheexpire;
3459 } else {
3460 if (empty($CFG->curlcache)) {
3461 $CFG->curlcache = 120;
3463 $this->ttl = $CFG->curlcache;
3468 * Get cached value
3470 * @global stdClass $CFG
3471 * @global stdClass $USER
3472 * @param mixed $param
3473 * @return bool|string
3475 public function get($param) {
3476 global $CFG, $USER;
3477 $this->cleanup($this->ttl);
3478 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3479 if(file_exists($this->dir.$filename)) {
3480 $lasttime = filemtime($this->dir.$filename);
3481 if (time()-$lasttime > $this->ttl) {
3482 return false;
3483 } else {
3484 $fp = fopen($this->dir.$filename, 'r');
3485 $size = filesize($this->dir.$filename);
3486 $content = fread($fp, $size);
3487 return unserialize($content);
3490 return false;
3494 * Set cache value
3496 * @global object $CFG
3497 * @global object $USER
3498 * @param mixed $param
3499 * @param mixed $val
3501 public function set($param, $val) {
3502 global $CFG, $USER;
3503 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3504 $fp = fopen($this->dir.$filename, 'w');
3505 fwrite($fp, serialize($val));
3506 fclose($fp);
3510 * Remove cache files
3512 * @param int $expire The number of seconds before expiry
3514 public function cleanup($expire) {
3515 if ($dir = opendir($this->dir)) {
3516 while (false !== ($file = readdir($dir))) {
3517 if(!is_dir($file) && $file != '.' && $file != '..') {
3518 $lasttime = @filemtime($this->dir.$file);
3519 if (time() - $lasttime > $expire) {
3520 @unlink($this->dir.$file);
3524 closedir($dir);
3528 * delete current user's cache file
3530 * @global object $CFG
3531 * @global object $USER
3533 public function refresh() {
3534 global $CFG, $USER;
3535 if ($dir = opendir($this->dir)) {
3536 while (false !== ($file = readdir($dir))) {
3537 if (!is_dir($file) && $file != '.' && $file != '..') {
3538 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3539 @unlink($this->dir.$file);
3548 * This function delegates file serving to individual plugins
3550 * @param string $relativepath
3551 * @param bool $forcedownload
3552 * @param null|string $preview the preview mode, defaults to serving the original file
3553 * @todo MDL-31088 file serving improments
3555 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3556 global $DB, $CFG, $USER;
3557 // relative path must start with '/'
3558 if (!$relativepath) {
3559 print_error('invalidargorconf');
3560 } else if ($relativepath[0] != '/') {
3561 print_error('pathdoesnotstartslash');
3564 // extract relative path components
3565 $args = explode('/', ltrim($relativepath, '/'));
3567 if (count($args) < 3) { // always at least context, component and filearea
3568 print_error('invalidarguments');
3571 $contextid = (int)array_shift($args);
3572 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3573 $filearea = clean_param(array_shift($args), PARAM_AREA);
3575 list($context, $course, $cm) = get_context_info_array($contextid);
3577 $fs = get_file_storage();
3579 // ========================================================================================================================
3580 if ($component === 'blog') {
3581 // Blog file serving
3582 if ($context->contextlevel != CONTEXT_SYSTEM) {
3583 send_file_not_found();
3585 if ($filearea !== 'attachment' and $filearea !== 'post') {
3586 send_file_not_found();
3589 if (empty($CFG->bloglevel)) {
3590 print_error('siteblogdisable', 'blog');
3593 $entryid = (int)array_shift($args);
3594 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3595 send_file_not_found();
3597 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3598 require_login();
3599 if (isguestuser()) {
3600 print_error('noguest');
3602 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3603 if ($USER->id != $entry->userid) {
3604 send_file_not_found();
3609 if ($entry->publishstate === 'public') {
3610 if ($CFG->forcelogin) {
3611 require_login();
3614 } else if ($entry->publishstate === 'site') {
3615 require_login();
3616 //ok
3617 } else if ($entry->publishstate === 'draft') {
3618 require_login();
3619 if ($USER->id != $entry->userid) {
3620 send_file_not_found();
3624 $filename = array_pop($args);
3625 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3627 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3628 send_file_not_found();
3631 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3633 // ========================================================================================================================
3634 } else if ($component === 'grade') {
3635 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3636 // Global gradebook files
3637 if ($CFG->forcelogin) {
3638 require_login();
3641 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3643 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3644 send_file_not_found();
3647 session_get_instance()->write_close(); // unlock session during fileserving
3648 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3650 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3651 //TODO: nobody implemented this yet in grade edit form!!
3652 send_file_not_found();
3654 if ($CFG->forcelogin || $course->id != SITEID) {
3655 require_login($course);
3658 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3660 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3661 send_file_not_found();
3664 session_get_instance()->write_close(); // unlock session during fileserving
3665 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3666 } else {
3667 send_file_not_found();
3670 // ========================================================================================================================
3671 } else if ($component === 'tag') {
3672 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3674 // All tag descriptions are going to be public but we still need to respect forcelogin
3675 if ($CFG->forcelogin) {
3676 require_login();
3679 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3681 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3682 send_file_not_found();
3685 session_get_instance()->write_close(); // unlock session during fileserving
3686 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3688 } else {
3689 send_file_not_found();
3692 // ========================================================================================================================
3693 } else if ($component === 'calendar') {
3694 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3696 // All events here are public the one requirement is that we respect forcelogin
3697 if ($CFG->forcelogin) {
3698 require_login();
3701 // Get the event if from the args array
3702 $eventid = array_shift($args);
3704 // Load the event from the database
3705 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3706 send_file_not_found();
3709 // Get the file and serve if successful
3710 $filename = array_pop($args);
3711 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3712 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3713 send_file_not_found();
3716 session_get_instance()->write_close(); // unlock session during fileserving
3717 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3719 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3721 // Must be logged in, if they are not then they obviously can't be this user
3722 require_login();
3724 // Don't want guests here, potentially saves a DB call
3725 if (isguestuser()) {
3726 send_file_not_found();
3729 // Get the event if from the args array
3730 $eventid = array_shift($args);
3732 // Load the event from the database - user id must match
3733 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3734 send_file_not_found();
3737 // Get the file and serve if successful
3738 $filename = array_pop($args);
3739 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3740 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3741 send_file_not_found();
3744 session_get_instance()->write_close(); // unlock session during fileserving
3745 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3747 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3749 // Respect forcelogin and require login unless this is the site.... it probably
3750 // should NEVER be the site
3751 if ($CFG->forcelogin || $course->id != SITEID) {
3752 require_login($course);
3755 // Must be able to at least view the course. This does not apply to the front page.
3756 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
3757 //TODO: hmm, do we really want to block guests here?
3758 send_file_not_found();
3761 // Get the event id
3762 $eventid = array_shift($args);
3764 // Load the event from the database we need to check whether it is
3765 // a) valid course event
3766 // b) a group event
3767 // Group events use the course context (there is no group context)
3768 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3769 send_file_not_found();
3772 // If its a group event require either membership of view all groups capability
3773 if ($event->eventtype === 'group') {
3774 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3775 send_file_not_found();
3777 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
3778 // Ok. Please note that the event type 'site' still uses a course context.
3779 } else {
3780 // Some other type.
3781 send_file_not_found();
3784 // If we get this far we can serve the file
3785 $filename = array_pop($args);
3786 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3787 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3788 send_file_not_found();
3791 session_get_instance()->write_close(); // unlock session during fileserving
3792 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3794 } else {
3795 send_file_not_found();
3798 // ========================================================================================================================
3799 } else if ($component === 'user') {
3800 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3801 if (count($args) == 1) {
3802 $themename = theme_config::DEFAULT_THEME;
3803 $filename = array_shift($args);
3804 } else {
3805 $themename = array_shift($args);
3806 $filename = array_shift($args);
3809 // fix file name automatically
3810 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3811 $filename = 'f1';
3814 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3815 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3816 // protect images if login required and not logged in;
3817 // also if login is required for profile images and is not logged in or guest
3818 // do not use require_login() because it is expensive and not suitable here anyway
3819 $theme = theme_config::load($themename);
3820 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3823 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3824 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3825 if ($filename === 'f3') {
3826 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3827 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3828 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3833 if (!$file) {
3834 // bad reference - try to prevent future retries as hard as possible!
3835 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3836 if ($user->picture > 0) {
3837 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3840 // no redirect here because it is not cached
3841 $theme = theme_config::load($themename);
3842 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle');
3843 send_file($imagefile, basename($imagefile), 60*60*24*14);
3846 send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3848 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3849 require_login();
3851 if (isguestuser()) {
3852 send_file_not_found();
3855 if ($USER->id !== $context->instanceid) {
3856 send_file_not_found();
3859 $filename = array_pop($args);
3860 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3861 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3862 send_file_not_found();
3865 session_get_instance()->write_close(); // unlock session during fileserving
3866 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3868 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3870 if ($CFG->forcelogin) {
3871 require_login();
3874 $userid = $context->instanceid;
3876 if ($USER->id == $userid) {
3877 // always can access own
3879 } else if (!empty($CFG->forceloginforprofiles)) {
3880 require_login();
3882 if (isguestuser()) {
3883 send_file_not_found();
3886 // we allow access to site profile of all course contacts (usually teachers)
3887 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3888 send_file_not_found();
3891 $canview = false;
3892 if (has_capability('moodle/user:viewdetails', $context)) {
3893 $canview = true;
3894 } else {
3895 $courses = enrol_get_my_courses();
3898 while (!$canview && count($courses) > 0) {
3899 $course = array_shift($courses);
3900 if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) {
3901 $canview = true;
3906 $filename = array_pop($args);
3907 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3908 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3909 send_file_not_found();
3912 session_get_instance()->write_close(); // unlock session during fileserving
3913 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3915 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3916 $userid = (int)array_shift($args);
3917 $usercontext = get_context_instance(CONTEXT_USER, $userid);
3919 if ($CFG->forcelogin) {
3920 require_login();
3923 if (!empty($CFG->forceloginforprofiles)) {
3924 require_login();
3925 if (isguestuser()) {
3926 print_error('noguest');
3929 //TODO: review this logic of user profile access prevention
3930 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3931 print_error('usernotavailable');
3933 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3934 print_error('cannotviewprofile');
3936 if (!is_enrolled($context, $userid)) {
3937 print_error('notenrolledprofile');
3939 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3940 print_error('groupnotamember');
3944 $filename = array_pop($args);
3945 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3946 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3947 send_file_not_found();
3950 session_get_instance()->write_close(); // unlock session during fileserving
3951 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3953 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3954 require_login();
3956 if (isguestuser()) {
3957 send_file_not_found();
3959 $userid = $context->instanceid;
3961 if ($USER->id != $userid) {
3962 send_file_not_found();
3965 $filename = array_pop($args);
3966 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3967 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3968 send_file_not_found();
3971 session_get_instance()->write_close(); // unlock session during fileserving
3972 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3974 } else {
3975 send_file_not_found();
3978 // ========================================================================================================================
3979 } else if ($component === 'coursecat') {
3980 if ($context->contextlevel != CONTEXT_COURSECAT) {
3981 send_file_not_found();
3984 if ($filearea === 'description') {
3985 if ($CFG->forcelogin) {
3986 // no login necessary - unless login forced everywhere
3987 require_login();
3990 $filename = array_pop($args);
3991 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3992 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3993 send_file_not_found();
3996 session_get_instance()->write_close(); // unlock session during fileserving
3997 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3998 } else {
3999 send_file_not_found();
4002 // ========================================================================================================================
4003 } else if ($component === 'course') {
4004 if ($context->contextlevel != CONTEXT_COURSE) {
4005 send_file_not_found();
4008 if ($filearea === 'summary') {
4009 if ($CFG->forcelogin) {
4010 require_login();
4013 $filename = array_pop($args);
4014 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4015 if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
4016 send_file_not_found();
4019 session_get_instance()->write_close(); // unlock session during fileserving
4020 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4022 } else if ($filearea === 'section') {
4023 if ($CFG->forcelogin) {
4024 require_login($course);
4025 } else if ($course->id != SITEID) {
4026 require_login($course);
4029 $sectionid = (int)array_shift($args);
4031 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4032 send_file_not_found();
4035 if ($course->numsections < $section->section) {
4036 if (!has_capability('moodle/course:update', $context)) {
4037 // block access to unavailable sections if can not edit course
4038 send_file_not_found();
4042 $filename = array_pop($args);
4043 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4044 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4045 send_file_not_found();
4048 session_get_instance()->write_close(); // unlock session during fileserving
4049 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4051 } else {
4052 send_file_not_found();
4055 } else if ($component === 'group') {
4056 if ($context->contextlevel != CONTEXT_COURSE) {
4057 send_file_not_found();
4060 require_course_login($course, true, null, false);
4062 $groupid = (int)array_shift($args);
4064 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4065 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4066 // do not allow access to separate group info if not member or teacher
4067 send_file_not_found();
4070 if ($filearea === 'description') {
4072 require_login($course);
4074 $filename = array_pop($args);
4075 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4076 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4077 send_file_not_found();
4080 session_get_instance()->write_close(); // unlock session during fileserving
4081 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4083 } else if ($filearea === 'icon') {
4084 $filename = array_pop($args);
4086 if ($filename !== 'f1' and $filename !== 'f2') {
4087 send_file_not_found();
4089 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4090 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4091 send_file_not_found();
4095 session_get_instance()->write_close(); // unlock session during fileserving
4096 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4098 } else {
4099 send_file_not_found();
4102 } else if ($component === 'grouping') {
4103 if ($context->contextlevel != CONTEXT_COURSE) {
4104 send_file_not_found();
4107 require_login($course);
4109 $groupingid = (int)array_shift($args);
4111 // note: everybody has access to grouping desc images for now
4112 if ($filearea === 'description') {
4114 $filename = array_pop($args);
4115 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4116 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4117 send_file_not_found();
4120 session_get_instance()->write_close(); // unlock session during fileserving
4121 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4123 } else {
4124 send_file_not_found();
4127 // ========================================================================================================================
4128 } else if ($component === 'backup') {
4129 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4130 require_login($course);
4131 require_capability('moodle/backup:downloadfile', $context);
4133 $filename = array_pop($args);
4134 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4135 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4136 send_file_not_found();
4139 session_get_instance()->write_close(); // unlock session during fileserving
4140 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4142 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4143 require_login($course);
4144 require_capability('moodle/backup:downloadfile', $context);
4146 $sectionid = (int)array_shift($args);
4148 $filename = array_pop($args);
4149 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4150 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4151 send_file_not_found();
4154 session_get_instance()->write_close();
4155 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4157 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4158 require_login($course, false, $cm);
4159 require_capability('moodle/backup:downloadfile', $context);
4161 $filename = array_pop($args);
4162 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4163 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4164 send_file_not_found();
4167 session_get_instance()->write_close();
4168 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4170 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4171 // Backup files that were generated by the automated backup systems.
4173 require_login($course);
4174 require_capability('moodle/site:config', $context);
4176 $filename = array_pop($args);
4177 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4178 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4179 send_file_not_found();
4182 session_get_instance()->write_close(); // unlock session during fileserving
4183 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4185 } else {
4186 send_file_not_found();
4189 // ========================================================================================================================
4190 } else if ($component === 'question') {
4191 require_once($CFG->libdir . '/questionlib.php');
4192 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4193 send_file_not_found();
4195 // ========================================================================================================================
4196 } else if ($component === 'grading') {
4197 if ($filearea === 'description') {
4198 // files embedded into the form definition description
4200 if ($context->contextlevel == CONTEXT_SYSTEM) {
4201 require_login();
4203 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4204 require_login($course, false, $cm);
4206 } else {
4207 send_file_not_found();
4210 $formid = (int)array_shift($args);
4212 $sql = "SELECT ga.id
4213 FROM {grading_areas} ga
4214 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4215 WHERE gd.id = ? AND ga.contextid = ?";
4216 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4218 if (!$areaid) {
4219 send_file_not_found();
4222 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4224 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4225 send_file_not_found();
4228 session_get_instance()->write_close(); // unlock session during fileserving
4229 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4232 // ========================================================================================================================
4233 } else if (strpos($component, 'mod_') === 0) {
4234 $modname = substr($component, 4);
4235 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4236 send_file_not_found();
4238 require_once("$CFG->dirroot/mod/$modname/lib.php");
4240 if ($context->contextlevel == CONTEXT_MODULE) {
4241 if ($cm->modname !== $modname) {
4242 // somebody tries to gain illegal access, cm type must match the component!
4243 send_file_not_found();
4247 if ($filearea === 'intro') {
4248 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4249 send_file_not_found();
4251 require_course_login($course, true, $cm);
4253 // all users may access it
4254 $filename = array_pop($args);
4255 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4256 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4257 send_file_not_found();
4260 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4262 // finally send the file
4263 send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4266 $filefunction = $component.'_pluginfile';
4267 $filefunctionold = $modname.'_pluginfile';
4268 if (function_exists($filefunction)) {
4269 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4270 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4271 } else if (function_exists($filefunctionold)) {
4272 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4273 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4276 send_file_not_found();
4278 // ========================================================================================================================
4279 } else if (strpos($component, 'block_') === 0) {
4280 $blockname = substr($component, 6);
4281 // note: no more class methods in blocks please, that is ....
4282 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4283 send_file_not_found();
4285 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4287 if ($context->contextlevel == CONTEXT_BLOCK) {
4288 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4289 if ($birecord->blockname !== $blockname) {
4290 // somebody tries to gain illegal access, cm type must match the component!
4291 send_file_not_found();
4294 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4295 // User can't access file, if block is hidden or doesn't have block:view capability
4296 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4297 send_file_not_found();
4299 } else {
4300 $birecord = null;
4303 $filefunction = $component.'_pluginfile';
4304 if (function_exists($filefunction)) {
4305 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4306 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4309 send_file_not_found();
4311 // ========================================================================================================================
4312 } else if (strpos($component, '_') === false) {
4313 // all core subsystems have to be specified above, no more guessing here!
4314 send_file_not_found();
4316 } else {
4317 // try to serve general plugin file in arbitrary context
4318 $dir = get_component_directory($component);
4319 if (!file_exists("$dir/lib.php")) {
4320 send_file_not_found();
4322 include_once("$dir/lib.php");
4324 $filefunction = $component.'_pluginfile';
4325 if (function_exists($filefunction)) {
4326 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4327 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4330 send_file_not_found();