MDL-33590 Correctly determine that file is an archive to enable unzip in filemanager
[moodle.git] / lib / filelib.php
blob62a21df96bc580b2320b75023afcaf66ec61eecf
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 // find the file this draft file was created from and count all references in local
600 // system pointing to that file
601 $source = unserialize($file->get_source());
602 if (isset($source->original)) {
603 $item->refcount = $fs->search_references_count($source->original);
606 if ($file->is_directory()) {
607 $item->filesize = 0;
608 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
609 $item->type = 'folder';
610 $foldername = explode('/', trim($item->filepath, '/'));
611 $item->fullname = trim(array_pop($foldername), '/');
612 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
613 } else {
614 // do NOT use file browser here!
615 $item->mimetype = get_mimetype_description($file);
616 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
617 $item->type = 'zip';
618 } else {
619 $item->type = 'file';
621 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
622 $item->url = $itemurl->out();
623 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
624 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
625 if ($imageinfo = $file->get_imageinfo()) {
626 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
627 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
628 $item->image_width = $imageinfo['width'];
629 $item->image_height = $imageinfo['height'];
632 $list[] = $item;
635 $data->itemid = $draftitemid;
636 $data->list = $list;
637 return $data;
641 * Returns draft area itemid for a given element.
643 * @category files
644 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
645 * @return int the itemid, or 0 if there is not one yet.
647 function file_get_submitted_draft_itemid($elname) {
648 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
649 if (!isset($_REQUEST[$elname])) {
650 return 0;
652 if (is_array($_REQUEST[$elname])) {
653 $param = optional_param_array($elname, 0, PARAM_INT);
654 if (!empty($param['itemid'])) {
655 $param = $param['itemid'];
656 } else {
657 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
658 return false;
661 } else {
662 $param = optional_param($elname, 0, PARAM_INT);
665 if ($param) {
666 require_sesskey();
669 return $param;
673 * Restore the original source field from draft files
675 * @param stored_file $storedfile This only works with draft files
676 * @return stored_file
678 function file_restore_source_field_from_draft_file($storedfile) {
679 $source = unserialize($storedfile->get_source());
680 if (!empty($source)) {
681 if (is_object($source)) {
682 $restoredsource = $source->source;
683 $storedfile->set_source($restoredsource);
684 } else {
685 throw new moodle_exception('invalidsourcefield', 'error');
688 return $storedfile;
691 * Saves files from a draft file area to a real one (merging the list of files).
692 * Can rewrite URLs in some content at the same time if desired.
694 * @category files
695 * @global stdClass $USER
696 * @param int $draftitemid the id of the draft area to use. Normally obtained
697 * from file_get_submitted_draft_itemid('elementname') or similar.
698 * @param int $contextid This parameter and the next two identify the file area to save to.
699 * @param string $component
700 * @param string $filearea indentifies the file area.
701 * @param int $itemid helps identifies the file area.
702 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
703 * @param string $text some html content that needs to have embedded links rewritten
704 * to the @@PLUGINFILE@@ form for saving in the database.
705 * @param bool $forcehttps force https urls.
706 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
708 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
709 global $USER;
711 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
712 $fs = get_file_storage();
714 $options = (array)$options;
715 if (!isset($options['subdirs'])) {
716 $options['subdirs'] = false;
718 if (!isset($options['maxfiles'])) {
719 $options['maxfiles'] = -1; // unlimited
721 if (!isset($options['maxbytes'])) {
722 $options['maxbytes'] = 0; // unlimited
725 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
726 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
728 if (count($draftfiles) < 2) {
729 // means there are no files - one file means root dir only ;-)
730 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
732 } else if (count($oldfiles) < 2) {
733 $filecount = 0;
734 // there were no files before - one file means root dir only ;-)
735 foreach ($draftfiles as $file) {
736 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
737 if (!$options['subdirs']) {
738 if ($file->get_filepath() !== '/' or $file->is_directory()) {
739 continue;
742 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
743 // oversized file - should not get here at all
744 continue;
746 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
747 // more files - should not get here at all
748 break;
750 if (!$file->is_directory()) {
751 $filecount++;
754 if ($file->is_external_file()) {
755 $repoid = $file->get_repository_id();
756 if (!empty($repoid)) {
757 $file_record['repositoryid'] = $repoid;
758 $file_record['reference'] = $file->get_reference();
761 file_restore_source_field_from_draft_file($file);
763 $fs->create_file_from_storedfile($file_record, $file);
766 } else {
767 // we have to merge old and new files - we want to keep file ids for files that were not changed
768 // we change time modified for all new and changed files, we keep time created as is
770 $newhashes = array();
771 foreach ($draftfiles as $file) {
772 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
773 $newhashes[$newhash] = $file;
775 $filecount = 0;
776 foreach ($oldfiles as $oldfile) {
777 $oldhash = $oldfile->get_pathnamehash();
778 if (!isset($newhashes[$oldhash])) {
779 // delete files not needed any more - deleted by user
780 $oldfile->delete();
781 continue;
784 $newfile = $newhashes[$oldhash];
785 // status changed, we delete old file, and create a new one
786 if ($oldfile->get_status() != $newfile->get_status()) {
787 // file was changed, use updated with new timemodified data
788 $oldfile->delete();
789 // This file will be added later
790 continue;
793 file_restore_source_field_from_draft_file($newfile);
794 // Replaced file content
795 if ($oldfile->get_contenthash() != $newfile->get_contenthash()) {
796 $oldfile->replace_content_with($newfile);
798 // Updated author
799 if ($oldfile->get_author() != $newfile->get_author()) {
800 $oldfile->set_author($newfile->get_author());
802 // Updated license
803 if ($oldfile->get_license() != $newfile->get_license()) {
804 $oldfile->set_license($newfile->get_license());
807 // Updated file source
808 if ($oldfile->get_source() != $newfile->get_source()) {
809 $oldfile->set_source($newfile->get_source());
812 // Updated sort order
813 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
814 $oldfile->set_sortorder($newfile->get_sortorder());
817 // Update file size
818 if ($oldfile->get_filesize() != $newfile->get_filesize()) {
819 $oldfile->set_filesize($newfile->get_filesize());
822 // Update file timemodified
823 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
824 $oldfile->set_timemodified($newfile->get_timemodified());
827 // unchanged file or directory - we keep it as is
828 unset($newhashes[$oldhash]);
829 if (!$oldfile->is_directory()) {
830 $filecount++;
834 // Add fresh file or the file which has changed status
835 // the size and subdirectory tests are extra safety only, the UI should prevent it
836 foreach ($newhashes as $file) {
837 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
838 if (!$options['subdirs']) {
839 if ($file->get_filepath() !== '/' or $file->is_directory()) {
840 continue;
843 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
844 // oversized file - should not get here at all
845 continue;
847 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
848 // more files - should not get here at all
849 break;
851 if (!$file->is_directory()) {
852 $filecount++;
855 if ($file->is_external_file()) {
856 $repoid = $file->get_repository_id();
857 if (!empty($repoid)) {
858 $file_record['repositoryid'] = $repoid;
859 $file_record['reference'] = $file->get_reference();
863 $fs->create_file_from_storedfile($file_record, $file);
867 // note: do not purge the draft area - we clean up areas later in cron,
868 // the reason is that user might press submit twice and they would loose the files,
869 // also sometimes we might want to use hacks that save files into two different areas
871 if (is_null($text)) {
872 return null;
873 } else {
874 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
879 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
880 * ready to be saved in the database. Normally, this is done automatically by
881 * {@link file_save_draft_area_files()}.
883 * @category files
884 * @param string $text the content to process.
885 * @param int $draftitemid the draft file area the content was using.
886 * @param bool $forcehttps whether the content contains https URLs. Default false.
887 * @return string the processed content.
889 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
890 global $CFG, $USER;
892 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
894 $wwwroot = $CFG->wwwroot;
895 if ($forcehttps) {
896 $wwwroot = str_replace('http://', 'https://', $wwwroot);
899 // relink embedded files if text submitted - no absolute links allowed in database!
900 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
902 if (strpos($text, 'draftfile.php?file=') !== false) {
903 $matches = array();
904 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
905 if ($matches) {
906 foreach ($matches[0] as $match) {
907 $replace = str_ireplace('%2F', '/', $match);
908 $text = str_replace($match, $replace, $text);
911 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
914 return $text;
918 * Set file sort order
920 * @global moodle_database $DB
921 * @param int $contextid the context id
922 * @param string $component file component
923 * @param string $filearea file area.
924 * @param int $itemid itemid.
925 * @param string $filepath file path.
926 * @param string $filename file name.
927 * @param int $sortorder the sort order of file.
928 * @return bool
930 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
931 global $DB;
932 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
933 if ($file_record = $DB->get_record('files', $conditions)) {
934 $sortorder = (int)$sortorder;
935 $file_record->sortorder = $sortorder;
936 $DB->update_record('files', $file_record);
937 return true;
939 return false;
943 * reset file sort order number to 0
944 * @global moodle_database $DB
945 * @param int $contextid the context id
946 * @param string $component
947 * @param string $filearea file area.
948 * @param int|bool $itemid itemid.
949 * @return bool
951 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
952 global $DB;
954 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
955 if ($itemid !== false) {
956 $conditions['itemid'] = $itemid;
959 $file_records = $DB->get_records('files', $conditions);
960 foreach ($file_records as $file_record) {
961 $file_record->sortorder = 0;
962 $DB->update_record('files', $file_record);
964 return true;
968 * Returns description of upload error
970 * @param int $errorcode found in $_FILES['filename.ext']['error']
971 * @return string error description string, '' if ok
973 function file_get_upload_error($errorcode) {
975 switch ($errorcode) {
976 case 0: // UPLOAD_ERR_OK - no error
977 $errmessage = '';
978 break;
980 case 1: // UPLOAD_ERR_INI_SIZE
981 $errmessage = get_string('uploadserverlimit');
982 break;
984 case 2: // UPLOAD_ERR_FORM_SIZE
985 $errmessage = get_string('uploadformlimit');
986 break;
988 case 3: // UPLOAD_ERR_PARTIAL
989 $errmessage = get_string('uploadpartialfile');
990 break;
992 case 4: // UPLOAD_ERR_NO_FILE
993 $errmessage = get_string('uploadnofilefound');
994 break;
996 // Note: there is no error with a value of 5
998 case 6: // UPLOAD_ERR_NO_TMP_DIR
999 $errmessage = get_string('uploadnotempdir');
1000 break;
1002 case 7: // UPLOAD_ERR_CANT_WRITE
1003 $errmessage = get_string('uploadcantwrite');
1004 break;
1006 case 8: // UPLOAD_ERR_EXTENSION
1007 $errmessage = get_string('uploadextension');
1008 break;
1010 default:
1011 $errmessage = get_string('uploadproblem');
1014 return $errmessage;
1018 * Recursive function formating an array in POST parameter
1019 * @param array $arraydata - the array that we are going to format and add into &$data array
1020 * @param string $currentdata - a row of the final postdata array at instant T
1021 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1022 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1024 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1025 foreach ($arraydata as $k=>$v) {
1026 $newcurrentdata = $currentdata;
1027 if (is_array($v)) { //the value is an array, call the function recursively
1028 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1029 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1030 } else { //add the POST parameter to the $data array
1031 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1037 * Transform a PHP array into POST parameter
1038 * (see the recursive function format_array_postdata_for_curlcall)
1039 * @param array $postdata
1040 * @return array containing all POST parameters (1 row = 1 POST parameter)
1042 function format_postdata_for_curlcall($postdata) {
1043 $data = array();
1044 foreach ($postdata as $k=>$v) {
1045 if (is_array($v)) {
1046 $currentdata = urlencode($k);
1047 format_array_postdata_for_curlcall($v, $currentdata, $data);
1048 } else {
1049 $data[] = urlencode($k).'='.urlencode($v);
1052 $convertedpostdata = implode('&', $data);
1053 return $convertedpostdata;
1057 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1058 * Due to security concerns only downloads from http(s) sources are supported.
1060 * @todo MDL-31073 add version test for '7.10.5'
1061 * @category files
1062 * @param string $url file url starting with http(s)://
1063 * @param array $headers http headers, null if none. If set, should be an
1064 * associative array of header name => value pairs.
1065 * @param array $postdata array means use POST request with given parameters
1066 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1067 * (if false, just returns content)
1068 * @param int $timeout timeout for complete download process including all file transfer
1069 * (default 5 minutes)
1070 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1071 * usually happens if the remote server is completely down (default 20 seconds);
1072 * may not work when using proxy
1073 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1074 * Only use this when already in a trusted location.
1075 * @param string $tofile store the downloaded content to file instead of returning it.
1076 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1077 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1078 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1080 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1081 global $CFG;
1083 // some extra security
1084 $newlines = array("\r", "\n");
1085 if (is_array($headers) ) {
1086 foreach ($headers as $key => $value) {
1087 $headers[$key] = str_replace($newlines, '', $value);
1090 $url = str_replace($newlines, '', $url);
1091 if (!preg_match('|^https?://|i', $url)) {
1092 if ($fullresponse) {
1093 $response = new stdClass();
1094 $response->status = 0;
1095 $response->headers = array();
1096 $response->response_code = 'Invalid protocol specified in url';
1097 $response->results = '';
1098 $response->error = 'Invalid protocol specified in url';
1099 return $response;
1100 } else {
1101 return false;
1105 // check if proxy (if used) should be bypassed for this url
1106 $proxybypass = is_proxybypass($url);
1108 if (!$ch = curl_init($url)) {
1109 debugging('Can not init curl.');
1110 return false;
1113 // set extra headers
1114 if (is_array($headers) ) {
1115 $headers2 = array();
1116 foreach ($headers as $key => $value) {
1117 $headers2[] = "$key: $value";
1119 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1122 if ($skipcertverify) {
1123 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1126 // use POST if requested
1127 if (is_array($postdata)) {
1128 $postdata = format_postdata_for_curlcall($postdata);
1129 curl_setopt($ch, CURLOPT_POST, true);
1130 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1133 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1134 curl_setopt($ch, CURLOPT_HEADER, false);
1135 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1137 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1138 // TODO: add version test for '7.10.5'
1139 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1140 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1143 if (!empty($CFG->proxyhost) and !$proxybypass) {
1144 // SOCKS supported in PHP5 only
1145 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1146 if (defined('CURLPROXY_SOCKS5')) {
1147 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1148 } else {
1149 curl_close($ch);
1150 if ($fullresponse) {
1151 $response = new stdClass();
1152 $response->status = '0';
1153 $response->headers = array();
1154 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1155 $response->results = '';
1156 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1157 return $response;
1158 } else {
1159 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1160 return false;
1165 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1167 if (empty($CFG->proxyport)) {
1168 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1169 } else {
1170 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1173 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1174 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1175 if (defined('CURLOPT_PROXYAUTH')) {
1176 // any proxy authentication if PHP 5.1
1177 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1182 // set up header and content handlers
1183 $received = new stdClass();
1184 $received->headers = array(); // received headers array
1185 $received->tofile = $tofile;
1186 $received->fh = null;
1187 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1188 if ($tofile) {
1189 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1192 if (!isset($CFG->curltimeoutkbitrate)) {
1193 //use very slow rate of 56kbps as a timeout speed when not set
1194 $bitrate = 56;
1195 } else {
1196 $bitrate = $CFG->curltimeoutkbitrate;
1199 // try to calculate the proper amount for timeout from remote file size.
1200 // if disabled or zero, we won't do any checks nor head requests.
1201 if ($calctimeout && $bitrate > 0) {
1202 //setup header request only options
1203 curl_setopt_array ($ch, array(
1204 CURLOPT_RETURNTRANSFER => false,
1205 CURLOPT_NOBODY => true)
1208 curl_exec($ch);
1209 $info = curl_getinfo($ch);
1210 $err = curl_error($ch);
1212 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1213 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1215 //reinstate affected curl options
1216 curl_setopt_array ($ch, array(
1217 CURLOPT_RETURNTRANSFER => true,
1218 CURLOPT_NOBODY => false)
1222 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1223 $result = curl_exec($ch);
1225 // try to detect encoding problems
1226 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1227 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1228 $result = curl_exec($ch);
1231 if ($received->fh) {
1232 fclose($received->fh);
1235 if (curl_errno($ch)) {
1236 $error = curl_error($ch);
1237 $error_no = curl_errno($ch);
1238 curl_close($ch);
1240 if ($fullresponse) {
1241 $response = new stdClass();
1242 if ($error_no == 28) {
1243 $response->status = '-100'; // mimic snoopy
1244 } else {
1245 $response->status = '0';
1247 $response->headers = array();
1248 $response->response_code = $error;
1249 $response->results = false;
1250 $response->error = $error;
1251 return $response;
1252 } else {
1253 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1254 return false;
1257 } else {
1258 $info = curl_getinfo($ch);
1259 curl_close($ch);
1261 if (empty($info['http_code'])) {
1262 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1263 $response = new stdClass();
1264 $response->status = '0';
1265 $response->headers = array();
1266 $response->response_code = 'Unknown cURL error';
1267 $response->results = false; // do NOT change this, we really want to ignore the result!
1268 $response->error = 'Unknown cURL error';
1270 } else {
1271 $response = new stdClass();;
1272 $response->status = (string)$info['http_code'];
1273 $response->headers = $received->headers;
1274 $response->response_code = $received->headers[0];
1275 $response->results = $result;
1276 $response->error = '';
1279 if ($fullresponse) {
1280 return $response;
1281 } else if ($info['http_code'] != 200) {
1282 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1283 return false;
1284 } else {
1285 return $response->results;
1291 * internal implementation
1292 * @param stdClass $received
1293 * @param resource $ch
1294 * @param mixed $header
1295 * @return int header length
1297 function download_file_content_header_handler($received, $ch, $header) {
1298 $received->headers[] = $header;
1299 return strlen($header);
1303 * internal implementation
1304 * @param stdClass $received
1305 * @param resource $ch
1306 * @param mixed $data
1308 function download_file_content_write_handler($received, $ch, $data) {
1309 if (!$received->fh) {
1310 $received->fh = fopen($received->tofile, 'w');
1311 if ($received->fh === false) {
1312 // bad luck, file creation or overriding failed
1313 return 0;
1316 if (fwrite($received->fh, $data) === false) {
1317 // bad luck, write failed, let's abort completely
1318 return 0;
1320 return strlen($data);
1324 * Returns a list of information about file types based on extensions.
1326 * The following elements expected in value array for each extension:
1327 * 'type' - mimetype
1328 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1329 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1330 * also files with bigger sizes under names
1331 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1332 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1333 * commonly used in moodle the following groups:
1334 * - web_image - image that can be included as <img> in HTML
1335 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1336 * - video - file that can be imported as video in text editor
1337 * - audio - file that can be imported as audio in text editor
1338 * - archive - we can extract files from this archive
1339 * - spreadsheet - used for portfolio format
1340 * - document - used for portfolio format
1341 * - presentation - used for portfolio format
1342 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1343 * human-readable description for this filetype;
1344 * Function {@link get_mimetype_description()} first looks at the presence of string for
1345 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1346 * attribute, if not found returns the value of 'type';
1347 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1348 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1349 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1351 * @category files
1352 * @return array List of information about file types based on extensions.
1353 * Associative array of extension (lower-case) to associative array
1354 * from 'element name' to data. Current element names are 'type' and 'icon'.
1355 * Unknown types should use the 'xxx' entry which includes defaults.
1357 function &get_mimetypes_array() {
1358 static $mimearray = array (
1359 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1360 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1361 'aac' => array ('type'=>'audio/aac', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1362 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1363 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1364 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1365 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1366 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1367 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1368 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1369 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1370 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1371 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1372 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1373 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1374 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1375 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1376 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1377 'csv' => array ('type'=>'text/csv', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1378 'dv' => array ('type'=>'video/x-dv', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1379 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1381 'doc' => array ('type'=>'application/msword', 'icon'=>'docx', 'groups'=>array('document')),
1382 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx', 'groups'=>array('document')),
1383 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docx'),
1384 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'docx'),
1385 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'docx'),
1387 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1388 'dif' => array ('type'=>'video/x-dv', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1389 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1390 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1391 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1392 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1393 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1394 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1395 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1396 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1397 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1398 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1399 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1400 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1401 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1402 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1403 'htc' => array ('type'=>'text/x-component', 'icon'=>'html'),
1404 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1405 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1406 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1407 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1408 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1409 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1410 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1411 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1412 'jcb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1413 'jcl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1414 'jcw' => array ('type'=>'text/xml', 'icon'=>'xml'),
1415 'jmt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1416 'jmx' => array ('type'=>'text/xml', 'icon'=>'xml'),
1417 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1418 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1419 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1420 'jqz' => array ('type'=>'text/xml', 'icon'=>'xml'),
1421 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1422 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1423 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1424 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1425 'mov' => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video','web_video'), 'string'=>'video'),
1426 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1427 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1428 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1429 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1430 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1431 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1432 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1433 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1434 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1436 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt', 'groups'=>array('document')),
1437 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt', 'groups'=>array('document')),
1438 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1439 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odt'),
1440 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1441 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1442 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1443 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1444 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods', 'groups'=>array('spreadsheet')),
1445 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods', 'groups'=>array('spreadsheet')),
1446 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1447 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1448 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1449 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odg'),
1450 'oga' => array ('type'=>'audio/ogg', 'icon'=>'wma', 'groups'=>array('audio'), 'string'=>'audio'),
1451 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'wma', 'groups'=>array('audio'), 'string'=>'audio'),
1452 'ogv' => array ('type'=>'video/ogg', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1454 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1455 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1456 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1457 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1458 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1459 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1461 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx', 'groups'=>array('presentation')),
1462 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx', 'groups'=>array('presentation')),
1463 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1464 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptx'),
1465 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'pptx'),
1466 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'pptx'),
1467 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'pptx'),
1468 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'pptx'),
1469 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'pptx'),
1471 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1472 'qt' => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video','web_video'), 'string'=>'video'),
1473 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1474 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1475 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1476 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1477 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1478 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1479 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1480 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1481 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1482 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1483 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1484 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1485 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1486 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1487 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1488 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1489 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1490 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1492 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1493 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1494 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'ods'),
1495 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'ods'),
1496 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odg'),
1497 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odg'),
1498 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odp'),
1499 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odp'),
1500 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1501 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odf'),
1503 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1504 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1505 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1506 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1507 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1508 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1509 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1510 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1511 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1512 'webm' => array ('type'=>'video/webm', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1513 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1514 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1515 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1516 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1517 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1519 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1520 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1521 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1522 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xlsx'),
1523 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xlsx'),
1524 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsx'),
1525 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlsx'),
1527 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1528 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1529 'zip' => array ('type'=>'application/zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive')
1531 return $mimearray;
1535 * Obtains information about a filetype based on its extension. Will
1536 * use a default if no information is present about that particular
1537 * extension.
1539 * @category files
1540 * @param string $element Desired information (usually 'icon'
1541 * for icon filename or 'type' for MIME type. Can also be
1542 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1543 * @param string $filename Filename we're looking up
1544 * @return string Requested piece of information from array
1546 function mimeinfo($element, $filename) {
1547 global $CFG;
1548 $mimeinfo = & get_mimetypes_array();
1549 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1551 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1552 if (empty($filetype)) {
1553 $filetype = 'xxx'; // file without extension
1555 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1556 $iconsize = max(array(16, (int)$iconsizematch[1]));
1557 $filenames = array($mimeinfo['xxx']['icon']);
1558 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1559 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1561 // find the file with the closest size, first search for specific icon then for default icon
1562 foreach ($filenames as $filename) {
1563 foreach ($iconpostfixes as $size => $postfix) {
1564 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1565 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1566 return $filename.$postfix;
1570 } else if (isset($mimeinfo[$filetype][$element])) {
1571 return $mimeinfo[$filetype][$element];
1572 } else if (isset($mimeinfo['xxx'][$element])) {
1573 return $mimeinfo['xxx'][$element]; // By default
1574 } else {
1575 return null;
1580 * Obtains information about a filetype based on the MIME type rather than
1581 * the other way around.
1583 * @category files
1584 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1585 * @param string $mimetype MIME type we're looking up
1586 * @return string Requested piece of information from array
1588 function mimeinfo_from_type($element, $mimetype) {
1589 /* array of cached mimetype->extension associations */
1590 static $cached = array();
1591 $mimeinfo = & get_mimetypes_array();
1593 if (!array_key_exists($mimetype, $cached)) {
1594 $cached[$mimetype] = null;
1595 foreach($mimeinfo as $filetype => $values) {
1596 if ($values['type'] == $mimetype) {
1597 if ($cached[$mimetype] === null) {
1598 $cached[$mimetype] = '.'.$filetype;
1600 if (!empty($values['defaulticon'])) {
1601 $cached[$mimetype] = '.'.$filetype;
1602 break;
1606 if (empty($cached[$mimetype])) {
1607 $cached[$mimetype] = '.xxx';
1610 if ($element === 'extension') {
1611 return $cached[$mimetype];
1612 } else {
1613 return mimeinfo($element, $cached[$mimetype]);
1618 * Return the relative icon path for a given file
1620 * Usage:
1621 * <code>
1622 * // $file - instance of stored_file or file_info
1623 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1624 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1625 * </code>
1626 * or
1627 * <code>
1628 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1629 * </code>
1631 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1632 * and $file->mimetype are expected)
1633 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1634 * @return string
1636 function file_file_icon($file, $size = null) {
1637 if (!is_object($file)) {
1638 $file = (object)$file;
1640 if (isset($file->filename)) {
1641 $filename = $file->filename;
1642 } else if (method_exists($file, 'get_filename')) {
1643 $filename = $file->get_filename();
1644 } else if (method_exists($file, 'get_visible_name')) {
1645 $filename = $file->get_visible_name();
1646 } else {
1647 $filename = '';
1649 if (isset($file->mimetype)) {
1650 $mimetype = $file->mimetype;
1651 } else if (method_exists($file, 'get_mimetype')) {
1652 $mimetype = $file->get_mimetype();
1653 } else {
1654 $mimetype = '';
1656 $mimetypes = &get_mimetypes_array();
1657 if ($filename) {
1658 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1659 if ($extension && !empty($mimetypes[$extension])) {
1660 // if file name has known extension, return icon for this extension
1661 return file_extension_icon($filename, $size);
1664 return file_mimetype_icon($mimetype, $size);
1668 * Return the relative icon path for a folder image
1670 * Usage:
1671 * <code>
1672 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1673 * echo html_writer::empty_tag('img', array('src' => $icon));
1674 * </code>
1675 * or
1676 * <code>
1677 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1678 * </code>
1680 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1681 * @return string
1683 function file_folder_icon($iconsize = null) {
1684 global $CFG;
1685 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1686 static $cached = array();
1687 $iconsize = max(array(16, (int)$iconsize));
1688 if (!array_key_exists($iconsize, $cached)) {
1689 foreach ($iconpostfixes as $size => $postfix) {
1690 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1691 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1692 $cached[$iconsize] = 'f/folder'.$postfix;
1693 break;
1697 return $cached[$iconsize];
1701 * Returns the relative icon path for a given mime type
1703 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1704 * a return the full path to an icon.
1706 * <code>
1707 * $mimetype = 'image/jpg';
1708 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1709 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1710 * </code>
1712 * @category files
1713 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1714 * to conform with that.
1715 * @param string $mimetype The mimetype to fetch an icon for
1716 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1717 * @return string The relative path to the icon
1719 function file_mimetype_icon($mimetype, $size = NULL) {
1720 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1724 * Returns the relative icon path for a given file name
1726 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1727 * a return the full path to an icon.
1729 * <code>
1730 * $filename = '.jpg';
1731 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1732 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1733 * </code>
1735 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1736 * to conform with that.
1737 * @todo MDL-31074 Implement $size
1738 * @category files
1739 * @param string $filename The filename to get the icon for
1740 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1741 * @return string
1743 function file_extension_icon($filename, $size = NULL) {
1744 return 'f/'.mimeinfo('icon'.$size, $filename);
1748 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1749 * mimetypes.php language file.
1751 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1752 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1753 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1754 * @param bool $capitalise If true, capitalises first character of result
1755 * @return string Text description
1757 function get_mimetype_description($obj, $capitalise=false) {
1758 $filename = $mimetype = '';
1759 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1760 // this is an instance of stored_file
1761 $mimetype = $obj->get_mimetype();
1762 $filename = $obj->get_filename();
1763 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1764 // this is an instance of file_info
1765 $mimetype = $obj->get_mimetype();
1766 $filename = $obj->get_visible_name();
1767 } else if (is_array($obj) || is_object ($obj)) {
1768 $obj = (array)$obj;
1769 if (!empty($obj['filename'])) {
1770 $filename = $obj['filename'];
1772 if (!empty($obj['mimetype'])) {
1773 $mimetype = $obj['mimetype'];
1775 } else {
1776 $mimetype = $obj;
1778 $mimetypefromext = mimeinfo('type', $filename);
1779 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1780 // if file has a known extension, overwrite the specified mimetype
1781 $mimetype = $mimetypefromext;
1783 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1784 if (empty($extension)) {
1785 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1786 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1787 } else {
1788 $mimetypestr = mimeinfo('string', $filename);
1790 $chunks = explode('/', $mimetype, 2);
1791 $chunks[] = '';
1792 $attr = array(
1793 'mimetype' => $mimetype,
1794 'ext' => $extension,
1795 'mimetype1' => $chunks[0],
1796 'mimetype2' => $chunks[1],
1798 $a = array();
1799 foreach ($attr as $key => $value) {
1800 $a[$key] = $value;
1801 $a[strtoupper($key)] = strtoupper($value);
1802 $a[ucfirst($key)] = ucfirst($value);
1804 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1805 $result = get_string($mimetype, 'mimetypes', (object)$a);
1806 } else if (get_string_manager()->string_exists($mimetypestr, 'mimetypes')) {
1807 $result = get_string($mimetypestr, 'mimetypes', (object)$a);
1808 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1809 $result = get_string('default', 'mimetypes', (object)$a);
1810 } else {
1811 $result = $mimetype;
1813 if ($capitalise) {
1814 $result=ucfirst($result);
1816 return $result;
1820 * Returns array of elements of type $element in type group(s)
1822 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1823 * @param string|array $groups one group or array of groups/extensions/mimetypes
1824 * @return array
1826 function file_get_typegroup($element, $groups) {
1827 static $cached = array();
1828 if (!is_array($groups)) {
1829 $groups = array($groups);
1831 if (!array_key_exists($element, $cached)) {
1832 $cached[$element] = array();
1834 $result = array();
1835 foreach ($groups as $group) {
1836 if (!array_key_exists($group, $cached[$element])) {
1837 // retrieive and cache all elements of type $element for group $group
1838 $mimeinfo = & get_mimetypes_array();
1839 $cached[$element][$group] = array();
1840 foreach ($mimeinfo as $extension => $value) {
1841 $value['extension'] = '.'.$extension;
1842 if (empty($value[$element])) {
1843 continue;
1845 if (($group === '.'.$extension || $group === $value['type'] ||
1846 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1847 !in_array($value[$element], $cached[$element][$group])) {
1848 $cached[$element][$group][] = $value[$element];
1852 $result = array_merge($result, $cached[$element][$group]);
1854 return array_unique($result);
1858 * Checks if file with name $filename has one of the extensions in groups $groups
1860 * @see get_mimetypes_array()
1861 * @param string $filename name of the file to check
1862 * @param string|array $groups one group or array of groups to check
1863 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1864 * file mimetype is in mimetypes in groups $groups
1865 * @return bool
1867 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1868 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1869 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1870 return true;
1872 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1876 * Checks if mimetype $mimetype belongs to one of the groups $groups
1878 * @see get_mimetypes_array()
1879 * @param string $mimetype
1880 * @param string|array $groups one group or array of groups to check
1881 * @return bool
1883 function file_mimetype_in_typegroup($mimetype, $groups) {
1884 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1888 * Requested file is not found or not accessible, does not return, terminates script
1890 * @global stdClass $CFG
1891 * @global stdClass $COURSE
1893 function send_file_not_found() {
1894 global $CFG, $COURSE;
1895 send_header_404();
1896 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1899 * Helper function to send correct 404 for server.
1901 function send_header_404() {
1902 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1903 header("Status: 404 Not Found");
1904 } else {
1905 header('HTTP/1.0 404 not found');
1910 * Enhanced readfile() with optional acceleration.
1911 * @param string|stored_file $file
1912 * @param string $mimetype
1913 * @param bool $accelerate
1914 * @return void
1916 function readfile_accel($file, $mimetype, $accelerate) {
1917 global $CFG;
1919 if ($mimetype === 'text/plain') {
1920 // there is no encoding specified in text files, we need something consistent
1921 header('Content-Type: text/plain; charset=utf-8');
1922 } else {
1923 header('Content-Type: '.$mimetype);
1926 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1927 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1929 if (is_object($file)) {
1930 header('ETag: ' . $file->get_contenthash());
1931 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1932 header('HTTP/1.1 304 Not Modified');
1933 return;
1937 // if etag present for stored file rely on it exclusively
1938 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1939 // get unixtime of request header; clip extra junk off first
1940 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1941 if ($since && $since >= $lastmodified) {
1942 header('HTTP/1.1 304 Not Modified');
1943 return;
1947 if ($accelerate and !empty($CFG->xsendfile)) {
1948 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1949 header('Accept-Ranges: bytes');
1950 } else {
1951 header('Accept-Ranges: none');
1954 if (is_object($file)) {
1955 $fs = get_file_storage();
1956 if ($fs->xsendfile($file->get_contenthash())) {
1957 return;
1960 } else {
1961 require_once("$CFG->libdir/xsendfilelib.php");
1962 if (xsendfile($file)) {
1963 return;
1968 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1970 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1972 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1973 header('Accept-Ranges: bytes');
1975 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1976 // byteserving stuff - for acrobat reader and download accelerators
1977 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1978 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1979 $ranges = false;
1980 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1981 foreach ($ranges as $key=>$value) {
1982 if ($ranges[$key][1] == '') {
1983 //suffix case
1984 $ranges[$key][1] = $filesize - $ranges[$key][2];
1985 $ranges[$key][2] = $filesize - 1;
1986 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1987 //fix range length
1988 $ranges[$key][2] = $filesize - 1;
1990 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1991 //invalid byte-range ==> ignore header
1992 $ranges = false;
1993 break;
1995 //prepare multipart header
1996 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1997 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1999 } else {
2000 $ranges = false;
2002 if ($ranges) {
2003 if (is_object($file)) {
2004 $handle = $file->get_content_file_handle();
2005 } else {
2006 $handle = fopen($file, 'rb');
2008 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2011 } else {
2012 // Do not byteserve
2013 header('Accept-Ranges: none');
2016 header('Content-Length: '.$filesize);
2018 if ($filesize > 10000000) {
2019 // for large files try to flush and close all buffers to conserve memory
2020 while(@ob_get_level()) {
2021 if (!@ob_end_flush()) {
2022 break;
2027 // send the whole file content
2028 if (is_object($file)) {
2029 $file->readfile();
2030 } else {
2031 readfile($file);
2036 * Similar to readfile_accel() but designed for strings.
2037 * @param string $string
2038 * @param string $mimetype
2039 * @param bool $accelerate
2040 * @return void
2042 function readstring_accel($string, $mimetype, $accelerate) {
2043 global $CFG;
2045 if ($mimetype === 'text/plain') {
2046 // there is no encoding specified in text files, we need something consistent
2047 header('Content-Type: text/plain; charset=utf-8');
2048 } else {
2049 header('Content-Type: '.$mimetype);
2051 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2052 header('Accept-Ranges: none');
2054 if ($accelerate and !empty($CFG->xsendfile)) {
2055 $fs = get_file_storage();
2056 if ($fs->xsendfile(sha1($string))) {
2057 return;
2061 header('Content-Length: '.strlen($string));
2062 echo $string;
2066 * Handles the sending of temporary file to user, download is forced.
2067 * File is deleted after abort or successful sending, does not return, script terminated
2069 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2070 * @param string $filename proposed file name when saving file
2071 * @param bool $pathisstring If the path is string
2073 function send_temp_file($path, $filename, $pathisstring=false) {
2074 global $CFG;
2076 if (check_browser_version('Firefox', '1.5')) {
2077 // only FF is known to correctly save to disk before opening...
2078 $mimetype = mimeinfo('type', $filename);
2079 } else {
2080 $mimetype = 'application/x-forcedownload';
2083 // close session - not needed anymore
2084 session_get_instance()->write_close();
2086 if (!$pathisstring) {
2087 if (!file_exists($path)) {
2088 send_header_404();
2089 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2091 // executed after normal finish or abort
2092 @register_shutdown_function('send_temp_file_finished', $path);
2095 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2096 if (check_browser_version('MSIE')) {
2097 $filename = urlencode($filename);
2100 header('Content-Disposition: attachment; filename="'.$filename.'"');
2101 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2102 header('Cache-Control: max-age=10');
2103 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2104 header('Pragma: ');
2105 } else { //normal http - prevent caching at all cost
2106 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2107 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2108 header('Pragma: no-cache');
2111 // send the contents - we can not accelerate this because the file will be deleted asap
2112 if ($pathisstring) {
2113 readstring_accel($path, $mimetype, false);
2114 } else {
2115 readfile_accel($path, $mimetype, false);
2116 @unlink($path);
2119 die; //no more chars to output
2123 * Internal callback function used by send_temp_file()
2125 * @param string $path
2127 function send_temp_file_finished($path) {
2128 if (file_exists($path)) {
2129 @unlink($path);
2134 * Handles the sending of file data to the user's browser, including support for
2135 * byteranges etc.
2137 * @category files
2138 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2139 * @param string $filename Filename to send
2140 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2141 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2142 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2143 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2144 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2145 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2146 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2147 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2148 * and should not be reopened.
2149 * @return null script execution stopped unless $dontdie is true
2151 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2152 global $CFG, $COURSE;
2154 if ($dontdie) {
2155 ignore_user_abort(true);
2158 // MDL-11789, apply $CFG->filelifetime here
2159 if ($lifetime === 'default') {
2160 if (!empty($CFG->filelifetime)) {
2161 $lifetime = $CFG->filelifetime;
2162 } else {
2163 $lifetime = 86400;
2167 session_get_instance()->write_close(); // unlock session during fileserving
2169 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2170 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2171 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2172 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2173 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2174 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2176 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2177 if (check_browser_version('MSIE')) {
2178 $filename = rawurlencode($filename);
2181 if ($forcedownload) {
2182 header('Content-Disposition: attachment; filename="'.$filename.'"');
2183 } else {
2184 header('Content-Disposition: inline; filename="'.$filename.'"');
2187 if ($lifetime > 0) {
2188 $nobyteserving = false;
2189 header('Cache-Control: max-age='.$lifetime);
2190 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2191 header('Pragma: ');
2193 } else { // Do not cache files in proxies and browsers
2194 $nobyteserving = true;
2195 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2196 header('Cache-Control: max-age=10');
2197 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2198 header('Pragma: ');
2199 } else { //normal http - prevent caching at all cost
2200 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2201 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2202 header('Pragma: no-cache');
2206 if (empty($filter)) {
2207 // send the contents
2208 if ($pathisstring) {
2209 readstring_accel($path, $mimetype, !$dontdie);
2210 } else {
2211 readfile_accel($path, $mimetype, !$dontdie);
2214 } else {
2215 // Try to put the file through filters
2216 if ($mimetype == 'text/html') {
2217 $options = new stdClass();
2218 $options->noclean = true;
2219 $options->nocache = true; // temporary workaround for MDL-5136
2220 $text = $pathisstring ? $path : implode('', file($path));
2222 $text = file_modify_html_header($text);
2223 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2225 readstring_accel($output, $mimetype, false);
2227 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2228 // only filter text if filter all files is selected
2229 $options = new stdClass();
2230 $options->newlines = false;
2231 $options->noclean = true;
2232 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
2233 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2235 readstring_accel($output, $mimetype, false);
2237 } else {
2238 // send the contents
2239 if ($pathisstring) {
2240 readstring_accel($path, $mimetype, !$dontdie);
2241 } else {
2242 readfile_accel($path, $mimetype, !$dontdie);
2246 if ($dontdie) {
2247 return;
2249 die; //no more chars to output!!!
2253 * Handles the sending of file data to the user's browser, including support for
2254 * byteranges etc.
2256 * The $options parameter supports the following keys:
2257 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2258 * (string|null) filename - overrides the implicit filename
2259 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2260 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2261 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2262 * and should not be reopened.
2264 * @category files
2265 * @param stored_file $stored_file local file object
2266 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2267 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2268 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2269 * @param array $options additional options affecting the file serving
2270 * @return null script execution stopped unless $options['dontdie'] is true
2272 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2273 global $CFG, $COURSE;
2275 if (empty($options['filename'])) {
2276 $filename = null;
2277 } else {
2278 $filename = $options['filename'];
2281 if (empty($options['dontdie'])) {
2282 $dontdie = false;
2283 } else {
2284 $dontdie = true;
2287 if (!empty($options['preview'])) {
2288 // replace the file with its preview
2289 $fs = get_file_storage();
2290 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2291 if (!$preview_file) {
2292 // unable to create a preview of the file, send its default mime icon instead
2293 if ($options['preview'] === 'tinyicon') {
2294 $size = 24;
2295 } else if ($options['preview'] === 'thumb') {
2296 $size = 90;
2297 } else {
2298 $size = 256;
2300 $fileicon = file_file_icon($stored_file, $size);
2301 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2302 } else {
2303 // preview images have fixed cache lifetime and they ignore forced download
2304 // (they are generated by GD and therefore they are considered reasonably safe).
2305 $stored_file = $preview_file;
2306 $lifetime = DAYSECS;
2307 $filter = 0;
2308 $forcedownload = false;
2312 // handle external resource
2313 if ($stored_file->is_external_file()) {
2314 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2315 die;
2318 if (!$stored_file or $stored_file->is_directory()) {
2319 // nothing to serve
2320 if ($dontdie) {
2321 return;
2323 die;
2326 if ($dontdie) {
2327 ignore_user_abort(true);
2330 session_get_instance()->write_close(); // unlock session during fileserving
2332 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2333 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2334 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2335 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2336 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2337 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2338 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2340 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2341 if (check_browser_version('MSIE')) {
2342 $filename = rawurlencode($filename);
2345 if ($forcedownload) {
2346 header('Content-Disposition: attachment; filename="'.$filename.'"');
2347 } else {
2348 header('Content-Disposition: inline; filename="'.$filename.'"');
2351 if ($lifetime > 0) {
2352 header('Cache-Control: max-age='.$lifetime);
2353 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2354 header('Pragma: ');
2356 } else { // Do not cache files in proxies and browsers
2357 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2358 header('Cache-Control: max-age=10');
2359 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2360 header('Pragma: ');
2361 } else { //normal http - prevent caching at all cost
2362 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2363 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2364 header('Pragma: no-cache');
2368 if (empty($filter)) {
2369 // send the contents
2370 readfile_accel($stored_file, $mimetype, !$dontdie);
2372 } else { // Try to put the file through filters
2373 if ($mimetype == 'text/html') {
2374 $options = new stdClass();
2375 $options->noclean = true;
2376 $options->nocache = true; // temporary workaround for MDL-5136
2377 $text = $stored_file->get_content();
2378 $text = file_modify_html_header($text);
2379 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2381 readstring_accel($output, $mimetype, false);
2383 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2384 // only filter text if filter all files is selected
2385 $options = new stdClass();
2386 $options->newlines = false;
2387 $options->noclean = true;
2388 $text = $stored_file->get_content();
2389 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2391 readstring_accel($output, $mimetype, false);
2393 } else { // Just send it out raw
2394 readfile_accel($stored_file, $mimetype, !$dontdie);
2397 if ($dontdie) {
2398 return;
2400 die; //no more chars to output!!!
2404 * Retrieves an array of records from a CSV file and places
2405 * them into a given table structure
2407 * @global stdClass $CFG
2408 * @global moodle_database $DB
2409 * @param string $file The path to a CSV file
2410 * @param string $table The table to retrieve columns from
2411 * @return bool|array Returns an array of CSV records or false
2413 function get_records_csv($file, $table) {
2414 global $CFG, $DB;
2416 if (!$metacolumns = $DB->get_columns($table)) {
2417 return false;
2420 if(!($handle = @fopen($file, 'r'))) {
2421 print_error('get_records_csv failed to open '.$file);
2424 $fieldnames = fgetcsv($handle, 4096);
2425 if(empty($fieldnames)) {
2426 fclose($handle);
2427 return false;
2430 $columns = array();
2432 foreach($metacolumns as $metacolumn) {
2433 $ord = array_search($metacolumn->name, $fieldnames);
2434 if(is_int($ord)) {
2435 $columns[$metacolumn->name] = $ord;
2439 $rows = array();
2441 while (($data = fgetcsv($handle, 4096)) !== false) {
2442 $item = new stdClass;
2443 foreach($columns as $name => $ord) {
2444 $item->$name = $data[$ord];
2446 $rows[] = $item;
2449 fclose($handle);
2450 return $rows;
2454 * Create a file with CSV contents
2456 * @global stdClass $CFG
2457 * @global moodle_database $DB
2458 * @param string $file The file to put the CSV content into
2459 * @param array $records An array of records to write to a CSV file
2460 * @param string $table The table to get columns from
2461 * @return bool success
2463 function put_records_csv($file, $records, $table = NULL) {
2464 global $CFG, $DB;
2466 if (empty($records)) {
2467 return true;
2470 $metacolumns = NULL;
2471 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2472 return false;
2475 echo "x";
2477 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2478 print_error('put_records_csv failed to open '.$file);
2481 $proto = reset($records);
2482 if(is_object($proto)) {
2483 $fields_records = array_keys(get_object_vars($proto));
2485 else if(is_array($proto)) {
2486 $fields_records = array_keys($proto);
2488 else {
2489 return false;
2491 echo "x";
2493 if(!empty($metacolumns)) {
2494 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2495 $fields = array_intersect($fields_records, $fields_table);
2497 else {
2498 $fields = $fields_records;
2501 fwrite($fp, implode(',', $fields));
2502 fwrite($fp, "\r\n");
2504 foreach($records as $record) {
2505 $array = (array)$record;
2506 $values = array();
2507 foreach($fields as $field) {
2508 if(strpos($array[$field], ',')) {
2509 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2511 else {
2512 $values[] = $array[$field];
2515 fwrite($fp, implode(',', $values)."\r\n");
2518 fclose($fp);
2519 return true;
2524 * Recursively delete the file or folder with path $location. That is,
2525 * if it is a file delete it. If it is a folder, delete all its content
2526 * then delete it. If $location does not exist to start, that is not
2527 * considered an error.
2529 * @param string $location the path to remove.
2530 * @return bool
2532 function fulldelete($location) {
2533 if (empty($location)) {
2534 // extra safety against wrong param
2535 return false;
2537 if (is_dir($location)) {
2538 if (!$currdir = opendir($location)) {
2539 return false;
2541 while (false !== ($file = readdir($currdir))) {
2542 if ($file <> ".." && $file <> ".") {
2543 $fullfile = $location."/".$file;
2544 if (is_dir($fullfile)) {
2545 if (!fulldelete($fullfile)) {
2546 return false;
2548 } else {
2549 if (!unlink($fullfile)) {
2550 return false;
2555 closedir($currdir);
2556 if (! rmdir($location)) {
2557 return false;
2560 } else if (file_exists($location)) {
2561 if (!unlink($location)) {
2562 return false;
2565 return true;
2569 * Send requested byterange of file.
2571 * @param resource $handle A file handle
2572 * @param string $mimetype The mimetype for the output
2573 * @param array $ranges An array of ranges to send
2574 * @param string $filesize The size of the content if only one range is used
2576 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2577 // better turn off any kind of compression and buffering
2578 @ini_set('zlib.output_compression', 'Off');
2580 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2581 if ($handle === false) {
2582 die;
2584 if (count($ranges) == 1) { //only one range requested
2585 $length = $ranges[0][2] - $ranges[0][1] + 1;
2586 header('HTTP/1.1 206 Partial content');
2587 header('Content-Length: '.$length);
2588 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2589 header('Content-Type: '.$mimetype);
2591 while(@ob_get_level()) {
2592 if (!@ob_end_flush()) {
2593 break;
2597 fseek($handle, $ranges[0][1]);
2598 while (!feof($handle) && $length > 0) {
2599 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2600 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2601 echo $buffer;
2602 flush();
2603 $length -= strlen($buffer);
2605 fclose($handle);
2606 die;
2607 } else { // multiple ranges requested - not tested much
2608 $totallength = 0;
2609 foreach($ranges as $range) {
2610 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2612 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2613 header('HTTP/1.1 206 Partial content');
2614 header('Content-Length: '.$totallength);
2615 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2617 while(@ob_get_level()) {
2618 if (!@ob_end_flush()) {
2619 break;
2623 foreach($ranges as $range) {
2624 $length = $range[2] - $range[1] + 1;
2625 echo $range[0];
2626 fseek($handle, $range[1]);
2627 while (!feof($handle) && $length > 0) {
2628 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2629 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2630 echo $buffer;
2631 flush();
2632 $length -= strlen($buffer);
2635 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2636 fclose($handle);
2637 die;
2642 * add includes (js and css) into uploaded files
2643 * before returning them, useful for themes and utf.js includes
2645 * @global stdClass $CFG
2646 * @param string $text text to search and replace
2647 * @return string text with added head includes
2648 * @todo MDL-21120
2650 function file_modify_html_header($text) {
2651 // first look for <head> tag
2652 global $CFG;
2654 $stylesheetshtml = '';
2655 /* foreach ($CFG->stylesheets as $stylesheet) {
2656 //TODO: MDL-21120
2657 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2660 $ufo = '';
2661 if (filter_is_enabled('filter/mediaplugin')) {
2662 // this script is needed by most media filter plugins.
2663 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2664 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2667 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2668 if ($matches) {
2669 $replacement = '<head>'.$ufo.$stylesheetshtml;
2670 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2671 return $text;
2674 // if not, look for <html> tag, and stick <head> right after
2675 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2676 if ($matches) {
2677 // replace <html> tag with <html><head>includes</head>
2678 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2679 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2680 return $text;
2683 // if not, look for <body> tag, and stick <head> before body
2684 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2685 if ($matches) {
2686 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2687 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2688 return $text;
2691 // if not, just stick a <head> tag at the beginning
2692 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2693 return $text;
2697 * RESTful cURL class
2699 * This is a wrapper class for curl, it is quite easy to use:
2700 * <code>
2701 * $c = new curl;
2702 * // enable cache
2703 * $c = new curl(array('cache'=>true));
2704 * // enable cookie
2705 * $c = new curl(array('cookie'=>true));
2706 * // enable proxy
2707 * $c = new curl(array('proxy'=>true));
2709 * // HTTP GET Method
2710 * $html = $c->get('http://example.com');
2711 * // HTTP POST Method
2712 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2713 * // HTTP PUT Method
2714 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2715 * </code>
2717 * @package core_files
2718 * @category files
2719 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2720 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2722 class curl {
2723 /** @var bool Caches http request contents */
2724 public $cache = false;
2725 /** @var bool Uses proxy */
2726 public $proxy = false;
2727 /** @var string library version */
2728 public $version = '0.4 dev';
2729 /** @var array http's response */
2730 public $response = array();
2731 /** @var array http header */
2732 public $header = array();
2733 /** @var string cURL information */
2734 public $info;
2735 /** @var string error */
2736 public $error;
2738 /** @var array cURL options */
2739 private $options;
2740 /** @var string Proxy host */
2741 private $proxy_host = '';
2742 /** @var string Proxy auth */
2743 private $proxy_auth = '';
2744 /** @var string Proxy type */
2745 private $proxy_type = '';
2746 /** @var bool Debug mode on */
2747 private $debug = false;
2748 /** @var bool|string Path to cookie file */
2749 private $cookie = false;
2752 * Constructor
2754 * @global stdClass $CFG
2755 * @param array $options
2757 public function __construct($options = array()){
2758 global $CFG;
2759 if (!function_exists('curl_init')) {
2760 $this->error = 'cURL module must be enabled!';
2761 trigger_error($this->error, E_USER_ERROR);
2762 return false;
2764 // the options of curl should be init here.
2765 $this->resetopt();
2766 if (!empty($options['debug'])) {
2767 $this->debug = true;
2769 if(!empty($options['cookie'])) {
2770 if($options['cookie'] === true) {
2771 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2772 } else {
2773 $this->cookie = $options['cookie'];
2776 if (!empty($options['cache'])) {
2777 if (class_exists('curl_cache')) {
2778 if (!empty($options['module_cache'])) {
2779 $this->cache = new curl_cache($options['module_cache']);
2780 } else {
2781 $this->cache = new curl_cache('misc');
2785 if (!empty($CFG->proxyhost)) {
2786 if (empty($CFG->proxyport)) {
2787 $this->proxy_host = $CFG->proxyhost;
2788 } else {
2789 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2791 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2792 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2793 $this->setopt(array(
2794 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2795 'proxyuserpwd'=>$this->proxy_auth));
2797 if (!empty($CFG->proxytype)) {
2798 if ($CFG->proxytype == 'SOCKS5') {
2799 $this->proxy_type = CURLPROXY_SOCKS5;
2800 } else {
2801 $this->proxy_type = CURLPROXY_HTTP;
2802 $this->setopt(array('httpproxytunnel'=>false));
2804 $this->setopt(array('proxytype'=>$this->proxy_type));
2807 if (!empty($this->proxy_host)) {
2808 $this->proxy = array('proxy'=>$this->proxy_host);
2812 * Resets the CURL options that have already been set
2814 public function resetopt(){
2815 $this->options = array();
2816 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2817 // True to include the header in the output
2818 $this->options['CURLOPT_HEADER'] = 0;
2819 // True to Exclude the body from the output
2820 $this->options['CURLOPT_NOBODY'] = 0;
2821 // TRUE to follow any "Location: " header that the server
2822 // sends as part of the HTTP header (note this is recursive,
2823 // PHP will follow as many "Location: " headers that it is sent,
2824 // unless CURLOPT_MAXREDIRS is set).
2825 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2826 $this->options['CURLOPT_MAXREDIRS'] = 10;
2827 $this->options['CURLOPT_ENCODING'] = '';
2828 // TRUE to return the transfer as a string of the return
2829 // value of curl_exec() instead of outputting it out directly.
2830 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2831 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2832 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2833 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2834 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2838 * Reset Cookie
2840 public function resetcookie() {
2841 if (!empty($this->cookie)) {
2842 if (is_file($this->cookie)) {
2843 $fp = fopen($this->cookie, 'w');
2844 if (!empty($fp)) {
2845 fwrite($fp, '');
2846 fclose($fp);
2853 * Set curl options
2855 * @param array $options If array is null, this function will
2856 * reset the options to default value.
2858 public function setopt($options = array()) {
2859 if (is_array($options)) {
2860 foreach($options as $name => $val){
2861 if (stripos($name, 'CURLOPT_') === false) {
2862 $name = strtoupper('CURLOPT_'.$name);
2864 $this->options[$name] = $val;
2870 * Reset http method
2872 public function cleanopt(){
2873 unset($this->options['CURLOPT_HTTPGET']);
2874 unset($this->options['CURLOPT_POST']);
2875 unset($this->options['CURLOPT_POSTFIELDS']);
2876 unset($this->options['CURLOPT_PUT']);
2877 unset($this->options['CURLOPT_INFILE']);
2878 unset($this->options['CURLOPT_INFILESIZE']);
2879 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2883 * Set HTTP Request Header
2885 * @param array $header
2887 public function setHeader($header) {
2888 if (is_array($header)){
2889 foreach ($header as $v) {
2890 $this->setHeader($v);
2892 } else {
2893 $this->header[] = $header;
2898 * Set HTTP Response Header
2901 public function getResponse(){
2902 return $this->response;
2906 * private callback function
2907 * Formatting HTTP Response Header
2909 * @param resource $ch Apparently not used
2910 * @param string $header
2911 * @return int The strlen of the header
2913 private function formatHeader($ch, $header)
2915 $this->count++;
2916 if (strlen($header) > 2) {
2917 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2918 $key = rtrim($key, ':');
2919 if (!empty($this->response[$key])) {
2920 if (is_array($this->response[$key])){
2921 $this->response[$key][] = $value;
2922 } else {
2923 $tmp = $this->response[$key];
2924 $this->response[$key] = array();
2925 $this->response[$key][] = $tmp;
2926 $this->response[$key][] = $value;
2929 } else {
2930 $this->response[$key] = $value;
2933 return strlen($header);
2937 * Set options for individual curl instance
2939 * @param resource $curl A curl handle
2940 * @param array $options
2941 * @return resource The curl handle
2943 private function apply_opt($curl, $options) {
2944 // Clean up
2945 $this->cleanopt();
2946 // set cookie
2947 if (!empty($this->cookie) || !empty($options['cookie'])) {
2948 $this->setopt(array('cookiejar'=>$this->cookie,
2949 'cookiefile'=>$this->cookie
2953 // set proxy
2954 if (!empty($this->proxy) || !empty($options['proxy'])) {
2955 $this->setopt($this->proxy);
2957 $this->setopt($options);
2958 // reset before set options
2959 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2960 // set headers
2961 if (empty($this->header)){
2962 $this->setHeader(array(
2963 'User-Agent: MoodleBot/1.0',
2964 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2965 'Connection: keep-alive'
2968 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2970 if ($this->debug){
2971 echo '<h1>Options</h1>';
2972 var_dump($this->options);
2973 echo '<h1>Header</h1>';
2974 var_dump($this->header);
2977 // set options
2978 foreach($this->options as $name => $val) {
2979 if (is_string($name)) {
2980 $name = constant(strtoupper($name));
2982 curl_setopt($curl, $name, $val);
2984 return $curl;
2988 * Download multiple files in parallel
2990 * Calls {@link multi()} with specific download headers
2992 * <code>
2993 * $c = new curl;
2994 * $c->download(array(
2995 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2996 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2997 * ));
2998 * </code>
3000 * @param array $requests An array of files to request
3001 * @param array $options An array of options to set
3002 * @return array An array of results
3004 public function download($requests, $options = array()) {
3005 $options['CURLOPT_BINARYTRANSFER'] = 1;
3006 $options['RETURNTRANSFER'] = false;
3007 return $this->multi($requests, $options);
3011 * Mulit HTTP Requests
3012 * This function could run multi-requests in parallel.
3014 * @param array $requests An array of files to request
3015 * @param array $options An array of options to set
3016 * @return array An array of results
3018 protected function multi($requests, $options = array()) {
3019 $count = count($requests);
3020 $handles = array();
3021 $results = array();
3022 $main = curl_multi_init();
3023 for ($i = 0; $i < $count; $i++) {
3024 $url = $requests[$i];
3025 foreach($url as $n=>$v){
3026 $options[$n] = $url[$n];
3028 $handles[$i] = curl_init($url['url']);
3029 $this->apply_opt($handles[$i], $options);
3030 curl_multi_add_handle($main, $handles[$i]);
3032 $running = 0;
3033 do {
3034 curl_multi_exec($main, $running);
3035 } while($running > 0);
3036 for ($i = 0; $i < $count; $i++) {
3037 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3038 $results[] = true;
3039 } else {
3040 $results[] = curl_multi_getcontent($handles[$i]);
3042 curl_multi_remove_handle($main, $handles[$i]);
3044 curl_multi_close($main);
3045 return $results;
3049 * Single HTTP Request
3051 * @param string $url The URL to request
3052 * @param array $options
3053 * @return bool
3055 protected function request($url, $options = array()){
3056 // create curl instance
3057 $curl = curl_init($url);
3058 $options['url'] = $url;
3059 $this->apply_opt($curl, $options);
3060 if ($this->cache && $ret = $this->cache->get($this->options)) {
3061 return $ret;
3062 } else {
3063 $ret = curl_exec($curl);
3064 if ($this->cache) {
3065 $this->cache->set($this->options, $ret);
3069 $this->info = curl_getinfo($curl);
3070 $this->error = curl_error($curl);
3072 if ($this->debug){
3073 echo '<h1>Return Data</h1>';
3074 var_dump($ret);
3075 echo '<h1>Info</h1>';
3076 var_dump($this->info);
3077 echo '<h1>Error</h1>';
3078 var_dump($this->error);
3081 curl_close($curl);
3083 if (empty($this->error)){
3084 return $ret;
3085 } else {
3086 return $this->error;
3087 // exception is not ajax friendly
3088 //throw new moodle_exception($this->error, 'curl');
3093 * HTTP HEAD method
3095 * @see request()
3097 * @param string $url
3098 * @param array $options
3099 * @return bool
3101 public function head($url, $options = array()){
3102 $options['CURLOPT_HTTPGET'] = 0;
3103 $options['CURLOPT_HEADER'] = 1;
3104 $options['CURLOPT_NOBODY'] = 1;
3105 return $this->request($url, $options);
3109 * HTTP POST method
3111 * @param string $url
3112 * @param array|string $params
3113 * @param array $options
3114 * @return bool
3116 public function post($url, $params = '', $options = array()){
3117 $options['CURLOPT_POST'] = 1;
3118 if (is_array($params)) {
3119 $this->_tmp_file_post_params = array();
3120 foreach ($params as $key => $value) {
3121 if ($value instanceof stored_file) {
3122 $value->add_to_curl_request($this, $key);
3123 } else {
3124 $this->_tmp_file_post_params[$key] = $value;
3127 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3128 unset($this->_tmp_file_post_params);
3129 } else {
3130 // $params is the raw post data
3131 $options['CURLOPT_POSTFIELDS'] = $params;
3133 return $this->request($url, $options);
3137 * HTTP GET method
3139 * @param string $url
3140 * @param array $params
3141 * @param array $options
3142 * @return bool
3144 public function get($url, $params = array(), $options = array()){
3145 $options['CURLOPT_HTTPGET'] = 1;
3147 if (!empty($params)){
3148 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3149 $url .= http_build_query($params, '', '&');
3151 return $this->request($url, $options);
3155 * HTTP PUT method
3157 * @param string $url
3158 * @param array $params
3159 * @param array $options
3160 * @return bool
3162 public function put($url, $params = array(), $options = array()){
3163 $file = $params['file'];
3164 if (!is_file($file)){
3165 return null;
3167 $fp = fopen($file, 'r');
3168 $size = filesize($file);
3169 $options['CURLOPT_PUT'] = 1;
3170 $options['CURLOPT_INFILESIZE'] = $size;
3171 $options['CURLOPT_INFILE'] = $fp;
3172 if (!isset($this->options['CURLOPT_USERPWD'])){
3173 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3175 $ret = $this->request($url, $options);
3176 fclose($fp);
3177 return $ret;
3181 * HTTP DELETE method
3183 * @param string $url
3184 * @param array $param
3185 * @param array $options
3186 * @return bool
3188 public function delete($url, $param = array(), $options = array()){
3189 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3190 if (!isset($options['CURLOPT_USERPWD'])) {
3191 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3193 $ret = $this->request($url, $options);
3194 return $ret;
3198 * HTTP TRACE method
3200 * @param string $url
3201 * @param array $options
3202 * @return bool
3204 public function trace($url, $options = array()){
3205 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3206 $ret = $this->request($url, $options);
3207 return $ret;
3211 * HTTP OPTIONS method
3213 * @param string $url
3214 * @param array $options
3215 * @return bool
3217 public function options($url, $options = array()){
3218 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3219 $ret = $this->request($url, $options);
3220 return $ret;
3224 * Get curl information
3226 * @return string
3228 public function get_info() {
3229 return $this->info;
3234 * This class is used by cURL class, use case:
3236 * <code>
3237 * $CFG->repositorycacheexpire = 120;
3238 * $CFG->curlcache = 120;
3240 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3241 * $ret = $c->get('http://www.google.com');
3242 * </code>
3244 * @package core_files
3245 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3248 class curl_cache {
3249 /** @var string Path to cache directory */
3250 public $dir = '';
3253 * Constructor
3255 * @global stdClass $CFG
3256 * @param string $module which module is using curl_cache
3258 public function __construct($module = 'repository') {
3259 global $CFG;
3260 if (!empty($module)) {
3261 $this->dir = $CFG->cachedir.'/'.$module.'/';
3262 } else {
3263 $this->dir = $CFG->cachedir.'/misc/';
3265 if (!file_exists($this->dir)) {
3266 mkdir($this->dir, $CFG->directorypermissions, true);
3268 if ($module == 'repository') {
3269 if (empty($CFG->repositorycacheexpire)) {
3270 $CFG->repositorycacheexpire = 120;
3272 $this->ttl = $CFG->repositorycacheexpire;
3273 } else {
3274 if (empty($CFG->curlcache)) {
3275 $CFG->curlcache = 120;
3277 $this->ttl = $CFG->curlcache;
3282 * Get cached value
3284 * @global stdClass $CFG
3285 * @global stdClass $USER
3286 * @param mixed $param
3287 * @return bool|string
3289 public function get($param) {
3290 global $CFG, $USER;
3291 $this->cleanup($this->ttl);
3292 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3293 if(file_exists($this->dir.$filename)) {
3294 $lasttime = filemtime($this->dir.$filename);
3295 if (time()-$lasttime > $this->ttl) {
3296 return false;
3297 } else {
3298 $fp = fopen($this->dir.$filename, 'r');
3299 $size = filesize($this->dir.$filename);
3300 $content = fread($fp, $size);
3301 return unserialize($content);
3304 return false;
3308 * Set cache value
3310 * @global object $CFG
3311 * @global object $USER
3312 * @param mixed $param
3313 * @param mixed $val
3315 public function set($param, $val) {
3316 global $CFG, $USER;
3317 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3318 $fp = fopen($this->dir.$filename, 'w');
3319 fwrite($fp, serialize($val));
3320 fclose($fp);
3324 * Remove cache files
3326 * @param int $expire The number of seconds before expiry
3328 public function cleanup($expire) {
3329 if ($dir = opendir($this->dir)) {
3330 while (false !== ($file = readdir($dir))) {
3331 if(!is_dir($file) && $file != '.' && $file != '..') {
3332 $lasttime = @filemtime($this->dir.$file);
3333 if (time() - $lasttime > $expire) {
3334 @unlink($this->dir.$file);
3338 closedir($dir);
3342 * delete current user's cache file
3344 * @global object $CFG
3345 * @global object $USER
3347 public function refresh() {
3348 global $CFG, $USER;
3349 if ($dir = opendir($this->dir)) {
3350 while (false !== ($file = readdir($dir))) {
3351 if (!is_dir($file) && $file != '.' && $file != '..') {
3352 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3353 @unlink($this->dir.$file);
3362 * This function delegates file serving to individual plugins
3364 * @param string $relativepath
3365 * @param bool $forcedownload
3366 * @param null|string $preview the preview mode, defaults to serving the original file
3367 * @todo MDL-31088 file serving improments
3369 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3370 global $DB, $CFG, $USER;
3371 // relative path must start with '/'
3372 if (!$relativepath) {
3373 print_error('invalidargorconf');
3374 } else if ($relativepath[0] != '/') {
3375 print_error('pathdoesnotstartslash');
3378 // extract relative path components
3379 $args = explode('/', ltrim($relativepath, '/'));
3381 if (count($args) < 3) { // always at least context, component and filearea
3382 print_error('invalidarguments');
3385 $contextid = (int)array_shift($args);
3386 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3387 $filearea = clean_param(array_shift($args), PARAM_AREA);
3389 list($context, $course, $cm) = get_context_info_array($contextid);
3391 $fs = get_file_storage();
3393 // ========================================================================================================================
3394 if ($component === 'blog') {
3395 // Blog file serving
3396 if ($context->contextlevel != CONTEXT_SYSTEM) {
3397 send_file_not_found();
3399 if ($filearea !== 'attachment' and $filearea !== 'post') {
3400 send_file_not_found();
3403 if (empty($CFG->bloglevel)) {
3404 print_error('siteblogdisable', 'blog');
3407 $entryid = (int)array_shift($args);
3408 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3409 send_file_not_found();
3411 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3412 require_login();
3413 if (isguestuser()) {
3414 print_error('noguest');
3416 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3417 if ($USER->id != $entry->userid) {
3418 send_file_not_found();
3423 if ('publishstate' === 'public') {
3424 if ($CFG->forcelogin) {
3425 require_login();
3428 } else if ('publishstate' === 'site') {
3429 require_login();
3430 //ok
3431 } else if ('publishstate' === 'draft') {
3432 require_login();
3433 if ($USER->id != $entry->userid) {
3434 send_file_not_found();
3438 $filename = array_pop($args);
3439 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3441 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3442 send_file_not_found();
3445 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3447 // ========================================================================================================================
3448 } else if ($component === 'grade') {
3449 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3450 // Global gradebook files
3451 if ($CFG->forcelogin) {
3452 require_login();
3455 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3457 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3458 send_file_not_found();
3461 session_get_instance()->write_close(); // unlock session during fileserving
3462 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3464 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3465 //TODO: nobody implemented this yet in grade edit form!!
3466 send_file_not_found();
3468 if ($CFG->forcelogin || $course->id != SITEID) {
3469 require_login($course);
3472 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3474 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3475 send_file_not_found();
3478 session_get_instance()->write_close(); // unlock session during fileserving
3479 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3480 } else {
3481 send_file_not_found();
3484 // ========================================================================================================================
3485 } else if ($component === 'tag') {
3486 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3488 // All tag descriptions are going to be public but we still need to respect forcelogin
3489 if ($CFG->forcelogin) {
3490 require_login();
3493 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3495 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3496 send_file_not_found();
3499 session_get_instance()->write_close(); // unlock session during fileserving
3500 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3502 } else {
3503 send_file_not_found();
3506 // ========================================================================================================================
3507 } else if ($component === 'calendar') {
3508 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3510 // All events here are public the one requirement is that we respect forcelogin
3511 if ($CFG->forcelogin) {
3512 require_login();
3515 // Get the event if from the args array
3516 $eventid = array_shift($args);
3518 // Load the event from the database
3519 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3520 send_file_not_found();
3522 // Check that we got an event and that it's userid is that of the user
3524 // Get the file and serve if successful
3525 $filename = array_pop($args);
3526 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3527 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3528 send_file_not_found();
3531 session_get_instance()->write_close(); // unlock session during fileserving
3532 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3534 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3536 // Must be logged in, if they are not then they obviously can't be this user
3537 require_login();
3539 // Don't want guests here, potentially saves a DB call
3540 if (isguestuser()) {
3541 send_file_not_found();
3544 // Get the event if from the args array
3545 $eventid = array_shift($args);
3547 // Load the event from the database - user id must match
3548 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3549 send_file_not_found();
3552 // Get the file and serve if successful
3553 $filename = array_pop($args);
3554 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3555 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3556 send_file_not_found();
3559 session_get_instance()->write_close(); // unlock session during fileserving
3560 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3562 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3564 // Respect forcelogin and require login unless this is the site.... it probably
3565 // should NEVER be the site
3566 if ($CFG->forcelogin || $course->id != SITEID) {
3567 require_login($course);
3570 // Must be able to at least view the course
3571 if (!is_enrolled($context) and !is_viewing($context)) {
3572 //TODO: hmm, do we really want to block guests here?
3573 send_file_not_found();
3576 // Get the event id
3577 $eventid = array_shift($args);
3579 // Load the event from the database we need to check whether it is
3580 // a) valid course event
3581 // b) a group event
3582 // Group events use the course context (there is no group context)
3583 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3584 send_file_not_found();
3587 // If its a group event require either membership of view all groups capability
3588 if ($event->eventtype === 'group') {
3589 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3590 send_file_not_found();
3592 } else if ($event->eventtype === 'course') {
3593 //ok
3594 } else {
3595 // some other type
3596 send_file_not_found();
3599 // If we get this far we can serve the file
3600 $filename = array_pop($args);
3601 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3602 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3603 send_file_not_found();
3606 session_get_instance()->write_close(); // unlock session during fileserving
3607 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3609 } else {
3610 send_file_not_found();
3613 // ========================================================================================================================
3614 } else if ($component === 'user') {
3615 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3616 if (count($args) == 1) {
3617 $themename = theme_config::DEFAULT_THEME;
3618 $filename = array_shift($args);
3619 } else {
3620 $themename = array_shift($args);
3621 $filename = array_shift($args);
3624 // fix file name automatically
3625 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3626 $filename = 'f1';
3629 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3630 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3631 // protect images if login required and not logged in;
3632 // also if login is required for profile images and is not logged in or guest
3633 // do not use require_login() because it is expensive and not suitable here anyway
3634 $theme = theme_config::load($themename);
3635 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3638 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3639 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3640 if ($filename === 'f3') {
3641 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3642 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3643 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3648 if (!$file) {
3649 // bad reference - try to prevent future retries as hard as possible!
3650 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3651 if ($user->picture > 0) {
3652 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3655 // no redirect here because it is not cached
3656 $theme = theme_config::load($themename);
3657 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle');
3658 send_file($imagefile, basename($imagefile), 60*60*24*14);
3661 send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3663 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3664 require_login();
3666 if (isguestuser()) {
3667 send_file_not_found();
3670 if ($USER->id !== $context->instanceid) {
3671 send_file_not_found();
3674 $filename = array_pop($args);
3675 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3676 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3677 send_file_not_found();
3680 session_get_instance()->write_close(); // unlock session during fileserving
3681 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3683 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3685 if ($CFG->forcelogin) {
3686 require_login();
3689 $userid = $context->instanceid;
3691 if ($USER->id == $userid) {
3692 // always can access own
3694 } else if (!empty($CFG->forceloginforprofiles)) {
3695 require_login();
3697 if (isguestuser()) {
3698 send_file_not_found();
3701 // we allow access to site profile of all course contacts (usually teachers)
3702 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3703 send_file_not_found();
3706 $canview = false;
3707 if (has_capability('moodle/user:viewdetails', $context)) {
3708 $canview = true;
3709 } else {
3710 $courses = enrol_get_my_courses();
3713 while (!$canview && count($courses) > 0) {
3714 $course = array_shift($courses);
3715 if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) {
3716 $canview = true;
3721 $filename = array_pop($args);
3722 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3723 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3724 send_file_not_found();
3727 session_get_instance()->write_close(); // unlock session during fileserving
3728 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3730 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3731 $userid = (int)array_shift($args);
3732 $usercontext = get_context_instance(CONTEXT_USER, $userid);
3734 if ($CFG->forcelogin) {
3735 require_login();
3738 if (!empty($CFG->forceloginforprofiles)) {
3739 require_login();
3740 if (isguestuser()) {
3741 print_error('noguest');
3744 //TODO: review this logic of user profile access prevention
3745 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3746 print_error('usernotavailable');
3748 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3749 print_error('cannotviewprofile');
3751 if (!is_enrolled($context, $userid)) {
3752 print_error('notenrolledprofile');
3754 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3755 print_error('groupnotamember');
3759 $filename = array_pop($args);
3760 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3761 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3762 send_file_not_found();
3765 session_get_instance()->write_close(); // unlock session during fileserving
3766 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3768 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3769 require_login();
3771 if (isguestuser()) {
3772 send_file_not_found();
3774 $userid = $context->instanceid;
3776 if ($USER->id != $userid) {
3777 send_file_not_found();
3780 $filename = array_pop($args);
3781 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3782 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3783 send_file_not_found();
3786 session_get_instance()->write_close(); // unlock session during fileserving
3787 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3789 } else {
3790 send_file_not_found();
3793 // ========================================================================================================================
3794 } else if ($component === 'coursecat') {
3795 if ($context->contextlevel != CONTEXT_COURSECAT) {
3796 send_file_not_found();
3799 if ($filearea === 'description') {
3800 if ($CFG->forcelogin) {
3801 // no login necessary - unless login forced everywhere
3802 require_login();
3805 $filename = array_pop($args);
3806 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3807 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3808 send_file_not_found();
3811 session_get_instance()->write_close(); // unlock session during fileserving
3812 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3813 } else {
3814 send_file_not_found();
3817 // ========================================================================================================================
3818 } else if ($component === 'course') {
3819 if ($context->contextlevel != CONTEXT_COURSE) {
3820 send_file_not_found();
3823 if ($filearea === 'summary') {
3824 if ($CFG->forcelogin) {
3825 require_login();
3828 $filename = array_pop($args);
3829 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3830 if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
3831 send_file_not_found();
3834 session_get_instance()->write_close(); // unlock session during fileserving
3835 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3837 } else if ($filearea === 'section') {
3838 if ($CFG->forcelogin) {
3839 require_login($course);
3840 } else if ($course->id != SITEID) {
3841 require_login($course);
3844 $sectionid = (int)array_shift($args);
3846 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
3847 send_file_not_found();
3850 if ($course->numsections < $section->section) {
3851 if (!has_capability('moodle/course:update', $context)) {
3852 // block access to unavailable sections if can not edit course
3853 send_file_not_found();
3857 $filename = array_pop($args);
3858 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3859 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3860 send_file_not_found();
3863 session_get_instance()->write_close(); // unlock session during fileserving
3864 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3866 } else {
3867 send_file_not_found();
3870 } else if ($component === 'group') {
3871 if ($context->contextlevel != CONTEXT_COURSE) {
3872 send_file_not_found();
3875 require_course_login($course, true, null, false);
3877 $groupid = (int)array_shift($args);
3879 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
3880 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
3881 // do not allow access to separate group info if not member or teacher
3882 send_file_not_found();
3885 if ($filearea === 'description') {
3887 require_login($course);
3889 $filename = array_pop($args);
3890 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3891 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
3892 send_file_not_found();
3895 session_get_instance()->write_close(); // unlock session during fileserving
3896 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3898 } else if ($filearea === 'icon') {
3899 $filename = array_pop($args);
3901 if ($filename !== 'f1' and $filename !== 'f2') {
3902 send_file_not_found();
3904 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
3905 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
3906 send_file_not_found();
3910 session_get_instance()->write_close(); // unlock session during fileserving
3911 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
3913 } else {
3914 send_file_not_found();
3917 } else if ($component === 'grouping') {
3918 if ($context->contextlevel != CONTEXT_COURSE) {
3919 send_file_not_found();
3922 require_login($course);
3924 $groupingid = (int)array_shift($args);
3926 // note: everybody has access to grouping desc images for now
3927 if ($filearea === 'description') {
3929 $filename = array_pop($args);
3930 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3931 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
3932 send_file_not_found();
3935 session_get_instance()->write_close(); // unlock session during fileserving
3936 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3938 } else {
3939 send_file_not_found();
3942 // ========================================================================================================================
3943 } else if ($component === 'backup') {
3944 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
3945 require_login($course);
3946 require_capability('moodle/backup:downloadfile', $context);
3948 $filename = array_pop($args);
3949 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3950 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
3951 send_file_not_found();
3954 session_get_instance()->write_close(); // unlock session during fileserving
3955 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
3957 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
3958 require_login($course);
3959 require_capability('moodle/backup:downloadfile', $context);
3961 $sectionid = (int)array_shift($args);
3963 $filename = array_pop($args);
3964 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3965 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3966 send_file_not_found();
3969 session_get_instance()->write_close();
3970 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3972 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
3973 require_login($course, false, $cm);
3974 require_capability('moodle/backup:downloadfile', $context);
3976 $filename = array_pop($args);
3977 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3978 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
3979 send_file_not_found();
3982 session_get_instance()->write_close();
3983 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3985 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
3986 // Backup files that were generated by the automated backup systems.
3988 require_login($course);
3989 require_capability('moodle/site:config', $context);
3991 $filename = array_pop($args);
3992 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3993 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
3994 send_file_not_found();
3997 session_get_instance()->write_close(); // unlock session during fileserving
3998 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4000 } else {
4001 send_file_not_found();
4004 // ========================================================================================================================
4005 } else if ($component === 'question') {
4006 require_once($CFG->libdir . '/questionlib.php');
4007 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4008 send_file_not_found();
4010 // ========================================================================================================================
4011 } else if ($component === 'grading') {
4012 if ($filearea === 'description') {
4013 // files embedded into the form definition description
4015 if ($context->contextlevel == CONTEXT_SYSTEM) {
4016 require_login();
4018 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4019 require_login($course, false, $cm);
4021 } else {
4022 send_file_not_found();
4025 $formid = (int)array_shift($args);
4027 $sql = "SELECT ga.id
4028 FROM {grading_areas} ga
4029 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4030 WHERE gd.id = ? AND ga.contextid = ?";
4031 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4033 if (!$areaid) {
4034 send_file_not_found();
4037 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4039 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4040 send_file_not_found();
4043 session_get_instance()->write_close(); // unlock session during fileserving
4044 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4047 // ========================================================================================================================
4048 } else if (strpos($component, 'mod_') === 0) {
4049 $modname = substr($component, 4);
4050 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4051 send_file_not_found();
4053 require_once("$CFG->dirroot/mod/$modname/lib.php");
4055 if ($context->contextlevel == CONTEXT_MODULE) {
4056 if ($cm->modname !== $modname) {
4057 // somebody tries to gain illegal access, cm type must match the component!
4058 send_file_not_found();
4062 if ($filearea === 'intro') {
4063 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4064 send_file_not_found();
4066 require_course_login($course, true, $cm);
4068 // all users may access it
4069 $filename = array_pop($args);
4070 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4071 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4072 send_file_not_found();
4075 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4077 // finally send the file
4078 send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4081 $filefunction = $component.'_pluginfile';
4082 $filefunctionold = $modname.'_pluginfile';
4083 if (function_exists($filefunction)) {
4084 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4085 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4086 } else if (function_exists($filefunctionold)) {
4087 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4088 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4091 send_file_not_found();
4093 // ========================================================================================================================
4094 } else if (strpos($component, 'block_') === 0) {
4095 $blockname = substr($component, 6);
4096 // note: no more class methods in blocks please, that is ....
4097 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4098 send_file_not_found();
4100 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4102 if ($context->contextlevel == CONTEXT_BLOCK) {
4103 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4104 if ($birecord->blockname !== $blockname) {
4105 // somebody tries to gain illegal access, cm type must match the component!
4106 send_file_not_found();
4109 $bprecord = $DB->get_record('block_positions', array('blockinstanceid' => $context->instanceid), 'visible');
4110 // User can't access file, if block is hidden or doesn't have block:view capability
4111 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4112 send_file_not_found();
4114 } else {
4115 $birecord = null;
4118 $filefunction = $component.'_pluginfile';
4119 if (function_exists($filefunction)) {
4120 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4121 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4124 send_file_not_found();
4126 // ========================================================================================================================
4127 } else if (strpos($component, '_') === false) {
4128 // all core subsystems have to be specified above, no more guessing here!
4129 send_file_not_found();
4131 } else {
4132 // try to serve general plugin file in arbitrary context
4133 $dir = get_component_directory($component);
4134 if (!file_exists("$dir/lib.php")) {
4135 send_file_not_found();
4137 include_once("$dir/lib.php");
4139 $filefunction = $component.'_pluginfile';
4140 if (function_exists($filefunction)) {
4141 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4142 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4145 send_file_not_found();
4151 * Universe file cacheing class
4153 * @package core_files
4154 * @category files
4155 * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org}
4156 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4158 class cache_file {
4159 /** @var string */
4160 public $cachedir = '';
4163 * static method to create cache_file class instance
4165 * @param array $options caching ooptions
4167 public static function get_instance($options = array()) {
4168 return new cache_file($options);
4172 * Constructor
4174 * @param array $options
4176 private function __construct($options = array()) {
4177 global $CFG;
4179 // Path to file caches.
4180 if (isset($options['cachedir'])) {
4181 $this->cachedir = $options['cachedir'];
4182 } else {
4183 $this->cachedir = $CFG->cachedir . '/filedir';
4186 // Create cache directory.
4187 if (!file_exists($this->cachedir)) {
4188 mkdir($this->cachedir, $CFG->directorypermissions, true);
4191 // When use cache_file::get, it will check ttl.
4192 if (isset($options['ttl']) && is_numeric($options['ttl'])) {
4193 $this->ttl = $options['ttl'];
4194 } else {
4195 // One day.
4196 $this->ttl = 60 * 60 * 24;
4201 * Get cached file, false if file expires
4203 * @param mixed $param
4204 * @param array $options caching options
4205 * @return bool|string
4207 public static function get($param, $options = array()) {
4208 $instance = self::get_instance($options);
4209 $filepath = $instance->generate_filepath($param);
4210 if (file_exists($filepath)) {
4211 $lasttime = filemtime($filepath);
4212 if (time() - $lasttime > $instance->ttl) {
4213 // Remove cache file.
4214 unlink($filepath);
4215 return false;
4216 } else {
4217 return $filepath;
4219 } else {
4220 return false;
4225 * Static method to create cache from a file
4227 * @param mixed $ref
4228 * @param string $srcfile
4229 * @param array $options
4230 * @return string cached file path
4232 public static function create_from_file($ref, $srcfile, $options = array()) {
4233 $instance = self::get_instance($options);
4234 $cachedfilepath = $instance->generate_filepath($ref);
4235 copy($srcfile, $cachedfilepath);
4236 return $cachedfilepath;
4240 * Static method to create cache from url
4242 * @param mixed $ref file reference
4243 * @param string $url file url
4244 * @param array $options options
4245 * @return string cached file path
4247 public static function create_from_url($ref, $url, $options = array()) {
4248 $instance = self::get_instance($options);
4249 $cachedfilepath = $instance->generate_filepath($ref);
4250 $fp = fopen($cachedfilepath, 'w');
4251 $curl = new curl;
4252 $curl->download(array(array('url'=>$url, 'file'=>$fp)));
4253 // Must close file handler.
4254 fclose($fp);
4255 return $cachedfilepath;
4259 * Static method to create cache from string
4261 * @param mixed $ref file reference
4262 * @param string $url file url
4263 * @param array $options options
4264 * @return string cached file path
4266 public static function create_from_string($ref, $string, $options = array()) {
4267 $instance = self::get_instance($options);
4268 $cachedfilepath = $instance->generate_filepath($ref);
4269 $fp = fopen($cachedfilepath, 'w');
4270 fwrite($fp, $string);
4271 // Must close file handler.
4272 fclose($fp);
4273 return $cachedfilepath;
4277 * Build path to cache file
4279 * @param mixed $ref
4280 * @return string
4282 private function generate_filepath($ref) {
4283 global $CFG;
4284 $hash = sha1(serialize($ref));
4285 $l1 = $hash[0].$hash[1];
4286 $l2 = $hash[2].$hash[3];
4287 $dir = $this->cachedir . "/$l1/$l2";
4288 if (!file_exists($dir)) {
4289 mkdir($dir, $CFG->directorypermissions, true);
4291 return "$dir/$hash";
4295 * Remove cache files
4297 * @param array $options options
4298 * @param int $expire The number of seconds before expiry
4300 public static function cleanup($options = array(), $expire) {
4301 global $CFG;
4302 $instance = self::get_instance($options);
4303 if ($dir = opendir($instance->cachedir)) {
4304 while (($file = readdir($dir)) !== false) {
4305 if (!is_dir($file) && $file != '.' && $file != '..') {
4306 $lasttime = @filemtime($instance->cachedir . $file);
4307 if(time() - $lasttime > $expire){
4308 @unlink($instance->cachedir . $file);
4312 closedir($dir);