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');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @todo MDL-31071 deprecate this function
43 * @global stdClass $CFG
44 * @param string $urlbase
45 * @param string $path /filearea/itemid/dir/dir/file.exe
46 * @param bool $forcedownload
47 * @param bool $https https url required
48 * @return string encoded file url
50 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
53 //TODO: deprecate this
55 if ($CFG->slasharguments) {
56 $parts = explode('/', $path);
57 $parts = array_map('rawurlencode', $parts);
58 $path = implode('/', $parts);
59 $return = $urlbase.$path;
61 $return .= '?forcedownload=1';
64 $path = rawurlencode($path);
65 $return = $urlbase.'?file='.$path;
67 $return .= '&forcedownload=1';
72 $return = str_replace('http://', 'https://', $return);
79 * Prepares 'editor' formslib element from data in database
81 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
82 * function then copies the embedded files into draft area (assigning itemids automatically),
83 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
85 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
86 * your mform's set_data() supplying the object returned by this function.
89 * @param stdClass $data database field that holds the html text with embedded media
90 * @param string $field the name of the database field that holds the html text with embedded media
91 * @param array $options editor options (like maxifiles, maxbytes etc.)
92 * @param stdClass $context context of the editor
93 * @param string $component
94 * @param string $filearea file area name
95 * @param int $itemid item id, required if item exists
96 * @return stdClass modified data object
98 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
99 $options = (array)$options;
100 if (!isset($options['trusttext'])) {
101 $options['trusttext'] = false;
103 if (!isset($options['forcehttps'])) {
104 $options['forcehttps'] = false;
106 if (!isset($options['subdirs'])) {
107 $options['subdirs'] = false;
109 if (!isset($options['maxfiles'])) {
110 $options['maxfiles'] = 0; // no files by default
112 if (!isset($options['noclean'])) {
113 $options['noclean'] = false;
116 //sanity check for passed context. This function doesn't expect $option['context'] to be set
117 //But this function is called before creating editor hence, this is one of the best places to check
118 //if context is used properly. This check notify developer that they missed passing context to editor.
119 if (isset($context) && !isset($options['context'])) {
120 //if $context is not null then make sure $option['context'] is also set.
121 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
122 } else if (isset($options['context']) && isset($context)) {
123 //If both are passed then they should be equal.
124 if ($options['context']->id != $context->id) {
125 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
126 throw new coding_exception($exceptionmsg);
130 if (is_null($itemid) or is_null($context)) {
134 $data = new stdClass();
136 if (!isset($data->{$field})) {
137 $data->{$field} = '';
139 if (!isset($data->{$field.'format'})) {
140 $data->{$field.'format'} = editors_get_preferred_format();
142 if (!$options['noclean']) {
143 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
147 if ($options['trusttext']) {
148 // noclean ignored if trusttext enabled
149 if (!isset($data->{$field.'trust'})) {
150 $data->{$field.'trust'} = 0;
152 $data = trusttext_pre_edit($data, $field, $context);
154 if (!$options['noclean']) {
155 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
158 $contextid = $context->id;
161 if ($options['maxfiles'] != 0) {
162 $draftid_editor = file_get_submitted_draft_itemid($field);
163 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
164 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
166 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
173 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
175 * This function moves files from draft area to the destination area and
176 * encodes URLs to the draft files so they can be safely saved into DB. The
177 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
178 * is the name of the database field to hold the wysiwyg editor content. The
179 * editor data comes as an array with text, format and itemid properties. This
180 * function automatically adds $data properties foobar, foobarformat and
181 * foobartrust, where foobar has URL to embedded files encoded.
184 * @param stdClass $data raw data submitted by the form
185 * @param string $field name of the database field containing the html with embedded media files
186 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
187 * @param stdClass $context context, required for existing data
188 * @param string $component file component
189 * @param string $filearea file area name
190 * @param int $itemid item id, required if item exists
191 * @return stdClass modified data object
193 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
194 $options = (array)$options;
195 if (!isset($options['trusttext'])) {
196 $options['trusttext'] = false;
198 if (!isset($options['forcehttps'])) {
199 $options['forcehttps'] = false;
201 if (!isset($options['subdirs'])) {
202 $options['subdirs'] = false;
204 if (!isset($options['maxfiles'])) {
205 $options['maxfiles'] = 0; // no files by default
207 if (!isset($options['maxbytes'])) {
208 $options['maxbytes'] = 0; // unlimited
211 if ($options['trusttext']) {
212 $data->{$field.'trust'} = trusttext_trusted($context);
214 $data->{$field.'trust'} = 0;
217 $editor = $data->{$field.'_editor'};
219 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
220 $data->{$field} = $editor['text'];
222 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
224 $data->{$field.'format'} = $editor['format'];
230 * Saves text and files modified by Editor formslib element
233 * @param stdClass $data $database entry field
234 * @param string $field name of data field
235 * @param array $options various options
236 * @param stdClass $context context - must already exist
237 * @param string $component
238 * @param string $filearea file area name
239 * @param int $itemid must already exist, usually means data is in db
240 * @return stdClass modified data obejct
242 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
243 $options = (array)$options;
244 if (!isset($options['subdirs'])) {
245 $options['subdirs'] = false;
247 if (is_null($itemid) or is_null($context)) {
251 $contextid = $context->id;
254 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
255 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
256 $data->{$field.'_filemanager'} = $draftid_editor;
262 * Saves files modified by File manager formslib element
264 * @todo MDL-31073 review this function
266 * @param stdClass $data $database entry field
267 * @param string $field name of data field
268 * @param array $options various options
269 * @param stdClass $context context - must already exist
270 * @param string $component
271 * @param string $filearea file area name
272 * @param int $itemid must already exist, usually means data is in db
273 * @return stdClass modified data obejct
275 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
276 $options = (array)$options;
277 if (!isset($options['subdirs'])) {
278 $options['subdirs'] = false;
280 if (!isset($options['maxfiles'])) {
281 $options['maxfiles'] = -1; // unlimited
283 if (!isset($options['maxbytes'])) {
284 $options['maxbytes'] = 0; // unlimited
287 if (empty($data->{$field.'_filemanager'})) {
291 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
292 $fs = get_file_storage();
294 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
295 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
305 * Generate a draft itemid
308 * @global moodle_database $DB
309 * @global stdClass $USER
310 * @return int a random but available draft itemid that can be used to create a new draft
313 function file_get_unused_draft_itemid() {
316 if (isguestuser() or !isloggedin()) {
317 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
318 print_error('noguest');
321 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
323 $fs = get_file_storage();
324 $draftitemid = rand(1, 999999999);
325 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
326 $draftitemid = rand(1, 999999999);
333 * Initialise a draft file area from a real one by copying the files. A draft
334 * area will be created if one does not already exist. Normally you should
335 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
338 * @global stdClass $CFG
339 * @global stdClass $USER
340 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
341 * @param int $contextid This parameter and the next two identify the file area to copy files from.
342 * @param string $component
343 * @param string $filearea helps indentify the file area.
344 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
345 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
346 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
347 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
349 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
350 global $CFG, $USER, $CFG;
352 $options = (array)$options;
353 if (!isset($options['subdirs'])) {
354 $options['subdirs'] = false;
356 if (!isset($options['forcehttps'])) {
357 $options['forcehttps'] = false;
360 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
361 $fs = get_file_storage();
363 if (empty($draftitemid)) {
364 // create a new area and copy existing files into
365 $draftitemid = file_get_unused_draft_itemid();
366 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
367 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
368 foreach ($files as $file) {
369 if ($file->is_directory() and $file->get_filepath() === '/') {
370 // we need a way to mark the age of each draft area,
371 // by not copying the root dir we force it to be created automatically with current timestamp
374 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
377 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
378 // XXX: This is a hack for file manager (MDL-28666)
379 // File manager needs to know the original file information before copying
380 // to draft area, so we append these information in mdl_files.source field
381 // {@link file_storage::search_references()}
382 // {@link file_storage::search_references_count()}
383 $sourcefield = $file->get_source();
384 $newsourcefield = new stdClass;
385 $newsourcefield->source = $sourcefield;
386 $original = new stdClass;
387 $original->contextid = $contextid;
388 $original->component = $component;
389 $original->filearea = $filearea;
390 $original->itemid = $itemid;
391 $original->filename = $file->get_filename();
392 $original->filepath = $file->get_filepath();
393 $newsourcefield->original = file_storage::pack_reference($original);
394 $draftfile->set_source(serialize($newsourcefield));
395 // End of file manager hack
398 if (!is_null($text)) {
399 // at this point there should not be any draftfile links yet,
400 // because this is a new text from database that should still contain the @@pluginfile@@ links
401 // this happens when developers forget to post process the text
402 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
408 if (is_null($text)) {
412 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
413 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
417 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
420 * @global stdClass $CFG
421 * @param string $text The content that may contain ULRs in need of rewriting.
422 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
423 * @param int $contextid This parameter and the next two identify the file area to use.
424 * @param string $component
425 * @param string $filearea helps identify the file area.
426 * @param int $itemid helps identify the file area.
427 * @param array $options text and file options ('forcehttps'=>false)
428 * @return string the processed text.
430 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
433 $options = (array)$options;
434 if (!isset($options['forcehttps'])) {
435 $options['forcehttps'] = false;
438 if (!$CFG->slasharguments) {
439 $file = $file . '?file=';
442 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
444 if ($itemid !== null) {
445 $baseurl .= "$itemid/";
448 if ($options['forcehttps']) {
449 $baseurl = str_replace('http://', 'https://', $baseurl);
452 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
456 * Returns information about files in a draft area.
458 * @global stdClass $CFG
459 * @global stdClass $USER
460 * @param int $draftitemid the draft area item id.
461 * @return array with the following entries:
462 * 'filecount' => number of files in the draft area.
463 * (more information will be added as needed).
465 function file_get_draft_area_info($draftitemid) {
468 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
469 $fs = get_file_storage();
473 // The number of files
474 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
475 $results['filecount'] = count($draftfiles);
476 $results['filesize'] = 0;
477 foreach ($draftfiles as $file) {
478 $results['filesize'] += $file->get_filesize();
485 * Get used space of files
486 * @global moodle_database $DB
487 * @global stdClass $USER
488 * @return int total bytes
490 function file_get_user_used_space() {
493 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
494 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
495 JOIN (SELECT contenthash, filename, MAX(id) AS id
497 WHERE contextid = ? AND component = ? AND filearea != ?
498 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
499 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
500 $record = $DB->get_record_sql($sql, $params);
501 return (int)$record->totalbytes;
505 * Convert any string to a valid filepath
506 * @todo review this function
508 * @return string path
510 function file_correct_filepath($str) { //TODO: what is this? (skodak)
511 if ($str == '/' or empty($str)) {
514 return '/'.trim($str, './@#$ ').'/';
519 * Generate a folder tree of draft area of current USER recursively
521 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
522 * @param int $draftitemid
523 * @param string $filepath
526 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
527 global $USER, $OUTPUT, $CFG;
528 $data->children = array();
529 $context = get_context_instance(CONTEXT_USER, $USER->id);
530 $fs = get_file_storage();
531 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
532 foreach ($files as $file) {
533 if ($file->is_directory()) {
534 $item = new stdClass();
535 $item->sortorder = $file->get_sortorder();
536 $item->filepath = $file->get_filepath();
538 $foldername = explode('/', trim($item->filepath, '/'));
539 $item->fullname = trim(array_pop($foldername), '/');
541 $item->id = uniqid();
542 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
543 $data->children[] = $item;
552 * Listing all files (including folders) in current path (draft area)
553 * used by file manager
554 * @param int $draftitemid
555 * @param string $filepath
558 function file_get_drafarea_files($draftitemid, $filepath = '/') {
559 global $USER, $OUTPUT, $CFG;
561 $context = get_context_instance(CONTEXT_USER, $USER->id);
562 $fs = get_file_storage();
564 $data = new stdClass();
565 $data->path = array();
566 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
568 // will be used to build breadcrumb
570 if ($filepath !== '/') {
571 $filepath = file_correct_filepath($filepath);
572 $parts = explode('/', $filepath);
573 foreach ($parts as $part) {
574 if ($part != '' && $part != null) {
575 $trail .= ($part.'/');
576 $data->path[] = array('name'=>$part, 'path'=>$trail);
583 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
584 foreach ($files as $file) {
585 $item = new stdClass();
586 $item->filename = $file->get_filename();
587 $item->filepath = $file->get_filepath();
588 $item->fullname = trim($item->filename, '/');
589 $filesize = $file->get_filesize();
590 $item->size = $filesize ? $filesize : null;
591 $item->filesize = $filesize ? display_size($filesize) : '';
593 $item->sortorder = $file->get_sortorder();
594 $item->author = $file->get_author();
595 $item->license = $file->get_license();
596 $item->datemodified = $file->get_timemodified();
597 $item->datecreated = $file->get_timecreated();
598 $item->isref = $file->is_external_file();
599 if ($item->isref && $file->get_status() == 666) {
600 $item->originalmissing = true;
602 // find the file this draft file was created from and count all references in local
603 // system pointing to that file
604 $source = @unserialize($file->get_source());
605 if (isset($source->original)) {
606 $item->refcount = $fs->search_references_count($source->original);
609 if ($file->is_directory()) {
611 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
612 $item->type = 'folder';
613 $foldername = explode('/', trim($item->filepath, '/'));
614 $item->fullname = trim(array_pop($foldername), '/');
615 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
617 // do NOT use file browser here!
618 $item->mimetype = get_mimetype_description($file);
619 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
622 $item->type = 'file';
624 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
625 $item->url = $itemurl->out();
626 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
627 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
628 if ($imageinfo = $file->get_imageinfo()) {
629 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
630 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
631 $item->image_width = $imageinfo['width'];
632 $item->image_height = $imageinfo['height'];
638 $data->itemid = $draftitemid;
644 * Returns draft area itemid for a given element.
647 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
648 * @return int the itemid, or 0 if there is not one yet.
650 function file_get_submitted_draft_itemid($elname) {
651 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
652 if (!isset($_REQUEST[$elname])) {
655 if (is_array($_REQUEST[$elname])) {
656 $param = optional_param_array($elname, 0, PARAM_INT);
657 if (!empty($param['itemid'])) {
658 $param = $param['itemid'];
660 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
665 $param = optional_param($elname, 0, PARAM_INT);
676 * Restore the original source field from draft files
678 * Do not use this function because it makes field files.source inconsistent
679 * for draft area files. This function will be deprecated in 2.6
681 * @param stored_file $storedfile This only works with draft files
682 * @return stored_file
684 function file_restore_source_field_from_draft_file($storedfile) {
685 $source = @unserialize($storedfile->get_source());
686 if (!empty($source)) {
687 if (is_object($source)) {
688 $restoredsource = $source->source;
689 $storedfile->set_source($restoredsource);
691 throw new moodle_exception('invalidsourcefield', 'error');
697 * Saves files from a draft file area to a real one (merging the list of files).
698 * Can rewrite URLs in some content at the same time if desired.
701 * @global stdClass $USER
702 * @param int $draftitemid the id of the draft area to use. Normally obtained
703 * from file_get_submitted_draft_itemid('elementname') or similar.
704 * @param int $contextid This parameter and the next two identify the file area to save to.
705 * @param string $component
706 * @param string $filearea indentifies the file area.
707 * @param int $itemid helps identifies the file area.
708 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
709 * @param string $text some html content that needs to have embedded links rewritten
710 * to the @@PLUGINFILE@@ form for saving in the database.
711 * @param bool $forcehttps force https urls.
712 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
714 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
717 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
718 $fs = get_file_storage();
720 $options = (array)$options;
721 if (!isset($options['subdirs'])) {
722 $options['subdirs'] = false;
724 if (!isset($options['maxfiles'])) {
725 $options['maxfiles'] = -1; // unlimited
727 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
728 $options['maxbytes'] = 0; // unlimited
730 $allowreferences = true;
731 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
732 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
733 // this is not exactly right. BUT there are many places in code where filemanager options
734 // are not passed to file_save_draft_area_files()
735 $allowreferences = false;
738 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
739 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
741 // One file in filearea means it is empty (it has only top-level directory '.').
742 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
743 // we have to merge old and new files - we want to keep file ids for files that were not changed
744 // we change time modified for all new and changed files, we keep time created as is
746 $newhashes = array();
748 foreach ($draftfiles as $file) {
749 if (!$options['subdirs'] && ($file->get_filepath() !== '/' or $file->is_directory())) {
752 if (!$allowreferences && $file->is_external_file()) {
755 if (!$file->is_directory()) {
756 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
757 // oversized file - should not get here at all
760 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
761 // more files - should not get here at all
766 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
767 $newhashes[$newhash] = $file;
770 // Loop through oldfiles and decide which we need to delete and which to update.
771 // After this cycle the array $newhashes will only contain the files that need to be added.
772 foreach ($oldfiles as $oldfile) {
773 $oldhash = $oldfile->get_pathnamehash();
774 if (!isset($newhashes[$oldhash])) {
775 // delete files not needed any more - deleted by user
780 $newfile = $newhashes[$oldhash];
781 // Now we know that we have $oldfile and $newfile for the same path.
782 // Let's check if we can update this file or we need to delete and create.
783 if ($newfile->is_directory()) {
784 // Directories are always ok to just update.
785 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
786 // File has the 'original' - we need to update the file (it may even have not been changed at all).
787 $original = file_storage::unpack_reference($source->original);
788 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
789 // Very odd, original points to another file. Delete and create file.
794 // The same file name but absence of 'original' means that file was deteled and uploaded again.
795 // By deleting and creating new file we properly manage all existing references.
800 // status changed, we delete old file, and create a new one
801 if ($oldfile->get_status() != $newfile->get_status()) {
802 // file was changed, use updated with new timemodified data
804 // This file will be added later
809 if ($oldfile->get_author() != $newfile->get_author()) {
810 $oldfile->set_author($newfile->get_author());
813 if ($oldfile->get_license() != $newfile->get_license()) {
814 $oldfile->set_license($newfile->get_license());
817 // Updated file source
818 // Field files.source for draftarea files contains serialised object with source and original information.
819 // We only store the source part of it for non-draft file area.
820 $newsource = $newfile->get_source();
821 if ($source = @unserialize($newfile->get_source())) {
822 $newsource = $source->source;
824 if ($oldfile->get_source() !== $newsource) {
825 $oldfile->set_source($newsource);
828 // Updated sort order
829 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
830 $oldfile->set_sortorder($newfile->get_sortorder());
833 // Update file timemodified
834 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
835 $oldfile->set_timemodified($newfile->get_timemodified());
838 // Replaced file content
839 if (!$oldfile->is_directory() &&
840 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
841 $oldfile->get_filesize() != $newfile->get_filesize() ||
842 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
843 $oldfile->get_userid() != $newfile->get_userid())) {
844 $oldfile->replace_file_with($newfile);
845 // push changes to all local files that are referencing this file
846 $fs->update_references_to_storedfile($oldfile);
849 // unchanged file or directory - we keep it as is
850 unset($newhashes[$oldhash]);
853 // Add fresh file or the file which has changed status
854 // the size and subdirectory tests are extra safety only, the UI should prevent it
855 foreach ($newhashes as $file) {
856 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
857 if ($source = @unserialize($file->get_source())) {
858 // Field files.source for draftarea files contains serialised object with source and original information.
859 // We only store the source part of it for non-draft file area.
860 $file_record['source'] = $source->source;
863 if ($file->is_external_file()) {
864 $repoid = $file->get_repository_id();
865 if (!empty($repoid)) {
866 $file_record['repositoryid'] = $repoid;
867 $file_record['reference'] = $file->get_reference();
871 $fs->create_file_from_storedfile($file_record, $file);
875 // note: do not purge the draft area - we clean up areas later in cron,
876 // the reason is that user might press submit twice and they would loose the files,
877 // also sometimes we might want to use hacks that save files into two different areas
879 if (is_null($text)) {
882 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
887 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
888 * ready to be saved in the database. Normally, this is done automatically by
889 * {@link file_save_draft_area_files()}.
892 * @param string $text the content to process.
893 * @param int $draftitemid the draft file area the content was using.
894 * @param bool $forcehttps whether the content contains https URLs. Default false.
895 * @return string the processed content.
897 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
900 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
902 $wwwroot = $CFG->wwwroot;
904 $wwwroot = str_replace('http://', 'https://', $wwwroot);
907 // relink embedded files if text submitted - no absolute links allowed in database!
908 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
910 if (strpos($text, 'draftfile.php?file=') !== false) {
912 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
914 foreach ($matches[0] as $match) {
915 $replace = str_ireplace('%2F', '/', $match);
916 $text = str_replace($match, $replace, $text);
919 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
926 * Set file sort order
928 * @global moodle_database $DB
929 * @param int $contextid the context id
930 * @param string $component file component
931 * @param string $filearea file area.
932 * @param int $itemid itemid.
933 * @param string $filepath file path.
934 * @param string $filename file name.
935 * @param int $sortorder the sort order of file.
938 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
940 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
941 if ($file_record = $DB->get_record('files', $conditions)) {
942 $sortorder = (int)$sortorder;
943 $file_record->sortorder = $sortorder;
944 $DB->update_record('files', $file_record);
951 * reset file sort order number to 0
952 * @global moodle_database $DB
953 * @param int $contextid the context id
954 * @param string $component
955 * @param string $filearea file area.
956 * @param int|bool $itemid itemid.
959 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
962 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
963 if ($itemid !== false) {
964 $conditions['itemid'] = $itemid;
967 $file_records = $DB->get_records('files', $conditions);
968 foreach ($file_records as $file_record) {
969 $file_record->sortorder = 0;
970 $DB->update_record('files', $file_record);
976 * Returns description of upload error
978 * @param int $errorcode found in $_FILES['filename.ext']['error']
979 * @return string error description string, '' if ok
981 function file_get_upload_error($errorcode) {
983 switch ($errorcode) {
984 case 0: // UPLOAD_ERR_OK - no error
988 case 1: // UPLOAD_ERR_INI_SIZE
989 $errmessage = get_string('uploadserverlimit');
992 case 2: // UPLOAD_ERR_FORM_SIZE
993 $errmessage = get_string('uploadformlimit');
996 case 3: // UPLOAD_ERR_PARTIAL
997 $errmessage = get_string('uploadpartialfile');
1000 case 4: // UPLOAD_ERR_NO_FILE
1001 $errmessage = get_string('uploadnofilefound');
1004 // Note: there is no error with a value of 5
1006 case 6: // UPLOAD_ERR_NO_TMP_DIR
1007 $errmessage = get_string('uploadnotempdir');
1010 case 7: // UPLOAD_ERR_CANT_WRITE
1011 $errmessage = get_string('uploadcantwrite');
1014 case 8: // UPLOAD_ERR_EXTENSION
1015 $errmessage = get_string('uploadextension');
1019 $errmessage = get_string('uploadproblem');
1026 * Recursive function formating an array in POST parameter
1027 * @param array $arraydata - the array that we are going to format and add into &$data array
1028 * @param string $currentdata - a row of the final postdata array at instant T
1029 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1030 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1032 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1033 foreach ($arraydata as $k=>$v) {
1034 $newcurrentdata = $currentdata;
1035 if (is_array($v)) { //the value is an array, call the function recursively
1036 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1037 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1038 } else { //add the POST parameter to the $data array
1039 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1045 * Transform a PHP array into POST parameter
1046 * (see the recursive function format_array_postdata_for_curlcall)
1047 * @param array $postdata
1048 * @return array containing all POST parameters (1 row = 1 POST parameter)
1050 function format_postdata_for_curlcall($postdata) {
1052 foreach ($postdata as $k=>$v) {
1054 $currentdata = urlencode($k);
1055 format_array_postdata_for_curlcall($v, $currentdata, $data);
1057 $data[] = urlencode($k).'='.urlencode($v);
1060 $convertedpostdata = implode('&', $data);
1061 return $convertedpostdata;
1065 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1066 * Due to security concerns only downloads from http(s) sources are supported.
1068 * @todo MDL-31073 add version test for '7.10.5'
1070 * @param string $url file url starting with http(s)://
1071 * @param array $headers http headers, null if none. If set, should be an
1072 * associative array of header name => value pairs.
1073 * @param array $postdata array means use POST request with given parameters
1074 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1075 * (if false, just returns content)
1076 * @param int $timeout timeout for complete download process including all file transfer
1077 * (default 5 minutes)
1078 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1079 * usually happens if the remote server is completely down (default 20 seconds);
1080 * may not work when using proxy
1081 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1082 * Only use this when already in a trusted location.
1083 * @param string $tofile store the downloaded content to file instead of returning it.
1084 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1085 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1086 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1088 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1091 // some extra security
1092 $newlines = array("\r", "\n");
1093 if (is_array($headers) ) {
1094 foreach ($headers as $key => $value) {
1095 $headers[$key] = str_replace($newlines, '', $value);
1098 $url = str_replace($newlines, '', $url);
1099 if (!preg_match('|^https?://|i', $url)) {
1100 if ($fullresponse) {
1101 $response = new stdClass();
1102 $response->status = 0;
1103 $response->headers = array();
1104 $response->response_code = 'Invalid protocol specified in url';
1105 $response->results = '';
1106 $response->error = 'Invalid protocol specified in url';
1113 // check if proxy (if used) should be bypassed for this url
1114 $proxybypass = is_proxybypass($url);
1116 if (!$ch = curl_init($url)) {
1117 debugging('Can not init curl.');
1121 // set extra headers
1122 if (is_array($headers) ) {
1123 $headers2 = array();
1124 foreach ($headers as $key => $value) {
1125 $headers2[] = "$key: $value";
1127 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1130 if ($skipcertverify) {
1131 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1134 // use POST if requested
1135 if (is_array($postdata)) {
1136 $postdata = format_postdata_for_curlcall($postdata);
1137 curl_setopt($ch, CURLOPT_POST, true);
1138 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1141 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1142 curl_setopt($ch, CURLOPT_HEADER, false);
1143 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1145 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1146 // TODO: add version test for '7.10.5'
1147 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1148 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1151 if (!empty($CFG->proxyhost) and !$proxybypass) {
1152 // SOCKS supported in PHP5 only
1153 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1154 if (defined('CURLPROXY_SOCKS5')) {
1155 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1158 if ($fullresponse) {
1159 $response = new stdClass();
1160 $response->status = '0';
1161 $response->headers = array();
1162 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1163 $response->results = '';
1164 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1167 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1173 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1175 if (empty($CFG->proxyport)) {
1176 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1178 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1181 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1182 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1183 if (defined('CURLOPT_PROXYAUTH')) {
1184 // any proxy authentication if PHP 5.1
1185 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1190 // set up header and content handlers
1191 $received = new stdClass();
1192 $received->headers = array(); // received headers array
1193 $received->tofile = $tofile;
1194 $received->fh = null;
1195 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1197 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1200 if (!isset($CFG->curltimeoutkbitrate)) {
1201 //use very slow rate of 56kbps as a timeout speed when not set
1204 $bitrate = $CFG->curltimeoutkbitrate;
1207 // try to calculate the proper amount for timeout from remote file size.
1208 // if disabled or zero, we won't do any checks nor head requests.
1209 if ($calctimeout && $bitrate > 0) {
1210 //setup header request only options
1211 curl_setopt_array ($ch, array(
1212 CURLOPT_RETURNTRANSFER => false,
1213 CURLOPT_NOBODY => true)
1217 $info = curl_getinfo($ch);
1218 $err = curl_error($ch);
1220 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1221 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1223 //reinstate affected curl options
1224 curl_setopt_array ($ch, array(
1225 CURLOPT_RETURNTRANSFER => true,
1226 CURLOPT_NOBODY => false,
1227 CURLOPT_HTTPGET => true)
1231 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1232 $result = curl_exec($ch);
1234 // try to detect encoding problems
1235 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1236 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1237 $result = curl_exec($ch);
1240 if ($received->fh) {
1241 fclose($received->fh);
1244 if (curl_errno($ch)) {
1245 $error = curl_error($ch);
1246 $error_no = curl_errno($ch);
1249 if ($fullresponse) {
1250 $response = new stdClass();
1251 if ($error_no == 28) {
1252 $response->status = '-100'; // mimic snoopy
1254 $response->status = '0';
1256 $response->headers = array();
1257 $response->response_code = $error;
1258 $response->results = false;
1259 $response->error = $error;
1262 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1267 $info = curl_getinfo($ch);
1270 if (empty($info['http_code'])) {
1271 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1272 $response = new stdClass();
1273 $response->status = '0';
1274 $response->headers = array();
1275 $response->response_code = 'Unknown cURL error';
1276 $response->results = false; // do NOT change this, we really want to ignore the result!
1277 $response->error = 'Unknown cURL error';
1280 $response = new stdClass();;
1281 $response->status = (string)$info['http_code'];
1282 $response->headers = $received->headers;
1283 $response->response_code = $received->headers[0];
1284 $response->results = $result;
1285 $response->error = '';
1288 if ($fullresponse) {
1290 } else if ($info['http_code'] != 200) {
1291 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1294 return $response->results;
1300 * internal implementation
1301 * @param stdClass $received
1302 * @param resource $ch
1303 * @param mixed $header
1304 * @return int header length
1306 function download_file_content_header_handler($received, $ch, $header) {
1307 $received->headers[] = $header;
1308 return strlen($header);
1312 * internal implementation
1313 * @param stdClass $received
1314 * @param resource $ch
1315 * @param mixed $data
1317 function download_file_content_write_handler($received, $ch, $data) {
1318 if (!$received->fh) {
1319 $received->fh = fopen($received->tofile, 'w');
1320 if ($received->fh === false) {
1321 // bad luck, file creation or overriding failed
1325 if (fwrite($received->fh, $data) === false) {
1326 // bad luck, write failed, let's abort completely
1329 return strlen($data);
1333 * Returns a list of information about file types based on extensions.
1335 * The following elements expected in value array for each extension:
1337 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1338 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1339 * also files with bigger sizes under names
1340 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1341 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1342 * commonly used in moodle the following groups:
1343 * - web_image - image that can be included as <img> in HTML
1344 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1345 * - video - file that can be imported as video in text editor
1346 * - audio - file that can be imported as audio in text editor
1347 * - archive - we can extract files from this archive
1348 * - spreadsheet - used for portfolio format
1349 * - document - used for portfolio format
1350 * - presentation - used for portfolio format
1351 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1352 * human-readable description for this filetype;
1353 * Function {@link get_mimetype_description()} first looks at the presence of string for
1354 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1355 * attribute, if not found returns the value of 'type';
1356 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1357 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1358 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1361 * @return array List of information about file types based on extensions.
1362 * Associative array of extension (lower-case) to associative array
1363 * from 'element name' to data. Current element names are 'type' and 'icon'.
1364 * Unknown types should use the 'xxx' entry which includes defaults.
1366 function &get_mimetypes_array() {
1367 static $mimearray = array (
1368 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1369 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1370 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1371 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1372 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1373 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1374 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1375 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1376 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1377 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1378 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1379 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1380 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1381 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1382 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1383 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1384 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1385 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1386 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1387 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1388 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1389 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1391 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1392 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1393 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1394 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1395 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1397 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1398 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1399 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1400 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1401 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1402 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1403 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1404 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1405 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1407 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1408 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1409 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1410 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1411 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1412 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1413 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1414 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1415 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1416 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1417 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1418 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1419 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1420 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1421 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1422 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1423 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1424 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1425 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1426 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1427 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1428 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1429 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1430 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1431 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1432 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1433 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1434 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1435 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1436 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1437 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1438 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1439 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1440 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1441 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1442 'mht' => array ('type'=>'message/rfc822', 'icon'=>'archive'),
1443 'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
1444 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1445 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1446 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1447 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1448 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1449 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1450 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1451 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1452 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1453 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1455 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1456 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1458 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1459 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1460 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1461 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1462 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1463 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1464 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1465 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1466 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1467 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1468 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1469 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1470 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1471 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1472 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1473 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1474 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1476 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1477 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1478 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1479 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1480 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1481 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1483 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1484 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1485 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1486 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1487 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1488 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1489 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1490 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1491 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1493 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1494 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1495 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1496 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1497 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1498 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1499 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1500 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1501 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1502 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1503 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1504 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1505 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1506 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1507 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1508 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1509 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1510 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1511 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1512 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1514 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1515 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1516 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1517 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1518 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1519 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1520 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1521 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1522 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1523 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1525 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1526 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1527 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1528 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1529 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1530 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1531 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1532 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1533 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1534 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1535 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1536 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1538 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1539 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1540 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1541 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1543 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1544 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1545 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1546 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1547 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1548 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1549 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1551 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1552 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1554 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1560 * Obtains information about a filetype based on its extension. Will
1561 * use a default if no information is present about that particular
1565 * @param string $element Desired information (usually 'icon'
1566 * for icon filename or 'type' for MIME type. Can also be
1567 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1568 * @param string $filename Filename we're looking up
1569 * @return string Requested piece of information from array
1571 function mimeinfo($element, $filename) {
1573 $mimeinfo = & get_mimetypes_array();
1574 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1576 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1577 if (empty($filetype)) {
1578 $filetype = 'xxx'; // file without extension
1580 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1581 $iconsize = max(array(16, (int)$iconsizematch[1]));
1582 $filenames = array($mimeinfo['xxx']['icon']);
1583 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1584 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1586 // find the file with the closest size, first search for specific icon then for default icon
1587 foreach ($filenames as $filename) {
1588 foreach ($iconpostfixes as $size => $postfix) {
1589 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1590 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1591 return $filename.$postfix;
1595 } else if (isset($mimeinfo[$filetype][$element])) {
1596 return $mimeinfo[$filetype][$element];
1597 } else if (isset($mimeinfo['xxx'][$element])) {
1598 return $mimeinfo['xxx'][$element]; // By default
1605 * Obtains information about a filetype based on the MIME type rather than
1606 * the other way around.
1609 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1610 * @param string $mimetype MIME type we're looking up
1611 * @return string Requested piece of information from array
1613 function mimeinfo_from_type($element, $mimetype) {
1614 /* array of cached mimetype->extension associations */
1615 static $cached = array();
1616 $mimeinfo = & get_mimetypes_array();
1618 if (!array_key_exists($mimetype, $cached)) {
1619 $cached[$mimetype] = null;
1620 foreach($mimeinfo as $filetype => $values) {
1621 if ($values['type'] == $mimetype) {
1622 if ($cached[$mimetype] === null) {
1623 $cached[$mimetype] = '.'.$filetype;
1625 if (!empty($values['defaulticon'])) {
1626 $cached[$mimetype] = '.'.$filetype;
1631 if (empty($cached[$mimetype])) {
1632 $cached[$mimetype] = '.xxx';
1635 if ($element === 'extension') {
1636 return $cached[$mimetype];
1638 return mimeinfo($element, $cached[$mimetype]);
1643 * Return the relative icon path for a given file
1647 * // $file - instance of stored_file or file_info
1648 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1649 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1653 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1656 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1657 * and $file->mimetype are expected)
1658 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1661 function file_file_icon($file, $size = null) {
1662 if (!is_object($file)) {
1663 $file = (object)$file;
1665 if (isset($file->filename)) {
1666 $filename = $file->filename;
1667 } else if (method_exists($file, 'get_filename')) {
1668 $filename = $file->get_filename();
1669 } else if (method_exists($file, 'get_visible_name')) {
1670 $filename = $file->get_visible_name();
1674 if (isset($file->mimetype)) {
1675 $mimetype = $file->mimetype;
1676 } else if (method_exists($file, 'get_mimetype')) {
1677 $mimetype = $file->get_mimetype();
1681 $mimetypes = &get_mimetypes_array();
1683 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1684 if ($extension && !empty($mimetypes[$extension])) {
1685 // if file name has known extension, return icon for this extension
1686 return file_extension_icon($filename, $size);
1689 return file_mimetype_icon($mimetype, $size);
1693 * Return the relative icon path for a folder image
1697 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1698 * echo html_writer::empty_tag('img', array('src' => $icon));
1702 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1705 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1708 function file_folder_icon($iconsize = null) {
1710 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1711 static $cached = array();
1712 $iconsize = max(array(16, (int)$iconsize));
1713 if (!array_key_exists($iconsize, $cached)) {
1714 foreach ($iconpostfixes as $size => $postfix) {
1715 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1716 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1717 $cached[$iconsize] = 'f/folder'.$postfix;
1722 return $cached[$iconsize];
1726 * Returns the relative icon path for a given mime type
1728 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1729 * a return the full path to an icon.
1732 * $mimetype = 'image/jpg';
1733 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1734 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1738 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1739 * to conform with that.
1740 * @param string $mimetype The mimetype to fetch an icon for
1741 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1742 * @return string The relative path to the icon
1744 function file_mimetype_icon($mimetype, $size = NULL) {
1745 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1749 * Returns the relative icon path for a given file name
1751 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1752 * a return the full path to an icon.
1755 * $filename = '.jpg';
1756 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1757 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1760 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1761 * to conform with that.
1762 * @todo MDL-31074 Implement $size
1764 * @param string $filename The filename to get the icon for
1765 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1768 function file_extension_icon($filename, $size = NULL) {
1769 return 'f/'.mimeinfo('icon'.$size, $filename);
1773 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1774 * mimetypes.php language file.
1776 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1777 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1778 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1779 * @param bool $capitalise If true, capitalises first character of result
1780 * @return string Text description
1782 function get_mimetype_description($obj, $capitalise=false) {
1783 $filename = $mimetype = '';
1784 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1785 // this is an instance of stored_file
1786 $mimetype = $obj->get_mimetype();
1787 $filename = $obj->get_filename();
1788 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1789 // this is an instance of file_info
1790 $mimetype = $obj->get_mimetype();
1791 $filename = $obj->get_visible_name();
1792 } else if (is_array($obj) || is_object ($obj)) {
1794 if (!empty($obj['filename'])) {
1795 $filename = $obj['filename'];
1797 if (!empty($obj['mimetype'])) {
1798 $mimetype = $obj['mimetype'];
1803 $mimetypefromext = mimeinfo('type', $filename);
1804 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1805 // if file has a known extension, overwrite the specified mimetype
1806 $mimetype = $mimetypefromext;
1808 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1809 if (empty($extension)) {
1810 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1811 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1813 $mimetypestr = mimeinfo('string', $filename);
1815 $chunks = explode('/', $mimetype, 2);
1818 'mimetype' => $mimetype,
1819 'ext' => $extension,
1820 'mimetype1' => $chunks[0],
1821 'mimetype2' => $chunks[1],
1824 foreach ($attr as $key => $value) {
1826 $a[strtoupper($key)] = strtoupper($value);
1827 $a[ucfirst($key)] = ucfirst($value);
1830 // MIME types may include + symbol but this is not permitted in string ids.
1831 $safemimetype = str_replace('+', '_', $mimetype);
1832 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1833 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1834 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1835 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1836 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1837 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1838 $result = get_string('default', 'mimetypes', (object)$a);
1840 $result = $mimetype;
1843 $result=ucfirst($result);
1849 * Returns array of elements of type $element in type group(s)
1851 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1852 * @param string|array $groups one group or array of groups/extensions/mimetypes
1855 function file_get_typegroup($element, $groups) {
1856 static $cached = array();
1857 if (!is_array($groups)) {
1858 $groups = array($groups);
1860 if (!array_key_exists($element, $cached)) {
1861 $cached[$element] = array();
1864 foreach ($groups as $group) {
1865 if (!array_key_exists($group, $cached[$element])) {
1866 // retrieive and cache all elements of type $element for group $group
1867 $mimeinfo = & get_mimetypes_array();
1868 $cached[$element][$group] = array();
1869 foreach ($mimeinfo as $extension => $value) {
1870 $value['extension'] = '.'.$extension;
1871 if (empty($value[$element])) {
1874 if (($group === '.'.$extension || $group === $value['type'] ||
1875 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1876 !in_array($value[$element], $cached[$element][$group])) {
1877 $cached[$element][$group][] = $value[$element];
1881 $result = array_merge($result, $cached[$element][$group]);
1883 return array_values(array_unique($result));
1887 * Checks if file with name $filename has one of the extensions in groups $groups
1889 * @see get_mimetypes_array()
1890 * @param string $filename name of the file to check
1891 * @param string|array $groups one group or array of groups to check
1892 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1893 * file mimetype is in mimetypes in groups $groups
1896 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1897 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1898 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1901 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1905 * Checks if mimetype $mimetype belongs to one of the groups $groups
1907 * @see get_mimetypes_array()
1908 * @param string $mimetype
1909 * @param string|array $groups one group or array of groups to check
1912 function file_mimetype_in_typegroup($mimetype, $groups) {
1913 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1917 * Requested file is not found or not accessible, does not return, terminates script
1919 * @global stdClass $CFG
1920 * @global stdClass $COURSE
1922 function send_file_not_found() {
1923 global $CFG, $COURSE;
1925 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1928 * Helper function to send correct 404 for server.
1930 function send_header_404() {
1931 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1932 header("Status: 404 Not Found");
1934 header('HTTP/1.0 404 not found');
1939 * Enhanced readfile() with optional acceleration.
1940 * @param string|stored_file $file
1941 * @param string $mimetype
1942 * @param bool $accelerate
1945 function readfile_accel($file, $mimetype, $accelerate) {
1948 if ($mimetype === 'text/plain') {
1949 // there is no encoding specified in text files, we need something consistent
1950 header('Content-Type: text/plain; charset=utf-8');
1952 header('Content-Type: '.$mimetype);
1955 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1956 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1958 if (is_object($file)) {
1959 header('Etag: "' . $file->get_contenthash() . '"');
1960 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1961 header('HTTP/1.1 304 Not Modified');
1966 // if etag present for stored file rely on it exclusively
1967 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1968 // get unixtime of request header; clip extra junk off first
1969 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1970 if ($since && $since >= $lastmodified) {
1971 header('HTTP/1.1 304 Not Modified');
1976 if ($accelerate and !empty($CFG->xsendfile)) {
1977 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1978 header('Accept-Ranges: bytes');
1980 header('Accept-Ranges: none');
1983 if (is_object($file)) {
1984 $fs = get_file_storage();
1985 if ($fs->xsendfile($file->get_contenthash())) {
1990 require_once("$CFG->libdir/xsendfilelib.php");
1991 if (xsendfile($file)) {
1997 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1999 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2001 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2002 header('Accept-Ranges: bytes');
2004 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2005 // byteserving stuff - for acrobat reader and download accelerators
2006 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2007 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2009 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2010 foreach ($ranges as $key=>$value) {
2011 if ($ranges[$key][1] == '') {
2013 $ranges[$key][1] = $filesize - $ranges[$key][2];
2014 $ranges[$key][2] = $filesize - 1;
2015 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2017 $ranges[$key][2] = $filesize - 1;
2019 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2020 //invalid byte-range ==> ignore header
2024 //prepare multipart header
2025 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2026 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2032 if (is_object($file)) {
2033 $handle = $file->get_content_file_handle();
2035 $handle = fopen($file, 'rb');
2037 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2042 header('Accept-Ranges: none');
2045 header('Content-Length: '.$filesize);
2047 if ($filesize > 10000000) {
2048 // for large files try to flush and close all buffers to conserve memory
2049 while(@ob_get_level()) {
2050 if (!@ob_end_flush()) {
2056 // send the whole file content
2057 if (is_object($file)) {
2065 * Similar to readfile_accel() but designed for strings.
2066 * @param string $string
2067 * @param string $mimetype
2068 * @param bool $accelerate
2071 function readstring_accel($string, $mimetype, $accelerate) {
2074 if ($mimetype === 'text/plain') {
2075 // there is no encoding specified in text files, we need something consistent
2076 header('Content-Type: text/plain; charset=utf-8');
2078 header('Content-Type: '.$mimetype);
2080 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2081 header('Accept-Ranges: none');
2083 if ($accelerate and !empty($CFG->xsendfile)) {
2084 $fs = get_file_storage();
2085 if ($fs->xsendfile(sha1($string))) {
2090 header('Content-Length: '.strlen($string));
2095 * Handles the sending of temporary file to user, download is forced.
2096 * File is deleted after abort or successful sending, does not return, script terminated
2098 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2099 * @param string $filename proposed file name when saving file
2100 * @param bool $pathisstring If the path is string
2102 function send_temp_file($path, $filename, $pathisstring=false) {
2105 if (check_browser_version('Firefox', '1.5')) {
2106 // only FF is known to correctly save to disk before opening...
2107 $mimetype = mimeinfo('type', $filename);
2109 $mimetype = 'application/x-forcedownload';
2112 // close session - not needed anymore
2113 session_get_instance()->write_close();
2115 if (!$pathisstring) {
2116 if (!file_exists($path)) {
2118 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2120 // executed after normal finish or abort
2121 @register_shutdown_function('send_temp_file_finished', $path);
2124 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2125 if (check_browser_version('MSIE')) {
2126 $filename = urlencode($filename);
2129 header('Content-Disposition: attachment; filename="'.$filename.'"');
2130 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2131 header('Cache-Control: max-age=10');
2132 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2134 } else { //normal http - prevent caching at all cost
2135 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2136 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2137 header('Pragma: no-cache');
2140 // send the contents - we can not accelerate this because the file will be deleted asap
2141 if ($pathisstring) {
2142 readstring_accel($path, $mimetype, false);
2144 readfile_accel($path, $mimetype, false);
2148 die; //no more chars to output
2152 * Internal callback function used by send_temp_file()
2154 * @param string $path
2156 function send_temp_file_finished($path) {
2157 if (file_exists($path)) {
2163 * Handles the sending of file data to the user's browser, including support for
2167 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2168 * @param string $filename Filename to send
2169 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2170 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2171 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2172 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2173 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2174 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2175 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2176 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2177 * and should not be reopened.
2178 * @return null script execution stopped unless $dontdie is true
2180 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2181 global $CFG, $COURSE;
2184 ignore_user_abort(true);
2187 // MDL-11789, apply $CFG->filelifetime here
2188 if ($lifetime === 'default') {
2189 if (!empty($CFG->filelifetime)) {
2190 $lifetime = $CFG->filelifetime;
2196 session_get_instance()->write_close(); // unlock session during fileserving
2198 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2199 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2200 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2201 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2202 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2203 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2205 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2206 if (check_browser_version('MSIE')) {
2207 $filename = rawurlencode($filename);
2210 if ($forcedownload) {
2211 header('Content-Disposition: attachment; filename="'.$filename.'"');
2213 header('Content-Disposition: inline; filename="'.$filename.'"');
2216 if ($lifetime > 0) {
2217 $nobyteserving = false;
2218 header('Cache-Control: max-age='.$lifetime);
2219 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2222 } else { // Do not cache files in proxies and browsers
2223 $nobyteserving = true;
2224 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2225 header('Cache-Control: max-age=10');
2226 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2228 } else { //normal http - prevent caching at all cost
2229 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2230 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2231 header('Pragma: no-cache');
2235 if (empty($filter)) {
2236 // send the contents
2237 if ($pathisstring) {
2238 readstring_accel($path, $mimetype, !$dontdie);
2240 readfile_accel($path, $mimetype, !$dontdie);
2244 // Try to put the file through filters
2245 if ($mimetype == 'text/html') {
2246 $options = new stdClass();
2247 $options->noclean = true;
2248 $options->nocache = true; // temporary workaround for MDL-5136
2249 $text = $pathisstring ? $path : implode('', file($path));
2251 $text = file_modify_html_header($text);
2252 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2254 readstring_accel($output, $mimetype, false);
2256 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2257 // only filter text if filter all files is selected
2258 $options = new stdClass();
2259 $options->newlines = false;
2260 $options->noclean = true;
2261 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2262 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2264 readstring_accel($output, $mimetype, false);
2267 // send the contents
2268 if ($pathisstring) {
2269 readstring_accel($path, $mimetype, !$dontdie);
2271 readfile_accel($path, $mimetype, !$dontdie);
2278 die; //no more chars to output!!!
2282 * Handles the sending of file data to the user's browser, including support for
2285 * The $options parameter supports the following keys:
2286 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2287 * (string|null) filename - overrides the implicit filename
2288 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2289 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2290 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2291 * and should not be reopened.
2294 * @param stored_file $stored_file local file object
2295 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2296 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2297 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2298 * @param array $options additional options affecting the file serving
2299 * @return null script execution stopped unless $options['dontdie'] is true
2301 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2302 global $CFG, $COURSE;
2304 if (empty($options['filename'])) {
2307 $filename = $options['filename'];
2310 if (empty($options['dontdie'])) {
2316 if (!empty($options['preview'])) {
2317 // replace the file with its preview
2318 $fs = get_file_storage();
2319 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2320 if (!$preview_file) {
2321 // unable to create a preview of the file, send its default mime icon instead
2322 if ($options['preview'] === 'tinyicon') {
2324 } else if ($options['preview'] === 'thumb') {
2329 $fileicon = file_file_icon($stored_file, $size);
2330 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2332 // preview images have fixed cache lifetime and they ignore forced download
2333 // (they are generated by GD and therefore they are considered reasonably safe).
2334 $stored_file = $preview_file;
2335 $lifetime = DAYSECS;
2337 $forcedownload = false;
2341 // handle external resource
2342 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2343 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2347 if (!$stored_file or $stored_file->is_directory()) {
2356 ignore_user_abort(true);
2359 session_get_instance()->write_close(); // unlock session during fileserving
2361 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2362 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2363 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2364 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2365 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2366 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2367 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2369 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2370 if (check_browser_version('MSIE')) {
2371 $filename = rawurlencode($filename);
2374 if ($forcedownload) {
2375 header('Content-Disposition: attachment; filename="'.$filename.'"');
2377 header('Content-Disposition: inline; filename="'.$filename.'"');
2380 if ($lifetime > 0) {
2381 header('Cache-Control: max-age='.$lifetime);
2382 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2385 } else { // Do not cache files in proxies and browsers
2386 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2387 header('Cache-Control: max-age=10');
2388 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2390 } else { //normal http - prevent caching at all cost
2391 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2392 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2393 header('Pragma: no-cache');
2397 if (empty($filter)) {
2398 // send the contents
2399 readfile_accel($stored_file, $mimetype, !$dontdie);
2401 } else { // Try to put the file through filters
2402 if ($mimetype == 'text/html') {
2403 $options = new stdClass();
2404 $options->noclean = true;
2405 $options->nocache = true; // temporary workaround for MDL-5136
2406 $text = $stored_file->get_content();
2407 $text = file_modify_html_header($text);
2408 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2410 readstring_accel($output, $mimetype, false);
2412 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2413 // only filter text if filter all files is selected
2414 $options = new stdClass();
2415 $options->newlines = false;
2416 $options->noclean = true;
2417 $text = $stored_file->get_content();
2418 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2420 readstring_accel($output, $mimetype, false);
2422 } else { // Just send it out raw
2423 readfile_accel($stored_file, $mimetype, !$dontdie);
2429 die; //no more chars to output!!!
2433 * Retrieves an array of records from a CSV file and places
2434 * them into a given table structure
2436 * @global stdClass $CFG
2437 * @global moodle_database $DB
2438 * @param string $file The path to a CSV file
2439 * @param string $table The table to retrieve columns from
2440 * @return bool|array Returns an array of CSV records or false
2442 function get_records_csv($file, $table) {
2445 if (!$metacolumns = $DB->get_columns($table)) {
2449 if(!($handle = @fopen($file, 'r'))) {
2450 print_error('get_records_csv failed to open '.$file);
2453 $fieldnames = fgetcsv($handle, 4096);
2454 if(empty($fieldnames)) {
2461 foreach($metacolumns as $metacolumn) {
2462 $ord = array_search($metacolumn->name, $fieldnames);
2464 $columns[$metacolumn->name] = $ord;
2470 while (($data = fgetcsv($handle, 4096)) !== false) {
2471 $item = new stdClass;
2472 foreach($columns as $name => $ord) {
2473 $item->$name = $data[$ord];
2483 * Create a file with CSV contents
2485 * @global stdClass $CFG
2486 * @global moodle_database $DB
2487 * @param string $file The file to put the CSV content into
2488 * @param array $records An array of records to write to a CSV file
2489 * @param string $table The table to get columns from
2490 * @return bool success
2492 function put_records_csv($file, $records, $table = NULL) {
2495 if (empty($records)) {
2499 $metacolumns = NULL;
2500 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2506 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2507 print_error('put_records_csv failed to open '.$file);
2510 $proto = reset($records);
2511 if(is_object($proto)) {
2512 $fields_records = array_keys(get_object_vars($proto));
2514 else if(is_array($proto)) {
2515 $fields_records = array_keys($proto);
2522 if(!empty($metacolumns)) {
2523 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2524 $fields = array_intersect($fields_records, $fields_table);
2527 $fields = $fields_records;
2530 fwrite($fp, implode(',', $fields));
2531 fwrite($fp, "\r\n");
2533 foreach($records as $record) {
2534 $array = (array)$record;
2536 foreach($fields as $field) {
2537 if(strpos($array[$field], ',')) {
2538 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2541 $values[] = $array[$field];
2544 fwrite($fp, implode(',', $values)."\r\n");
2553 * Recursively delete the file or folder with path $location. That is,
2554 * if it is a file delete it. If it is a folder, delete all its content
2555 * then delete it. If $location does not exist to start, that is not
2556 * considered an error.
2558 * @param string $location the path to remove.
2561 function fulldelete($location) {
2562 if (empty($location)) {
2563 // extra safety against wrong param
2566 if (is_dir($location)) {
2567 if (!$currdir = opendir($location)) {
2570 while (false !== ($file = readdir($currdir))) {
2571 if ($file <> ".." && $file <> ".") {
2572 $fullfile = $location."/".$file;
2573 if (is_dir($fullfile)) {
2574 if (!fulldelete($fullfile)) {
2578 if (!unlink($fullfile)) {
2585 if (! rmdir($location)) {
2589 } else if (file_exists($location)) {
2590 if (!unlink($location)) {
2598 * Send requested byterange of file.
2600 * @param resource $handle A file handle
2601 * @param string $mimetype The mimetype for the output
2602 * @param array $ranges An array of ranges to send
2603 * @param string $filesize The size of the content if only one range is used
2605 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2606 // better turn off any kind of compression and buffering
2607 @ini_set('zlib.output_compression', 'Off');
2609 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2610 if ($handle === false) {
2613 if (count($ranges) == 1) { //only one range requested
2614 $length = $ranges[0][2] - $ranges[0][1] + 1;
2615 header('HTTP/1.1 206 Partial content');
2616 header('Content-Length: '.$length);
2617 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2618 header('Content-Type: '.$mimetype);
2620 while(@ob_get_level()) {
2621 if (!@ob_end_flush()) {
2626 fseek($handle, $ranges[0][1]);
2627 while (!feof($handle) && $length > 0) {
2628 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2629 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2632 $length -= strlen($buffer);
2636 } else { // multiple ranges requested - not tested much
2638 foreach($ranges as $range) {
2639 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2641 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2642 header('HTTP/1.1 206 Partial content');
2643 header('Content-Length: '.$totallength);
2644 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2646 while(@ob_get_level()) {
2647 if (!@ob_end_flush()) {
2652 foreach($ranges as $range) {
2653 $length = $range[2] - $range[1] + 1;
2655 fseek($handle, $range[1]);
2656 while (!feof($handle) && $length > 0) {
2657 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2658 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2661 $length -= strlen($buffer);
2664 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2671 * add includes (js and css) into uploaded files
2672 * before returning them, useful for themes and utf.js includes
2674 * @global stdClass $CFG
2675 * @param string $text text to search and replace
2676 * @return string text with added head includes
2679 function file_modify_html_header($text) {
2680 // first look for <head> tag
2683 $stylesheetshtml = '';
2684 /* foreach ($CFG->stylesheets as $stylesheet) {
2686 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2690 if (filter_is_enabled('filter/mediaplugin')) {
2691 // this script is needed by most media filter plugins.
2692 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2693 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2696 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2698 $replacement = '<head>'.$ufo.$stylesheetshtml;
2699 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2703 // if not, look for <html> tag, and stick <head> right after
2704 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2706 // replace <html> tag with <html><head>includes</head>
2707 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2708 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2712 // if not, look for <body> tag, and stick <head> before body
2713 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2715 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2716 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2720 // if not, just stick a <head> tag at the beginning
2721 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2726 * RESTful cURL class
2728 * This is a wrapper class for curl, it is quite easy to use:
2732 * $c = new curl(array('cache'=>true));
2734 * $c = new curl(array('cookie'=>true));
2736 * $c = new curl(array('proxy'=>true));
2738 * // HTTP GET Method
2739 * $html = $c->get('http://example.com');
2740 * // HTTP POST Method
2741 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2742 * // HTTP PUT Method
2743 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2746 * @package core_files
2748 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2749 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2752 /** @var bool Caches http request contents */
2753 public $cache = false;
2754 /** @var bool Uses proxy */
2755 public $proxy = false;
2756 /** @var string library version */
2757 public $version = '0.4 dev';
2758 /** @var array http's response */
2759 public $response = array();
2760 /** @var array http header */
2761 public $header = array();
2762 /** @var string cURL information */
2764 /** @var string error */
2766 /** @var int error code */
2769 /** @var array cURL options */
2771 /** @var string Proxy host */
2772 private $proxy_host = '';
2773 /** @var string Proxy auth */
2774 private $proxy_auth = '';
2775 /** @var string Proxy type */
2776 private $proxy_type = '';
2777 /** @var bool Debug mode on */
2778 private $debug = false;
2779 /** @var bool|string Path to cookie file */
2780 private $cookie = false;
2785 * @global stdClass $CFG
2786 * @param array $options
2788 public function __construct($options = array()){
2790 if (!function_exists('curl_init')) {
2791 $this->error = 'cURL module must be enabled!';
2792 trigger_error($this->error, E_USER_ERROR);
2795 // the options of curl should be init here.
2797 if (!empty($options['debug'])) {
2798 $this->debug = true;
2800 if(!empty($options['cookie'])) {
2801 if($options['cookie'] === true) {
2802 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2804 $this->cookie = $options['cookie'];
2807 if (!empty($options['cache'])) {
2808 if (class_exists('curl_cache')) {
2809 if (!empty($options['module_cache'])) {
2810 $this->cache = new curl_cache($options['module_cache']);
2812 $this->cache = new curl_cache('misc');
2816 if (!empty($CFG->proxyhost)) {
2817 if (empty($CFG->proxyport)) {
2818 $this->proxy_host = $CFG->proxyhost;
2820 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2822 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2823 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2824 $this->setopt(array(
2825 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2826 'proxyuserpwd'=>$this->proxy_auth));
2828 if (!empty($CFG->proxytype)) {
2829 if ($CFG->proxytype == 'SOCKS5') {
2830 $this->proxy_type = CURLPROXY_SOCKS5;
2832 $this->proxy_type = CURLPROXY_HTTP;
2833 $this->setopt(array('httpproxytunnel'=>false));
2835 $this->setopt(array('proxytype'=>$this->proxy_type));
2838 if (!empty($this->proxy_host)) {
2839 $this->proxy = array('proxy'=>$this->proxy_host);
2843 * Resets the CURL options that have already been set
2845 public function resetopt(){
2846 $this->options = array();
2847 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2848 // True to include the header in the output
2849 $this->options['CURLOPT_HEADER'] = 0;
2850 // True to Exclude the body from the output
2851 $this->options['CURLOPT_NOBODY'] = 0;
2852 // TRUE to follow any "Location: " header that the server
2853 // sends as part of the HTTP header (note this is recursive,
2854 // PHP will follow as many "Location: " headers that it is sent,
2855 // unless CURLOPT_MAXREDIRS is set).
2856 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2857 $this->options['CURLOPT_MAXREDIRS'] = 10;
2858 $this->options['CURLOPT_ENCODING'] = '';
2859 // TRUE to return the transfer as a string of the return
2860 // value of curl_exec() instead of outputting it out directly.
2861 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2862 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2863 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2864 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2865 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2871 public function resetcookie() {
2872 if (!empty($this->cookie)) {
2873 if (is_file($this->cookie)) {
2874 $fp = fopen($this->cookie, 'w');
2886 * @param array $options If array is null, this function will
2887 * reset the options to default value.
2889 public function setopt($options = array()) {
2890 if (is_array($options)) {
2891 foreach($options as $name => $val){
2892 if (stripos($name, 'CURLOPT_') === false) {
2893 $name = strtoupper('CURLOPT_'.$name);
2895 $this->options[$name] = $val;
2903 public function cleanopt(){
2904 unset($this->options['CURLOPT_HTTPGET']);
2905 unset($this->options['CURLOPT_POST']);
2906 unset($this->options['CURLOPT_POSTFIELDS']);
2907 unset($this->options['CURLOPT_PUT']);
2908 unset($this->options['CURLOPT_INFILE']);
2909 unset($this->options['CURLOPT_INFILESIZE']);
2910 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2911 unset($this->options['CURLOPT_FILE']);
2915 * Resets the HTTP Request headers (to prepare for the new request)
2917 public function resetHeader() {
2918 $this->header = array();
2922 * Set HTTP Request Header
2924 * @param array $header
2926 public function setHeader($header) {
2927 if (is_array($header)){
2928 foreach ($header as $v) {
2929 $this->setHeader($v);
2932 $this->header[] = $header;
2937 * Set HTTP Response Header
2940 public function getResponse(){
2941 return $this->response;
2945 * private callback function
2946 * Formatting HTTP Response Header
2948 * @param resource $ch Apparently not used
2949 * @param string $header
2950 * @return int The strlen of the header
2952 private function formatHeader($ch, $header)
2955 if (strlen($header) > 2) {
2956 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2957 $key = rtrim($key, ':');
2958 if (!empty($this->response[$key])) {
2959 if (is_array($this->response[$key])){
2960 $this->response[$key][] = $value;
2962 $tmp = $this->response[$key];
2963 $this->response[$key] = array();
2964 $this->response[$key][] = $tmp;
2965 $this->response[$key][] = $value;
2969 $this->response[$key] = $value;
2972 return strlen($header);
2976 * Set options for individual curl instance
2978 * @param resource $curl A curl handle
2979 * @param array $options
2980 * @return resource The curl handle
2982 private function apply_opt($curl, $options) {
2986 if (!empty($this->cookie) || !empty($options['cookie'])) {
2987 $this->setopt(array('cookiejar'=>$this->cookie,
2988 'cookiefile'=>$this->cookie
2993 if (!empty($this->proxy) || !empty($options['proxy'])) {
2994 $this->setopt($this->proxy);
2996 $this->setopt($options);
2997 // reset before set options
2998 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3000 if (empty($this->header)){
3001 $this->setHeader(array(
3002 'User-Agent: MoodleBot/1.0',
3003 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3004 'Connection: keep-alive'
3007 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3009 // Bypass proxy (for this request only) if required.
3010 if (!empty($this->options['CURLOPT_URL']) &&
3011 is_proxybypass($this->options['CURLOPT_URL'])) {
3012 unset($this->options['CURLOPT_PROXY']);
3016 echo '<h1>Options</h1>';
3017 var_dump($this->options);
3018 echo '<h1>Header</h1>';
3019 var_dump($this->header);
3023 foreach($this->options as $name => $val) {
3024 if (is_string($name)) {
3025 $name = constant(strtoupper($name));
3027 curl_setopt($curl, $name, $val);
3033 * Download multiple files in parallel
3035 * Calls {@link multi()} with specific download headers
3039 * $file1 = fopen('a', 'wb');
3040 * $file2 = fopen('b', 'wb');
3041 * $c->download(array(
3042 * array('url'=>'http://localhost/', 'file'=>$file1),
3043 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3053 * $c->download(array(
3054 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3055 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3059 * @param array $requests An array of files to request {
3060 * url => url to download the file [required]
3061 * file => file handler, or
3062 * filepath => file path
3064 * If 'file' and 'filepath' parameters are both specified in one request, the
3065 * open file handle in the 'file' parameter will take precedence and 'filepath'
3068 * @param array $options An array of options to set
3069 * @return array An array of results
3071 public function download($requests, $options = array()) {
3072 $options['CURLOPT_BINARYTRANSFER'] = 1;
3073 $options['RETURNTRANSFER'] = false;
3074 return $this->multi($requests, $options);
3078 * Mulit HTTP Requests
3079 * This function could run multi-requests in parallel.
3081 * @param array $requests An array of files to request
3082 * @param array $options An array of options to set
3083 * @return array An array of results
3085 protected function multi($requests, $options = array()) {
3086 $count = count($requests);
3089 $main = curl_multi_init();
3090 for ($i = 0; $i < $count; $i++) {
3091 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3093 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3094 $requests[$i]['auto-handle'] = true;
3096 foreach($requests[$i] as $n=>$v){
3099 $handles[$i] = curl_init($requests[$i]['url']);
3100 $this->apply_opt($handles[$i], $options);
3101 curl_multi_add_handle($main, $handles[$i]);
3105 curl_multi_exec($main, $running);
3106 } while($running > 0);
3107 for ($i = 0; $i < $count; $i++) {
3108 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3111 $results[] = curl_multi_getcontent($handles[$i]);
3113 curl_multi_remove_handle($main, $handles[$i]);
3115 curl_multi_close($main);
3117 for ($i = 0; $i < $count; $i++) {
3118 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3119 // close file handler if file is opened in this function
3120 fclose($requests[$i]['file']);
3127 * Single HTTP Request
3129 * @param string $url The URL to request
3130 * @param array $options
3133 protected function request($url, $options = array()){
3134 // create curl instance
3135 $curl = curl_init($url);
3136 $options['url'] = $url;
3137 $this->apply_opt($curl, $options);
3138 if ($this->cache && $ret = $this->cache->get($this->options)) {
3141 $ret = curl_exec($curl);
3143 $this->cache->set($this->options, $ret);
3147 $this->info = curl_getinfo($curl);
3148 $this->error = curl_error($curl);
3149 $this->errno = curl_errno($curl);
3152 echo '<h1>Return Data</h1>';
3154 echo '<h1>Info</h1>';
3155 var_dump($this->info);
3156 echo '<h1>Error</h1>';
3157 var_dump($this->error);
3162 if (empty($this->error)){
3165 return $this->error;
3166 // exception is not ajax friendly
3167 //throw new moodle_exception($this->error, 'curl');
3176 * @param string $url
3177 * @param array $options
3180 public function head($url, $options = array()){
3181 $options['CURLOPT_HTTPGET'] = 0;
3182 $options['CURLOPT_HEADER'] = 1;
3183 $options['CURLOPT_NOBODY'] = 1;
3184 return $this->request($url, $options);
3190 * @param string $url
3191 * @param array|string $params
3192 * @param array $options
3195 public function post($url, $params = '', $options = array()){
3196 $options['CURLOPT_POST'] = 1;
3197 if (is_array($params)) {
3198 $this->_tmp_file_post_params = array();
3199 foreach ($params as $key => $value) {
3200 if ($value instanceof stored_file) {
3201 $value->add_to_curl_request($this, $key);
3203 $this->_tmp_file_post_params[$key] = $value;
3206 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3207 unset($this->_tmp_file_post_params);
3209 // $params is the raw post data
3210 $options['CURLOPT_POSTFIELDS'] = $params;
3212 return $this->request($url, $options);
3218 * @param string $url
3219 * @param array $params
3220 * @param array $options
3223 public function get($url, $params = array(), $options = array()){
3224 $options['CURLOPT_HTTPGET'] = 1;
3226 if (!empty($params)){
3227 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3228 $url .= http_build_query($params, '', '&');
3230 return $this->request($url, $options);
3234 * Downloads one file and writes it to the specified file handler
3238 * $file = fopen('savepath', 'w');
3239 * $result = $c->download_one('http://localhost/', null,
3240 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3242 * $download_info = $c->get_info();
3243 * if ($result === true) {
3244 * // file downloaded successfully
3246 * $error_text = $result;
3247 * $error_code = $c->get_errno();
3253 * $result = $c->download_one('http://localhost/', null,
3254 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3255 * // ... see above, no need to close handle and remove file if unsuccessful
3258 * @param string $url
3259 * @param array|null $params key-value pairs to be added to $url as query string
3260 * @param array $options request options. Must include either 'file' or 'filepath'
3261 * @return bool|string true on success or error string on failure
3263 public function download_one($url, $params, $options = array()) {
3264 $options['CURLOPT_HTTPGET'] = 1;
3265 $options['CURLOPT_BINARYTRANSFER'] = true;
3266 if (!empty($params)){
3267 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3268 $url .= http_build_query($params, '', '&');
3270 if (!empty($options['filepath']) && empty($options['file'])) {
3272 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3274 return get_string('cannotwritefile', 'error', $options['filepath']);
3276 $filepath = $options['filepath'];
3278 unset($options['filepath']);
3279 $result = $this->request($url, $options);
3280 if (isset($filepath)) {
3281 fclose($options['file']);
3282 if ($result !== true) {
3292 * @param string $url
3293 * @param array $params
3294 * @param array $options
3297 public function put($url, $params = array(), $options = array()){
3298 $file = $params['file'];
3299 if (!is_file($file)){
3302 $fp = fopen($file, 'r');
3303 $size = filesize($file);
3304 $options['CURLOPT_PUT'] = 1;
3305 $options['CURLOPT_INFILESIZE'] = $size;
3306 $options['CURLOPT_INFILE'] = $fp;
3307 if (!isset($this->options['CURLOPT_USERPWD'])){
3308 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3310 $ret = $this->request($url, $options);
3316 * HTTP DELETE method
3318 * @param string $url
3319 * @param array $param
3320 * @param array $options
3323 public function delete($url, $param = array(), $options = array()){
3324 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3325 if (!isset($options['CURLOPT_USERPWD'])) {
3326 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3328 $ret = $this->request($url, $options);
3335 * @param string $url
3336 * @param array $options
3339 public function trace($url, $options = array()){
3340 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3341 $ret = $this->request($url, $options);
3346 * HTTP OPTIONS method
3348 * @param string $url
3349 * @param array $options
3352 public function options($url, $options = array()){
3353 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3354 $ret = $this->request($url, $options);
3359 * Get curl information
3363 public function get_info() {
3368 * Get curl error code
3372 public function get_errno() {
3373 return $this->errno;
3377 * When using a proxy, an additional HTTP response code may appear at
3378 * the start of the header. For example, when using https over a proxy
3379 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3380 * also possible and some may come with their own headers.
3382 * If using the return value containing all headers, this function can be
3383 * called to remove unwanted doubles.
3385 * Note that it is not possible to distinguish this situation from valid
3386 * data unless you know the actual response part (below the headers)
3387 * will not be included in this string, or else will not 'look like' HTTP
3388 * headers. As a result it is not safe to call this function for general
3391 * @param string $input Input HTTP response
3392 * @return string HTTP response with additional headers stripped if any
3394 public static function strip_double_headers($input) {
3395 // I have tried to make this regular expression as specific as possible
3396 // to avoid any case where it does weird stuff if you happen to put
3397 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3398 // also make it faster because it can abandon regex processing as soon
3399 // as it hits something that doesn't look like an http header. The
3400 // header definition is taken from RFC 822, except I didn't support
3401 // folding which is never used in practice.
3403 return preg_replace(
3404 // HTTP version and status code (ignore value of code).
3405 '~^HTTP/1\..*' . $crlf .
3406 // Header name: character between 33 and 126 decimal, except colon.
3407 // Colon. Header value: any character except \r and \n. CRLF.
3408 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3409 // Headers are terminated by another CRLF (blank line).
3411 // Second HTTP status code, this time must be 200.
3412 '(HTTP/1.[01] 200 )~', '$1', $input);
3417 * This class is used by cURL class, use case:
3420 * $CFG->repositorycacheexpire = 120;
3421 * $CFG->curlcache = 120;
3423 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3424 * $ret = $c->get('http://www.google.com');
3427 * @package core_files
3428 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3432 /** @var string Path to cache directory */
3438 * @global stdClass $CFG
3439 * @param string $module which module is using curl_cache
3441 public function __construct($module = 'repository') {
3443 if (!empty($module)) {
3444 $this->dir = $CFG->cachedir.'/'.$module.'/';
3446 $this->dir = $CFG->cachedir.'/misc/';
3448 if (!file_exists($this->dir)) {
3449 mkdir($this->dir, $CFG->directorypermissions, true);
3451 if ($module == 'repository') {
3452 if (empty($CFG->repositorycacheexpire)) {
3453 $CFG->repositorycacheexpire = 120;
3455 $this->ttl = $CFG->repositorycacheexpire;
3457 if (empty($CFG->curlcache)) {
3458 $CFG->curlcache = 120;
3460 $this->ttl = $CFG->curlcache;
3467 * @global stdClass $CFG
3468 * @global stdClass $USER
3469 * @param mixed $param
3470 * @return bool|string
3472 public function get($param) {
3474 $this->cleanup($this->ttl);
3475 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3476 if(file_exists($this->dir.$filename)) {
3477 $lasttime = filemtime($this->dir.$filename);
3478 if (time()-$lasttime > $this->ttl) {
3481 $fp = fopen($this->dir.$filename, 'r');
3482 $size = filesize($this->dir.$filename);
3483 $content = fread($fp, $size);
3484 return unserialize($content);
3493 * @global object $CFG
3494 * @global object $USER
3495 * @param mixed $param
3498 public function set($param, $val) {
3500 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3501 $fp = fopen($this->dir.$filename, 'w');
3502 fwrite($fp, serialize($val));
3507 * Remove cache files
3509 * @param int $expire The number of seconds before expiry
3511 public function cleanup($expire) {
3512 if ($dir = opendir($this->dir)) {
3513 while (false !== ($file = readdir($dir))) {
3514 if(!is_dir($file) && $file != '.' && $file != '..') {
3515 $lasttime = @filemtime($this->dir.$file);
3516 if (time() - $lasttime > $expire) {
3517 @unlink($this->dir.$file);
3525 * delete current user's cache file
3527 * @global object $CFG
3528 * @global object $USER