MDL-32003 fix phpdocs in xmldb abstraction
[moodle.git] / lib / filelib.php
blob0d18cfa6c6d16c354839b2ebe715da47d4a97f7a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for file handling.
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @todo MDL-31071 deprecate this function
43 * @global stdClass $CFG
44 * @param string $urlbase
45 * @param string $path /filearea/itemid/dir/dir/file.exe
46 * @param bool $forcedownload
47 * @param bool $https https url required
48 * @return string encoded file url
50 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
51 global $CFG;
53 //TODO: deprecate this
55 if ($CFG->slasharguments) {
56 $parts = explode('/', $path);
57 $parts = array_map('rawurlencode', $parts);
58 $path = implode('/', $parts);
59 $return = $urlbase.$path;
60 if ($forcedownload) {
61 $return .= '?forcedownload=1';
63 } else {
64 $path = rawurlencode($path);
65 $return = $urlbase.'?file='.$path;
66 if ($forcedownload) {
67 $return .= '&amp;forcedownload=1';
71 if ($https) {
72 $return = str_replace('http://', 'https://', $return);
75 return $return;
78 /**
79 * Prepares 'editor' formslib element from data in database
81 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
82 * function then copies the embedded files into draft area (assigning itemids automatically),
83 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
84 * displayed.
85 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
86 * your mform's set_data() supplying the object returned by this function.
88 * @category files
89 * @param stdClass $data database field that holds the html text with embedded media
90 * @param string $field the name of the database field that holds the html text with embedded media
91 * @param array $options editor options (like maxifiles, maxbytes etc.)
92 * @param stdClass $context context of the editor
93 * @param string $component
94 * @param string $filearea file area name
95 * @param int $itemid item id, required if item exists
96 * @return stdClass modified data object
98 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
99 $options = (array)$options;
100 if (!isset($options['trusttext'])) {
101 $options['trusttext'] = false;
103 if (!isset($options['forcehttps'])) {
104 $options['forcehttps'] = false;
106 if (!isset($options['subdirs'])) {
107 $options['subdirs'] = false;
109 if (!isset($options['maxfiles'])) {
110 $options['maxfiles'] = 0; // no files by default
112 if (!isset($options['noclean'])) {
113 $options['noclean'] = false;
116 //sanity check for passed context. This function doesn't expect $option['context'] to be set
117 //But this function is called before creating editor hence, this is one of the best places to check
118 //if context is used properly. This check notify developer that they missed passing context to editor.
119 if (isset($context) && !isset($options['context'])) {
120 //if $context is not null then make sure $option['context'] is also set.
121 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
122 } else if (isset($options['context']) && isset($context)) {
123 //If both are passed then they should be equal.
124 if ($options['context']->id != $context->id) {
125 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
126 throw new coding_exception($exceptionmsg);
130 if (is_null($itemid) or is_null($context)) {
131 $contextid = null;
132 $itemid = null;
133 if (!isset($data)) {
134 $data = new stdClass();
136 if (!isset($data->{$field})) {
137 $data->{$field} = '';
139 if (!isset($data->{$field.'format'})) {
140 $data->{$field.'format'} = editors_get_preferred_format();
142 if (!$options['noclean']) {
143 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
146 } else {
147 if ($options['trusttext']) {
148 // noclean ignored if trusttext enabled
149 if (!isset($data->{$field.'trust'})) {
150 $data->{$field.'trust'} = 0;
152 $data = trusttext_pre_edit($data, $field, $context);
153 } else {
154 if (!$options['noclean']) {
155 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
158 $contextid = $context->id;
161 if ($options['maxfiles'] != 0) {
162 $draftid_editor = file_get_submitted_draft_itemid($field);
163 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
164 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
165 } else {
166 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
169 return $data;
173 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
175 * This function moves files from draft area to the destination area and
176 * encodes URLs to the draft files so they can be safely saved into DB. The
177 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
178 * is the name of the database field to hold the wysiwyg editor content. The
179 * editor data comes as an array with text, format and itemid properties. This
180 * function automatically adds $data properties foobar, foobarformat and
181 * foobartrust, where foobar has URL to embedded files encoded.
183 * @category files
184 * @param stdClass $data raw data submitted by the form
185 * @param string $field name of the database field containing the html with embedded media files
186 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
187 * @param stdClass $context context, required for existing data
188 * @param string $component file component
189 * @param string $filearea file area name
190 * @param int $itemid item id, required if item exists
191 * @return stdClass modified data object
193 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
194 $options = (array)$options;
195 if (!isset($options['trusttext'])) {
196 $options['trusttext'] = false;
198 if (!isset($options['forcehttps'])) {
199 $options['forcehttps'] = false;
201 if (!isset($options['subdirs'])) {
202 $options['subdirs'] = false;
204 if (!isset($options['maxfiles'])) {
205 $options['maxfiles'] = 0; // no files by default
207 if (!isset($options['maxbytes'])) {
208 $options['maxbytes'] = 0; // unlimited
211 if ($options['trusttext']) {
212 $data->{$field.'trust'} = trusttext_trusted($context);
213 } else {
214 $data->{$field.'trust'} = 0;
217 $editor = $data->{$field.'_editor'};
219 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
220 $data->{$field} = $editor['text'];
221 } else {
222 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
224 $data->{$field.'format'} = $editor['format'];
226 return $data;
230 * Saves text and files modified by Editor formslib element
232 * @category files
233 * @param stdClass $data $database entry field
234 * @param string $field name of data field
235 * @param array $options various options
236 * @param stdClass $context context - must already exist
237 * @param string $component
238 * @param string $filearea file area name
239 * @param int $itemid must already exist, usually means data is in db
240 * @return stdClass modified data obejct
242 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
243 $options = (array)$options;
244 if (!isset($options['subdirs'])) {
245 $options['subdirs'] = false;
247 if (is_null($itemid) or is_null($context)) {
248 $itemid = null;
249 $contextid = null;
250 } else {
251 $contextid = $context->id;
254 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
255 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
256 $data->{$field.'_filemanager'} = $draftid_editor;
258 return $data;
262 * Saves files modified by File manager formslib element
264 * @todo MDL-31073 review this function
265 * @category files
266 * @param stdClass $data $database entry field
267 * @param string $field name of data field
268 * @param array $options various options
269 * @param stdClass $context context - must already exist
270 * @param string $component
271 * @param string $filearea file area name
272 * @param int $itemid must already exist, usually means data is in db
273 * @return stdClass modified data obejct
275 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
276 $options = (array)$options;
277 if (!isset($options['subdirs'])) {
278 $options['subdirs'] = false;
280 if (!isset($options['maxfiles'])) {
281 $options['maxfiles'] = -1; // unlimited
283 if (!isset($options['maxbytes'])) {
284 $options['maxbytes'] = 0; // unlimited
287 if (empty($data->{$field.'_filemanager'})) {
288 $data->$field = '';
290 } else {
291 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
292 $fs = get_file_storage();
294 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
295 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
296 } else {
297 $data->$field = '';
301 return $data;
305 * Generate a draft itemid
307 * @category files
308 * @global moodle_database $DB
309 * @global stdClass $USER
310 * @return int a random but available draft itemid that can be used to create a new draft
311 * file area.
313 function file_get_unused_draft_itemid() {
314 global $DB, $USER;
316 if (isguestuser() or !isloggedin()) {
317 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
318 print_error('noguest');
321 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
323 $fs = get_file_storage();
324 $draftitemid = rand(1, 999999999);
325 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
326 $draftitemid = rand(1, 999999999);
329 return $draftitemid;
333 * Initialise a draft file area from a real one by copying the files. A draft
334 * area will be created if one does not already exist. Normally you should
335 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
337 * @category files
338 * @global stdClass $CFG
339 * @global stdClass $USER
340 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
341 * @param int $contextid This parameter and the next two identify the file area to copy files from.
342 * @param string $component
343 * @param string $filearea helps indentify the file area.
344 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
345 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
346 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
347 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
349 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
350 global $CFG, $USER, $CFG;
352 $options = (array)$options;
353 if (!isset($options['subdirs'])) {
354 $options['subdirs'] = false;
356 if (!isset($options['forcehttps'])) {
357 $options['forcehttps'] = false;
360 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
361 $fs = get_file_storage();
363 if (empty($draftitemid)) {
364 // create a new area and copy existing files into
365 $draftitemid = file_get_unused_draft_itemid();
366 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
367 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
368 foreach ($files as $file) {
369 if ($file->is_directory() and $file->get_filepath() === '/') {
370 // we need a way to mark the age of each draft area,
371 // by not copying the root dir we force it to be created automatically with current timestamp
372 continue;
374 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
375 continue;
377 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
378 // XXX: This is a hack for file manager (MDL-28666)
379 // File manager needs to know the original file information before copying
380 // to draft area, so we append these information in mdl_files.source field
381 // {@link file_storage::search_references()}
382 // {@link file_storage::search_references_count()}
383 $sourcefield = $file->get_source();
384 $newsourcefield = new stdClass;
385 $newsourcefield->source = $sourcefield;
386 $original = new stdClass;
387 $original->contextid = $contextid;
388 $original->component = $component;
389 $original->filearea = $filearea;
390 $original->itemid = $itemid;
391 $original->filename = $file->get_filename();
392 $original->filepath = $file->get_filepath();
393 $newsourcefield->original = file_storage::pack_reference($original);
394 $draftfile->set_source(serialize($newsourcefield));
395 // End of file manager hack
398 if (!is_null($text)) {
399 // at this point there should not be any draftfile links yet,
400 // because this is a new text from database that should still contain the @@pluginfile@@ links
401 // this happens when developers forget to post process the text
402 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
404 } else {
405 // nothing to do
408 if (is_null($text)) {
409 return null;
412 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
413 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
417 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
419 * @category files
420 * @global stdClass $CFG
421 * @param string $text The content that may contain ULRs in need of rewriting.
422 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
423 * @param int $contextid This parameter and the next two identify the file area to use.
424 * @param string $component
425 * @param string $filearea helps identify the file area.
426 * @param int $itemid helps identify the file area.
427 * @param array $options text and file options ('forcehttps'=>false)
428 * @return string the processed text.
430 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
431 global $CFG;
433 $options = (array)$options;
434 if (!isset($options['forcehttps'])) {
435 $options['forcehttps'] = false;
438 if (!$CFG->slasharguments) {
439 $file = $file . '?file=';
442 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
444 if ($itemid !== null) {
445 $baseurl .= "$itemid/";
448 if ($options['forcehttps']) {
449 $baseurl = str_replace('http://', 'https://', $baseurl);
452 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
456 * Returns information about files in a draft area.
458 * @global stdClass $CFG
459 * @global stdClass $USER
460 * @param int $draftitemid the draft area item id.
461 * @return array with the following entries:
462 * 'filecount' => number of files in the draft area.
463 * (more information will be added as needed).
465 function file_get_draft_area_info($draftitemid) {
466 global $CFG, $USER;
468 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
469 $fs = get_file_storage();
471 $results = array();
473 // The number of files
474 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
475 $results['filecount'] = count($draftfiles);
476 $results['filesize'] = 0;
477 foreach ($draftfiles as $file) {
478 $results['filesize'] += $file->get_filesize();
481 return $results;
485 * Get used space of files
486 * @global moodle_database $DB
487 * @global stdClass $USER
488 * @return int total bytes
490 function file_get_user_used_space() {
491 global $DB, $USER;
493 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
494 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
495 JOIN (SELECT contenthash, filename, MAX(id) AS id
496 FROM {files}
497 WHERE contextid = ? AND component = ? AND filearea != ?
498 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
499 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
500 $record = $DB->get_record_sql($sql, $params);
501 return (int)$record->totalbytes;
505 * Convert any string to a valid filepath
506 * @todo review this function
507 * @param string $str
508 * @return string path
510 function file_correct_filepath($str) { //TODO: what is this? (skodak)
511 if ($str == '/' or empty($str)) {
512 return '/';
513 } else {
514 return '/'.trim($str, './@#$ ').'/';
519 * Generate a folder tree of draft area of current USER recursively
521 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
522 * @param int $draftitemid
523 * @param string $filepath
524 * @param mixed $data
526 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
527 global $USER, $OUTPUT, $CFG;
528 $data->children = array();
529 $context = get_context_instance(CONTEXT_USER, $USER->id);
530 $fs = get_file_storage();
531 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
532 foreach ($files as $file) {
533 if ($file->is_directory()) {
534 $item = new stdClass();
535 $item->sortorder = $file->get_sortorder();
536 $item->filepath = $file->get_filepath();
538 $foldername = explode('/', trim($item->filepath, '/'));
539 $item->fullname = trim(array_pop($foldername), '/');
541 $item->id = uniqid();
542 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
543 $data->children[] = $item;
544 } else {
545 continue;
552 * Listing all files (including folders) in current path (draft area)
553 * used by file manager
554 * @param int $draftitemid
555 * @param string $filepath
556 * @return stdClass
558 function file_get_drafarea_files($draftitemid, $filepath = '/') {
559 global $USER, $OUTPUT, $CFG;
561 $context = get_context_instance(CONTEXT_USER, $USER->id);
562 $fs = get_file_storage();
564 $data = new stdClass();
565 $data->path = array();
566 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
568 // will be used to build breadcrumb
569 $trail = '/';
570 if ($filepath !== '/') {
571 $filepath = file_correct_filepath($filepath);
572 $parts = explode('/', $filepath);
573 foreach ($parts as $part) {
574 if ($part != '' && $part != null) {
575 $trail .= ($part.'/');
576 $data->path[] = array('name'=>$part, 'path'=>$trail);
581 $list = array();
582 $maxlength = 12;
583 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
584 foreach ($files as $file) {
585 $item = new stdClass();
586 $item->filename = $file->get_filename();
587 $item->filepath = $file->get_filepath();
588 $item->fullname = trim($item->filename, '/');
589 $filesize = $file->get_filesize();
590 $item->size = $filesize ? $filesize : null;
591 $item->filesize = $filesize ? display_size($filesize) : '';
593 $item->sortorder = $file->get_sortorder();
594 $item->author = $file->get_author();
595 $item->license = $file->get_license();
596 $item->datemodified = $file->get_timemodified();
597 $item->datecreated = $file->get_timecreated();
598 $item->isref = $file->is_external_file();
599 if ($item->isref && $file->get_status() == 666) {
600 $item->originalmissing = true;
602 // find the file this draft file was created from and count all references in local
603 // system pointing to that file
604 $source = unserialize($file->get_source());
605 if (isset($source->original)) {
606 $item->refcount = $fs->search_references_count($source->original);
609 if ($file->is_directory()) {
610 $item->filesize = 0;
611 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
612 $item->type = 'folder';
613 $foldername = explode('/', trim($item->filepath, '/'));
614 $item->fullname = trim(array_pop($foldername), '/');
615 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
616 } else {
617 // do NOT use file browser here!
618 $item->mimetype = get_mimetype_description($file);
619 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
620 $item->type = 'zip';
621 } else {
622 $item->type = 'file';
624 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
625 $item->url = $itemurl->out();
626 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
627 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
628 if ($imageinfo = $file->get_imageinfo()) {
629 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
630 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
631 $item->image_width = $imageinfo['width'];
632 $item->image_height = $imageinfo['height'];
635 $list[] = $item;
638 $data->itemid = $draftitemid;
639 $data->list = $list;
640 return $data;
644 * Returns draft area itemid for a given element.
646 * @category files
647 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
648 * @return int the itemid, or 0 if there is not one yet.
650 function file_get_submitted_draft_itemid($elname) {
651 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
652 if (!isset($_REQUEST[$elname])) {
653 return 0;
655 if (is_array($_REQUEST[$elname])) {
656 $param = optional_param_array($elname, 0, PARAM_INT);
657 if (!empty($param['itemid'])) {
658 $param = $param['itemid'];
659 } else {
660 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
661 return false;
664 } else {
665 $param = optional_param($elname, 0, PARAM_INT);
668 if ($param) {
669 require_sesskey();
672 return $param;
676 * Restore the original source field from draft files
678 * @param stored_file $storedfile This only works with draft files
679 * @return stored_file
681 function file_restore_source_field_from_draft_file($storedfile) {
682 $source = unserialize($storedfile->get_source());
683 if (!empty($source)) {
684 if (is_object($source)) {
685 $restoredsource = $source->source;
686 $storedfile->set_source($restoredsource);
687 } else {
688 throw new moodle_exception('invalidsourcefield', 'error');
691 return $storedfile;
694 * Saves files from a draft file area to a real one (merging the list of files).
695 * Can rewrite URLs in some content at the same time if desired.
697 * @category files
698 * @global stdClass $USER
699 * @param int $draftitemid the id of the draft area to use. Normally obtained
700 * from file_get_submitted_draft_itemid('elementname') or similar.
701 * @param int $contextid This parameter and the next two identify the file area to save to.
702 * @param string $component
703 * @param string $filearea indentifies the file area.
704 * @param int $itemid helps identifies the file area.
705 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
706 * @param string $text some html content that needs to have embedded links rewritten
707 * to the @@PLUGINFILE@@ form for saving in the database.
708 * @param bool $forcehttps force https urls.
709 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
711 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
712 global $USER;
714 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
715 $fs = get_file_storage();
717 $options = (array)$options;
718 if (!isset($options['subdirs'])) {
719 $options['subdirs'] = false;
721 if (!isset($options['maxfiles'])) {
722 $options['maxfiles'] = -1; // unlimited
724 if (!isset($options['maxbytes'])) {
725 $options['maxbytes'] = 0; // unlimited
728 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
729 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
731 if (count($draftfiles) < 2) {
732 // means there are no files - one file means root dir only ;-)
733 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
735 } else if (count($oldfiles) < 2) {
736 $filecount = 0;
737 // there were no files before - one file means root dir only ;-)
738 foreach ($draftfiles as $file) {
739 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
740 if (!$options['subdirs']) {
741 if ($file->get_filepath() !== '/' or $file->is_directory()) {
742 continue;
745 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
746 // oversized file - should not get here at all
747 continue;
749 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
750 // more files - should not get here at all
751 break;
753 if (!$file->is_directory()) {
754 $filecount++;
757 if ($file->is_external_file()) {
758 $repoid = $file->get_repository_id();
759 if (!empty($repoid)) {
760 $file_record['repositoryid'] = $repoid;
761 $file_record['reference'] = $file->get_reference();
764 file_restore_source_field_from_draft_file($file);
766 $fs->create_file_from_storedfile($file_record, $file);
769 } else {
770 // we have to merge old and new files - we want to keep file ids for files that were not changed
771 // we change time modified for all new and changed files, we keep time created as is
773 $newhashes = array();
774 foreach ($draftfiles as $file) {
775 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
776 file_restore_source_field_from_draft_file($file);
777 $newhashes[$newhash] = $file;
779 $filecount = 0;
780 foreach ($oldfiles as $oldfile) {
781 $oldhash = $oldfile->get_pathnamehash();
782 if (!isset($newhashes[$oldhash])) {
783 // delete files not needed any more - deleted by user
784 $oldfile->delete();
785 continue;
788 $newfile = $newhashes[$oldhash];
789 // status changed, we delete old file, and create a new one
790 if ($oldfile->get_status() != $newfile->get_status()) {
791 // file was changed, use updated with new timemodified data
792 $oldfile->delete();
793 // This file will be added later
794 continue;
797 // Replaced file content
798 if ($oldfile->get_contenthash() != $newfile->get_contenthash()) {
799 $oldfile->replace_content_with($newfile);
801 // Updated author
802 if ($oldfile->get_author() != $newfile->get_author()) {
803 $oldfile->set_author($newfile->get_author());
805 // Updated license
806 if ($oldfile->get_license() != $newfile->get_license()) {
807 $oldfile->set_license($newfile->get_license());
810 // Updated file source
811 if ($oldfile->get_source() != $newfile->get_source()) {
812 $oldfile->set_source($newfile->get_source());
815 // Updated sort order
816 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
817 $oldfile->set_sortorder($newfile->get_sortorder());
820 // Update file size
821 if ($oldfile->get_filesize() != $newfile->get_filesize()) {
822 $oldfile->set_filesize($newfile->get_filesize());
825 // Update file timemodified
826 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
827 $oldfile->set_timemodified($newfile->get_timemodified());
830 // unchanged file or directory - we keep it as is
831 unset($newhashes[$oldhash]);
832 if (!$oldfile->is_directory()) {
833 $filecount++;
837 // Add fresh file or the file which has changed status
838 // the size and subdirectory tests are extra safety only, the UI should prevent it
839 foreach ($newhashes as $file) {
840 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
841 if (!$options['subdirs']) {
842 if ($file->get_filepath() !== '/' or $file->is_directory()) {
843 continue;
846 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
847 // oversized file - should not get here at all
848 continue;
850 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
851 // more files - should not get here at all
852 break;
854 if (!$file->is_directory()) {
855 $filecount++;
858 if ($file->is_external_file()) {
859 $repoid = $file->get_repository_id();
860 if (!empty($repoid)) {
861 $file_record['repositoryid'] = $repoid;
862 $file_record['reference'] = $file->get_reference();
866 $fs->create_file_from_storedfile($file_record, $file);
870 // note: do not purge the draft area - we clean up areas later in cron,
871 // the reason is that user might press submit twice and they would loose the files,
872 // also sometimes we might want to use hacks that save files into two different areas
874 if (is_null($text)) {
875 return null;
876 } else {
877 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
882 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
883 * ready to be saved in the database. Normally, this is done automatically by
884 * {@link file_save_draft_area_files()}.
886 * @category files
887 * @param string $text the content to process.
888 * @param int $draftitemid the draft file area the content was using.
889 * @param bool $forcehttps whether the content contains https URLs. Default false.
890 * @return string the processed content.
892 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
893 global $CFG, $USER;
895 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
897 $wwwroot = $CFG->wwwroot;
898 if ($forcehttps) {
899 $wwwroot = str_replace('http://', 'https://', $wwwroot);
902 // relink embedded files if text submitted - no absolute links allowed in database!
903 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
905 if (strpos($text, 'draftfile.php?file=') !== false) {
906 $matches = array();
907 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
908 if ($matches) {
909 foreach ($matches[0] as $match) {
910 $replace = str_ireplace('%2F', '/', $match);
911 $text = str_replace($match, $replace, $text);
914 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
917 return $text;
921 * Set file sort order
923 * @global moodle_database $DB
924 * @param int $contextid the context id
925 * @param string $component file component
926 * @param string $filearea file area.
927 * @param int $itemid itemid.
928 * @param string $filepath file path.
929 * @param string $filename file name.
930 * @param int $sortorder the sort order of file.
931 * @return bool
933 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
934 global $DB;
935 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
936 if ($file_record = $DB->get_record('files', $conditions)) {
937 $sortorder = (int)$sortorder;
938 $file_record->sortorder = $sortorder;
939 $DB->update_record('files', $file_record);
940 return true;
942 return false;
946 * reset file sort order number to 0
947 * @global moodle_database $DB
948 * @param int $contextid the context id
949 * @param string $component
950 * @param string $filearea file area.
951 * @param int|bool $itemid itemid.
952 * @return bool
954 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
955 global $DB;
957 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
958 if ($itemid !== false) {
959 $conditions['itemid'] = $itemid;
962 $file_records = $DB->get_records('files', $conditions);
963 foreach ($file_records as $file_record) {
964 $file_record->sortorder = 0;
965 $DB->update_record('files', $file_record);
967 return true;
971 * Returns description of upload error
973 * @param int $errorcode found in $_FILES['filename.ext']['error']
974 * @return string error description string, '' if ok
976 function file_get_upload_error($errorcode) {
978 switch ($errorcode) {
979 case 0: // UPLOAD_ERR_OK - no error
980 $errmessage = '';
981 break;
983 case 1: // UPLOAD_ERR_INI_SIZE
984 $errmessage = get_string('uploadserverlimit');
985 break;
987 case 2: // UPLOAD_ERR_FORM_SIZE
988 $errmessage = get_string('uploadformlimit');
989 break;
991 case 3: // UPLOAD_ERR_PARTIAL
992 $errmessage = get_string('uploadpartialfile');
993 break;
995 case 4: // UPLOAD_ERR_NO_FILE
996 $errmessage = get_string('uploadnofilefound');
997 break;
999 // Note: there is no error with a value of 5
1001 case 6: // UPLOAD_ERR_NO_TMP_DIR
1002 $errmessage = get_string('uploadnotempdir');
1003 break;
1005 case 7: // UPLOAD_ERR_CANT_WRITE
1006 $errmessage = get_string('uploadcantwrite');
1007 break;
1009 case 8: // UPLOAD_ERR_EXTENSION
1010 $errmessage = get_string('uploadextension');
1011 break;
1013 default:
1014 $errmessage = get_string('uploadproblem');
1017 return $errmessage;
1021 * Recursive function formating an array in POST parameter
1022 * @param array $arraydata - the array that we are going to format and add into &$data array
1023 * @param string $currentdata - a row of the final postdata array at instant T
1024 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1025 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1027 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1028 foreach ($arraydata as $k=>$v) {
1029 $newcurrentdata = $currentdata;
1030 if (is_array($v)) { //the value is an array, call the function recursively
1031 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1032 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1033 } else { //add the POST parameter to the $data array
1034 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1040 * Transform a PHP array into POST parameter
1041 * (see the recursive function format_array_postdata_for_curlcall)
1042 * @param array $postdata
1043 * @return array containing all POST parameters (1 row = 1 POST parameter)
1045 function format_postdata_for_curlcall($postdata) {
1046 $data = array();
1047 foreach ($postdata as $k=>$v) {
1048 if (is_array($v)) {
1049 $currentdata = urlencode($k);
1050 format_array_postdata_for_curlcall($v, $currentdata, $data);
1051 } else {
1052 $data[] = urlencode($k).'='.urlencode($v);
1055 $convertedpostdata = implode('&', $data);
1056 return $convertedpostdata;
1060 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1061 * Due to security concerns only downloads from http(s) sources are supported.
1063 * @todo MDL-31073 add version test for '7.10.5'
1064 * @category files
1065 * @param string $url file url starting with http(s)://
1066 * @param array $headers http headers, null if none. If set, should be an
1067 * associative array of header name => value pairs.
1068 * @param array $postdata array means use POST request with given parameters
1069 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1070 * (if false, just returns content)
1071 * @param int $timeout timeout for complete download process including all file transfer
1072 * (default 5 minutes)
1073 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1074 * usually happens if the remote server is completely down (default 20 seconds);
1075 * may not work when using proxy
1076 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1077 * Only use this when already in a trusted location.
1078 * @param string $tofile store the downloaded content to file instead of returning it.
1079 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1080 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1081 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1083 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1084 global $CFG;
1086 // some extra security
1087 $newlines = array("\r", "\n");
1088 if (is_array($headers) ) {
1089 foreach ($headers as $key => $value) {
1090 $headers[$key] = str_replace($newlines, '', $value);
1093 $url = str_replace($newlines, '', $url);
1094 if (!preg_match('|^https?://|i', $url)) {
1095 if ($fullresponse) {
1096 $response = new stdClass();
1097 $response->status = 0;
1098 $response->headers = array();
1099 $response->response_code = 'Invalid protocol specified in url';
1100 $response->results = '';
1101 $response->error = 'Invalid protocol specified in url';
1102 return $response;
1103 } else {
1104 return false;
1108 // check if proxy (if used) should be bypassed for this url
1109 $proxybypass = is_proxybypass($url);
1111 if (!$ch = curl_init($url)) {
1112 debugging('Can not init curl.');
1113 return false;
1116 // set extra headers
1117 if (is_array($headers) ) {
1118 $headers2 = array();
1119 foreach ($headers as $key => $value) {
1120 $headers2[] = "$key: $value";
1122 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1125 if ($skipcertverify) {
1126 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1129 // use POST if requested
1130 if (is_array($postdata)) {
1131 $postdata = format_postdata_for_curlcall($postdata);
1132 curl_setopt($ch, CURLOPT_POST, true);
1133 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1136 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1137 curl_setopt($ch, CURLOPT_HEADER, false);
1138 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1140 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1141 // TODO: add version test for '7.10.5'
1142 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1143 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1146 if (!empty($CFG->proxyhost) and !$proxybypass) {
1147 // SOCKS supported in PHP5 only
1148 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1149 if (defined('CURLPROXY_SOCKS5')) {
1150 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1151 } else {
1152 curl_close($ch);
1153 if ($fullresponse) {
1154 $response = new stdClass();
1155 $response->status = '0';
1156 $response->headers = array();
1157 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1158 $response->results = '';
1159 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1160 return $response;
1161 } else {
1162 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1163 return false;
1168 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1170 if (empty($CFG->proxyport)) {
1171 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1172 } else {
1173 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1176 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1177 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1178 if (defined('CURLOPT_PROXYAUTH')) {
1179 // any proxy authentication if PHP 5.1
1180 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1185 // set up header and content handlers
1186 $received = new stdClass();
1187 $received->headers = array(); // received headers array
1188 $received->tofile = $tofile;
1189 $received->fh = null;
1190 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1191 if ($tofile) {
1192 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1195 if (!isset($CFG->curltimeoutkbitrate)) {
1196 //use very slow rate of 56kbps as a timeout speed when not set
1197 $bitrate = 56;
1198 } else {
1199 $bitrate = $CFG->curltimeoutkbitrate;
1202 // try to calculate the proper amount for timeout from remote file size.
1203 // if disabled or zero, we won't do any checks nor head requests.
1204 if ($calctimeout && $bitrate > 0) {
1205 //setup header request only options
1206 curl_setopt_array ($ch, array(
1207 CURLOPT_RETURNTRANSFER => false,
1208 CURLOPT_NOBODY => true)
1211 curl_exec($ch);
1212 $info = curl_getinfo($ch);
1213 $err = curl_error($ch);
1215 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1216 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1218 //reinstate affected curl options
1219 curl_setopt_array ($ch, array(
1220 CURLOPT_RETURNTRANSFER => true,
1221 CURLOPT_NOBODY => false)
1225 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1226 $result = curl_exec($ch);
1228 // try to detect encoding problems
1229 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1230 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1231 $result = curl_exec($ch);
1234 if ($received->fh) {
1235 fclose($received->fh);
1238 if (curl_errno($ch)) {
1239 $error = curl_error($ch);
1240 $error_no = curl_errno($ch);
1241 curl_close($ch);
1243 if ($fullresponse) {
1244 $response = new stdClass();
1245 if ($error_no == 28) {
1246 $response->status = '-100'; // mimic snoopy
1247 } else {
1248 $response->status = '0';
1250 $response->headers = array();
1251 $response->response_code = $error;
1252 $response->results = false;
1253 $response->error = $error;
1254 return $response;
1255 } else {
1256 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1257 return false;
1260 } else {
1261 $info = curl_getinfo($ch);
1262 curl_close($ch);
1264 if (empty($info['http_code'])) {
1265 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1266 $response = new stdClass();
1267 $response->status = '0';
1268 $response->headers = array();
1269 $response->response_code = 'Unknown cURL error';
1270 $response->results = false; // do NOT change this, we really want to ignore the result!
1271 $response->error = 'Unknown cURL error';
1273 } else {
1274 $response = new stdClass();;
1275 $response->status = (string)$info['http_code'];
1276 $response->headers = $received->headers;
1277 $response->response_code = $received->headers[0];
1278 $response->results = $result;
1279 $response->error = '';
1282 if ($fullresponse) {
1283 return $response;
1284 } else if ($info['http_code'] != 200) {
1285 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1286 return false;
1287 } else {
1288 return $response->results;
1294 * internal implementation
1295 * @param stdClass $received
1296 * @param resource $ch
1297 * @param mixed $header
1298 * @return int header length
1300 function download_file_content_header_handler($received, $ch, $header) {
1301 $received->headers[] = $header;
1302 return strlen($header);
1306 * internal implementation
1307 * @param stdClass $received
1308 * @param resource $ch
1309 * @param mixed $data
1311 function download_file_content_write_handler($received, $ch, $data) {
1312 if (!$received->fh) {
1313 $received->fh = fopen($received->tofile, 'w');
1314 if ($received->fh === false) {
1315 // bad luck, file creation or overriding failed
1316 return 0;
1319 if (fwrite($received->fh, $data) === false) {
1320 // bad luck, write failed, let's abort completely
1321 return 0;
1323 return strlen($data);
1327 * Returns a list of information about file types based on extensions.
1329 * The following elements expected in value array for each extension:
1330 * 'type' - mimetype
1331 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1332 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1333 * also files with bigger sizes under names
1334 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1335 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1336 * commonly used in moodle the following groups:
1337 * - web_image - image that can be included as <img> in HTML
1338 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1339 * - video - file that can be imported as video in text editor
1340 * - audio - file that can be imported as audio in text editor
1341 * - archive - we can extract files from this archive
1342 * - spreadsheet - used for portfolio format
1343 * - document - used for portfolio format
1344 * - presentation - used for portfolio format
1345 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1346 * human-readable description for this filetype;
1347 * Function {@link get_mimetype_description()} first looks at the presence of string for
1348 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1349 * attribute, if not found returns the value of 'type';
1350 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1351 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1352 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1354 * @category files
1355 * @return array List of information about file types based on extensions.
1356 * Associative array of extension (lower-case) to associative array
1357 * from 'element name' to data. Current element names are 'type' and 'icon'.
1358 * Unknown types should use the 'xxx' entry which includes defaults.
1360 function &get_mimetypes_array() {
1361 static $mimearray = array (
1362 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1363 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1364 'aac' => array ('type'=>'audio/aac', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1365 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1366 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1367 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1368 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1369 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1370 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1371 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1372 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1373 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1374 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1375 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1376 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1377 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1378 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1379 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1380 'csv' => array ('type'=>'text/csv', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1381 'dv' => array ('type'=>'video/x-dv', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1382 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1384 'doc' => array ('type'=>'application/msword', 'icon'=>'docx', 'groups'=>array('document')),
1385 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx', 'groups'=>array('document')),
1386 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docx'),
1387 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'docx'),
1388 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'docx'),
1390 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1391 'dif' => array ('type'=>'video/x-dv', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1392 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1393 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1394 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1395 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1396 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1397 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1398 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1399 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1400 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1401 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1402 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1403 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1404 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1405 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1406 'htc' => array ('type'=>'text/x-component', 'icon'=>'html'),
1407 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1408 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1409 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1410 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1411 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1412 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1413 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1414 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1415 'jcb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1416 'jcl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1417 'jcw' => array ('type'=>'text/xml', 'icon'=>'xml'),
1418 'jmt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1419 'jmx' => array ('type'=>'text/xml', 'icon'=>'xml'),
1420 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1421 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1422 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1423 'jqz' => array ('type'=>'text/xml', 'icon'=>'xml'),
1424 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1425 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1426 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1427 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1428 'mov' => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video','web_video'), 'string'=>'video'),
1429 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1430 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1431 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1432 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1433 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1434 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1435 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1436 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1437 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1439 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt', 'groups'=>array('document')),
1440 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt', 'groups'=>array('document')),
1441 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1442 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odt'),
1443 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1444 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1445 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1446 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1447 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods', 'groups'=>array('spreadsheet')),
1448 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods', 'groups'=>array('spreadsheet')),
1449 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1450 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1451 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1452 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odg'),
1453 'oga' => array ('type'=>'audio/ogg', 'icon'=>'wma', 'groups'=>array('audio'), 'string'=>'audio'),
1454 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'wma', 'groups'=>array('audio'), 'string'=>'audio'),
1455 'ogv' => array ('type'=>'video/ogg', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1457 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1458 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1459 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1460 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1461 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1462 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1464 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx', 'groups'=>array('presentation')),
1465 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx', 'groups'=>array('presentation')),
1466 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1467 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptx'),
1468 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'pptx'),
1469 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'pptx'),
1470 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'pptx'),
1471 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'pptx'),
1472 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'pptx'),
1474 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1475 'qt' => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video','web_video'), 'string'=>'video'),
1476 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1477 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1478 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1479 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1480 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1481 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1482 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1483 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1484 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1485 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1486 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1487 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1488 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1489 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1490 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1491 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1492 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1493 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1495 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1496 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1497 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'ods'),
1498 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'ods'),
1499 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odg'),
1500 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odg'),
1501 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odp'),
1502 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odp'),
1503 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1504 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odf'),
1506 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1507 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1508 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1509 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1510 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1511 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1512 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1513 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1514 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1515 'webm' => array ('type'=>'video/webm', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1516 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1517 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1518 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1519 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1520 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1522 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1523 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1524 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1525 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xlsx'),
1526 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xlsx'),
1527 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsx'),
1528 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlsx'),
1530 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1531 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1532 'zip' => array ('type'=>'application/zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive')
1534 return $mimearray;
1538 * Obtains information about a filetype based on its extension. Will
1539 * use a default if no information is present about that particular
1540 * extension.
1542 * @category files
1543 * @param string $element Desired information (usually 'icon'
1544 * for icon filename or 'type' for MIME type. Can also be
1545 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1546 * @param string $filename Filename we're looking up
1547 * @return string Requested piece of information from array
1549 function mimeinfo($element, $filename) {
1550 global $CFG;
1551 $mimeinfo = & get_mimetypes_array();
1552 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1554 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1555 if (empty($filetype)) {
1556 $filetype = 'xxx'; // file without extension
1558 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1559 $iconsize = max(array(16, (int)$iconsizematch[1]));
1560 $filenames = array($mimeinfo['xxx']['icon']);
1561 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1562 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1564 // find the file with the closest size, first search for specific icon then for default icon
1565 foreach ($filenames as $filename) {
1566 foreach ($iconpostfixes as $size => $postfix) {
1567 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1568 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1569 return $filename.$postfix;
1573 } else if (isset($mimeinfo[$filetype][$element])) {
1574 return $mimeinfo[$filetype][$element];
1575 } else if (isset($mimeinfo['xxx'][$element])) {
1576 return $mimeinfo['xxx'][$element]; // By default
1577 } else {
1578 return null;
1583 * Obtains information about a filetype based on the MIME type rather than
1584 * the other way around.
1586 * @category files
1587 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1588 * @param string $mimetype MIME type we're looking up
1589 * @return string Requested piece of information from array
1591 function mimeinfo_from_type($element, $mimetype) {
1592 /* array of cached mimetype->extension associations */
1593 static $cached = array();
1594 $mimeinfo = & get_mimetypes_array();
1596 if (!array_key_exists($mimetype, $cached)) {
1597 $cached[$mimetype] = null;
1598 foreach($mimeinfo as $filetype => $values) {
1599 if ($values['type'] == $mimetype) {
1600 if ($cached[$mimetype] === null) {
1601 $cached[$mimetype] = '.'.$filetype;
1603 if (!empty($values['defaulticon'])) {
1604 $cached[$mimetype] = '.'.$filetype;
1605 break;
1609 if (empty($cached[$mimetype])) {
1610 $cached[$mimetype] = '.xxx';
1613 if ($element === 'extension') {
1614 return $cached[$mimetype];
1615 } else {
1616 return mimeinfo($element, $cached[$mimetype]);
1621 * Return the relative icon path for a given file
1623 * Usage:
1624 * <code>
1625 * // $file - instance of stored_file or file_info
1626 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1627 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1628 * </code>
1629 * or
1630 * <code>
1631 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1632 * </code>
1634 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1635 * and $file->mimetype are expected)
1636 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1637 * @return string
1639 function file_file_icon($file, $size = null) {
1640 if (!is_object($file)) {
1641 $file = (object)$file;
1643 if (isset($file->filename)) {
1644 $filename = $file->filename;
1645 } else if (method_exists($file, 'get_filename')) {
1646 $filename = $file->get_filename();
1647 } else if (method_exists($file, 'get_visible_name')) {
1648 $filename = $file->get_visible_name();
1649 } else {
1650 $filename = '';
1652 if (isset($file->mimetype)) {
1653 $mimetype = $file->mimetype;
1654 } else if (method_exists($file, 'get_mimetype')) {
1655 $mimetype = $file->get_mimetype();
1656 } else {
1657 $mimetype = '';
1659 $mimetypes = &get_mimetypes_array();
1660 if ($filename) {
1661 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1662 if ($extension && !empty($mimetypes[$extension])) {
1663 // if file name has known extension, return icon for this extension
1664 return file_extension_icon($filename, $size);
1667 return file_mimetype_icon($mimetype, $size);
1671 * Return the relative icon path for a folder image
1673 * Usage:
1674 * <code>
1675 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1676 * echo html_writer::empty_tag('img', array('src' => $icon));
1677 * </code>
1678 * or
1679 * <code>
1680 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1681 * </code>
1683 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1684 * @return string
1686 function file_folder_icon($iconsize = null) {
1687 global $CFG;
1688 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1689 static $cached = array();
1690 $iconsize = max(array(16, (int)$iconsize));
1691 if (!array_key_exists($iconsize, $cached)) {
1692 foreach ($iconpostfixes as $size => $postfix) {
1693 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1694 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1695 $cached[$iconsize] = 'f/folder'.$postfix;
1696 break;
1700 return $cached[$iconsize];
1704 * Returns the relative icon path for a given mime type
1706 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1707 * a return the full path to an icon.
1709 * <code>
1710 * $mimetype = 'image/jpg';
1711 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1712 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1713 * </code>
1715 * @category files
1716 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1717 * to conform with that.
1718 * @param string $mimetype The mimetype to fetch an icon for
1719 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1720 * @return string The relative path to the icon
1722 function file_mimetype_icon($mimetype, $size = NULL) {
1723 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1727 * Returns the relative icon path for a given file name
1729 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1730 * a return the full path to an icon.
1732 * <code>
1733 * $filename = '.jpg';
1734 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1735 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1736 * </code>
1738 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1739 * to conform with that.
1740 * @todo MDL-31074 Implement $size
1741 * @category files
1742 * @param string $filename The filename to get the icon for
1743 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1744 * @return string
1746 function file_extension_icon($filename, $size = NULL) {
1747 return 'f/'.mimeinfo('icon'.$size, $filename);
1751 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1752 * mimetypes.php language file.
1754 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1755 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1756 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1757 * @param bool $capitalise If true, capitalises first character of result
1758 * @return string Text description
1760 function get_mimetype_description($obj, $capitalise=false) {
1761 $filename = $mimetype = '';
1762 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1763 // this is an instance of stored_file
1764 $mimetype = $obj->get_mimetype();
1765 $filename = $obj->get_filename();
1766 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1767 // this is an instance of file_info
1768 $mimetype = $obj->get_mimetype();
1769 $filename = $obj->get_visible_name();
1770 } else if (is_array($obj) || is_object ($obj)) {
1771 $obj = (array)$obj;
1772 if (!empty($obj['filename'])) {
1773 $filename = $obj['filename'];
1775 if (!empty($obj['mimetype'])) {
1776 $mimetype = $obj['mimetype'];
1778 } else {
1779 $mimetype = $obj;
1781 $mimetypefromext = mimeinfo('type', $filename);
1782 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1783 // if file has a known extension, overwrite the specified mimetype
1784 $mimetype = $mimetypefromext;
1786 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1787 if (empty($extension)) {
1788 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1789 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1790 } else {
1791 $mimetypestr = mimeinfo('string', $filename);
1793 $chunks = explode('/', $mimetype, 2);
1794 $chunks[] = '';
1795 $attr = array(
1796 'mimetype' => $mimetype,
1797 'ext' => $extension,
1798 'mimetype1' => $chunks[0],
1799 'mimetype2' => $chunks[1],
1801 $a = array();
1802 foreach ($attr as $key => $value) {
1803 $a[$key] = $value;
1804 $a[strtoupper($key)] = strtoupper($value);
1805 $a[ucfirst($key)] = ucfirst($value);
1807 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1808 $result = get_string($mimetype, 'mimetypes', (object)$a);
1809 } else if (get_string_manager()->string_exists($mimetypestr, 'mimetypes')) {
1810 $result = get_string($mimetypestr, 'mimetypes', (object)$a);
1811 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1812 $result = get_string('default', 'mimetypes', (object)$a);
1813 } else {
1814 $result = $mimetype;
1816 if ($capitalise) {
1817 $result=ucfirst($result);
1819 return $result;
1823 * Returns array of elements of type $element in type group(s)
1825 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1826 * @param string|array $groups one group or array of groups/extensions/mimetypes
1827 * @return array
1829 function file_get_typegroup($element, $groups) {
1830 static $cached = array();
1831 if (!is_array($groups)) {
1832 $groups = array($groups);
1834 if (!array_key_exists($element, $cached)) {
1835 $cached[$element] = array();
1837 $result = array();
1838 foreach ($groups as $group) {
1839 if (!array_key_exists($group, $cached[$element])) {
1840 // retrieive and cache all elements of type $element for group $group
1841 $mimeinfo = & get_mimetypes_array();
1842 $cached[$element][$group] = array();
1843 foreach ($mimeinfo as $extension => $value) {
1844 $value['extension'] = '.'.$extension;
1845 if (empty($value[$element])) {
1846 continue;
1848 if (($group === '.'.$extension || $group === $value['type'] ||
1849 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1850 !in_array($value[$element], $cached[$element][$group])) {
1851 $cached[$element][$group][] = $value[$element];
1855 $result = array_merge($result, $cached[$element][$group]);
1857 return array_unique($result);
1861 * Checks if file with name $filename has one of the extensions in groups $groups
1863 * @see get_mimetypes_array()
1864 * @param string $filename name of the file to check
1865 * @param string|array $groups one group or array of groups to check
1866 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1867 * file mimetype is in mimetypes in groups $groups
1868 * @return bool
1870 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1871 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1872 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1873 return true;
1875 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1879 * Checks if mimetype $mimetype belongs to one of the groups $groups
1881 * @see get_mimetypes_array()
1882 * @param string $mimetype
1883 * @param string|array $groups one group or array of groups to check
1884 * @return bool
1886 function file_mimetype_in_typegroup($mimetype, $groups) {
1887 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1891 * Requested file is not found or not accessible, does not return, terminates script
1893 * @global stdClass $CFG
1894 * @global stdClass $COURSE
1896 function send_file_not_found() {
1897 global $CFG, $COURSE;
1898 send_header_404();
1899 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1902 * Helper function to send correct 404 for server.
1904 function send_header_404() {
1905 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1906 header("Status: 404 Not Found");
1907 } else {
1908 header('HTTP/1.0 404 not found');
1913 * Enhanced readfile() with optional acceleration.
1914 * @param string|stored_file $file
1915 * @param string $mimetype
1916 * @param bool $accelerate
1917 * @return void
1919 function readfile_accel($file, $mimetype, $accelerate) {
1920 global $CFG;
1922 if ($mimetype === 'text/plain') {
1923 // there is no encoding specified in text files, we need something consistent
1924 header('Content-Type: text/plain; charset=utf-8');
1925 } else {
1926 header('Content-Type: '.$mimetype);
1929 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1930 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1932 if (is_object($file)) {
1933 header('ETag: ' . $file->get_contenthash());
1934 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1935 header('HTTP/1.1 304 Not Modified');
1936 return;
1940 // if etag present for stored file rely on it exclusively
1941 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1942 // get unixtime of request header; clip extra junk off first
1943 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1944 if ($since && $since >= $lastmodified) {
1945 header('HTTP/1.1 304 Not Modified');
1946 return;
1950 if ($accelerate and !empty($CFG->xsendfile)) {
1951 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1952 header('Accept-Ranges: bytes');
1953 } else {
1954 header('Accept-Ranges: none');
1957 if (is_object($file)) {
1958 $fs = get_file_storage();
1959 if ($fs->xsendfile($file->get_contenthash())) {
1960 return;
1963 } else {
1964 require_once("$CFG->libdir/xsendfilelib.php");
1965 if (xsendfile($file)) {
1966 return;
1971 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1973 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1975 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1976 header('Accept-Ranges: bytes');
1978 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1979 // byteserving stuff - for acrobat reader and download accelerators
1980 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1981 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1982 $ranges = false;
1983 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1984 foreach ($ranges as $key=>$value) {
1985 if ($ranges[$key][1] == '') {
1986 //suffix case
1987 $ranges[$key][1] = $filesize - $ranges[$key][2];
1988 $ranges[$key][2] = $filesize - 1;
1989 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1990 //fix range length
1991 $ranges[$key][2] = $filesize - 1;
1993 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1994 //invalid byte-range ==> ignore header
1995 $ranges = false;
1996 break;
1998 //prepare multipart header
1999 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2000 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2002 } else {
2003 $ranges = false;
2005 if ($ranges) {
2006 if (is_object($file)) {
2007 $handle = $file->get_content_file_handle();
2008 } else {
2009 $handle = fopen($file, 'rb');
2011 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2014 } else {
2015 // Do not byteserve
2016 header('Accept-Ranges: none');
2019 header('Content-Length: '.$filesize);
2021 if ($filesize > 10000000) {
2022 // for large files try to flush and close all buffers to conserve memory
2023 while(@ob_get_level()) {
2024 if (!@ob_end_flush()) {
2025 break;
2030 // send the whole file content
2031 if (is_object($file)) {
2032 $file->readfile();
2033 } else {
2034 readfile($file);
2039 * Similar to readfile_accel() but designed for strings.
2040 * @param string $string
2041 * @param string $mimetype
2042 * @param bool $accelerate
2043 * @return void
2045 function readstring_accel($string, $mimetype, $accelerate) {
2046 global $CFG;
2048 if ($mimetype === 'text/plain') {
2049 // there is no encoding specified in text files, we need something consistent
2050 header('Content-Type: text/plain; charset=utf-8');
2051 } else {
2052 header('Content-Type: '.$mimetype);
2054 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2055 header('Accept-Ranges: none');
2057 if ($accelerate and !empty($CFG->xsendfile)) {
2058 $fs = get_file_storage();
2059 if ($fs->xsendfile(sha1($string))) {
2060 return;
2064 header('Content-Length: '.strlen($string));
2065 echo $string;
2069 * Handles the sending of temporary file to user, download is forced.
2070 * File is deleted after abort or successful sending, does not return, script terminated
2072 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2073 * @param string $filename proposed file name when saving file
2074 * @param bool $pathisstring If the path is string
2076 function send_temp_file($path, $filename, $pathisstring=false) {
2077 global $CFG;
2079 if (check_browser_version('Firefox', '1.5')) {
2080 // only FF is known to correctly save to disk before opening...
2081 $mimetype = mimeinfo('type', $filename);
2082 } else {
2083 $mimetype = 'application/x-forcedownload';
2086 // close session - not needed anymore
2087 session_get_instance()->write_close();
2089 if (!$pathisstring) {
2090 if (!file_exists($path)) {
2091 send_header_404();
2092 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2094 // executed after normal finish or abort
2095 @register_shutdown_function('send_temp_file_finished', $path);
2098 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2099 if (check_browser_version('MSIE')) {
2100 $filename = urlencode($filename);
2103 header('Content-Disposition: attachment; filename="'.$filename.'"');
2104 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2105 header('Cache-Control: max-age=10');
2106 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2107 header('Pragma: ');
2108 } else { //normal http - prevent caching at all cost
2109 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2110 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2111 header('Pragma: no-cache');
2114 // send the contents - we can not accelerate this because the file will be deleted asap
2115 if ($pathisstring) {
2116 readstring_accel($path, $mimetype, false);
2117 } else {
2118 readfile_accel($path, $mimetype, false);
2119 @unlink($path);
2122 die; //no more chars to output
2126 * Internal callback function used by send_temp_file()
2128 * @param string $path
2130 function send_temp_file_finished($path) {
2131 if (file_exists($path)) {
2132 @unlink($path);
2137 * Handles the sending of file data to the user's browser, including support for
2138 * byteranges etc.
2140 * @category files
2141 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2142 * @param string $filename Filename to send
2143 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2144 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2145 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2146 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2147 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2148 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2149 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2150 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2151 * and should not be reopened.
2152 * @return null script execution stopped unless $dontdie is true
2154 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2155 global $CFG, $COURSE;
2157 if ($dontdie) {
2158 ignore_user_abort(true);
2161 // MDL-11789, apply $CFG->filelifetime here
2162 if ($lifetime === 'default') {
2163 if (!empty($CFG->filelifetime)) {
2164 $lifetime = $CFG->filelifetime;
2165 } else {
2166 $lifetime = 86400;
2170 session_get_instance()->write_close(); // unlock session during fileserving
2172 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2173 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2174 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2175 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2176 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2177 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2179 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2180 if (check_browser_version('MSIE')) {
2181 $filename = rawurlencode($filename);
2184 if ($forcedownload) {
2185 header('Content-Disposition: attachment; filename="'.$filename.'"');
2186 } else {
2187 header('Content-Disposition: inline; filename="'.$filename.'"');
2190 if ($lifetime > 0) {
2191 $nobyteserving = false;
2192 header('Cache-Control: max-age='.$lifetime);
2193 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2194 header('Pragma: ');
2196 } else { // Do not cache files in proxies and browsers
2197 $nobyteserving = true;
2198 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2199 header('Cache-Control: max-age=10');
2200 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2201 header('Pragma: ');
2202 } else { //normal http - prevent caching at all cost
2203 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2204 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2205 header('Pragma: no-cache');
2209 if (empty($filter)) {
2210 // send the contents
2211 if ($pathisstring) {
2212 readstring_accel($path, $mimetype, !$dontdie);
2213 } else {
2214 readfile_accel($path, $mimetype, !$dontdie);
2217 } else {
2218 // Try to put the file through filters
2219 if ($mimetype == 'text/html') {
2220 $options = new stdClass();
2221 $options->noclean = true;
2222 $options->nocache = true; // temporary workaround for MDL-5136
2223 $text = $pathisstring ? $path : implode('', file($path));
2225 $text = file_modify_html_header($text);
2226 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2228 readstring_accel($output, $mimetype, false);
2230 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2231 // only filter text if filter all files is selected
2232 $options = new stdClass();
2233 $options->newlines = false;
2234 $options->noclean = true;
2235 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
2236 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2238 readstring_accel($output, $mimetype, false);
2240 } else {
2241 // send the contents
2242 if ($pathisstring) {
2243 readstring_accel($path, $mimetype, !$dontdie);
2244 } else {
2245 readfile_accel($path, $mimetype, !$dontdie);
2249 if ($dontdie) {
2250 return;
2252 die; //no more chars to output!!!
2256 * Handles the sending of file data to the user's browser, including support for
2257 * byteranges etc.
2259 * The $options parameter supports the following keys:
2260 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2261 * (string|null) filename - overrides the implicit filename
2262 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2263 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2264 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2265 * and should not be reopened.
2267 * @category files
2268 * @param stored_file $stored_file local file object
2269 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2270 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2271 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2272 * @param array $options additional options affecting the file serving
2273 * @return null script execution stopped unless $options['dontdie'] is true
2275 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2276 global $CFG, $COURSE;
2278 if (empty($options['filename'])) {
2279 $filename = null;
2280 } else {
2281 $filename = $options['filename'];
2284 if (empty($options['dontdie'])) {
2285 $dontdie = false;
2286 } else {
2287 $dontdie = true;
2290 if (!empty($options['preview'])) {
2291 // replace the file with its preview
2292 $fs = get_file_storage();
2293 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2294 if (!$preview_file) {
2295 // unable to create a preview of the file, send its default mime icon instead
2296 if ($options['preview'] === 'tinyicon') {
2297 $size = 24;
2298 } else if ($options['preview'] === 'thumb') {
2299 $size = 90;
2300 } else {
2301 $size = 256;
2303 $fileicon = file_file_icon($stored_file, $size);
2304 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2305 } else {
2306 // preview images have fixed cache lifetime and they ignore forced download
2307 // (they are generated by GD and therefore they are considered reasonably safe).
2308 $stored_file = $preview_file;
2309 $lifetime = DAYSECS;
2310 $filter = 0;
2311 $forcedownload = false;
2315 // handle external resource
2316 if ($stored_file && $stored_file->is_external_file()) {
2317 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2318 die;
2321 if (!$stored_file or $stored_file->is_directory()) {
2322 // nothing to serve
2323 if ($dontdie) {
2324 return;
2326 die;
2329 if ($dontdie) {
2330 ignore_user_abort(true);
2333 session_get_instance()->write_close(); // unlock session during fileserving
2335 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2336 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2337 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2338 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2339 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2340 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2341 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2343 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2344 if (check_browser_version('MSIE')) {
2345 $filename = rawurlencode($filename);
2348 if ($forcedownload) {
2349 header('Content-Disposition: attachment; filename="'.$filename.'"');
2350 } else {
2351 header('Content-Disposition: inline; filename="'.$filename.'"');
2354 if ($lifetime > 0) {
2355 header('Cache-Control: max-age='.$lifetime);
2356 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2357 header('Pragma: ');
2359 } else { // Do not cache files in proxies and browsers
2360 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2361 header('Cache-Control: max-age=10');
2362 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2363 header('Pragma: ');
2364 } else { //normal http - prevent caching at all cost
2365 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2366 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2367 header('Pragma: no-cache');
2371 if (empty($filter)) {
2372 // send the contents
2373 readfile_accel($stored_file, $mimetype, !$dontdie);
2375 } else { // Try to put the file through filters
2376 if ($mimetype == 'text/html') {
2377 $options = new stdClass();
2378 $options->noclean = true;
2379 $options->nocache = true; // temporary workaround for MDL-5136
2380 $text = $stored_file->get_content();
2381 $text = file_modify_html_header($text);
2382 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2384 readstring_accel($output, $mimetype, false);
2386 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2387 // only filter text if filter all files is selected
2388 $options = new stdClass();
2389 $options->newlines = false;
2390 $options->noclean = true;
2391 $text = $stored_file->get_content();
2392 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2394 readstring_accel($output, $mimetype, false);
2396 } else { // Just send it out raw
2397 readfile_accel($stored_file, $mimetype, !$dontdie);
2400 if ($dontdie) {
2401 return;
2403 die; //no more chars to output!!!
2407 * Retrieves an array of records from a CSV file and places
2408 * them into a given table structure
2410 * @global stdClass $CFG
2411 * @global moodle_database $DB
2412 * @param string $file The path to a CSV file
2413 * @param string $table The table to retrieve columns from
2414 * @return bool|array Returns an array of CSV records or false
2416 function get_records_csv($file, $table) {
2417 global $CFG, $DB;
2419 if (!$metacolumns = $DB->get_columns($table)) {
2420 return false;
2423 if(!($handle = @fopen($file, 'r'))) {
2424 print_error('get_records_csv failed to open '.$file);
2427 $fieldnames = fgetcsv($handle, 4096);
2428 if(empty($fieldnames)) {
2429 fclose($handle);
2430 return false;
2433 $columns = array();
2435 foreach($metacolumns as $metacolumn) {
2436 $ord = array_search($metacolumn->name, $fieldnames);
2437 if(is_int($ord)) {
2438 $columns[$metacolumn->name] = $ord;
2442 $rows = array();
2444 while (($data = fgetcsv($handle, 4096)) !== false) {
2445 $item = new stdClass;
2446 foreach($columns as $name => $ord) {
2447 $item->$name = $data[$ord];
2449 $rows[] = $item;
2452 fclose($handle);
2453 return $rows;
2457 * Create a file with CSV contents
2459 * @global stdClass $CFG
2460 * @global moodle_database $DB
2461 * @param string $file The file to put the CSV content into
2462 * @param array $records An array of records to write to a CSV file
2463 * @param string $table The table to get columns from
2464 * @return bool success
2466 function put_records_csv($file, $records, $table = NULL) {
2467 global $CFG, $DB;
2469 if (empty($records)) {
2470 return true;
2473 $metacolumns = NULL;
2474 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2475 return false;
2478 echo "x";
2480 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2481 print_error('put_records_csv failed to open '.$file);
2484 $proto = reset($records);
2485 if(is_object($proto)) {
2486 $fields_records = array_keys(get_object_vars($proto));
2488 else if(is_array($proto)) {
2489 $fields_records = array_keys($proto);
2491 else {
2492 return false;
2494 echo "x";
2496 if(!empty($metacolumns)) {
2497 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2498 $fields = array_intersect($fields_records, $fields_table);
2500 else {
2501 $fields = $fields_records;
2504 fwrite($fp, implode(',', $fields));
2505 fwrite($fp, "\r\n");
2507 foreach($records as $record) {
2508 $array = (array)$record;
2509 $values = array();
2510 foreach($fields as $field) {
2511 if(strpos($array[$field], ',')) {
2512 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2514 else {
2515 $values[] = $array[$field];
2518 fwrite($fp, implode(',', $values)."\r\n");
2521 fclose($fp);
2522 return true;
2527 * Recursively delete the file or folder with path $location. That is,
2528 * if it is a file delete it. If it is a folder, delete all its content
2529 * then delete it. If $location does not exist to start, that is not
2530 * considered an error.
2532 * @param string $location the path to remove.
2533 * @return bool
2535 function fulldelete($location) {
2536 if (empty($location)) {
2537 // extra safety against wrong param
2538 return false;
2540 if (is_dir($location)) {
2541 if (!$currdir = opendir($location)) {
2542 return false;
2544 while (false !== ($file = readdir($currdir))) {
2545 if ($file <> ".." && $file <> ".") {
2546 $fullfile = $location."/".$file;
2547 if (is_dir($fullfile)) {
2548 if (!fulldelete($fullfile)) {
2549 return false;
2551 } else {
2552 if (!unlink($fullfile)) {
2553 return false;
2558 closedir($currdir);
2559 if (! rmdir($location)) {
2560 return false;
2563 } else if (file_exists($location)) {
2564 if (!unlink($location)) {
2565 return false;
2568 return true;
2572 * Send requested byterange of file.
2574 * @param resource $handle A file handle
2575 * @param string $mimetype The mimetype for the output
2576 * @param array $ranges An array of ranges to send
2577 * @param string $filesize The size of the content if only one range is used
2579 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2580 // better turn off any kind of compression and buffering
2581 @ini_set('zlib.output_compression', 'Off');
2583 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2584 if ($handle === false) {
2585 die;
2587 if (count($ranges) == 1) { //only one range requested
2588 $length = $ranges[0][2] - $ranges[0][1] + 1;
2589 header('HTTP/1.1 206 Partial content');
2590 header('Content-Length: '.$length);
2591 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2592 header('Content-Type: '.$mimetype);
2594 while(@ob_get_level()) {
2595 if (!@ob_end_flush()) {
2596 break;
2600 fseek($handle, $ranges[0][1]);
2601 while (!feof($handle) && $length > 0) {
2602 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2603 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2604 echo $buffer;
2605 flush();
2606 $length -= strlen($buffer);
2608 fclose($handle);
2609 die;
2610 } else { // multiple ranges requested - not tested much
2611 $totallength = 0;
2612 foreach($ranges as $range) {
2613 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2615 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2616 header('HTTP/1.1 206 Partial content');
2617 header('Content-Length: '.$totallength);
2618 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2620 while(@ob_get_level()) {
2621 if (!@ob_end_flush()) {
2622 break;
2626 foreach($ranges as $range) {
2627 $length = $range[2] - $range[1] + 1;
2628 echo $range[0];
2629 fseek($handle, $range[1]);
2630 while (!feof($handle) && $length > 0) {
2631 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2632 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2633 echo $buffer;
2634 flush();
2635 $length -= strlen($buffer);
2638 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2639 fclose($handle);
2640 die;
2645 * add includes (js and css) into uploaded files
2646 * before returning them, useful for themes and utf.js includes
2648 * @global stdClass $CFG
2649 * @param string $text text to search and replace
2650 * @return string text with added head includes
2651 * @todo MDL-21120
2653 function file_modify_html_header($text) {
2654 // first look for <head> tag
2655 global $CFG;
2657 $stylesheetshtml = '';
2658 /* foreach ($CFG->stylesheets as $stylesheet) {
2659 //TODO: MDL-21120
2660 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2663 $ufo = '';
2664 if (filter_is_enabled('filter/mediaplugin')) {
2665 // this script is needed by most media filter plugins.
2666 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2667 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2670 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2671 if ($matches) {
2672 $replacement = '<head>'.$ufo.$stylesheetshtml;
2673 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2674 return $text;
2677 // if not, look for <html> tag, and stick <head> right after
2678 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2679 if ($matches) {
2680 // replace <html> tag with <html><head>includes</head>
2681 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2682 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2683 return $text;
2686 // if not, look for <body> tag, and stick <head> before body
2687 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2688 if ($matches) {
2689 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2690 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2691 return $text;
2694 // if not, just stick a <head> tag at the beginning
2695 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2696 return $text;
2700 * RESTful cURL class
2702 * This is a wrapper class for curl, it is quite easy to use:
2703 * <code>
2704 * $c = new curl;
2705 * // enable cache
2706 * $c = new curl(array('cache'=>true));
2707 * // enable cookie
2708 * $c = new curl(array('cookie'=>true));
2709 * // enable proxy
2710 * $c = new curl(array('proxy'=>true));
2712 * // HTTP GET Method
2713 * $html = $c->get('http://example.com');
2714 * // HTTP POST Method
2715 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2716 * // HTTP PUT Method
2717 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2718 * </code>
2720 * @package core_files
2721 * @category files
2722 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2723 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2725 class curl {
2726 /** @var bool Caches http request contents */
2727 public $cache = false;
2728 /** @var bool Uses proxy */
2729 public $proxy = false;
2730 /** @var string library version */
2731 public $version = '0.4 dev';
2732 /** @var array http's response */
2733 public $response = array();
2734 /** @var array http header */
2735 public $header = array();
2736 /** @var string cURL information */
2737 public $info;
2738 /** @var string error */
2739 public $error;
2741 /** @var array cURL options */
2742 private $options;
2743 /** @var string Proxy host */
2744 private $proxy_host = '';
2745 /** @var string Proxy auth */
2746 private $proxy_auth = '';
2747 /** @var string Proxy type */
2748 private $proxy_type = '';
2749 /** @var bool Debug mode on */
2750 private $debug = false;
2751 /** @var bool|string Path to cookie file */
2752 private $cookie = false;
2755 * Constructor
2757 * @global stdClass $CFG
2758 * @param array $options
2760 public function __construct($options = array()){
2761 global $CFG;
2762 if (!function_exists('curl_init')) {
2763 $this->error = 'cURL module must be enabled!';
2764 trigger_error($this->error, E_USER_ERROR);
2765 return false;
2767 // the options of curl should be init here.
2768 $this->resetopt();
2769 if (!empty($options['debug'])) {
2770 $this->debug = true;
2772 if(!empty($options['cookie'])) {
2773 if($options['cookie'] === true) {
2774 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2775 } else {
2776 $this->cookie = $options['cookie'];
2779 if (!empty($options['cache'])) {
2780 if (class_exists('curl_cache')) {
2781 if (!empty($options['module_cache'])) {
2782 $this->cache = new curl_cache($options['module_cache']);
2783 } else {
2784 $this->cache = new curl_cache('misc');
2788 if (!empty($CFG->proxyhost)) {
2789 if (empty($CFG->proxyport)) {
2790 $this->proxy_host = $CFG->proxyhost;
2791 } else {
2792 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2794 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2795 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2796 $this->setopt(array(
2797 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2798 'proxyuserpwd'=>$this->proxy_auth));
2800 if (!empty($CFG->proxytype)) {
2801 if ($CFG->proxytype == 'SOCKS5') {
2802 $this->proxy_type = CURLPROXY_SOCKS5;
2803 } else {
2804 $this->proxy_type = CURLPROXY_HTTP;
2805 $this->setopt(array('httpproxytunnel'=>false));
2807 $this->setopt(array('proxytype'=>$this->proxy_type));
2810 if (!empty($this->proxy_host)) {
2811 $this->proxy = array('proxy'=>$this->proxy_host);
2815 * Resets the CURL options that have already been set
2817 public function resetopt(){
2818 $this->options = array();
2819 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2820 // True to include the header in the output
2821 $this->options['CURLOPT_HEADER'] = 0;
2822 // True to Exclude the body from the output
2823 $this->options['CURLOPT_NOBODY'] = 0;
2824 // TRUE to follow any "Location: " header that the server
2825 // sends as part of the HTTP header (note this is recursive,
2826 // PHP will follow as many "Location: " headers that it is sent,
2827 // unless CURLOPT_MAXREDIRS is set).
2828 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2829 $this->options['CURLOPT_MAXREDIRS'] = 10;
2830 $this->options['CURLOPT_ENCODING'] = '';
2831 // TRUE to return the transfer as a string of the return
2832 // value of curl_exec() instead of outputting it out directly.
2833 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2834 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2835 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2836 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2837 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2841 * Reset Cookie
2843 public function resetcookie() {
2844 if (!empty($this->cookie)) {
2845 if (is_file($this->cookie)) {
2846 $fp = fopen($this->cookie, 'w');
2847 if (!empty($fp)) {
2848 fwrite($fp, '');
2849 fclose($fp);
2856 * Set curl options
2858 * @param array $options If array is null, this function will
2859 * reset the options to default value.
2861 public function setopt($options = array()) {
2862 if (is_array($options)) {
2863 foreach($options as $name => $val){
2864 if (stripos($name, 'CURLOPT_') === false) {
2865 $name = strtoupper('CURLOPT_'.$name);
2867 $this->options[$name] = $val;
2873 * Reset http method
2875 public function cleanopt(){
2876 unset($this->options['CURLOPT_HTTPGET']);
2877 unset($this->options['CURLOPT_POST']);
2878 unset($this->options['CURLOPT_POSTFIELDS']);
2879 unset($this->options['CURLOPT_PUT']);
2880 unset($this->options['CURLOPT_INFILE']);
2881 unset($this->options['CURLOPT_INFILESIZE']);
2882 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2886 * Set HTTP Request Header
2888 * @param array $header
2890 public function setHeader($header) {
2891 if (is_array($header)){
2892 foreach ($header as $v) {
2893 $this->setHeader($v);
2895 } else {
2896 $this->header[] = $header;
2901 * Set HTTP Response Header
2904 public function getResponse(){
2905 return $this->response;
2909 * private callback function
2910 * Formatting HTTP Response Header
2912 * @param resource $ch Apparently not used
2913 * @param string $header
2914 * @return int The strlen of the header
2916 private function formatHeader($ch, $header)
2918 $this->count++;
2919 if (strlen($header) > 2) {
2920 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2921 $key = rtrim($key, ':');
2922 if (!empty($this->response[$key])) {
2923 if (is_array($this->response[$key])){
2924 $this->response[$key][] = $value;
2925 } else {
2926 $tmp = $this->response[$key];
2927 $this->response[$key] = array();
2928 $this->response[$key][] = $tmp;
2929 $this->response[$key][] = $value;
2932 } else {
2933 $this->response[$key] = $value;
2936 return strlen($header);
2940 * Set options for individual curl instance
2942 * @param resource $curl A curl handle
2943 * @param array $options
2944 * @return resource The curl handle
2946 private function apply_opt($curl, $options) {
2947 // Clean up
2948 $this->cleanopt();
2949 // set cookie
2950 if (!empty($this->cookie) || !empty($options['cookie'])) {
2951 $this->setopt(array('cookiejar'=>$this->cookie,
2952 'cookiefile'=>$this->cookie
2956 // set proxy
2957 if (!empty($this->proxy) || !empty($options['proxy'])) {
2958 $this->setopt($this->proxy);
2960 $this->setopt($options);
2961 // reset before set options
2962 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2963 // set headers
2964 if (empty($this->header)){
2965 $this->setHeader(array(
2966 'User-Agent: MoodleBot/1.0',
2967 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2968 'Connection: keep-alive'
2971 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2973 if ($this->debug){
2974 echo '<h1>Options</h1>';
2975 var_dump($this->options);
2976 echo '<h1>Header</h1>';
2977 var_dump($this->header);
2980 // set options
2981 foreach($this->options as $name => $val) {
2982 if (is_string($name)) {
2983 $name = constant(strtoupper($name));
2985 curl_setopt($curl, $name, $val);
2987 return $curl;
2991 * Download multiple files in parallel
2993 * Calls {@link multi()} with specific download headers
2995 * <code>
2996 * $c = new curl;
2997 * $c->download(array(
2998 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2999 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
3000 * ));
3001 * </code>
3003 * @param array $requests An array of files to request
3004 * @param array $options An array of options to set
3005 * @return array An array of results
3007 public function download($requests, $options = array()) {
3008 $options['CURLOPT_BINARYTRANSFER'] = 1;
3009 $options['RETURNTRANSFER'] = false;
3010 return $this->multi($requests, $options);
3014 * Mulit HTTP Requests
3015 * This function could run multi-requests in parallel.
3017 * @param array $requests An array of files to request
3018 * @param array $options An array of options to set
3019 * @return array An array of results
3021 protected function multi($requests, $options = array()) {
3022 $count = count($requests);
3023 $handles = array();
3024 $results = array();
3025 $main = curl_multi_init();
3026 for ($i = 0; $i < $count; $i++) {
3027 $url = $requests[$i];
3028 foreach($url as $n=>$v){
3029 $options[$n] = $url[$n];
3031 $handles[$i] = curl_init($url['url']);
3032 $this->apply_opt($handles[$i], $options);
3033 curl_multi_add_handle($main, $handles[$i]);
3035 $running = 0;
3036 do {
3037 curl_multi_exec($main, $running);
3038 } while($running > 0);
3039 for ($i = 0; $i < $count; $i++) {
3040 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3041 $results[] = true;
3042 } else {
3043 $results[] = curl_multi_getcontent($handles[$i]);
3045 curl_multi_remove_handle($main, $handles[$i]);
3047 curl_multi_close($main);
3048 return $results;
3052 * Single HTTP Request
3054 * @param string $url The URL to request
3055 * @param array $options
3056 * @return bool
3058 protected function request($url, $options = array()){
3059 // create curl instance
3060 $curl = curl_init($url);
3061 $options['url'] = $url;
3062 $this->apply_opt($curl, $options);
3063 if ($this->cache && $ret = $this->cache->get($this->options)) {
3064 return $ret;
3065 } else {
3066 $ret = curl_exec($curl);
3067 if ($this->cache) {
3068 $this->cache->set($this->options, $ret);
3072 $this->info = curl_getinfo($curl);
3073 $this->error = curl_error($curl);
3075 if ($this->debug){
3076 echo '<h1>Return Data</h1>';
3077 var_dump($ret);
3078 echo '<h1>Info</h1>';
3079 var_dump($this->info);
3080 echo '<h1>Error</h1>';
3081 var_dump($this->error);
3084 curl_close($curl);
3086 if (empty($this->error)){
3087 return $ret;
3088 } else {
3089 return $this->error;
3090 // exception is not ajax friendly
3091 //throw new moodle_exception($this->error, 'curl');
3096 * HTTP HEAD method
3098 * @see request()
3100 * @param string $url
3101 * @param array $options
3102 * @return bool
3104 public function head($url, $options = array()){
3105 $options['CURLOPT_HTTPGET'] = 0;
3106 $options['CURLOPT_HEADER'] = 1;
3107 $options['CURLOPT_NOBODY'] = 1;
3108 return $this->request($url, $options);
3112 * HTTP POST method
3114 * @param string $url
3115 * @param array|string $params
3116 * @param array $options
3117 * @return bool
3119 public function post($url, $params = '', $options = array()){
3120 $options['CURLOPT_POST'] = 1;
3121 if (is_array($params)) {
3122 $this->_tmp_file_post_params = array();
3123 foreach ($params as $key => $value) {
3124 if ($value instanceof stored_file) {
3125 $value->add_to_curl_request($this, $key);
3126 } else {
3127 $this->_tmp_file_post_params[$key] = $value;
3130 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3131 unset($this->_tmp_file_post_params);
3132 } else {
3133 // $params is the raw post data
3134 $options['CURLOPT_POSTFIELDS'] = $params;
3136 return $this->request($url, $options);
3140 * HTTP GET method
3142 * @param string $url
3143 * @param array $params
3144 * @param array $options
3145 * @return bool
3147 public function get($url, $params = array(), $options = array()){
3148 $options['CURLOPT_HTTPGET'] = 1;
3150 if (!empty($params)){
3151 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3152 $url .= http_build_query($params, '', '&');
3154 return $this->request($url, $options);
3158 * HTTP PUT method
3160 * @param string $url
3161 * @param array $params
3162 * @param array $options
3163 * @return bool
3165 public function put($url, $params = array(), $options = array()){
3166 $file = $params['file'];
3167 if (!is_file($file)){
3168 return null;
3170 $fp = fopen($file, 'r');
3171 $size = filesize($file);
3172 $options['CURLOPT_PUT'] = 1;
3173 $options['CURLOPT_INFILESIZE'] = $size;
3174 $options['CURLOPT_INFILE'] = $fp;
3175 if (!isset($this->options['CURLOPT_USERPWD'])){
3176 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3178 $ret = $this->request($url, $options);
3179 fclose($fp);
3180 return $ret;
3184 * HTTP DELETE method
3186 * @param string $url
3187 * @param array $param
3188 * @param array $options
3189 * @return bool
3191 public function delete($url, $param = array(), $options = array()){
3192 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3193 if (!isset($options['CURLOPT_USERPWD'])) {
3194 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3196 $ret = $this->request($url, $options);
3197 return $ret;
3201 * HTTP TRACE method
3203 * @param string $url
3204 * @param array $options
3205 * @return bool
3207 public function trace($url, $options = array()){
3208 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3209 $ret = $this->request($url, $options);
3210 return $ret;
3214 * HTTP OPTIONS method
3216 * @param string $url
3217 * @param array $options
3218 * @return bool
3220 public function options($url, $options = array()){
3221 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3222 $ret = $this->request($url, $options);
3223 return $ret;
3227 * Get curl information
3229 * @return string
3231 public function get_info() {
3232 return $this->info;
3237 * This class is used by cURL class, use case:
3239 * <code>
3240 * $CFG->repositorycacheexpire = 120;
3241 * $CFG->curlcache = 120;
3243 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3244 * $ret = $c->get('http://www.google.com');
3245 * </code>
3247 * @package core_files
3248 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3249 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3251 class curl_cache {
3252 /** @var string Path to cache directory */
3253 public $dir = '';
3256 * Constructor
3258 * @global stdClass $CFG
3259 * @param string $module which module is using curl_cache
3261 public function __construct($module = 'repository') {
3262 global $CFG;
3263 if (!empty($module)) {
3264 $this->dir = $CFG->cachedir.'/'.$module.'/';
3265 } else {
3266 $this->dir = $CFG->cachedir.'/misc/';
3268 if (!file_exists($this->dir)) {
3269 mkdir($this->dir, $CFG->directorypermissions, true);
3271 if ($module == 'repository') {
3272 if (empty($CFG->repositorycacheexpire)) {
3273 $CFG->repositorycacheexpire = 120;
3275 $this->ttl = $CFG->repositorycacheexpire;
3276 } else {
3277 if (empty($CFG->curlcache)) {
3278 $CFG->curlcache = 120;
3280 $this->ttl = $CFG->curlcache;
3285 * Get cached value
3287 * @global stdClass $CFG
3288 * @global stdClass $USER
3289 * @param mixed $param
3290 * @return bool|string
3292 public function get($param) {
3293 global $CFG, $USER;
3294 $this->cleanup($this->ttl);
3295 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3296 if(file_exists($this->dir.$filename)) {
3297 $lasttime = filemtime($this->dir.$filename);
3298 if (time()-$lasttime > $this->ttl) {
3299 return false;
3300 } else {
3301 $fp = fopen($this->dir.$filename, 'r');
3302 $size = filesize($this->dir.$filename);
3303 $content = fread($fp, $size);
3304 return unserialize($content);
3307 return false;
3311 * Set cache value
3313 * @global object $CFG
3314 * @global object $USER
3315 * @param mixed $param
3316 * @param mixed $val
3318 public function set($param, $val) {
3319 global $CFG, $USER;
3320 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3321 $fp = fopen($this->dir.$filename, 'w');
3322 fwrite($fp, serialize($val));
3323 fclose($fp);
3327 * Remove cache files
3329 * @param int $expire The number of seconds before expiry
3331 public function cleanup($expire) {
3332 if ($dir = opendir($this->dir)) {
3333 while (false !== ($file = readdir($dir))) {
3334 if(!is_dir($file) && $file != '.' && $file != '..') {
3335 $lasttime = @filemtime($this->dir.$file);
3336 if (time() - $lasttime > $expire) {
3337 @unlink($this->dir.$file);
3341 closedir($dir);
3345 * delete current user's cache file
3347 * @global object $CFG
3348 * @global object $USER
3350 public function refresh() {
3351 global $CFG, $USER;
3352 if ($dir = opendir($this->dir)) {
3353 while (false !== ($file = readdir($dir))) {
3354 if (!is_dir($file) && $file != '.' && $file != '..') {
3355 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3356 @unlink($this->dir.$file);
3365 * This function delegates file serving to individual plugins
3367 * @param string $relativepath
3368 * @param bool $forcedownload
3369 * @param null|string $preview the preview mode, defaults to serving the original file
3370 * @todo MDL-31088 file serving improments
3372 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3373 global $DB, $CFG, $USER;
3374 // relative path must start with '/'
3375 if (!$relativepath) {
3376 print_error('invalidargorconf');
3377 } else if ($relativepath[0] != '/') {
3378 print_error('pathdoesnotstartslash');
3381 // extract relative path components
3382 $args = explode('/', ltrim($relativepath, '/'));
3384 if (count($args) < 3) { // always at least context, component and filearea
3385 print_error('invalidarguments');
3388 $contextid = (int)array_shift($args);
3389 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3390 $filearea = clean_param(array_shift($args), PARAM_AREA);
3392 list($context, $course, $cm) = get_context_info_array($contextid);
3394 $fs = get_file_storage();
3396 // ========================================================================================================================
3397 if ($component === 'blog') {
3398 // Blog file serving
3399 if ($context->contextlevel != CONTEXT_SYSTEM) {
3400 send_file_not_found();
3402 if ($filearea !== 'attachment' and $filearea !== 'post') {
3403 send_file_not_found();
3406 if (empty($CFG->bloglevel)) {
3407 print_error('siteblogdisable', 'blog');
3410 $entryid = (int)array_shift($args);
3411 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3412 send_file_not_found();
3414 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3415 require_login();
3416 if (isguestuser()) {
3417 print_error('noguest');
3419 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3420 if ($USER->id != $entry->userid) {
3421 send_file_not_found();
3426 if ('publishstate' === 'public') {
3427 if ($CFG->forcelogin) {
3428 require_login();
3431 } else if ('publishstate' === 'site') {
3432 require_login();
3433 //ok
3434 } else if ('publishstate' === 'draft') {
3435 require_login();
3436 if ($USER->id != $entry->userid) {
3437 send_file_not_found();
3441 $filename = array_pop($args);
3442 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3444 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3445 send_file_not_found();
3448 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3450 // ========================================================================================================================
3451 } else if ($component === 'grade') {
3452 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3453 // Global gradebook files
3454 if ($CFG->forcelogin) {
3455 require_login();
3458 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3460 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3461 send_file_not_found();
3464 session_get_instance()->write_close(); // unlock session during fileserving
3465 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3467 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3468 //TODO: nobody implemented this yet in grade edit form!!
3469 send_file_not_found();
3471 if ($CFG->forcelogin || $course->id != SITEID) {
3472 require_login($course);
3475 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3477 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3478 send_file_not_found();
3481 session_get_instance()->write_close(); // unlock session during fileserving
3482 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3483 } else {
3484 send_file_not_found();
3487 // ========================================================================================================================
3488 } else if ($component === 'tag') {
3489 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3491 // All tag descriptions are going to be public but we still need to respect forcelogin
3492 if ($CFG->forcelogin) {
3493 require_login();
3496 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3498 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3499 send_file_not_found();
3502 session_get_instance()->write_close(); // unlock session during fileserving
3503 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3505 } else {
3506 send_file_not_found();
3509 // ========================================================================================================================
3510 } else if ($component === 'calendar') {
3511 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3513 // All events here are public the one requirement is that we respect forcelogin
3514 if ($CFG->forcelogin) {
3515 require_login();
3518 // Get the event if from the args array
3519 $eventid = array_shift($args);
3521 // Load the event from the database
3522 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3523 send_file_not_found();
3525 // Check that we got an event and that it's userid is that of the user
3527 // Get the file and serve if successful
3528 $filename = array_pop($args);
3529 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3530 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3531 send_file_not_found();
3534 session_get_instance()->write_close(); // unlock session during fileserving
3535 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3537 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3539 // Must be logged in, if they are not then they obviously can't be this user
3540 require_login();
3542 // Don't want guests here, potentially saves a DB call
3543 if (isguestuser()) {
3544 send_file_not_found();
3547 // Get the event if from the args array
3548 $eventid = array_shift($args);
3550 // Load the event from the database - user id must match
3551 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3552 send_file_not_found();
3555 // Get the file and serve if successful
3556 $filename = array_pop($args);
3557 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3558 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3559 send_file_not_found();
3562 session_get_instance()->write_close(); // unlock session during fileserving
3563 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3565 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3567 // Respect forcelogin and require login unless this is the site.... it probably
3568 // should NEVER be the site
3569 if ($CFG->forcelogin || $course->id != SITEID) {
3570 require_login($course);
3573 // Must be able to at least view the course
3574 if (!is_enrolled($context) and !is_viewing($context)) {
3575 //TODO: hmm, do we really want to block guests here?
3576 send_file_not_found();
3579 // Get the event id
3580 $eventid = array_shift($args);
3582 // Load the event from the database we need to check whether it is
3583 // a) valid course event
3584 // b) a group event
3585 // Group events use the course context (there is no group context)
3586 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3587 send_file_not_found();
3590 // If its a group event require either membership of view all groups capability
3591 if ($event->eventtype === 'group') {
3592 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3593 send_file_not_found();
3595 } else if ($event->eventtype === 'course') {
3596 //ok
3597 } else {
3598 // some other type
3599 send_file_not_found();
3602 // If we get this far we can serve the file
3603 $filename = array_pop($args);
3604 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3605 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3606 send_file_not_found();
3609 session_get_instance()->write_close(); // unlock session during fileserving
3610 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3612 } else {
3613 send_file_not_found();
3616 // ========================================================================================================================
3617 } else if ($component === 'user') {
3618 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3619 if (count($args) == 1) {
3620 $themename = theme_config::DEFAULT_THEME;
3621 $filename = array_shift($args);
3622 } else {
3623 $themename = array_shift($args);
3624 $filename = array_shift($args);
3627 // fix file name automatically
3628 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3629 $filename = 'f1';
3632 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3633 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3634 // protect images if login required and not logged in;
3635 // also if login is required for profile images and is not logged in or guest
3636 // do not use require_login() because it is expensive and not suitable here anyway
3637 $theme = theme_config::load($themename);
3638 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3641 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3642 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3643 if ($filename === 'f3') {
3644 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3645 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3646 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3651 if (!$file) {
3652 // bad reference - try to prevent future retries as hard as possible!
3653 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3654 if ($user->picture > 0) {
3655 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3658 // no redirect here because it is not cached
3659 $theme = theme_config::load($themename);
3660 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle');
3661 send_file($imagefile, basename($imagefile), 60*60*24*14);
3664 send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3666 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3667 require_login();
3669 if (isguestuser()) {
3670 send_file_not_found();
3673 if ($USER->id !== $context->instanceid) {
3674 send_file_not_found();
3677 $filename = array_pop($args);
3678 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3679 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3680 send_file_not_found();
3683 session_get_instance()->write_close(); // unlock session during fileserving
3684 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3686 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3688 if ($CFG->forcelogin) {
3689 require_login();
3692 $userid = $context->instanceid;
3694 if ($USER->id == $userid) {
3695 // always can access own
3697 } else if (!empty($CFG->forceloginforprofiles)) {
3698 require_login();
3700 if (isguestuser()) {
3701 send_file_not_found();
3704 // we allow access to site profile of all course contacts (usually teachers)
3705 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3706 send_file_not_found();
3709 $canview = false;
3710 if (has_capability('moodle/user:viewdetails', $context)) {
3711 $canview = true;
3712 } else {
3713 $courses = enrol_get_my_courses();
3716 while (!$canview && count($courses) > 0) {
3717 $course = array_shift($courses);
3718 if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) {
3719 $canview = true;
3724 $filename = array_pop($args);
3725 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3726 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3727 send_file_not_found();
3730 session_get_instance()->write_close(); // unlock session during fileserving
3731 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3733 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3734 $userid = (int)array_shift($args);
3735 $usercontext = get_context_instance(CONTEXT_USER, $userid);
3737 if ($CFG->forcelogin) {
3738 require_login();
3741 if (!empty($CFG->forceloginforprofiles)) {
3742 require_login();
3743 if (isguestuser()) {
3744 print_error('noguest');
3747 //TODO: review this logic of user profile access prevention
3748 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3749 print_error('usernotavailable');
3751 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3752 print_error('cannotviewprofile');
3754 if (!is_enrolled($context, $userid)) {
3755 print_error('notenrolledprofile');
3757 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3758 print_error('groupnotamember');
3762 $filename = array_pop($args);
3763 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3764 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3765 send_file_not_found();
3768 session_get_instance()->write_close(); // unlock session during fileserving
3769 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3771 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3772 require_login();
3774 if (isguestuser()) {
3775 send_file_not_found();
3777 $userid = $context->instanceid;
3779 if ($USER->id != $userid) {
3780 send_file_not_found();
3783 $filename = array_pop($args);
3784 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3785 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3786 send_file_not_found();
3789 session_get_instance()->write_close(); // unlock session during fileserving
3790 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3792 } else {
3793 send_file_not_found();
3796 // ========================================================================================================================
3797 } else if ($component === 'coursecat') {
3798 if ($context->contextlevel != CONTEXT_COURSECAT) {
3799 send_file_not_found();
3802 if ($filearea === 'description') {
3803 if ($CFG->forcelogin) {
3804 // no login necessary - unless login forced everywhere
3805 require_login();
3808 $filename = array_pop($args);
3809 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3810 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3811 send_file_not_found();
3814 session_get_instance()->write_close(); // unlock session during fileserving
3815 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3816 } else {
3817 send_file_not_found();
3820 // ========================================================================================================================
3821 } else if ($component === 'course') {
3822 if ($context->contextlevel != CONTEXT_COURSE) {
3823 send_file_not_found();
3826 if ($filearea === 'summary') {
3827 if ($CFG->forcelogin) {
3828 require_login();
3831 $filename = array_pop($args);
3832 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3833 if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
3834 send_file_not_found();
3837 session_get_instance()->write_close(); // unlock session during fileserving
3838 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3840 } else if ($filearea === 'section') {
3841 if ($CFG->forcelogin) {
3842 require_login($course);
3843 } else if ($course->id != SITEID) {
3844 require_login($course);
3847 $sectionid = (int)array_shift($args);
3849 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
3850 send_file_not_found();
3853 if ($course->numsections < $section->section) {
3854 if (!has_capability('moodle/course:update', $context)) {
3855 // block access to unavailable sections if can not edit course
3856 send_file_not_found();
3860 $filename = array_pop($args);
3861 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3862 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3863 send_file_not_found();
3866 session_get_instance()->write_close(); // unlock session during fileserving
3867 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3869 } else {
3870 send_file_not_found();
3873 } else if ($component === 'group') {
3874 if ($context->contextlevel != CONTEXT_COURSE) {
3875 send_file_not_found();
3878 require_course_login($course, true, null, false);
3880 $groupid = (int)array_shift($args);
3882 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
3883 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
3884 // do not allow access to separate group info if not member or teacher
3885 send_file_not_found();
3888 if ($filearea === 'description') {
3890 require_login($course);
3892 $filename = array_pop($args);
3893 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3894 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
3895 send_file_not_found();
3898 session_get_instance()->write_close(); // unlock session during fileserving
3899 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3901 } else if ($filearea === 'icon') {
3902 $filename = array_pop($args);
3904 if ($filename !== 'f1' and $filename !== 'f2') {
3905 send_file_not_found();
3907 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
3908 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
3909 send_file_not_found();
3913 session_get_instance()->write_close(); // unlock session during fileserving
3914 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
3916 } else {
3917 send_file_not_found();
3920 } else if ($component === 'grouping') {
3921 if ($context->contextlevel != CONTEXT_COURSE) {
3922 send_file_not_found();
3925 require_login($course);
3927 $groupingid = (int)array_shift($args);
3929 // note: everybody has access to grouping desc images for now
3930 if ($filearea === 'description') {
3932 $filename = array_pop($args);
3933 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3934 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
3935 send_file_not_found();
3938 session_get_instance()->write_close(); // unlock session during fileserving
3939 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3941 } else {
3942 send_file_not_found();
3945 // ========================================================================================================================
3946 } else if ($component === 'backup') {
3947 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
3948 require_login($course);
3949 require_capability('moodle/backup:downloadfile', $context);
3951 $filename = array_pop($args);
3952 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3953 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
3954 send_file_not_found();
3957 session_get_instance()->write_close(); // unlock session during fileserving
3958 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
3960 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
3961 require_login($course);
3962 require_capability('moodle/backup:downloadfile', $context);
3964 $sectionid = (int)array_shift($args);
3966 $filename = array_pop($args);
3967 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3968 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3969 send_file_not_found();
3972 session_get_instance()->write_close();
3973 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3975 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
3976 require_login($course, false, $cm);
3977 require_capability('moodle/backup:downloadfile', $context);
3979 $filename = array_pop($args);
3980 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3981 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
3982 send_file_not_found();
3985 session_get_instance()->write_close();
3986 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3988 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
3989 // Backup files that were generated by the automated backup systems.
3991 require_login($course);
3992 require_capability('moodle/site:config', $context);
3994 $filename = array_pop($args);
3995 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3996 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
3997 send_file_not_found();
4000 session_get_instance()->write_close(); // unlock session during fileserving
4001 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4003 } else {
4004 send_file_not_found();
4007 // ========================================================================================================================
4008 } else if ($component === 'question') {
4009 require_once($CFG->libdir . '/questionlib.php');
4010 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4011 send_file_not_found();
4013 // ========================================================================================================================
4014 } else if ($component === 'grading') {
4015 if ($filearea === 'description') {
4016 // files embedded into the form definition description
4018 if ($context->contextlevel == CONTEXT_SYSTEM) {
4019 require_login();
4021 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4022 require_login($course, false, $cm);
4024 } else {
4025 send_file_not_found();
4028 $formid = (int)array_shift($args);
4030 $sql = "SELECT ga.id
4031 FROM {grading_areas} ga
4032 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4033 WHERE gd.id = ? AND ga.contextid = ?";
4034 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4036 if (!$areaid) {
4037 send_file_not_found();
4040 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4042 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4043 send_file_not_found();
4046 session_get_instance()->write_close(); // unlock session during fileserving
4047 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4050 // ========================================================================================================================
4051 } else if (strpos($component, 'mod_') === 0) {
4052 $modname = substr($component, 4);
4053 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4054 send_file_not_found();
4056 require_once("$CFG->dirroot/mod/$modname/lib.php");
4058 if ($context->contextlevel == CONTEXT_MODULE) {
4059 if ($cm->modname !== $modname) {
4060 // somebody tries to gain illegal access, cm type must match the component!
4061 send_file_not_found();
4065 if ($filearea === 'intro') {
4066 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4067 send_file_not_found();
4069 require_course_login($course, true, $cm);
4071 // all users may access it
4072 $filename = array_pop($args);
4073 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4074 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4075 send_file_not_found();
4078 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4080 // finally send the file
4081 send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4084 $filefunction = $component.'_pluginfile';
4085 $filefunctionold = $modname.'_pluginfile';
4086 if (function_exists($filefunction)) {
4087 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4088 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4089 } else if (function_exists($filefunctionold)) {
4090 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4091 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4094 send_file_not_found();
4096 // ========================================================================================================================
4097 } else if (strpos($component, 'block_') === 0) {
4098 $blockname = substr($component, 6);
4099 // note: no more class methods in blocks please, that is ....
4100 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4101 send_file_not_found();
4103 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4105 if ($context->contextlevel == CONTEXT_BLOCK) {
4106 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4107 if ($birecord->blockname !== $blockname) {
4108 // somebody tries to gain illegal access, cm type must match the component!
4109 send_file_not_found();
4112 $bprecord = $DB->get_record('block_positions', array('blockinstanceid' => $context->instanceid), 'visible');
4113 // User can't access file, if block is hidden or doesn't have block:view capability
4114 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4115 send_file_not_found();
4117 } else {
4118 $birecord = null;
4121 $filefunction = $component.'_pluginfile';
4122 if (function_exists($filefunction)) {
4123 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4124 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4127 send_file_not_found();
4129 // ========================================================================================================================
4130 } else if (strpos($component, '_') === false) {
4131 // all core subsystems have to be specified above, no more guessing here!
4132 send_file_not_found();
4134 } else {
4135 // try to serve general plugin file in arbitrary context
4136 $dir = get_component_directory($component);
4137 if (!file_exists("$dir/lib.php")) {
4138 send_file_not_found();
4140 include_once("$dir/lib.php");
4142 $filefunction = $component.'_pluginfile';
4143 if (function_exists($filefunction)) {
4144 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4145 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4148 send_file_not_found();
4154 * Universe file cacheing class
4156 * @package core_files
4157 * @category files
4158 * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org}
4159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4161 class cache_file {
4162 /** @var string */
4163 public $cachedir = '';
4166 * static method to create cache_file class instance
4168 * @param array $options caching ooptions
4170 public static function get_instance($options = array()) {
4171 return new cache_file($options);
4175 * Constructor
4177 * @param array $options
4179 private function __construct($options = array()) {
4180 global $CFG;
4182 // Path to file caches.
4183 if (isset($options['cachedir'])) {
4184 $this->cachedir = $options['cachedir'];
4185 } else {
4186 $this->cachedir = $CFG->cachedir . '/filedir';
4189 // Create cache directory.
4190 if (!file_exists($this->cachedir)) {
4191 mkdir($this->cachedir, $CFG->directorypermissions, true);
4194 // When use cache_file::get, it will check ttl.
4195 if (isset($options['ttl']) && is_numeric($options['ttl'])) {
4196 $this->ttl = $options['ttl'];
4197 } else {
4198 // One day.
4199 $this->ttl = 60 * 60 * 24;
4204 * Get cached file, false if file expires
4206 * @param mixed $param
4207 * @param array $options caching options
4208 * @return bool|string
4210 public static function get($param, $options = array()) {
4211 $instance = self::get_instance($options);
4212 $filepath = $instance->generate_filepath($param);
4213 if (file_exists($filepath)) {
4214 $lasttime = filemtime($filepath);
4215 if (time() - $lasttime > $instance->ttl) {
4216 // Remove cache file.
4217 unlink($filepath);
4218 return false;
4219 } else {
4220 return $filepath;
4222 } else {
4223 return false;
4228 * Static method to create cache from a file
4230 * @param mixed $ref
4231 * @param string $srcfile
4232 * @param array $options
4233 * @return string cached file path
4235 public static function create_from_file($ref, $srcfile, $options = array()) {
4236 $instance = self::get_instance($options);
4237 $cachedfilepath = $instance->generate_filepath($ref);
4238 copy($srcfile, $cachedfilepath);
4239 return $cachedfilepath;
4243 * Static method to create cache from url
4245 * @param mixed $ref file reference
4246 * @param string $url file url
4247 * @param array $options options
4248 * @return string cached file path
4250 public static function create_from_url($ref, $url, $options = array()) {
4251 $instance = self::get_instance($options);
4252 $cachedfilepath = $instance->generate_filepath($ref);
4253 $fp = fopen($cachedfilepath, 'w');
4254 $curl = new curl;
4255 $curl->download(array(array('url'=>$url, 'file'=>$fp)));
4256 // Must close file handler.
4257 fclose($fp);
4258 return $cachedfilepath;
4262 * Static method to create cache from string
4264 * @param mixed $ref file reference
4265 * @param string $url file url
4266 * @param array $options options
4267 * @return string cached file path
4269 public static function create_from_string($ref, $string, $options = array()) {
4270 $instance = self::get_instance($options);
4271 $cachedfilepath = $instance->generate_filepath($ref);
4272 $fp = fopen($cachedfilepath, 'w');
4273 fwrite($fp, $string);
4274 // Must close file handler.
4275 fclose($fp);
4276 return $cachedfilepath;
4280 * Build path to cache file
4282 * @param mixed $ref
4283 * @return string
4285 private function generate_filepath($ref) {
4286 global $CFG;
4287 $hash = sha1(serialize($ref));
4288 $l1 = $hash[0].$hash[1];
4289 $l2 = $hash[2].$hash[3];
4290 $dir = $this->cachedir . "/$l1/$l2";
4291 if (!file_exists($dir)) {
4292 mkdir($dir, $CFG->directorypermissions, true);
4294 return "$dir/$hash";
4298 * Remove cache files
4300 * @param array $options options
4301 * @param int $expire The number of seconds before expiry
4303 public static function cleanup($options = array(), $expire) {
4304 global $CFG;
4305 $instance = self::get_instance($options);
4306 if ($dir = opendir($instance->cachedir)) {
4307 while (($file = readdir($dir)) !== false) {
4308 if (!is_dir($file) && $file != '.' && $file != '..') {
4309 $lasttime = @filemtime($instance->cachedir . $file);
4310 if(time() - $lasttime > $expire){
4311 @unlink($instance->cachedir . $file);
4315 closedir($dir);