2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Functions for file handling.
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();
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
66 $return .= '?forcedownload=1';
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
72 $return .= '&forcedownload=1';
77 $return = str_replace('http://', 'https://', $return);
84 * Prepares 'editor' formslib element from data in database
86 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
87 * function then copies the embedded files into draft area (assigning itemids automatically),
88 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
90 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
91 * your mform's set_data() supplying the object returned by this function.
94 * @param stdClass $data database field that holds the html text with embedded media
95 * @param string $field the name of the database field that holds the html text with embedded media
96 * @param array $options editor options (like maxifiles, maxbytes etc.)
97 * @param stdClass $context context of the editor
98 * @param string $component
99 * @param string $filearea file area name
100 * @param int $itemid item id, required if item exists
101 * @return stdClass modified data object
103 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
104 $options = (array)$options;
105 if (!isset($options['trusttext'])) {
106 $options['trusttext'] = false;
108 if (!isset($options['forcehttps'])) {
109 $options['forcehttps'] = false;
111 if (!isset($options['subdirs'])) {
112 $options['subdirs'] = false;
114 if (!isset($options['maxfiles'])) {
115 $options['maxfiles'] = 0; // no files by default
117 if (!isset($options['noclean'])) {
118 $options['noclean'] = false;
121 //sanity check for passed context. This function doesn't expect $option['context'] to be set
122 //But this function is called before creating editor hence, this is one of the best places to check
123 //if context is used properly. This check notify developer that they missed passing context to editor.
124 if (isset($context) && !isset($options['context'])) {
125 //if $context is not null then make sure $option['context'] is also set.
126 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
127 } else if (isset($options['context']) && isset($context)) {
128 //If both are passed then they should be equal.
129 if ($options['context']->id != $context->id) {
130 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
131 throw new coding_exception($exceptionmsg);
135 if (is_null($itemid) or is_null($context)) {
139 $data = new stdClass();
141 if (!isset($data->{$field})) {
142 $data->{$field} = '';
144 if (!isset($data->{$field.'format'})) {
145 $data->{$field.'format'} = editors_get_preferred_format();
147 if (!$options['noclean']) {
148 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
152 if ($options['trusttext']) {
153 // noclean ignored if trusttext enabled
154 if (!isset($data->{$field.'trust'})) {
155 $data->{$field.'trust'} = 0;
157 $data = trusttext_pre_edit($data, $field, $context);
159 if (!$options['noclean']) {
160 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
163 $contextid = $context->id;
166 if ($options['maxfiles'] != 0) {
167 $draftid_editor = file_get_submitted_draft_itemid($field);
168 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
169 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
171 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
178 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
180 * This function moves files from draft area to the destination area and
181 * encodes URLs to the draft files so they can be safely saved into DB. The
182 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
183 * is the name of the database field to hold the wysiwyg editor content. The
184 * editor data comes as an array with text, format and itemid properties. This
185 * function automatically adds $data properties foobar, foobarformat and
186 * foobartrust, where foobar has URL to embedded files encoded.
189 * @param stdClass $data raw data submitted by the form
190 * @param string $field name of the database field containing the html with embedded media files
191 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
192 * @param stdClass $context context, required for existing data
193 * @param string $component file component
194 * @param string $filearea file area name
195 * @param int $itemid item id, required if item exists
196 * @return stdClass modified data object
198 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
199 $options = (array)$options;
200 if (!isset($options['trusttext'])) {
201 $options['trusttext'] = false;
203 if (!isset($options['forcehttps'])) {
204 $options['forcehttps'] = false;
206 if (!isset($options['subdirs'])) {
207 $options['subdirs'] = false;
209 if (!isset($options['maxfiles'])) {
210 $options['maxfiles'] = 0; // no files by default
212 if (!isset($options['maxbytes'])) {
213 $options['maxbytes'] = 0; // unlimited
216 if ($options['trusttext']) {
217 $data->{$field.'trust'} = trusttext_trusted($context);
219 $data->{$field.'trust'} = 0;
222 $editor = $data->{$field.'_editor'};
224 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
225 $data->{$field} = $editor['text'];
227 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
229 $data->{$field.'format'} = $editor['format'];
235 * Saves text and files modified by Editor formslib element
238 * @param stdClass $data $database entry field
239 * @param string $field name of data field
240 * @param array $options various options
241 * @param stdClass $context context - must already exist
242 * @param string $component
243 * @param string $filearea file area name
244 * @param int $itemid must already exist, usually means data is in db
245 * @return stdClass modified data obejct
247 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
248 $options = (array)$options;
249 if (!isset($options['subdirs'])) {
250 $options['subdirs'] = false;
252 if (is_null($itemid) or is_null($context)) {
256 $contextid = $context->id;
259 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
260 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
261 $data->{$field.'_filemanager'} = $draftid_editor;
267 * Saves files modified by File manager formslib element
269 * @todo MDL-31073 review this function
271 * @param stdClass $data $database entry field
272 * @param string $field name of data field
273 * @param array $options various options
274 * @param stdClass $context context - must already exist
275 * @param string $component
276 * @param string $filearea file area name
277 * @param int $itemid must already exist, usually means data is in db
278 * @return stdClass modified data obejct
280 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
281 $options = (array)$options;
282 if (!isset($options['subdirs'])) {
283 $options['subdirs'] = false;
285 if (!isset($options['maxfiles'])) {
286 $options['maxfiles'] = -1; // unlimited
288 if (!isset($options['maxbytes'])) {
289 $options['maxbytes'] = 0; // unlimited
292 if (empty($data->{$field.'_filemanager'})) {
296 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
297 $fs = get_file_storage();
299 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
300 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
310 * Generate a draft itemid
313 * @global moodle_database $DB
314 * @global stdClass $USER
315 * @return int a random but available draft itemid that can be used to create a new draft
318 function file_get_unused_draft_itemid() {
321 if (isguestuser() or !isloggedin()) {
322 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
323 print_error('noguest');
326 $contextid = context_user::instance($USER->id)->id;
328 $fs = get_file_storage();
329 $draftitemid = rand(1, 999999999);
330 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
331 $draftitemid = rand(1, 999999999);
338 * Initialise a draft file area from a real one by copying the files. A draft
339 * area will be created if one does not already exist. Normally you should
340 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
343 * @global stdClass $CFG
344 * @global stdClass $USER
345 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
346 * @param int $contextid This parameter and the next two identify the file area to copy files from.
347 * @param string $component
348 * @param string $filearea helps indentify the file area.
349 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
350 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
351 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
352 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
354 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
355 global $CFG, $USER, $CFG;
357 $options = (array)$options;
358 if (!isset($options['subdirs'])) {
359 $options['subdirs'] = false;
361 if (!isset($options['forcehttps'])) {
362 $options['forcehttps'] = false;
365 $usercontext = context_user::instance($USER->id);
366 $fs = get_file_storage();
368 if (empty($draftitemid)) {
369 // create a new area and copy existing files into
370 $draftitemid = file_get_unused_draft_itemid();
371 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
372 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
373 foreach ($files as $file) {
374 if ($file->is_directory() and $file->get_filepath() === '/') {
375 // we need a way to mark the age of each draft area,
376 // by not copying the root dir we force it to be created automatically with current timestamp
379 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
382 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
383 // XXX: This is a hack for file manager (MDL-28666)
384 // File manager needs to know the original file information before copying
385 // to draft area, so we append these information in mdl_files.source field
386 // {@link file_storage::search_references()}
387 // {@link file_storage::search_references_count()}
388 $sourcefield = $file->get_source();
389 $newsourcefield = new stdClass;
390 $newsourcefield->source = $sourcefield;
391 $original = new stdClass;
392 $original->contextid = $contextid;
393 $original->component = $component;
394 $original->filearea = $filearea;
395 $original->itemid = $itemid;
396 $original->filename = $file->get_filename();
397 $original->filepath = $file->get_filepath();
398 $newsourcefield->original = file_storage::pack_reference($original);
399 $draftfile->set_source(serialize($newsourcefield));
400 // End of file manager hack
403 if (!is_null($text)) {
404 // at this point there should not be any draftfile links yet,
405 // because this is a new text from database that should still contain the @@pluginfile@@ links
406 // this happens when developers forget to post process the text
407 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
413 if (is_null($text)) {
417 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
418 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
422 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
425 * @global stdClass $CFG
426 * @param string $text The content that may contain ULRs in need of rewriting.
427 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
428 * @param int $contextid This parameter and the next two identify the file area to use.
429 * @param string $component
430 * @param string $filearea helps identify the file area.
431 * @param int $itemid helps identify the file area.
432 * @param array $options text and file options ('forcehttps'=>false)
433 * @return string the processed text.
435 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
438 $options = (array)$options;
439 if (!isset($options['forcehttps'])) {
440 $options['forcehttps'] = false;
443 if (!$CFG->slasharguments) {
444 $file = $file . '?file=';
447 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
449 if ($itemid !== null) {
450 $baseurl .= "$itemid/";
453 if ($options['forcehttps']) {
454 $baseurl = str_replace('http://', 'https://', $baseurl);
457 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
461 * Returns information about files in a draft area.
463 * @global stdClass $CFG
464 * @global stdClass $USER
465 * @param int $draftitemid the draft area item id.
466 * @param string $filepath path to the directory from which the information have to be retrieved.
467 * @return array with the following entries:
468 * 'filecount' => number of files in the draft area.
469 * 'filesize' => total size of the files in the draft area.
470 * 'foldercount' => number of folders in the draft area.
471 * 'filesize_without_references' => total size of the area excluding file references.
472 * (more information will be added as needed).
474 function file_get_draft_area_info($draftitemid, $filepath = '/') {
477 $usercontext = context_user::instance($USER->id);
478 $fs = get_file_storage();
484 'filesize_without_references' => 0
487 if ($filepath != '/') {
488 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
490 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
492 foreach ($draftfiles as $file) {
493 if ($file->is_directory()) {
494 $results['foldercount'] += 1;
496 $results['filecount'] += 1;
499 $filesize = $file->get_filesize();
500 $results['filesize'] += $filesize;
501 if (!$file->is_external_file()) {
502 $results['filesize_without_references'] += $filesize;
510 * Returns whether a draft area has exceeded/will exceed its size limit.
512 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
514 * @param int $draftitemid the draft area item id.
515 * @param int $areamaxbytes the maximum size allowed in this draft area.
516 * @param int $newfilesize the size that would be added to the current area.
517 * @param bool $includereferences true to include the size of the references in the area size.
518 * @return bool true if the area will/has exceeded its limit.
521 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
522 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
523 $draftinfo = file_get_draft_area_info($draftitemid);
524 $areasize = $draftinfo['filesize_without_references'];
525 if ($includereferences) {
526 $areasize = $draftinfo['filesize'];
528 if ($areasize + $newfilesize > $areamaxbytes) {
536 * Get used space of files
537 * @global moodle_database $DB
538 * @global stdClass $USER
539 * @return int total bytes
541 function file_get_user_used_space() {
544 $usercontext = context_user::instance($USER->id);
545 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
546 JOIN (SELECT contenthash, filename, MAX(id) AS id
548 WHERE contextid = ? AND component = ? AND filearea != ?
549 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
550 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
551 $record = $DB->get_record_sql($sql, $params);
552 return (int)$record->totalbytes;
556 * Convert any string to a valid filepath
557 * @todo review this function
559 * @return string path
561 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
562 if ($str == '/' or empty($str)) {
565 return '/'.trim($str, '/').'/';
570 * Generate a folder tree of draft area of current USER recursively
572 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
573 * @param int $draftitemid
574 * @param string $filepath
577 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
578 global $USER, $OUTPUT, $CFG;
579 $data->children = array();
580 $context = context_user::instance($USER->id);
581 $fs = get_file_storage();
582 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
583 foreach ($files as $file) {
584 if ($file->is_directory()) {
585 $item = new stdClass();
586 $item->sortorder = $file->get_sortorder();
587 $item->filepath = $file->get_filepath();
589 $foldername = explode('/', trim($item->filepath, '/'));
590 $item->fullname = trim(array_pop($foldername), '/');
592 $item->id = uniqid();
593 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
594 $data->children[] = $item;
603 * Listing all files (including folders) in current path (draft area)
604 * used by file manager
605 * @param int $draftitemid
606 * @param string $filepath
609 function file_get_drafarea_files($draftitemid, $filepath = '/') {
610 global $USER, $OUTPUT, $CFG;
612 $context = context_user::instance($USER->id);
613 $fs = get_file_storage();
615 $data = new stdClass();
616 $data->path = array();
617 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
619 // will be used to build breadcrumb
621 if ($filepath !== '/') {
622 $filepath = file_correct_filepath($filepath);
623 $parts = explode('/', $filepath);
624 foreach ($parts as $part) {
625 if ($part != '' && $part != null) {
626 $trail .= ($part.'/');
627 $data->path[] = array('name'=>$part, 'path'=>$trail);
634 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
635 foreach ($files as $file) {
636 $item = new stdClass();
637 $item->filename = $file->get_filename();
638 $item->filepath = $file->get_filepath();
639 $item->fullname = trim($item->filename, '/');
640 $filesize = $file->get_filesize();
641 $item->size = $filesize ? $filesize : null;
642 $item->filesize = $filesize ? display_size($filesize) : '';
644 $item->sortorder = $file->get_sortorder();
645 $item->author = $file->get_author();
646 $item->license = $file->get_license();
647 $item->datemodified = $file->get_timemodified();
648 $item->datecreated = $file->get_timecreated();
649 $item->isref = $file->is_external_file();
650 if ($item->isref && $file->get_status() == 666) {
651 $item->originalmissing = true;
653 // find the file this draft file was created from and count all references in local
654 // system pointing to that file
655 $source = @unserialize($file->get_source());
656 if (isset($source->original)) {
657 $item->refcount = $fs->search_references_count($source->original);
660 if ($file->is_directory()) {
662 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
663 $item->type = 'folder';
664 $foldername = explode('/', trim($item->filepath, '/'));
665 $item->fullname = trim(array_pop($foldername), '/');
666 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
668 // do NOT use file browser here!
669 $item->mimetype = get_mimetype_description($file);
670 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
673 $item->type = 'file';
675 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
676 $item->url = $itemurl->out();
677 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
678 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
679 if ($imageinfo = $file->get_imageinfo()) {
680 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
681 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
682 $item->image_width = $imageinfo['width'];
683 $item->image_height = $imageinfo['height'];
689 $data->itemid = $draftitemid;
695 * Returns draft area itemid for a given element.
698 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
699 * @return int the itemid, or 0 if there is not one yet.
701 function file_get_submitted_draft_itemid($elname) {
702 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
703 if (!isset($_REQUEST[$elname])) {
706 if (is_array($_REQUEST[$elname])) {
707 $param = optional_param_array($elname, 0, PARAM_INT);
708 if (!empty($param['itemid'])) {
709 $param = $param['itemid'];
711 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
716 $param = optional_param($elname, 0, PARAM_INT);
727 * Restore the original source field from draft files
729 * @param stored_file $storedfile This only works with draft files
730 * @return stored_file
732 function file_restore_source_field_from_draft_file($storedfile) {
733 $source = @unserialize($storedfile->get_source());
734 if (!empty($source)) {
735 if (is_object($source)) {
736 $restoredsource = $source->source;
737 $storedfile->set_source($restoredsource);
739 throw new moodle_exception('invalidsourcefield', 'error');
745 * Saves files from a draft file area to a real one (merging the list of files).
746 * Can rewrite URLs in some content at the same time if desired.
749 * @global stdClass $USER
750 * @param int $draftitemid the id of the draft area to use. Normally obtained
751 * from file_get_submitted_draft_itemid('elementname') or similar.
752 * @param int $contextid This parameter and the next two identify the file area to save to.
753 * @param string $component
754 * @param string $filearea indentifies the file area.
755 * @param int $itemid helps identifies the file area.
756 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
757 * @param string $text some html content that needs to have embedded links rewritten
758 * to the @@PLUGINFILE@@ form for saving in the database.
759 * @param bool $forcehttps force https urls.
760 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
762 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
765 $usercontext = context_user::instance($USER->id);
766 $fs = get_file_storage();
768 $options = (array)$options;
769 if (!isset($options['subdirs'])) {
770 $options['subdirs'] = false;
772 if (!isset($options['maxfiles'])) {
773 $options['maxfiles'] = -1; // unlimited
775 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
776 $options['maxbytes'] = 0; // unlimited
778 if (!isset($options['areamaxbytes'])) {
779 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
781 $allowreferences = true;
782 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
783 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
784 // this is not exactly right. BUT there are many places in code where filemanager options
785 // are not passed to file_save_draft_area_files()
786 $allowreferences = false;
789 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
790 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
791 // anything at all in the next area.
792 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
796 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
797 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
799 if (count($draftfiles) < 2) {
800 // means there are no files - one file means root dir only ;-)
801 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
803 } else if (count($oldfiles) < 2) {
805 // there were no files before - one file means root dir only ;-)
806 foreach ($draftfiles as $file) {
807 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
808 if (!$options['subdirs']) {
809 if ($file->get_filepath() !== '/' or $file->is_directory()) {
813 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
814 // oversized file - should not get here at all
817 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
818 // more files - should not get here at all
821 if (!$file->is_directory()) {
825 if ($file->is_external_file()) {
826 if (!$allowreferences) {
829 $repoid = $file->get_repository_id();
830 if (!empty($repoid)) {
831 $file_record['repositoryid'] = $repoid;
832 $file_record['reference'] = $file->get_reference();
835 file_restore_source_field_from_draft_file($file);
837 $fs->create_file_from_storedfile($file_record, $file);
841 // we have to merge old and new files - we want to keep file ids for files that were not changed
842 // we change time modified for all new and changed files, we keep time created as is
844 $newhashes = array();
845 foreach ($draftfiles as $file) {
846 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
847 file_restore_source_field_from_draft_file($file);
848 $newhashes[$newhash] = $file;
851 foreach ($oldfiles as $oldfile) {
852 $oldhash = $oldfile->get_pathnamehash();
853 if (!isset($newhashes[$oldhash])) {
854 // delete files not needed any more - deleted by user
859 $newfile = $newhashes[$oldhash];
860 // status changed, we delete old file, and create a new one
861 if ($oldfile->get_status() != $newfile->get_status()) {
862 // file was changed, use updated with new timemodified data
864 // This file will be added later
869 if ($oldfile->get_author() != $newfile->get_author()) {
870 $oldfile->set_author($newfile->get_author());
873 if ($oldfile->get_license() != $newfile->get_license()) {
874 $oldfile->set_license($newfile->get_license());
877 // Updated file source
878 if ($oldfile->get_source() != $newfile->get_source()) {
879 $oldfile->set_source($newfile->get_source());
882 // Updated sort order
883 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
884 $oldfile->set_sortorder($newfile->get_sortorder());
887 // Update file timemodified
888 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
889 $oldfile->set_timemodified($newfile->get_timemodified());
892 // Replaced file content
893 if ($oldfile->get_contenthash() != $newfile->get_contenthash() || $oldfile->get_filesize() != $newfile->get_filesize()) {
894 $oldfile->replace_content_with($newfile);
895 // push changes to all local files that are referencing this file
896 $fs->update_references_to_storedfile($oldfile);
899 // unchanged file or directory - we keep it as is
900 unset($newhashes[$oldhash]);
901 if (!$oldfile->is_directory()) {
906 // Add fresh file or the file which has changed status
907 // the size and subdirectory tests are extra safety only, the UI should prevent it
908 foreach ($newhashes as $file) {
909 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
910 if (!$options['subdirs']) {
911 if ($file->get_filepath() !== '/' or $file->is_directory()) {
915 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
916 // oversized file - should not get here at all
919 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
920 // more files - should not get here at all
923 if (!$file->is_directory()) {
927 if ($file->is_external_file()) {
928 if (!$allowreferences) {
931 $repoid = $file->get_repository_id();
932 if (!empty($repoid)) {
933 $file_record['repositoryid'] = $repoid;
934 $file_record['reference'] = $file->get_reference();
938 $fs->create_file_from_storedfile($file_record, $file);
942 // note: do not purge the draft area - we clean up areas later in cron,
943 // the reason is that user might press submit twice and they would loose the files,
944 // also sometimes we might want to use hacks that save files into two different areas
946 if (is_null($text)) {
949 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
954 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
955 * ready to be saved in the database. Normally, this is done automatically by
956 * {@link file_save_draft_area_files()}.
959 * @param string $text the content to process.
960 * @param int $draftitemid the draft file area the content was using.
961 * @param bool $forcehttps whether the content contains https URLs. Default false.
962 * @return string the processed content.
964 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
967 $usercontext = context_user::instance($USER->id);
969 $wwwroot = $CFG->wwwroot;
971 $wwwroot = str_replace('http://', 'https://', $wwwroot);
974 // relink embedded files if text submitted - no absolute links allowed in database!
975 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
977 if (strpos($text, 'draftfile.php?file=') !== false) {
979 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
981 foreach ($matches[0] as $match) {
982 $replace = str_ireplace('%2F', '/', $match);
983 $text = str_replace($match, $replace, $text);
986 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
993 * Set file sort order
995 * @global moodle_database $DB
996 * @param int $contextid the context id
997 * @param string $component file component
998 * @param string $filearea file area.
999 * @param int $itemid itemid.
1000 * @param string $filepath file path.
1001 * @param string $filename file name.
1002 * @param int $sortorder the sort order of file.
1005 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1007 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1008 if ($file_record = $DB->get_record('files', $conditions)) {
1009 $sortorder = (int)$sortorder;
1010 $file_record->sortorder = $sortorder;
1011 $DB->update_record('files', $file_record);
1018 * reset file sort order number to 0
1019 * @global moodle_database $DB
1020 * @param int $contextid the context id
1021 * @param string $component
1022 * @param string $filearea file area.
1023 * @param int|bool $itemid itemid.
1026 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1029 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1030 if ($itemid !== false) {
1031 $conditions['itemid'] = $itemid;
1034 $file_records = $DB->get_records('files', $conditions);
1035 foreach ($file_records as $file_record) {
1036 $file_record->sortorder = 0;
1037 $DB->update_record('files', $file_record);
1043 * Returns description of upload error
1045 * @param int $errorcode found in $_FILES['filename.ext']['error']
1046 * @return string error description string, '' if ok
1048 function file_get_upload_error($errorcode) {
1050 switch ($errorcode) {
1051 case 0: // UPLOAD_ERR_OK - no error
1055 case 1: // UPLOAD_ERR_INI_SIZE
1056 $errmessage = get_string('uploadserverlimit');
1059 case 2: // UPLOAD_ERR_FORM_SIZE
1060 $errmessage = get_string('uploadformlimit');
1063 case 3: // UPLOAD_ERR_PARTIAL
1064 $errmessage = get_string('uploadpartialfile');
1067 case 4: // UPLOAD_ERR_NO_FILE
1068 $errmessage = get_string('uploadnofilefound');
1071 // Note: there is no error with a value of 5
1073 case 6: // UPLOAD_ERR_NO_TMP_DIR
1074 $errmessage = get_string('uploadnotempdir');
1077 case 7: // UPLOAD_ERR_CANT_WRITE
1078 $errmessage = get_string('uploadcantwrite');
1081 case 8: // UPLOAD_ERR_EXTENSION
1082 $errmessage = get_string('uploadextension');
1086 $errmessage = get_string('uploadproblem');
1093 * Recursive function formating an array in POST parameter
1094 * @param array $arraydata - the array that we are going to format and add into &$data array
1095 * @param string $currentdata - a row of the final postdata array at instant T
1096 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1097 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1099 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1100 foreach ($arraydata as $k=>$v) {
1101 $newcurrentdata = $currentdata;
1102 if (is_array($v)) { //the value is an array, call the function recursively
1103 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1104 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1105 } else { //add the POST parameter to the $data array
1106 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1112 * Transform a PHP array into POST parameter
1113 * (see the recursive function format_array_postdata_for_curlcall)
1114 * @param array $postdata
1115 * @return array containing all POST parameters (1 row = 1 POST parameter)
1117 function format_postdata_for_curlcall($postdata) {
1119 foreach ($postdata as $k=>$v) {
1121 $currentdata = urlencode($k);
1122 format_array_postdata_for_curlcall($v, $currentdata, $data);
1124 $data[] = urlencode($k).'='.urlencode($v);
1127 $convertedpostdata = implode('&', $data);
1128 return $convertedpostdata;
1132 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1133 * Due to security concerns only downloads from http(s) sources are supported.
1135 * @todo MDL-31073 add version test for '7.10.5'
1137 * @param string $url file url starting with http(s)://
1138 * @param array $headers http headers, null if none. If set, should be an
1139 * associative array of header name => value pairs.
1140 * @param array $postdata array means use POST request with given parameters
1141 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1142 * (if false, just returns content)
1143 * @param int $timeout timeout for complete download process including all file transfer
1144 * (default 5 minutes)
1145 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1146 * usually happens if the remote server is completely down (default 20 seconds);
1147 * may not work when using proxy
1148 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1149 * Only use this when already in a trusted location.
1150 * @param string $tofile store the downloaded content to file instead of returning it.
1151 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1152 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1153 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1155 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1158 // some extra security
1159 $newlines = array("\r", "\n");
1160 if (is_array($headers) ) {
1161 foreach ($headers as $key => $value) {
1162 $headers[$key] = str_replace($newlines, '', $value);
1165 $url = str_replace($newlines, '', $url);
1166 if (!preg_match('|^https?://|i', $url)) {
1167 if ($fullresponse) {
1168 $response = new stdClass();
1169 $response->status = 0;
1170 $response->headers = array();
1171 $response->response_code = 'Invalid protocol specified in url';
1172 $response->results = '';
1173 $response->error = 'Invalid protocol specified in url';
1180 // check if proxy (if used) should be bypassed for this url
1181 $proxybypass = is_proxybypass($url);
1183 if (!$ch = curl_init($url)) {
1184 debugging('Can not init curl.');
1188 // set extra headers
1189 if (is_array($headers) ) {
1190 $headers2 = array();
1191 foreach ($headers as $key => $value) {
1192 $headers2[] = "$key: $value";
1194 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1197 if ($skipcertverify) {
1198 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1201 // use POST if requested
1202 if (is_array($postdata)) {
1203 $postdata = format_postdata_for_curlcall($postdata);
1204 curl_setopt($ch, CURLOPT_POST, true);
1205 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1208 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1209 curl_setopt($ch, CURLOPT_HEADER, false);
1210 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1212 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1213 // TODO: add version test for '7.10.5'
1214 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1215 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1218 if (!empty($CFG->proxyhost) and !$proxybypass) {
1219 // SOCKS supported in PHP5 only
1220 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1221 if (defined('CURLPROXY_SOCKS5')) {
1222 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1225 if ($fullresponse) {
1226 $response = new stdClass();
1227 $response->status = '0';
1228 $response->headers = array();
1229 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1230 $response->results = '';
1231 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1234 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1240 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1242 if (empty($CFG->proxyport)) {
1243 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1245 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1248 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1249 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1250 if (defined('CURLOPT_PROXYAUTH')) {
1251 // any proxy authentication if PHP 5.1
1252 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1257 // set up header and content handlers
1258 $received = new stdClass();
1259 $received->headers = array(); // received headers array
1260 $received->tofile = $tofile;
1261 $received->fh = null;
1262 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1264 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1267 if (!isset($CFG->curltimeoutkbitrate)) {
1268 //use very slow rate of 56kbps as a timeout speed when not set
1271 $bitrate = $CFG->curltimeoutkbitrate;
1274 // try to calculate the proper amount for timeout from remote file size.
1275 // if disabled or zero, we won't do any checks nor head requests.
1276 if ($calctimeout && $bitrate > 0) {
1277 //setup header request only options
1278 curl_setopt_array ($ch, array(
1279 CURLOPT_RETURNTRANSFER => false,
1280 CURLOPT_NOBODY => true)
1284 $info = curl_getinfo($ch);
1285 $err = curl_error($ch);
1287 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1288 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1290 //reinstate affected curl options
1291 curl_setopt_array ($ch, array(
1292 CURLOPT_RETURNTRANSFER => true,
1293 CURLOPT_NOBODY => false)
1297 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1298 $result = curl_exec($ch);
1300 // try to detect encoding problems
1301 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1302 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1303 $result = curl_exec($ch);
1306 if ($received->fh) {
1307 fclose($received->fh);
1310 if (curl_errno($ch)) {
1311 $error = curl_error($ch);
1312 $error_no = curl_errno($ch);
1315 if ($fullresponse) {
1316 $response = new stdClass();
1317 if ($error_no == 28) {
1318 $response->status = '-100'; // mimic snoopy
1320 $response->status = '0';
1322 $response->headers = array();
1323 $response->response_code = $error;
1324 $response->results = false;
1325 $response->error = $error;
1328 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1333 $info = curl_getinfo($ch);
1336 if (empty($info['http_code'])) {
1337 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1338 $response = new stdClass();
1339 $response->status = '0';
1340 $response->headers = array();
1341 $response->response_code = 'Unknown cURL error';
1342 $response->results = false; // do NOT change this, we really want to ignore the result!
1343 $response->error = 'Unknown cURL error';
1346 $response = new stdClass();
1347 $response->status = (string)$info['http_code'];
1348 $response->headers = $received->headers;
1349 $response->response_code = $received->headers[0];
1350 $response->results = $result;
1351 $response->error = '';
1354 if ($fullresponse) {
1356 } else if ($info['http_code'] != 200) {
1357 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1360 return $response->results;
1366 * internal implementation
1367 * @param stdClass $received
1368 * @param resource $ch
1369 * @param mixed $header
1370 * @return int header length
1372 function download_file_content_header_handler($received, $ch, $header) {
1373 $received->headers[] = $header;
1374 return strlen($header);
1378 * internal implementation
1379 * @param stdClass $received
1380 * @param resource $ch
1381 * @param mixed $data
1383 function download_file_content_write_handler($received, $ch, $data) {
1384 if (!$received->fh) {
1385 $received->fh = fopen($received->tofile, 'w');
1386 if ($received->fh === false) {
1387 // bad luck, file creation or overriding failed
1391 if (fwrite($received->fh, $data) === false) {
1392 // bad luck, write failed, let's abort completely
1395 return strlen($data);
1399 * Returns a list of information about file types based on extensions.
1401 * The following elements expected in value array for each extension:
1403 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1404 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1405 * also files with bigger sizes under names
1406 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1407 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1408 * commonly used in moodle the following groups:
1409 * - web_image - image that can be included as <img> in HTML
1410 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1411 * - video - file that can be imported as video in text editor
1412 * - audio - file that can be imported as audio in text editor
1413 * - archive - we can extract files from this archive
1414 * - spreadsheet - used for portfolio format
1415 * - document - used for portfolio format
1416 * - presentation - used for portfolio format
1417 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1418 * human-readable description for this filetype;
1419 * Function {@link get_mimetype_description()} first looks at the presence of string for
1420 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1421 * attribute, if not found returns the value of 'type';
1422 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1423 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1424 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1427 * @return array List of information about file types based on extensions.
1428 * Associative array of extension (lower-case) to associative array
1429 * from 'element name' to data. Current element names are 'type' and 'icon'.
1430 * Unknown types should use the 'xxx' entry which includes defaults.
1432 function &get_mimetypes_array() {
1433 static $mimearray = array (
1434 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1435 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1436 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1437 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1438 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1439 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1440 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1441 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1442 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1443 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1444 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1445 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1446 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1447 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1448 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1449 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1450 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1451 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1452 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1453 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1454 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1455 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1457 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1458 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1459 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1460 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1461 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1463 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1464 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1465 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1466 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1467 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1468 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1469 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1470 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1471 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1473 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1474 'galleryitem,' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1475 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1476 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1477 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1478 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1479 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1480 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1481 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1482 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1483 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1484 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1485 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1486 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1487 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1488 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1489 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1490 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1491 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1492 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1493 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1494 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1495 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1496 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1497 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1498 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1499 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1500 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1501 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1502 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1503 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1504 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1505 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1506 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1507 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1508 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1509 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1510 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1511 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1512 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1513 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1514 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1515 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1516 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1517 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1519 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1520 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1522 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1523 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1524 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1525 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1526 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1527 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1528 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1529 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1530 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1531 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1532 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1533 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1534 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1535 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1536 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1537 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1538 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1540 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1541 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1542 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1543 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1544 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1545 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1547 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1548 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1549 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1550 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1551 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1552 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1553 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1554 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1555 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1557 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1558 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1559 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1560 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1561 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1562 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1563 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1564 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1565 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1566 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1567 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1568 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1569 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1570 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1571 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1572 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1573 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1574 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1575 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1576 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1578 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1579 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1580 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1581 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1582 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1583 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1584 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1585 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1586 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1587 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1589 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1590 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1591 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1592 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1593 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1594 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1595 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1596 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1597 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1598 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1599 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1600 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1602 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1603 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1604 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1605 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1607 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1608 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1609 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1610 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1611 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1612 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1613 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1615 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1616 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1618 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1624 * Obtains information about a filetype based on its extension. Will
1625 * use a default if no information is present about that particular
1629 * @param string $element Desired information (usually 'icon'
1630 * for icon filename or 'type' for MIME type. Can also be
1631 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1632 * @param string $filename Filename we're looking up
1633 * @return string Requested piece of information from array
1635 function mimeinfo($element, $filename) {
1637 $mimeinfo = & get_mimetypes_array();
1638 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1640 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1641 if (empty($filetype)) {
1642 $filetype = 'xxx'; // file without extension
1644 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1645 $iconsize = max(array(16, (int)$iconsizematch[1]));
1646 $filenames = array($mimeinfo['xxx']['icon']);
1647 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1648 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1650 // find the file with the closest size, first search for specific icon then for default icon
1651 foreach ($filenames as $filename) {
1652 foreach ($iconpostfixes as $size => $postfix) {
1653 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1654 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1655 return $filename.$postfix;
1659 } else if (isset($mimeinfo[$filetype][$element])) {
1660 return $mimeinfo[$filetype][$element];
1661 } else if (isset($mimeinfo['xxx'][$element])) {
1662 return $mimeinfo['xxx'][$element]; // By default
1669 * Obtains information about a filetype based on the MIME type rather than
1670 * the other way around.
1673 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1674 * @param string $mimetype MIME type we're looking up
1675 * @return string Requested piece of information from array
1677 function mimeinfo_from_type($element, $mimetype) {
1678 /* array of cached mimetype->extension associations */
1679 static $cached = array();
1680 $mimeinfo = & get_mimetypes_array();
1682 if (!array_key_exists($mimetype, $cached)) {
1683 $cached[$mimetype] = null;
1684 foreach($mimeinfo as $filetype => $values) {
1685 if ($values['type'] == $mimetype) {
1686 if ($cached[$mimetype] === null) {
1687 $cached[$mimetype] = '.'.$filetype;
1689 if (!empty($values['defaulticon'])) {
1690 $cached[$mimetype] = '.'.$filetype;
1695 if (empty($cached[$mimetype])) {
1696 $cached[$mimetype] = '.xxx';
1699 if ($element === 'extension') {
1700 return $cached[$mimetype];
1702 return mimeinfo($element, $cached[$mimetype]);
1707 * Return the relative icon path for a given file
1711 * // $file - instance of stored_file or file_info
1712 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1713 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1717 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1720 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1721 * and $file->mimetype are expected)
1722 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1725 function file_file_icon($file, $size = null) {
1726 if (!is_object($file)) {
1727 $file = (object)$file;
1729 if (isset($file->filename)) {
1730 $filename = $file->filename;
1731 } else if (method_exists($file, 'get_filename')) {
1732 $filename = $file->get_filename();
1733 } else if (method_exists($file, 'get_visible_name')) {
1734 $filename = $file->get_visible_name();
1738 if (isset($file->mimetype)) {
1739 $mimetype = $file->mimetype;
1740 } else if (method_exists($file, 'get_mimetype')) {
1741 $mimetype = $file->get_mimetype();
1745 $mimetypes = &get_mimetypes_array();
1747 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1748 if ($extension && !empty($mimetypes[$extension])) {
1749 // if file name has known extension, return icon for this extension
1750 return file_extension_icon($filename, $size);
1753 return file_mimetype_icon($mimetype, $size);
1757 * Return the relative icon path for a folder image
1761 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1762 * echo html_writer::empty_tag('img', array('src' => $icon));
1766 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1769 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1772 function file_folder_icon($iconsize = null) {
1774 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1775 static $cached = array();
1776 $iconsize = max(array(16, (int)$iconsize));
1777 if (!array_key_exists($iconsize, $cached)) {
1778 foreach ($iconpostfixes as $size => $postfix) {
1779 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1780 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1781 $cached[$iconsize] = 'f/folder'.$postfix;
1786 return $cached[$iconsize];
1790 * Returns the relative icon path for a given mime type
1792 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1793 * a return the full path to an icon.
1796 * $mimetype = 'image/jpg';
1797 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1798 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1802 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1803 * to conform with that.
1804 * @param string $mimetype The mimetype to fetch an icon for
1805 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1806 * @return string The relative path to the icon
1808 function file_mimetype_icon($mimetype, $size = NULL) {
1809 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1813 * Returns the relative icon path for a given file name
1815 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1816 * a return the full path to an icon.
1819 * $filename = '.jpg';
1820 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1821 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1824 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1825 * to conform with that.
1826 * @todo MDL-31074 Implement $size
1828 * @param string $filename The filename to get the icon for
1829 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1832 function file_extension_icon($filename, $size = NULL) {
1833 return 'f/'.mimeinfo('icon'.$size, $filename);
1837 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1838 * mimetypes.php language file.
1840 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1841 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1842 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1843 * @param bool $capitalise If true, capitalises first character of result
1844 * @return string Text description
1846 function get_mimetype_description($obj, $capitalise=false) {
1847 $filename = $mimetype = '';
1848 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1849 // this is an instance of stored_file
1850 $mimetype = $obj->get_mimetype();
1851 $filename = $obj->get_filename();
1852 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1853 // this is an instance of file_info
1854 $mimetype = $obj->get_mimetype();
1855 $filename = $obj->get_visible_name();
1856 } else if (is_array($obj) || is_object ($obj)) {
1858 if (!empty($obj['filename'])) {
1859 $filename = $obj['filename'];
1861 if (!empty($obj['mimetype'])) {
1862 $mimetype = $obj['mimetype'];
1867 $mimetypefromext = mimeinfo('type', $filename);
1868 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1869 // if file has a known extension, overwrite the specified mimetype
1870 $mimetype = $mimetypefromext;
1872 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1873 if (empty($extension)) {
1874 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1875 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1877 $mimetypestr = mimeinfo('string', $filename);
1879 $chunks = explode('/', $mimetype, 2);
1882 'mimetype' => $mimetype,
1883 'ext' => $extension,
1884 'mimetype1' => $chunks[0],
1885 'mimetype2' => $chunks[1],
1888 foreach ($attr as $key => $value) {
1890 $a[strtoupper($key)] = strtoupper($value);
1891 $a[ucfirst($key)] = ucfirst($value);
1894 // MIME types may include + symbol but this is not permitted in string ids.
1895 $safemimetype = str_replace('+', '_', $mimetype);
1896 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1897 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1898 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1899 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1900 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1901 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1902 $result = get_string('default', 'mimetypes', (object)$a);
1904 $result = $mimetype;
1907 $result=ucfirst($result);
1913 * Returns array of elements of type $element in type group(s)
1915 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1916 * @param string|array $groups one group or array of groups/extensions/mimetypes
1919 function file_get_typegroup($element, $groups) {
1920 static $cached = array();
1921 if (!is_array($groups)) {
1922 $groups = array($groups);
1924 if (!array_key_exists($element, $cached)) {
1925 $cached[$element] = array();
1928 foreach ($groups as $group) {
1929 if (!array_key_exists($group, $cached[$element])) {
1930 // retrieive and cache all elements of type $element for group $group
1931 $mimeinfo = & get_mimetypes_array();
1932 $cached[$element][$group] = array();
1933 foreach ($mimeinfo as $extension => $value) {
1934 $value['extension'] = '.'.$extension;
1935 if (empty($value[$element])) {
1938 if (($group === '.'.$extension || $group === $value['type'] ||
1939 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1940 !in_array($value[$element], $cached[$element][$group])) {
1941 $cached[$element][$group][] = $value[$element];
1945 $result = array_merge($result, $cached[$element][$group]);
1947 return array_unique($result);
1951 * Checks if file with name $filename has one of the extensions in groups $groups
1953 * @see get_mimetypes_array()
1954 * @param string $filename name of the file to check
1955 * @param string|array $groups one group or array of groups to check
1956 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1957 * file mimetype is in mimetypes in groups $groups
1960 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1961 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1962 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1965 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1969 * Checks if mimetype $mimetype belongs to one of the groups $groups
1971 * @see get_mimetypes_array()
1972 * @param string $mimetype
1973 * @param string|array $groups one group or array of groups to check
1976 function file_mimetype_in_typegroup($mimetype, $groups) {
1977 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1981 * Requested file is not found or not accessible, does not return, terminates script
1983 * @global stdClass $CFG
1984 * @global stdClass $COURSE
1986 function send_file_not_found() {
1987 global $CFG, $COURSE;
1989 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1992 * Helper function to send correct 404 for server.
1994 function send_header_404() {
1995 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1996 header("Status: 404 Not Found");
1998 header('HTTP/1.0 404 not found');
2003 * Enhanced readfile() with optional acceleration.
2004 * @param string|stored_file $file
2005 * @param string $mimetype
2006 * @param bool $accelerate
2009 function readfile_accel($file, $mimetype, $accelerate) {
2012 if ($mimetype === 'text/plain') {
2013 // there is no encoding specified in text files, we need something consistent
2014 header('Content-Type: text/plain; charset=utf-8');
2016 header('Content-Type: '.$mimetype);
2019 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2020 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2022 if (is_object($file)) {
2023 header('ETag: ' . $file->get_contenthash());
2024 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
2025 header('HTTP/1.1 304 Not Modified');
2030 // if etag present for stored file rely on it exclusively
2031 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2032 // get unixtime of request header; clip extra junk off first
2033 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2034 if ($since && $since >= $lastmodified) {
2035 header('HTTP/1.1 304 Not Modified');
2040 if ($accelerate and !empty($CFG->xsendfile)) {
2041 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2042 header('Accept-Ranges: bytes');
2044 header('Accept-Ranges: none');
2047 if (is_object($file)) {
2048 $fs = get_file_storage();
2049 if ($fs->xsendfile($file->get_contenthash())) {
2054 require_once("$CFG->libdir/xsendfilelib.php");
2055 if (xsendfile($file)) {
2061 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2063 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2065 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2066 header('Accept-Ranges: bytes');
2068 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2069 // byteserving stuff - for acrobat reader and download accelerators
2070 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2071 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2073 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2074 foreach ($ranges as $key=>$value) {
2075 if ($ranges[$key][1] == '') {
2077 $ranges[$key][1] = $filesize - $ranges[$key][2];
2078 $ranges[$key][2] = $filesize - 1;
2079 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2081 $ranges[$key][2] = $filesize - 1;
2083 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2084 //invalid byte-range ==> ignore header
2088 //prepare multipart header
2089 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2090 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2096 if (is_object($file)) {
2097 $handle = $file->get_content_file_handle();
2099 $handle = fopen($file, 'rb');
2101 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2106 header('Accept-Ranges: none');
2109 header('Content-Length: '.$filesize);
2111 if ($filesize > 10000000) {
2112 // for large files try to flush and close all buffers to conserve memory
2113 while(@ob_get_level()) {
2114 if (!@ob_end_flush()) {
2120 // send the whole file content
2121 if (is_object($file)) {
2129 * Similar to readfile_accel() but designed for strings.
2130 * @param string $string
2131 * @param string $mimetype
2132 * @param bool $accelerate
2135 function readstring_accel($string, $mimetype, $accelerate) {
2138 if ($mimetype === 'text/plain') {
2139 // there is no encoding specified in text files, we need something consistent
2140 header('Content-Type: text/plain; charset=utf-8');
2142 header('Content-Type: '.$mimetype);
2144 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2145 header('Accept-Ranges: none');
2147 if ($accelerate and !empty($CFG->xsendfile)) {
2148 $fs = get_file_storage();
2149 if ($fs->xsendfile(sha1($string))) {
2154 header('Content-Length: '.strlen($string));
2159 * Handles the sending of temporary file to user, download is forced.
2160 * File is deleted after abort or successful sending, does not return, script terminated
2162 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2163 * @param string $filename proposed file name when saving file
2164 * @param bool $pathisstring If the path is string
2166 function send_temp_file($path, $filename, $pathisstring=false) {
2169 if (check_browser_version('Firefox', '1.5')) {
2170 // only FF is known to correctly save to disk before opening...
2171 $mimetype = mimeinfo('type', $filename);
2173 $mimetype = 'application/x-forcedownload';
2176 // close session - not needed anymore
2177 session_get_instance()->write_close();
2179 if (!$pathisstring) {
2180 if (!file_exists($path)) {
2182 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2184 // executed after normal finish or abort
2185 @register_shutdown_function('send_temp_file_finished', $path);
2188 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2189 if (check_browser_version('MSIE')) {
2190 $filename = urlencode($filename);
2193 header('Content-Disposition: attachment; filename="'.$filename.'"');
2194 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2195 header('Cache-Control: max-age=10');
2196 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2198 } else { //normal http - prevent caching at all cost
2199 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2200 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2201 header('Pragma: no-cache');
2204 // send the contents - we can not accelerate this because the file will be deleted asap
2205 if ($pathisstring) {
2206 readstring_accel($path, $mimetype, false);
2208 readfile_accel($path, $mimetype, false);
2212 die; //no more chars to output
2216 * Internal callback function used by send_temp_file()
2218 * @param string $path
2220 function send_temp_file_finished($path) {
2221 if (file_exists($path)) {
2227 * Handles the sending of file data to the user's browser, including support for
2231 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2232 * @param string $filename Filename to send
2233 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2234 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2235 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2236 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2237 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2238 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2239 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2240 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2241 * and should not be reopened.
2242 * @return null script execution stopped unless $dontdie is true
2244 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2245 global $CFG, $COURSE;
2248 ignore_user_abort(true);
2251 // MDL-11789, apply $CFG->filelifetime here
2252 if ($lifetime === 'default') {
2253 if (!empty($CFG->filelifetime)) {
2254 $lifetime = $CFG->filelifetime;
2260 session_get_instance()->write_close(); // unlock session during fileserving
2262 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2263 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2264 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2265 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2266 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2267 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2269 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2270 if (check_browser_version('MSIE')) {
2271 $filename = rawurlencode($filename);
2274 if ($forcedownload) {
2275 header('Content-Disposition: attachment; filename="'.$filename.'"');
2277 header('Content-Disposition: inline; filename="'.$filename.'"');
2280 if ($lifetime > 0) {
2281 $nobyteserving = false;
2282 header('Cache-Control: max-age='.$lifetime);
2283 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2286 } else { // Do not cache files in proxies and browsers
2287 $nobyteserving = true;
2288 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2289 header('Cache-Control: max-age=10');
2290 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2292 } else { //normal http - prevent caching at all cost
2293 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2294 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2295 header('Pragma: no-cache');
2299 if (empty($filter)) {
2300 // send the contents
2301 if ($pathisstring) {
2302 readstring_accel($path, $mimetype, !$dontdie);
2304 readfile_accel($path, $mimetype, !$dontdie);
2308 // Try to put the file through filters
2309 if ($mimetype == 'text/html') {
2310 $options = new stdClass();
2311 $options->noclean = true;
2312 $options->nocache = true; // temporary workaround for MDL-5136
2313 $text = $pathisstring ? $path : implode('', file($path));
2315 $text = file_modify_html_header($text);
2316 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2318 readstring_accel($output, $mimetype, false);
2320 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2321 // only filter text if filter all files is selected
2322 $options = new stdClass();
2323 $options->newlines = false;
2324 $options->noclean = true;
2325 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2326 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2328 readstring_accel($output, $mimetype, false);
2331 // send the contents
2332 if ($pathisstring) {
2333 readstring_accel($path, $mimetype, !$dontdie);
2335 readfile_accel($path, $mimetype, !$dontdie);
2342 die; //no more chars to output!!!
2346 * Handles the sending of file data to the user's browser, including support for
2349 * The $options parameter supports the following keys:
2350 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2351 * (string|null) filename - overrides the implicit filename
2352 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2353 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2354 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2355 * and should not be reopened.
2358 * @param stored_file $stored_file local file object
2359 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2360 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2361 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2362 * @param array $options additional options affecting the file serving
2363 * @return null script execution stopped unless $options['dontdie'] is true
2365 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2366 global $CFG, $COURSE;
2368 if (empty($options['filename'])) {
2371 $filename = $options['filename'];
2374 if (empty($options['dontdie'])) {
2380 if (!empty($options['preview'])) {
2381 // replace the file with its preview
2382 $fs = get_file_storage();
2383 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2384 if (!$preview_file) {
2385 // unable to create a preview of the file, send its default mime icon instead
2386 if ($options['preview'] === 'tinyicon') {
2388 } else if ($options['preview'] === 'thumb') {
2393 $fileicon = file_file_icon($stored_file, $size);
2394 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2396 // preview images have fixed cache lifetime and they ignore forced download
2397 // (they are generated by GD and therefore they are considered reasonably safe).
2398 $stored_file = $preview_file;
2399 $lifetime = DAYSECS;
2401 $forcedownload = false;
2405 // handle external resource
2406 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2407 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2411 if (!$stored_file or $stored_file->is_directory()) {
2420 ignore_user_abort(true);
2423 session_get_instance()->write_close(); // unlock session during fileserving
2425 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2426 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2427 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2428 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2429 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2430 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2431 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2433 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2434 if (check_browser_version('MSIE')) {
2435 $filename = rawurlencode($filename);
2438 if ($forcedownload) {
2439 header('Content-Disposition: attachment; filename="'.$filename.'"');
2441 header('Content-Disposition: inline; filename="'.$filename.'"');
2444 if ($lifetime > 0) {
2445 header('Cache-Control: max-age='.$lifetime);
2446 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2449 } else { // Do not cache files in proxies and browsers
2450 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2451 header('Cache-Control: max-age=10');
2452 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2454 } else { //normal http - prevent caching at all cost
2455 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2456 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2457 header('Pragma: no-cache');
2461 if (empty($filter)) {
2462 // send the contents
2463 readfile_accel($stored_file, $mimetype, !$dontdie);
2465 } else { // Try to put the file through filters
2466 if ($mimetype == 'text/html') {
2467 $options = new stdClass();
2468 $options->noclean = true;
2469 $options->nocache = true; // temporary workaround for MDL-5136
2470 $text = $stored_file->get_content();
2471 $text = file_modify_html_header($text);
2472 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2474 readstring_accel($output, $mimetype, false);
2476 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2477 // only filter text if filter all files is selected
2478 $options = new stdClass();
2479 $options->newlines = false;
2480 $options->noclean = true;
2481 $text = $stored_file->get_content();
2482 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2484 readstring_accel($output, $mimetype, false);
2486 } else { // Just send it out raw
2487 readfile_accel($stored_file, $mimetype, !$dontdie);
2493 die; //no more chars to output!!!
2497 * Retrieves an array of records from a CSV file and places
2498 * them into a given table structure
2500 * @global stdClass $CFG
2501 * @global moodle_database $DB
2502 * @param string $file The path to a CSV file
2503 * @param string $table The table to retrieve columns from
2504 * @return bool|array Returns an array of CSV records or false
2506 function get_records_csv($file, $table) {
2509 if (!$metacolumns = $DB->get_columns($table)) {
2513 if(!($handle = @fopen($file, 'r'))) {
2514 print_error('get_records_csv failed to open '.$file);
2517 $fieldnames = fgetcsv($handle, 4096);
2518 if(empty($fieldnames)) {
2525 foreach($metacolumns as $metacolumn) {
2526 $ord = array_search($metacolumn->name, $fieldnames);
2528 $columns[$metacolumn->name] = $ord;
2534 while (($data = fgetcsv($handle, 4096)) !== false) {
2535 $item = new stdClass;
2536 foreach($columns as $name => $ord) {
2537 $item->$name = $data[$ord];
2547 * Create a file with CSV contents
2549 * @global stdClass $CFG
2550 * @global moodle_database $DB
2551 * @param string $file The file to put the CSV content into
2552 * @param array $records An array of records to write to a CSV file
2553 * @param string $table The table to get columns from
2554 * @return bool success
2556 function put_records_csv($file, $records, $table = NULL) {
2559 if (empty($records)) {
2563 $metacolumns = NULL;
2564 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2570 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2571 print_error('put_records_csv failed to open '.$file);
2574 $proto = reset($records);
2575 if(is_object($proto)) {
2576 $fields_records = array_keys(get_object_vars($proto));
2578 else if(is_array($proto)) {
2579 $fields_records = array_keys($proto);
2586 if(!empty($metacolumns)) {
2587 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2588 $fields = array_intersect($fields_records, $fields_table);
2591 $fields = $fields_records;
2594 fwrite($fp, implode(',', $fields));
2595 fwrite($fp, "\r\n");
2597 foreach($records as $record) {
2598 $array = (array)$record;
2600 foreach($fields as $field) {
2601 if(strpos($array[$field], ',')) {
2602 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2605 $values[] = $array[$field];
2608 fwrite($fp, implode(',', $values)."\r\n");
2617 * Recursively delete the file or folder with path $location. That is,
2618 * if it is a file delete it. If it is a folder, delete all its content
2619 * then delete it. If $location does not exist to start, that is not
2620 * considered an error.
2622 * @param string $location the path to remove.
2625 function fulldelete($location) {
2626 if (empty($location)) {
2627 // extra safety against wrong param
2630 if (is_dir($location)) {
2631 if (!$currdir = opendir($location)) {
2634 while (false !== ($file = readdir($currdir))) {
2635 if ($file <> ".." && $file <> ".") {
2636 $fullfile = $location."/".$file;
2637 if (is_dir($fullfile)) {
2638 if (!fulldelete($fullfile)) {
2642 if (!unlink($fullfile)) {
2649 if (! rmdir($location)) {
2653 } else if (file_exists($location)) {
2654 if (!unlink($location)) {
2662 * Send requested byterange of file.
2664 * @param resource $handle A file handle
2665 * @param string $mimetype The mimetype for the output
2666 * @param array $ranges An array of ranges to send
2667 * @param string $filesize The size of the content if only one range is used
2669 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2670 // better turn off any kind of compression and buffering
2671 @ini_set('zlib.output_compression', 'Off');
2673 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2674 if ($handle === false) {
2677 if (count($ranges) == 1) { //only one range requested
2678 $length = $ranges[0][2] - $ranges[0][1] + 1;
2679 header('HTTP/1.1 206 Partial content');
2680 header('Content-Length: '.$length);
2681 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2682 header('Content-Type: '.$mimetype);
2684 while(@ob_get_level()) {
2685 if (!@ob_end_flush()) {
2690 fseek($handle, $ranges[0][1]);
2691 while (!feof($handle) && $length > 0) {
2692 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2693 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2696 $length -= strlen($buffer);
2700 } else { // multiple ranges requested - not tested much
2702 foreach($ranges as $range) {
2703 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2705 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2706 header('HTTP/1.1 206 Partial content');
2707 header('Content-Length: '.$totallength);
2708 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2710 while(@ob_get_level()) {
2711 if (!@ob_end_flush()) {
2716 foreach($ranges as $range) {
2717 $length = $range[2] - $range[1] + 1;
2719 fseek($handle, $range[1]);
2720 while (!feof($handle) && $length > 0) {
2721 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2722 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2725 $length -= strlen($buffer);
2728 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2735 * add includes (js and css) into uploaded files
2736 * before returning them, useful for themes and utf.js includes
2738 * @global stdClass $CFG
2739 * @param string $text text to search and replace
2740 * @return string text with added head includes
2743 function file_modify_html_header($text) {
2744 // first look for <head> tag
2747 $stylesheetshtml = '';
2748 /* foreach ($CFG->stylesheets as $stylesheet) {
2750 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2754 if (filter_is_enabled('mediaplugin')) {
2755 // this script is needed by most media filter plugins.
2756 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2757 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2760 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2762 $replacement = '<head>'.$ufo.$stylesheetshtml;
2763 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2767 // if not, look for <html> tag, and stick <head> right after
2768 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2770 // replace <html> tag with <html><head>includes</head>
2771 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2772 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2776 // if not, look for <body> tag, and stick <head> before body
2777 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2779 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2780 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2784 // if not, just stick a <head> tag at the beginning
2785 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2790 * RESTful cURL class
2792 * This is a wrapper class for curl, it is quite easy to use:
2796 * $c = new curl(array('cache'=>true));
2798 * $c = new curl(array('cookie'=>true));
2800 * $c = new curl(array('proxy'=>true));
2802 * // HTTP GET Method
2803 * $html = $c->get('http://example.com');
2804 * // HTTP POST Method
2805 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2806 * // HTTP PUT Method
2807 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2810 * @package core_files
2812 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2813 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2816 /** @var bool Caches http request contents */
2817 public $cache = false;
2818 /** @var bool Uses proxy */
2819 public $proxy = false;
2820 /** @var string library version */
2821 public $version = '0.4 dev';
2822 /** @var array http's response */
2823 public $response = array();
2824 /** @var array http header */
2825 public $header = array();
2826 /** @var string cURL information */
2828 /** @var string error */
2830 /** @var int error code */
2833 /** @var array cURL options */
2835 /** @var string Proxy host */
2836 private $proxy_host = '';
2837 /** @var string Proxy auth */
2838 private $proxy_auth = '';
2839 /** @var string Proxy type */
2840 private $proxy_type = '';
2841 /** @var bool Debug mode on */
2842 private $debug = false;
2843 /** @var bool|string Path to cookie file */
2844 private $cookie = false;
2849 * @global stdClass $CFG
2850 * @param array $options
2852 public function __construct($options = array()){
2854 if (!function_exists('curl_init')) {
2855 $this->error = 'cURL module must be enabled!';
2856 trigger_error($this->error, E_USER_ERROR);
2859 // the options of curl should be init here.
2861 if (!empty($options['debug'])) {
2862 $this->debug = true;
2864 if(!empty($options['cookie'])) {
2865 if($options['cookie'] === true) {
2866 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2868 $this->cookie = $options['cookie'];
2871 if (!empty($options['cache'])) {
2872 if (class_exists('curl_cache')) {
2873 if (!empty($options['module_cache'])) {
2874 $this->cache = new curl_cache($options['module_cache']);
2876 $this->cache = new curl_cache('misc');
2880 if (!empty($CFG->proxyhost)) {
2881 if (empty($CFG->proxyport)) {
2882 $this->proxy_host = $CFG->proxyhost;
2884 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2886 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2887 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2888 $this->setopt(array(
2889 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2890 'proxyuserpwd'=>$this->proxy_auth));
2892 if (!empty($CFG->proxytype)) {
2893 if ($CFG->proxytype == 'SOCKS5') {
2894 $this->proxy_type = CURLPROXY_SOCKS5;
2896 $this->proxy_type = CURLPROXY_HTTP;
2897 $this->setopt(array('httpproxytunnel'=>false));
2899 $this->setopt(array('proxytype'=>$this->proxy_type));
2902 if (!empty($this->proxy_host)) {
2903 $this->proxy = array('proxy'=>$this->proxy_host);
2907 * Resets the CURL options that have already been set
2909 public function resetopt(){
2910 $this->options = array();
2911 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2912 // True to include the header in the output
2913 $this->options['CURLOPT_HEADER'] = 0;
2914 // True to Exclude the body from the output
2915 $this->options['CURLOPT_NOBODY'] = 0;
2916 // TRUE to follow any "Location: " header that the server
2917 // sends as part of the HTTP header (note this is recursive,
2918 // PHP will follow as many "Location: " headers that it is sent,
2919 // unless CURLOPT_MAXREDIRS is set).
2920 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2921 $this->options['CURLOPT_MAXREDIRS'] = 10;
2922 $this->options['CURLOPT_ENCODING'] = '';
2923 // TRUE to return the transfer as a string of the return
2924 // value of curl_exec() instead of outputting it out directly.
2925 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2926 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2927 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2928 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2929 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2935 public function resetcookie() {
2936 if (!empty($this->cookie)) {
2937 if (is_file($this->cookie)) {
2938 $fp = fopen($this->cookie, 'w');
2950 * Do not use the curl constants to define the options, pass a string
2951 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2952 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2954 * @param array $options If array is null, this function will reset the options to default value.
2956 * @throws coding_exception If an option uses constant value instead of option name.
2958 public function setopt($options = array()) {
2959 if (is_array($options)) {
2960 foreach ($options as $name => $val){
2961 if (!is_string($name)) {
2962 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2964 if (stripos($name, 'CURLOPT_') === false) {
2965 $name = strtoupper('CURLOPT_'.$name);
2967 $this->options[$name] = $val;
2975 public function cleanopt(){
2976 unset($this->options['CURLOPT_HTTPGET']);
2977 unset($this->options['CURLOPT_POST']);
2978 unset($this->options['CURLOPT_POSTFIELDS']);
2979 unset($this->options['CURLOPT_PUT']);
2980 unset($this->options['CURLOPT_INFILE']);
2981 unset($this->options['CURLOPT_INFILESIZE']);
2982 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2983 unset($this->options['CURLOPT_FILE']);
2987 * Resets the HTTP Request headers (to prepare for the new request)
2989 public function resetHeader() {
2990 $this->header = array();
2994 * Set HTTP Request Header
2996 * @param array $header
2998 public function setHeader($header) {
2999 if (is_array($header)){
3000 foreach ($header as $v) {
3001 $this->setHeader($v);
3004 $this->header[] = $header;
3009 * Set HTTP Response Header
3012 public function getResponse(){
3013 return $this->response;
3017 * private callback function
3018 * Formatting HTTP Response Header
3020 * @param resource $ch Apparently not used
3021 * @param string $header
3022 * @return int The strlen of the header
3024 private function formatHeader($ch, $header)
3027 if (strlen($header) > 2) {
3028 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3029 $key = rtrim($key, ':');
3030 if (!empty($this->response[$key])) {
3031 if (is_array($this->response[$key])){
3032 $this->response[$key][] = $value;
3034 $tmp = $this->response[$key];
3035 $this->response[$key] = array();
3036 $this->response[$key][] = $tmp;
3037 $this->response[$key][] = $value;
3041 $this->response[$key] = $value;
3044 return strlen($header);
3048 * Set options for individual curl instance
3050 * @param resource $curl A curl handle
3051 * @param array $options
3052 * @return resource The curl handle
3054 private function apply_opt($curl, $options) {
3058 if (!empty($this->cookie) || !empty($options['cookie'])) {
3059 $this->setopt(array('cookiejar'=>$this->cookie,
3060 'cookiefile'=>$this->cookie
3065 if (!empty($this->proxy) || !empty($options['proxy'])) {
3066 $this->setopt($this->proxy);
3068 $this->setopt($options);
3069 // reset before set options
3070 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3072 if (empty($this->header)){
3073 $this->setHeader(array(
3074 'User-Agent: MoodleBot/1.0',
3075 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3076 'Connection: keep-alive'
3079 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3082 echo '<h1>Options</h1>';
3083 var_dump($this->options);
3084 echo '<h1>Header</h1>';
3085 var_dump($this->header);
3089 foreach($this->options as $name => $val) {
3090 $name = constant(strtoupper($name));
3091 curl_setopt($curl, $name, $val);
3097 * Download multiple files in parallel
3099 * Calls {@link multi()} with specific download headers
3103 * $file1 = fopen('a', 'wb');
3104 * $file2 = fopen('b', 'wb');
3105 * $c->download(array(
3106 * array('url'=>'http://localhost/', 'file'=>$file1),
3107 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3117 * $c->download(array(
3118 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3119 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3123 * @param array $requests An array of files to request {
3124 * url => url to download the file [required]
3125 * file => file handler, or
3126 * filepath => file path
3128 * If 'file' and 'filepath' parameters are both specified in one request, the
3129 * open file handle in the 'file' parameter will take precedence and 'filepath'
3132 * @param array $options An array of options to set
3133 * @return array An array of results
3135 public function download($requests, $options = array()) {
3136 $options['CURLOPT_BINARYTRANSFER'] = 1;
3137 $options['RETURNTRANSFER'] = false;
3138 return $this->multi($requests, $options);
3142 * Mulit HTTP Requests
3143 * This function could run multi-requests in parallel.
3145 * @param array $requests An array of files to request
3146 * @param array $options An array of options to set
3147 * @return array An array of results
3149 protected function multi($requests, $options = array()) {
3150 $count = count($requests);
3153 $main = curl_multi_init();
3154 for ($i = 0; $i < $count; $i++) {
3155 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3157 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3158 $requests[$i]['auto-handle'] = true;
3160 foreach($requests[$i] as $n=>$v){
3163 $handles[$i] = curl_init($requests[$i]['url']);
3164 $this->apply_opt($handles[$i], $options);
3165 curl_multi_add_handle($main, $handles[$i]);
3169 curl_multi_exec($main, $running);
3170 } while($running > 0);
3171 for ($i = 0; $i < $count; $i++) {
3172 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3175 $results[] = curl_multi_getcontent($handles[$i]);
3177 curl_multi_remove_handle($main, $handles[$i]);
3179 curl_multi_close($main);
3181 for ($i = 0; $i < $count; $i++) {
3182 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3183 // close file handler if file is opened in this function
3184 fclose($requests[$i]['file']);
3191 * Single HTTP Request
3193 * @param string $url The URL to request
3194 * @param array $options
3197 protected function request($url, $options = array()){
3198 // create curl instance
3199 $curl = curl_init($url);
3200 $options['url'] = $url;
3201 $this->apply_opt($curl, $options);
3202 if ($this->cache && $ret = $this->cache->get($this->options)) {
3205 $ret = curl_exec($curl);
3207 $this->cache->set($this->options, $ret);
3211 $this->info = curl_getinfo($curl);
3212 $this->error = curl_error($curl);
3213 $this->errno = curl_errno($curl);
3216 echo '<h1>Return Data</h1>';
3218 echo '<h1>Info</h1>';
3219 var_dump($this->info);
3220 echo '<h1>Error</h1>';
3221 var_dump($this->error);
3226 if (empty($this->error)){
3229 return $this->error;
3230 // exception is not ajax friendly
3231 //throw new moodle_exception($this->error, 'curl');
3240 * @param string $url
3241 * @param array $options
3244 public function head($url, $options = array()){
3245 $options['CURLOPT_HTTPGET'] = 0;
3246 $options['CURLOPT_HEADER'] = 1;
3247 $options['CURLOPT_NOBODY'] = 1;
3248 return $this->request($url, $options);
3254 * @param string $url
3255 * @param array|string $params
3256 * @param array $options
3259 public function post($url, $params = '', $options = array()){
3260 $options['CURLOPT_POST'] = 1;
3261 if (is_array($params)) {
3262 $this->_tmp_file_post_params = array();
3263 foreach ($params as $key => $value) {
3264 if ($value instanceof stored_file) {
3265 $value->add_to_curl_request($this, $key);
3267 $this->_tmp_file_post_params[$key] = $value;
3270 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3271 unset($this->_tmp_file_post_params);
3273 // $params is the raw post data
3274 $options['CURLOPT_POSTFIELDS'] = $params;
3276 return $this->request($url, $options);
3282 * @param string $url
3283 * @param array $params
3284 * @param array $options
3287 public function get($url, $params = array(), $options = array()){
3288 $options['CURLOPT_HTTPGET'] = 1;
3290 if (!empty($params)){
3291 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3292 $url .= http_build_query($params, '', '&');
3294 return $this->request($url, $options);
3298 * Downloads one file and writes it to the specified file handler
3302 * $file = fopen('savepath', 'w');
3303 * $result = $c->download_one('http://localhost/', null,
3304 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3306 * $download_info = $c->get_info();
3307 * if ($result === true) {
3308 * // file downloaded successfully
3310 * $error_text = $result;
3311 * $error_code = $c->get_errno();
3317 * $result = $c->download_one('http://localhost/', null,
3318 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3319 * // ... see above, no need to close handle and remove file if unsuccessful
3322 * @param string $url
3323 * @param array|null $params key-value pairs to be added to $url as query string
3324 * @param array $options request options. Must include either 'file' or 'filepath'
3325 * @return bool|string true on success or error string on failure
3327 public function download_one($url, $params, $options = array()) {
3328 $options['CURLOPT_HTTPGET'] = 1;
3329 $options['CURLOPT_BINARYTRANSFER'] = true;
3330 if (!empty($params)){
3331 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3332 $url .= http_build_query($params, '', '&');
3334 if (!empty($options['filepath']) && empty($options['file'])) {
3336 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3338 return get_string('cannotwritefile', 'error', $options['filepath']);
3340 $filepath = $options['filepath'];
3342 unset($options['filepath']);
3343 $result = $this->request($url, $options);
3344 if (isset($filepath)) {
3345 fclose($options['file']);
3346 if ($result !== true) {
3356 * @param string $url
3357 * @param array $params
3358 * @param array $options
3361 public function put($url, $params = array(), $options = array()){
3362 $file = $params['file'];
3363 if (!is_file($file)){
3366 $fp = fopen($file, 'r');
3367 $size = filesize($file);
3368 $options['CURLOPT_PUT'] = 1;
3369 $options['CURLOPT_INFILESIZE'] = $size;
3370 $options['CURLOPT_INFILE'] = $fp;
3371 if (!isset($this->options['CURLOPT_USERPWD'])){
3372 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3374 $ret = $this->request($url, $options);
3380 * HTTP DELETE method
3382 * @param string $url
3383 * @param array $param
3384 * @param array $options
3387 public function delete($url, $param = array(), $options = array()){
3388 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3389 if (!isset($options['CURLOPT_USERPWD'])) {
3390 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3392 $ret = $this->request($url, $options);
3399 * @param string $url
3400 * @param array $options
3403 public function trace($url, $options = array()){
3404 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3405 $ret = $this->request($url, $options);
3410 * HTTP OPTIONS method
3412 * @param string $url
3413 * @param array $options
3416 public function options($url, $options = array()){
3417 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3418 $ret = $this->request($url, $options);
3423 * Get curl information
3427 public function get_info() {
3432 * Get curl error code
3436 public function get_errno() {
3437 return $this->errno;
3442 * This class is used by cURL class, use case:
3445 * $CFG->repositorycacheexpire = 120;
3446 * $CFG->curlcache = 120;
3448 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3449 * $ret = $c->get('http://www.google.com');
3452 * @package core_files
3453 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3457 /** @var string Path to cache directory */
3463 * @global stdClass $CFG
3464 * @param string $module which module is using curl_cache
3466 public function __construct($module = 'repository') {
3468 if (!empty($module)) {
3469 $this->dir = $CFG->cachedir.'/'.$module.'/';
3471 $this->dir = $CFG->cachedir.'/misc/';
3473 if (!file_exists($this->dir)) {
3474 mkdir($this->dir, $CFG->directorypermissions, true);
3476 if ($module == 'repository') {
3477 if (empty($CFG->repositorycacheexpire)) {
3478 $CFG->repositorycacheexpire = 120;
3480 $this->ttl = $CFG->repositorycacheexpire;
3482 if (empty($CFG->curlcache)) {
3483 $CFG->curlcache = 120;
3485 $this->ttl = $CFG->curlcache;
3492 * @global stdClass $CFG
3493 * @global stdClass $USER
3494 * @param mixed $param
3495 * @return bool|string
3497 public function get($param) {
3499 $this->cleanup($this->ttl);
3500 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3501 if(file_exists($this->dir.$filename)) {
3502 $lasttime = filemtime($this->dir.$filename);
3503 if (time()-$lasttime > $this->ttl) {
3506 $fp = fopen($this->dir.$filename, 'r');
3507 $size = filesize($this->dir.$filename);
3508 $content = fread($fp, $size);
3509 return unserialize($content);
3518 * @global object $CFG
3519 * @global object $USER
3520 * @param mixed $param
3523 public function set($param, $val) {
3525 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3526 $fp = fopen($this->dir.$filename, 'w');
3527 fwrite($fp, serialize($val));
3532 * Remove cache files
3534 * @param int $expire The number of seconds before expiry
3536 public function cleanup($expire) {
3537 if ($dir = opendir($this->dir)) {
3538 while (false !== ($file = readdir($dir))) {
3539 if(!is_dir($file) && $file != '.' && $file != '..') {
3540 $lasttime = @filemtime($this->dir.$file);