3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Functions for file handling.
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** @var 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
43 * @param string $urlbase
44 * @param string $path /filearea/itemid/dir/dir/file.exe
45 * @param bool $forcedownload
46 * @param bool $https https url required
47 * @return string encoded file url
49 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
52 //TODO: deprecate this
54 if ($CFG->slasharguments) {
55 $parts = explode('/', $path);
56 $parts = array_map('rawurlencode', $parts);
57 $path = implode('/', $parts);
58 $return = $urlbase.$path;
60 $return .= '?forcedownload=1';
63 $path = rawurlencode($path);
64 $return = $urlbase.'?file='.$path;
66 $return .= '&forcedownload=1';
71 $return = str_replace('http://', 'https://', $return);
78 * Prepares 'editor' formslib element from data in database
80 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
81 * function then copies the embedded files into draft area (assigning itemids automatically),
82 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
84 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
85 * your mform's set_data() supplying the object returned by this function.
87 * @param object $data database field that holds the html text with embedded media
88 * @param string $field the name of the database field that holds the html text with embedded media
89 * @param array $options editor options (like maxifiles, maxbytes etc.)
90 * @param object $context context of the editor
91 * @param string $component
92 * @param string $filearea file area name
93 * @param int $itemid item id, required if item exists
94 * @return object modified data object
96 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
97 $options = (array)$options;
98 if (!isset($options['trusttext'])) {
99 $options['trusttext'] = false;
101 if (!isset($options['forcehttps'])) {
102 $options['forcehttps'] = false;
104 if (!isset($options['subdirs'])) {
105 $options['subdirs'] = false;
107 if (!isset($options['maxfiles'])) {
108 $options['maxfiles'] = 0; // no files by default
110 if (!isset($options['noclean'])) {
111 $options['noclean'] = false;
114 //sanity check for passed context. This function doesn't expect $option['context'] to be set
115 //But this function is called before creating editor hence, this is one of the best places to check
116 //if context is used properly. This check notify developer that they missed passing context to editor.
117 if (isset($context) && !isset($options['context'])) {
118 //if $context is not null then make sure $option['context'] is also set.
119 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
120 } else if (isset($options['context']) && isset($context)) {
121 //If both are passed then they should be equal.
122 if ($options['context']->id != $context->id) {
123 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
124 throw new coding_exception($exceptionmsg);
128 if (is_null($itemid) or is_null($context)) {
131 if (!isset($data->{$field})) {
132 $data->{$field} = '';
134 if (!isset($data->{$field.'format'})) {
135 $data->{$field.'format'} = editors_get_preferred_format();
137 if (!$options['noclean']) {
138 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
142 if ($options['trusttext']) {
143 // noclean ignored if trusttext enabled
144 if (!isset($data->{$field.'trust'})) {
145 $data->{$field.'trust'} = 0;
147 $data = trusttext_pre_edit($data, $field, $context);
149 if (!$options['noclean']) {
150 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
153 $contextid = $context->id;
156 if ($options['maxfiles'] != 0) {
157 $draftid_editor = file_get_submitted_draft_itemid($field);
158 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
159 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
161 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
168 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
170 * This function moves files from draft area to the destination area and
171 * encodes URLs to the draft files so they can be safely saved into DB. The
172 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
173 * is the name of the database field to hold the wysiwyg editor content. The
174 * editor data comes as an array with text, format and itemid properties. This
175 * function automatically adds $data properties foobar, foobarformat and
176 * foobartrust, where foobar has URL to embedded files encoded.
178 * @param object $data raw data submitted by the form
179 * @param string $field name of the database field containing the html with embedded media files
180 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
181 * @param object $context context, required for existing data
182 * @param string component
183 * @param string $filearea file area name
184 * @param int $itemid item id, required if item exists
185 * @return object modified data object
187 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
188 $options = (array)$options;
189 if (!isset($options['trusttext'])) {
190 $options['trusttext'] = false;
192 if (!isset($options['forcehttps'])) {
193 $options['forcehttps'] = false;
195 if (!isset($options['subdirs'])) {
196 $options['subdirs'] = false;
198 if (!isset($options['maxfiles'])) {
199 $options['maxfiles'] = 0; // no files by default
201 if (!isset($options['maxbytes'])) {
202 $options['maxbytes'] = 0; // unlimited
205 if ($options['trusttext']) {
206 $data->{$field.'trust'} = trusttext_trusted($context);
208 $data->{$field.'trust'} = 0;
211 $editor = $data->{$field.'_editor'};
213 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
214 $data->{$field} = $editor['text'];
216 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
218 $data->{$field.'format'} = $editor['format'];
224 * Saves text and files modified by Editor formslib element
226 * @param object $data $database entry field
227 * @param string $field name of data field
228 * @param array $options various options
229 * @param object $context context - must already exist
230 * @param string $component
231 * @param string $filearea file area name
232 * @param int $itemid must already exist, usually means data is in db
233 * @return object modified data obejct
235 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
236 $options = (array)$options;
237 if (!isset($options['subdirs'])) {
238 $options['subdirs'] = false;
240 if (is_null($itemid) or is_null($context)) {
244 $contextid = $context->id;
247 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
248 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
249 $data->{$field.'_filemanager'} = $draftid_editor;
255 * Saves files modified by File manager formslib element
257 * @param object $data $database entry field
258 * @param string $field name of data field
259 * @param array $options various options
260 * @param object $context context - must already exist
261 * @param string $component
262 * @param string $filearea file area name
263 * @param int $itemid must already exist, usually means data is in db
264 * @return object modified data obejct
266 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
267 $options = (array)$options;
268 if (!isset($options['subdirs'])) {
269 $options['subdirs'] = false;
271 if (!isset($options['maxfiles'])) {
272 $options['maxfiles'] = -1; // unlimited
274 if (!isset($options['maxbytes'])) {
275 $options['maxbytes'] = 0; // unlimited
278 if (empty($data->{$field.'_filemanager'})) {
282 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
283 $fs = get_file_storage();
285 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
286 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
299 * @return int a random but available draft itemid that can be used to create a new draft
302 function file_get_unused_draft_itemid() {
305 if (isguestuser() or !isloggedin()) {
306 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
307 print_error('noguest');
310 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
312 $fs = get_file_storage();
313 $draftitemid = rand(1, 999999999);
314 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
315 $draftitemid = rand(1, 999999999);
322 * Initialise a draft file area from a real one by copying the files. A draft
323 * area will be created if one does not already exist. Normally you should
324 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
328 * @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.
329 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
330 * @param string $component
331 * @param string $filearea helps indentify the file area.
332 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
333 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
334 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
335 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
337 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
338 global $CFG, $USER, $CFG;
340 $options = (array)$options;
341 if (!isset($options['subdirs'])) {
342 $options['subdirs'] = false;
344 if (!isset($options['forcehttps'])) {
345 $options['forcehttps'] = false;
348 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
349 $fs = get_file_storage();
351 if (empty($draftitemid)) {
352 // create a new area and copy existing files into
353 $draftitemid = file_get_unused_draft_itemid();
354 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
355 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
356 foreach ($files as $file) {
357 if ($file->is_directory() and $file->get_filepath() === '/') {
358 // we need a way to mark the age of each draft area,
359 // by not copying the root dir we force it to be created automatically with current timestamp
362 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
365 $fs->create_file_from_storedfile($file_record, $file);
368 if (!is_null($text)) {
369 // at this point there should not be any draftfile links yet,
370 // because this is a new text from database that should still contain the @@pluginfile@@ links
371 // this happens when developers forget to post process the text
372 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
378 if (is_null($text)) {
382 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
383 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
387 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
390 * @param string $text The content that may contain ULRs in need of rewriting.
391 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
392 * @param integer $contextid This parameter and the next two identify the file area to use.
393 * @param string $component
394 * @param string $filearea helps identify the file area.
395 * @param integer $itemid helps identify the file area.
396 * @param array $options text and file options ('forcehttps'=>false)
397 * @return string the processed text.
399 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
402 $options = (array)$options;
403 if (!isset($options['forcehttps'])) {
404 $options['forcehttps'] = false;
407 if (!$CFG->slasharguments) {
408 $file = $file . '?file=';
411 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
413 if ($itemid !== null) {
414 $baseurl .= "$itemid/";
417 if ($options['forcehttps']) {
418 $baseurl = str_replace('http://', 'https://', $baseurl);
421 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
425 * Returns information about files in a draft area.
429 * @param integer $draftitemid the draft area item id.
430 * @return array with the following entries:
431 * 'filecount' => number of files in the draft area.
432 * (more information will be added as needed).
434 function file_get_draft_area_info($draftitemid) {
437 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
438 $fs = get_file_storage();
442 // The number of files
443 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
444 $results['filecount'] = count($draftfiles);
445 $results['filesize'] = 0;
446 foreach ($draftfiles as $file) {
447 $results['filesize'] += $file->get_filesize();
454 * Get used space of files
455 * @return int total bytes
457 function file_get_user_used_space() {
460 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
461 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
462 JOIN (SELECT contenthash, filename, MAX(id) AS id
464 WHERE contextid = ? AND component = ? AND filearea != ?
465 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
466 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
467 $record = $DB->get_record_sql($sql, $params);
468 return (int)$record->totalbytes;
472 * Convert any string to a valid filepath
474 * @return string path
476 function file_correct_filepath($str) { //TODO: what is this? (skodak)
477 if ($str == '/' or empty($str)) {
480 return '/'.trim($str, './@#$ ').'/';
485 * Generate a folder tree of draft area of current USER recursively
487 * @param string $filepath
488 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
490 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
491 global $USER, $OUTPUT, $CFG;
492 $data->children = array();
493 $context = get_context_instance(CONTEXT_USER, $USER->id);
494 $fs = get_file_storage();
495 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
496 foreach ($files as $file) {
497 if ($file->is_directory()) {
498 $item = new stdClass();
499 $item->sortorder = $file->get_sortorder();
500 $item->filepath = $file->get_filepath();
502 $foldername = explode('/', trim($item->filepath, '/'));
503 $item->fullname = trim(array_pop($foldername), '/');
505 $item->id = uniqid();
506 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
507 $data->children[] = $item;
516 * Listing all files (including folders) in current path (draft area)
517 * used by file manager
518 * @param int $draftitemid
519 * @param string $filepath
522 function file_get_drafarea_files($draftitemid, $filepath = '/') {
523 global $USER, $OUTPUT, $CFG;
525 $context = get_context_instance(CONTEXT_USER, $USER->id);
526 $fs = get_file_storage();
528 $data = new stdClass();
529 $data->path = array();
530 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
532 // will be used to build breadcrumb
534 if ($filepath !== '/') {
535 $filepath = file_correct_filepath($filepath);
536 $parts = explode('/', $filepath);
537 foreach ($parts as $part) {
538 if ($part != '' && $part != null) {
539 $trail .= ('/'.$part.'/');
540 $data->path[] = array('name'=>$part, 'path'=>$trail);
547 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
548 foreach ($files as $file) {
549 $item = new stdClass();
550 $item->filename = $file->get_filename();
551 $item->filepath = $file->get_filepath();
552 $item->fullname = trim($item->filename, '/');
553 $filesize = $file->get_filesize();
554 $item->filesize = $filesize ? display_size($filesize) : '';
556 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
557 $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
558 $item->sortorder = $file->get_sortorder();
560 if ($icon == 'zip') {
563 $item->type = 'file';
566 if ($file->is_directory()) {
568 $item->icon = $OUTPUT->pix_url('f/folder')->out();
569 $item->type = 'folder';
570 $foldername = explode('/', trim($item->filepath, '/'));
571 $item->fullname = trim(array_pop($foldername), '/');
573 // do NOT use file browser here!
574 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
579 $data->itemid = $draftitemid;
585 * Returns draft area itemid for a given element.
587 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
588 * @return integer the itemid, or 0 if there is not one yet.
590 function file_get_submitted_draft_itemid($elname) {
591 $param = optional_param($elname, 0, PARAM_INT);
595 if (is_array($param)) {
596 if (!empty($param['itemid'])) {
597 $param = $param['itemid'];
599 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
607 * Saves files from a draft file area to a real one (merging the list of files).
608 * Can rewrite URLs in some content at the same time if desired.
612 * @param integer $draftitemid the id of the draft area to use. Normally obtained
613 * from file_get_submitted_draft_itemid('elementname') or similar.
614 * @param integer $contextid This parameter and the next two identify the file area to save to.
615 * @param string $component
616 * @param string $filearea indentifies the file area.
617 * @param integer $itemid helps identifies the file area.
618 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
619 * @param string $text some html content that needs to have embedded links rewritten
620 * to the @@PLUGINFILE@@ form for saving in the database.
621 * @param boolean $forcehttps force https urls.
622 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
624 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
627 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
628 $fs = get_file_storage();
630 $options = (array)$options;
631 if (!isset($options['subdirs'])) {
632 $options['subdirs'] = false;
634 if (!isset($options['maxfiles'])) {
635 $options['maxfiles'] = -1; // unlimited
637 if (!isset($options['maxbytes'])) {
638 $options['maxbytes'] = 0; // unlimited
641 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
642 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
644 if (count($draftfiles) < 2) {
645 // means there are no files - one file means root dir only ;-)
646 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
648 } else if (count($oldfiles) < 2) {
650 // there were no files before - one file means root dir only ;-)
651 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
652 foreach ($draftfiles as $file) {
653 if (!$options['subdirs']) {
654 if ($file->get_filepath() !== '/' or $file->is_directory()) {
658 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
659 // oversized file - should not get here at all
662 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
663 // more files - should not get here at all
666 if (!$file->is_directory()) {
669 $fs->create_file_from_storedfile($file_record, $file);
673 // we have to merge old and new files - we want to keep file ids for files that were not changed
674 // we change time modified for all new and changed files, we keep time created as is
675 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
677 $newhashes = array();
678 foreach ($draftfiles as $file) {
679 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
680 $newhashes[$newhash] = $file;
683 foreach ($oldfiles as $oldfile) {
684 $oldhash = $oldfile->get_pathnamehash();
685 if (!isset($newhashes[$oldhash])) {
686 // delete files not needed any more - deleted by user
690 $newfile = $newhashes[$oldhash];
691 if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
692 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
693 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
694 // file was changed, use updated with new timemodified data
698 // unchanged file or directory - we keep it as is
699 unset($newhashes[$oldhash]);
700 if (!$oldfile->is_directory()) {
705 // now add new/changed files
706 // the size and subdirectory tests are extra safety only, the UI should prevent it
707 foreach ($newhashes as $file) {
708 if (!$options['subdirs']) {
709 if ($file->get_filepath() !== '/' or $file->is_directory()) {
713 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
714 // oversized file - should not get here at all
717 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
718 // more files - should not get here at all
721 if (!$file->is_directory()) {
724 $fs->create_file_from_storedfile($file_record, $file);
728 // note: do not purge the draft area - we clean up areas later in cron,
729 // the reason is that user might press submit twice and they would loose the files,
730 // also sometimes we might want to use hacks that save files into two different areas
732 if (is_null($text)) {
735 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
740 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
741 * ready to be saved in the database. Normally, this is done automatically by
742 * {@link file_save_draft_area_files()}.
743 * @param string $text the content to process.
744 * @param int $draftitemid the draft file area the content was using.
745 * @param bool $forcehttps whether the content contains https URLs. Default false.
746 * @return string the processed content.
748 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
751 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
753 $wwwroot = $CFG->wwwroot;
755 $wwwroot = str_replace('http://', 'https://', $wwwroot);
758 // relink embedded files if text submitted - no absolute links allowed in database!
759 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
761 if (strpos($text, 'draftfile.php?file=') !== false) {
763 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
765 foreach ($matches[0] as $match) {
766 $replace = str_ireplace('%2F', '/', $match);
767 $text = str_replace($match, $replace, $text);
770 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
777 * Set file sort order
779 * @param integer $contextid the context id
780 * @param string $component
781 * @param string $filearea file area.
782 * @param integer $itemid itemid.
783 * @param string $filepath file path.
784 * @param string $filename file name.
785 * @param integer $sortorer the sort order of file.
788 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
790 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
791 if ($file_record = $DB->get_record('files', $conditions)) {
792 $sortorder = (int)$sortorder;
793 $file_record->sortorder = $sortorder;
794 $DB->update_record('files', $file_record);
801 * reset file sort order number to 0
803 * @param integer $contextid the context id
804 * @param string $component
805 * @param string $filearea file area.
806 * @param integer $itemid itemid.
809 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
812 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
813 if ($itemid !== false) {
814 $conditions['itemid'] = $itemid;
817 $file_records = $DB->get_records('files', $conditions);
818 foreach ($file_records as $file_record) {
819 $file_record->sortorder = 0;
820 $DB->update_record('files', $file_record);
826 * Returns description of upload error
828 * @param int $errorcode found in $_FILES['filename.ext']['error']
829 * @return string error description string, '' if ok
831 function file_get_upload_error($errorcode) {
833 switch ($errorcode) {
834 case 0: // UPLOAD_ERR_OK - no error
838 case 1: // UPLOAD_ERR_INI_SIZE
839 $errmessage = get_string('uploadserverlimit');
842 case 2: // UPLOAD_ERR_FORM_SIZE
843 $errmessage = get_string('uploadformlimit');
846 case 3: // UPLOAD_ERR_PARTIAL
847 $errmessage = get_string('uploadpartialfile');
850 case 4: // UPLOAD_ERR_NO_FILE
851 $errmessage = get_string('uploadnofilefound');
854 // Note: there is no error with a value of 5
856 case 6: // UPLOAD_ERR_NO_TMP_DIR
857 $errmessage = get_string('uploadnotempdir');
860 case 7: // UPLOAD_ERR_CANT_WRITE
861 $errmessage = get_string('uploadcantwrite');
864 case 8: // UPLOAD_ERR_EXTENSION
865 $errmessage = get_string('uploadextension');
869 $errmessage = get_string('uploadproblem');
876 * Recursive function formating an array in POST parameter
877 * @param array $arraydata - the array that we are going to format and add into &$data array
878 * @param string $currentdata - a row of the final postdata array at instant T
879 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
880 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
882 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
883 foreach ($arraydata as $k=>$v) {
884 $newcurrentdata = $currentdata;
885 if (is_array($v)) { //the value is an array, call the function recursively
886 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
887 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
888 } else { //add the POST parameter to the $data array
889 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
895 * Transform a PHP array into POST parameter
896 * (see the recursive function format_array_postdata_for_curlcall)
897 * @param array $postdata
898 * @return array containing all POST parameters (1 row = 1 POST parameter)
900 function format_postdata_for_curlcall($postdata) {
902 foreach ($postdata as $k=>$v) {
904 $currentdata = urlencode($k);
905 format_array_postdata_for_curlcall($v, $currentdata, $data);
907 $data[] = urlencode($k).'='.urlencode($v);
910 $convertedpostdata = implode('&', $data);
911 return $convertedpostdata;
918 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
919 * Due to security concerns only downloads from http(s) sources are supported.
921 * @param string $url file url starting with http(s)://
922 * @param array $headers http headers, null if none. If set, should be an
923 * associative array of header name => value pairs.
924 * @param array $postdata array means use POST request with given parameters
925 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
926 * (if false, just returns content)
927 * @param int $timeout timeout for complete download process including all file transfer
928 * (default 5 minutes)
929 * @param int $connecttimeout timeout for connection to server; this is the timeout that
930 * usually happens if the remote server is completely down (default 20 seconds);
931 * may not work when using proxy
932 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
933 * Only use this when already in a trusted location.
934 * @param string $tofile store the downloaded content to file instead of returning it.
935 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
936 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
937 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
939 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
942 // some extra security
943 $newlines = array("\r", "\n");
944 if (is_array($headers) ) {
945 foreach ($headers as $key => $value) {
946 $headers[$key] = str_replace($newlines, '', $value);
949 $url = str_replace($newlines, '', $url);
950 if (!preg_match('|^https?://|i', $url)) {
952 $response = new stdClass();
953 $response->status = 0;
954 $response->headers = array();
955 $response->response_code = 'Invalid protocol specified in url';
956 $response->results = '';
957 $response->error = 'Invalid protocol specified in url';
964 // check if proxy (if used) should be bypassed for this url
965 $proxybypass = is_proxybypass($url);
967 if (!$ch = curl_init($url)) {
968 debugging('Can not init curl.');
973 if (is_array($headers) ) {
975 foreach ($headers as $key => $value) {
976 $headers2[] = "$key: $value";
978 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
981 if ($skipcertverify) {
982 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
985 // use POST if requested
986 if (is_array($postdata)) {
987 $postdata = format_postdata_for_curlcall($postdata);
988 curl_setopt($ch, CURLOPT_POST, true);
989 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
992 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
993 curl_setopt($ch, CURLOPT_HEADER, false);
994 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
996 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
997 // TODO: add version test for '7.10.5'
998 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
999 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1002 if (!empty($CFG->proxyhost) and !$proxybypass) {
1003 // SOCKS supported in PHP5 only
1004 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1005 if (defined('CURLPROXY_SOCKS5')) {
1006 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1009 if ($fullresponse) {
1010 $response = new stdClass();
1011 $response->status = '0';
1012 $response->headers = array();
1013 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1014 $response->results = '';
1015 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1018 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1024 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1026 if (empty($CFG->proxyport)) {
1027 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1029 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1032 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1033 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1034 if (defined('CURLOPT_PROXYAUTH')) {
1035 // any proxy authentication if PHP 5.1
1036 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1041 // set up header and content handlers
1042 $received = new stdClass();
1043 $received->headers = array(); // received headers array
1044 $received->tofile = $tofile;
1045 $received->fh = null;
1046 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1048 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1051 if (!isset($CFG->curltimeoutkbitrate)) {
1052 //use very slow rate of 56kbps as a timeout speed when not set
1055 $bitrate = $CFG->curltimeoutkbitrate;
1058 // try to calculate the proper amount for timeout from remote file size.
1059 // if disabled or zero, we won't do any checks nor head requests.
1060 if ($calctimeout && $bitrate > 0) {
1061 //setup header request only options
1062 curl_setopt_array ($ch, array(
1063 CURLOPT_RETURNTRANSFER => false,
1064 CURLOPT_NOBODY => true)
1068 $info = curl_getinfo($ch);
1069 $err = curl_error($ch);
1071 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1072 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1074 //reinstate affected curl options
1075 curl_setopt_array ($ch, array(
1076 CURLOPT_RETURNTRANSFER => true,
1077 CURLOPT_NOBODY => false)
1081 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1082 $result = curl_exec($ch);
1084 // try to detect encoding problems
1085 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1086 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1087 $result = curl_exec($ch);
1090 if ($received->fh) {
1091 fclose($received->fh);
1094 if (curl_errno($ch)) {
1095 $error = curl_error($ch);
1096 $error_no = curl_errno($ch);
1099 if ($fullresponse) {
1100 $response = new stdClass();
1101 if ($error_no == 28) {
1102 $response->status = '-100'; // mimic snoopy
1104 $response->status = '0';
1106 $response->headers = array();
1107 $response->response_code = $error;
1108 $response->results = false;
1109 $response->error = $error;
1112 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1117 $info = curl_getinfo($ch);
1120 if (empty($info['http_code'])) {
1121 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1122 $response = new stdClass();
1123 $response->status = '0';
1124 $response->headers = array();
1125 $response->response_code = 'Unknown cURL error';
1126 $response->results = false; // do NOT change this, we really want to ignore the result!
1127 $response->error = 'Unknown cURL error';
1130 $response = new stdClass();;
1131 $response->status = (string)$info['http_code'];
1132 $response->headers = $received->headers;
1133 $response->response_code = $received->headers[0];
1134 $response->results = $result;
1135 $response->error = '';
1138 if ($fullresponse) {
1140 } else if ($info['http_code'] != 200) {
1141 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1144 return $response->results;
1150 * internal implementation
1152 function download_file_content_header_handler($received, $ch, $header) {
1153 $received->headers[] = $header;
1154 return strlen($header);
1158 * internal implementation
1160 function download_file_content_write_handler($received, $ch, $data) {
1161 if (!$received->fh) {
1162 $received->fh = fopen($received->tofile, 'w');
1163 if ($received->fh === false) {
1164 // bad luck, file creation or overriding failed
1168 if (fwrite($received->fh, $data) === false) {
1169 // bad luck, write failed, let's abort completely
1172 return strlen($data);
1176 * @return array List of information about file types based on extensions.
1177 * Associative array of extension (lower-case) to associative array
1178 * from 'element name' to data. Current element names are 'type' and 'icon'.
1179 * Unknown types should use the 'xxx' entry which includes defaults.
1181 function get_mimetypes_array() {
1182 static $mimearray = array (
1183 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1184 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1185 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
1186 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1187 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1188 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1189 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1190 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1191 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1192 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1193 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1194 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1195 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1196 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1197 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1198 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1199 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1200 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1201 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1202 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1203 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1205 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1206 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1207 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1208 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1209 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1211 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1212 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1213 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1214 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1215 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1216 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1217 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1218 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1219 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1220 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1221 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1222 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1223 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1224 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1225 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1226 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1227 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1228 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1229 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1230 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1231 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1232 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1233 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1234 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1235 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1236 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1237 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1238 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1239 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1240 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1241 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1242 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1243 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1244 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1245 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1246 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1247 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1248 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1249 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1250 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1251 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1252 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1253 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1254 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1255 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1256 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1257 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1258 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1260 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1261 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1262 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1263 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1264 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1265 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1266 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1267 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1268 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1269 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1270 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1271 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1272 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1273 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1274 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1275 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1276 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
1278 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1279 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1280 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1281 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1282 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1283 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1285 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1286 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1287 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1288 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1289 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1290 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1291 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1292 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1293 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1295 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1296 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1297 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1298 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1299 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1300 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1301 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
1302 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1303 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1304 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
1305 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1306 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1307 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1308 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1309 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1310 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1311 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1312 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1313 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1314 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1316 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1317 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1318 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1319 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1320 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1321 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1322 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1323 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1324 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1325 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1327 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1328 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1329 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1330 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1331 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1332 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1333 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1334 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1335 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1336 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
1337 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1338 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1339 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1340 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1341 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1343 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1344 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1345 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1346 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1347 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1348 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1349 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1351 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1352 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1353 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1359 * Obtains information about a filetype based on its extension. Will
1360 * use a default if no information is present about that particular
1363 * @param string $element Desired information (usually 'icon'
1364 * for icon filename or 'type' for MIME type)
1365 * @param string $filename Filename we're looking up
1366 * @return string Requested piece of information from array
1368 function mimeinfo($element, $filename) {
1370 $mimeinfo = get_mimetypes_array();
1372 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1373 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1374 return $mimeinfo[strtolower($match[1])][$element];
1376 if ($element == 'icon32') {
1377 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1378 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1380 $filename = 'unknown';
1383 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1386 return 'unknown-32';
1389 return $mimeinfo['xxx'][$element]; // By default
1393 if ($element == 'icon32') {
1394 return 'unknown-32';
1396 return $mimeinfo['xxx'][$element]; // By default
1401 * Obtains information about a filetype based on the MIME type rather than
1402 * the other way around.
1404 * @param string $element Desired information (usually 'icon')
1405 * @param string $mimetype MIME type we're looking up
1406 * @return string Requested piece of information from array
1408 function mimeinfo_from_type($element, $mimetype) {
1409 $mimeinfo = get_mimetypes_array();
1411 foreach($mimeinfo as $values) {
1412 if ($values['type']==$mimetype) {
1413 if (isset($values[$element])) {
1414 return $values[$element];
1419 return $mimeinfo['xxx'][$element]; // Default
1423 * Get information about a filetype based on the icon file.
1425 * @param string $element Desired information (usually 'icon')
1426 * @param string $icon Icon file name without extension
1427 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1428 * @return string Requested piece of information from array
1430 function mimeinfo_from_icon($element, $icon, $all=false) {
1431 $mimeinfo = get_mimetypes_array();
1433 if (preg_match("/\/(.*)/", $icon, $matches)) {
1434 $icon = $matches[1];
1436 // Try to get the extension
1438 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1439 $extension = substr($icon, $cutat + 1);
1441 $info = array($mimeinfo['xxx'][$element]); // Default
1442 foreach($mimeinfo as $key => $values) {
1443 if ($values['icon']==$icon) {
1444 if (isset($values[$element])) {
1445 $info[$key] = $values[$element];
1447 //No break, for example for 'excel' we don't want 'csv'!
1451 if (count($info) > 1) {
1452 array_shift($info); // take off document/unknown if we have better options
1454 return array_values($info); // Keep keys out when requesting all
1457 // Requested only one, try to get the best by extension coincidence, else return the last
1458 if ($extension && isset($info[$extension])) {
1459 return $info[$extension];
1462 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1466 * Returns the relative icon path for a given mime type
1468 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1469 * a return the full path to an icon.
1472 * $mimetype = 'image/jpg';
1473 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1474 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1477 * @todo When an $OUTPUT->icon method is available this function should be altered
1478 * to conform with that.
1480 * @param string $mimetype The mimetype to fetch an icon for
1481 * @param int $size The size of the icon. Not yet implemented
1482 * @return string The relative path to the icon
1484 function file_mimetype_icon($mimetype, $size = NULL) {
1487 $icon = mimeinfo_from_type('icon', $mimetype);
1489 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1490 $icon = "$icon-$size";
1497 * Returns the relative icon path for a given file name
1499 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1500 * a return the full path to an icon.
1503 * $filename = 'jpg';
1504 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1505 * echo '<img src="'.$icon.'" alt="blah" />';
1508 * @todo When an $OUTPUT->icon method is available this function should be altered
1509 * to conform with that.
1510 * @todo Implement $size
1512 * @param string filename The filename to get the icon for
1513 * @param int $size The size of the icon. Defaults to null can also be 32
1516 function file_extension_icon($filename, $size = NULL) {
1519 $icon = mimeinfo('icon', $filename);
1521 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1522 $icon = "$icon-$size";
1529 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1530 * mimetypes.php language file.
1532 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1533 * @param bool $capitalise If true, capitalises first character of result
1534 * @return string Text description
1536 function get_mimetype_description($mimetype, $capitalise=false) {
1537 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1538 $result = get_string($mimetype, 'mimetypes');
1540 $result = get_string('document/unknown','mimetypes');
1543 $result=ucfirst($result);
1549 * Requested file is not found or not accessible
1551 * @return does not return, terminates script
1553 function send_file_not_found() {
1554 global $CFG, $COURSE;
1555 header('HTTP/1.0 404 not found');
1556 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1560 * Check output buffering settings before sending file.
1561 * Please note you should not send any other headers after calling this function.
1563 * @private to be called only from lib/filelib.php !
1566 function prepare_file_content_sending() {
1567 // We needed to be able to send headers up until now
1568 if (headers_sent()) {
1569 throw new file_serving_exception('Headers already sent, can not serve file.');
1572 $olddebug = error_reporting(0);
1574 // IE compatibility HACK - it does not like zlib compression much
1575 // there is also a problem with the length header in older PHP versions
1576 if (ini_get_bool('zlib.output_compression')) {
1577 ini_set('zlib.output_compression', 'Off');
1580 // flush and close all buffers if possible
1581 while(ob_get_level()) {
1582 if (!ob_end_flush()) {
1583 // prevent infinite loop when buffer can not be closed
1588 error_reporting($olddebug);
1590 //NOTE: we can not reliable test headers_sent() here because
1591 // the headers might be sent which trying to close the buffers,
1592 // this happens especially if browser does not support gzip or deflate
1596 * Handles the sending of temporary file to user, download is forced.
1597 * File is deleted after abort or successful sending.
1599 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1600 * @param string $filename proposed file name when saving file
1601 * @param bool $path is content of file
1602 * @return does not return, script terminated
1604 function send_temp_file($path, $filename, $pathisstring=false) {
1607 // close session - not needed anymore
1608 @session_get_instance()->write_close();
1610 if (!$pathisstring) {
1611 if (!file_exists($path)) {
1612 header('HTTP/1.0 404 not found');
1613 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1615 // executed after normal finish or abort
1616 @register_shutdown_function('send_temp_file_finished', $path);
1619 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1620 if (check_browser_version('MSIE')) {
1621 $filename = urlencode($filename);
1624 $filesize = $pathisstring ? strlen($path) : filesize($path);
1626 header('Content-Disposition: attachment; filename='.$filename);
1627 header('Content-Length: '.$filesize);
1628 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1629 header('Cache-Control: max-age=10');
1630 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1632 } else { //normal http - prevent caching at all cost
1633 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1634 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1635 header('Pragma: no-cache');
1637 header('Accept-Ranges: none'); // Do not allow byteserving
1639 //flush the buffers - save memory and disable sid rewrite
1640 // this also disables zlib compression
1641 prepare_file_content_sending();
1643 // send the contents
1644 if ($pathisstring) {
1650 die; //no more chars to output
1654 * Internal callback function used by send_temp_file()
1656 function send_temp_file_finished($path) {
1657 if (file_exists($path)) {
1663 * Handles the sending of file data to the user's browser, including support for
1669 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1670 * @param string $filename Filename to send
1671 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1672 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1673 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1674 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1675 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1676 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1677 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1678 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1679 * and should not be reopened.
1680 * @return no return or void, script execution stopped unless $dontdie is true
1682 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1683 global $CFG, $COURSE, $SESSION;
1686 ignore_user_abort(true);
1689 // MDL-11789, apply $CFG->filelifetime here
1690 if ($lifetime === 'default') {
1691 if (!empty($CFG->filelifetime)) {
1692 $lifetime = $CFG->filelifetime;
1698 session_get_instance()->write_close(); // unlock session during fileserving
1700 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1701 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1702 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1703 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1704 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1705 ($mimetype ? $mimetype : mimeinfo('type', $filename));
1707 $lastmodified = $pathisstring ? time() : filemtime($path);
1708 $filesize = $pathisstring ? strlen($path) : filesize($path);
1711 //Adobe Acrobat Reader XSS prevention
1712 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1713 //please note that it prevents opening of pdfs in browser when http referer disabled
1714 //or file linked from another site; browser caching of pdfs is now disabled too
1715 if (!empty($_SERVER['HTTP_RANGE'])) {
1716 //already byteserving
1717 $lifetime = 1; // >0 needed for byteserving
1718 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1719 $mimetype = 'application/x-forcedownload';
1720 $forcedownload = true;
1723 $lifetime = 1; // >0 needed for byteserving
1728 //try to disable automatic sid rewrite in cookieless mode
1729 @ini_set("session.use_trans_sid", "false");
1731 if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1732 // get unixtime of request header; clip extra junk off first
1733 $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1734 if ($since && $since >= $lastmodified) {
1735 header('HTTP/1.1 304 Not Modified');
1736 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1737 header('Cache-Control: max-age='.$lifetime);
1738 header('Content-Type: '.$mimetype);
1746 //do not put '@' before the next header to detect incorrect moodle configurations,
1747 //error should be better than "weird" empty lines for admins/users
1748 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1750 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1751 if (check_browser_version('MSIE')) {
1752 $filename = rawurlencode($filename);
1755 if ($forcedownload) {
1756 header('Content-Disposition: attachment; filename="'.$filename.'"');
1758 header('Content-Disposition: inline; filename="'.$filename.'"');
1761 if ($lifetime > 0) {
1762 header('Cache-Control: max-age='.$lifetime);
1763 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1766 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1768 header('Accept-Ranges: bytes');
1770 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1771 // byteserving stuff - for acrobat reader and download accelerators
1772 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1773 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1775 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1776 foreach ($ranges as $key=>$value) {
1777 if ($ranges[$key][1] == '') {
1779 $ranges[$key][1] = $filesize - $ranges[$key][2];
1780 $ranges[$key][2] = $filesize - 1;
1781 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1783 $ranges[$key][2] = $filesize - 1;
1785 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1786 //invalid byte-range ==> ignore header
1790 //prepare multipart header
1791 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1792 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1798 $handle = fopen($path, 'rb');
1799 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1803 /// Do not byteserve (disabled, strings, text and html files).
1804 header('Accept-Ranges: none');
1806 } else { // Do not cache files in proxies and browsers
1807 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1808 header('Cache-Control: max-age=10');
1809 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1811 } else { //normal http - prevent caching at all cost
1812 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1813 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1814 header('Pragma: no-cache');
1816 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1819 if (empty($filter)) {
1820 if ($mimetype == 'text/plain') {
1821 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1823 header('Content-Type: '.$mimetype);
1825 header('Content-Length: '.$filesize);
1827 //flush the buffers - save memory and disable sid rewrite
1828 //this also disables zlib compression
1829 prepare_file_content_sending();
1831 // send the contents
1832 if ($pathisstring) {
1838 } else { // Try to put the file through filters
1839 if ($mimetype == 'text/html') {
1840 $options = new stdClass();
1841 $options->noclean = true;
1842 $options->nocache = true; // temporary workaround for MDL-5136
1843 $text = $pathisstring ? $path : implode('', file($path));
1845 $text = file_modify_html_header($text);
1846 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1848 header('Content-Length: '.strlen($output));
1849 header('Content-Type: text/html');
1851 //flush the buffers - save memory and disable sid rewrite
1852 //this also disables zlib compression
1853 prepare_file_content_sending();
1855 // send the contents
1857 // only filter text if filter all files is selected
1858 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1859 $options = new stdClass();
1860 $options->newlines = false;
1861 $options->noclean = true;
1862 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1863 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1865 header('Content-Length: '.strlen($output));
1866 header('Content-Type: text/html; charset=utf-8'); //add encoding
1868 //flush the buffers - save memory and disable sid rewrite
1869 //this also disables zlib compression
1870 prepare_file_content_sending();
1872 // send the contents
1875 } else { // Just send it out raw
1876 header('Content-Length: '.$filesize);
1877 header('Content-Type: '.$mimetype);
1879 //flush the buffers - save memory and disable sid rewrite
1880 //this also disables zlib compression
1881 prepare_file_content_sending();
1883 // send the contents
1884 if ($pathisstring) {
1894 die; //no more chars to output!!!
1898 * Handles the sending of file data to the user's browser, including support for
1904 * @param object $stored_file local file object
1905 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1906 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1907 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1908 * @param string $filename Override filename
1909 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1910 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1911 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1912 * and should not be reopened.
1913 * @return void no return or void, script execution stopped unless $dontdie is true
1915 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1916 global $CFG, $COURSE, $SESSION;
1918 if (!$stored_file or $stored_file->is_directory()) {
1927 ignore_user_abort(true);
1930 session_get_instance()->write_close(); // unlock session during fileserving
1932 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1933 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1934 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1935 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1936 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1937 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1938 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1940 $lastmodified = $stored_file->get_timemodified();
1941 $filesize = $stored_file->get_filesize();
1943 //try to disable automatic sid rewrite in cookieless mode
1944 @ini_set("session.use_trans_sid", "false");
1946 if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1947 // get unixtime of request header; clip extra junk off first
1948 $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1949 if ($since && $since >= $lastmodified) {
1950 header('HTTP/1.1 304 Not Modified');
1951 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1952 header('Cache-Control: max-age='.$lifetime);
1953 header('Content-Type: '.$mimetype);
1961 //do not put '@' before the next header to detect incorrect moodle configurations,
1962 //error should be better than "weird" empty lines for admins/users
1963 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1964 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1966 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1967 if (check_browser_version('MSIE')) {
1968 $filename = rawurlencode($filename);
1971 if ($forcedownload) {
1972 header('Content-Disposition: attachment; filename="'.$filename.'"');
1974 header('Content-Disposition: inline; filename="'.$filename.'"');
1977 if ($lifetime > 0) {
1978 header('Cache-Control: max-age='.$lifetime);
1979 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1982 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1984 header('Accept-Ranges: bytes');
1986 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1987 // byteserving stuff - for acrobat reader and download accelerators
1988 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1989 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1991 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1992 foreach ($ranges as $key=>$value) {
1993 if ($ranges[$key][1] == '') {
1995 $ranges[$key][1] = $filesize - $ranges[$key][2];
1996 $ranges[$key][2] = $filesize - 1;
1997 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1999 $ranges[$key][2] = $filesize - 1;
2001 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2002 //invalid byte-range ==> ignore header
2006 //prepare multipart header
2007 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2008 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2014 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
2018 /// Do not byteserve (disabled, strings, text and html files).
2019 header('Accept-Ranges: none');
2021 } else { // Do not cache files in proxies and browsers
2022 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2023 header('Cache-Control: max-age=10');
2024 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2026 } else { //normal http - prevent caching at all cost
2027 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2028 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2029 header('Pragma: no-cache');
2031 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
2034 if (empty($filter)) {
2036 if ($mimetype == 'text/plain') {
2037 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
2039 header('Content-Type: '.$mimetype);
2041 header('Content-Length: '.$filesize);
2043 //flush the buffers - save memory and disable sid rewrite
2044 //this also disables zlib compression
2045 prepare_file_content_sending();
2047 // send the contents
2051 $stored_file->readfile();
2054 } else { // Try to put the file through filters
2055 if ($mimetype == 'text/html') {
2056 $options = new stdClass();
2057 $options->noclean = true;
2058 $options->nocache = true; // temporary workaround for MDL-5136
2059 $text = $stored_file->get_content();
2060 $text = file_modify_html_header($text);
2061 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2063 header('Content-Length: '.strlen($output));
2064 header('Content-Type: text/html');
2066 //flush the buffers - save memory and disable sid rewrite
2067 //this also disables zlib compression
2068 prepare_file_content_sending();
2070 // send the contents
2073 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2074 // only filter text if filter all files is selected
2075 $options = new stdClass();
2076 $options->newlines = false;
2077 $options->noclean = true;
2078 $text = $stored_file->get_content();
2079 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2081 header('Content-Length: '.strlen($output));
2082 header('Content-Type: text/html; charset=utf-8'); //add encoding
2084 //flush the buffers - save memory and disable sid rewrite
2085 //this also disables zlib compression
2086 prepare_file_content_sending();
2088 // send the contents
2091 } else { // Just send it out raw
2092 header('Content-Length: '.$filesize);
2093 header('Content-Type: '.$mimetype);
2095 //flush the buffers - save memory and disable sid rewrite
2096 //this also disables zlib compression
2097 prepare_file_content_sending();
2099 // send the contents
2100 $stored_file->readfile();
2106 die; //no more chars to output!!!
2110 * Retrieves an array of records from a CSV file and places
2111 * them into a given table structure
2115 * @param string $file The path to a CSV file
2116 * @param string $table The table to retrieve columns from
2117 * @return bool|array Returns an array of CSV records or false
2119 function get_records_csv($file, $table) {
2122 if (!$metacolumns = $DB->get_columns($table)) {
2126 if(!($handle = @fopen($file, 'r'))) {
2127 print_error('get_records_csv failed to open '.$file);
2130 $fieldnames = fgetcsv($handle, 4096);
2131 if(empty($fieldnames)) {
2138 foreach($metacolumns as $metacolumn) {
2139 $ord = array_search($metacolumn->name, $fieldnames);
2141 $columns[$metacolumn->name] = $ord;
2147 while (($data = fgetcsv($handle, 4096)) !== false) {
2148 $item = new stdClass;
2149 foreach($columns as $name => $ord) {
2150 $item->$name = $data[$ord];
2163 * @param string $file The file to put the CSV content into
2164 * @param array $records An array of records to write to a CSV file
2165 * @param string $table The table to get columns from
2166 * @return bool success
2168 function put_records_csv($file, $records, $table = NULL) {
2171 if (empty($records)) {
2175 $metacolumns = NULL;
2176 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2182 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
2183 print_error('put_records_csv failed to open '.$file);
2186 $proto = reset($records);
2187 if(is_object($proto)) {
2188 $fields_records = array_keys(get_object_vars($proto));
2190 else if(is_array($proto)) {
2191 $fields_records = array_keys($proto);
2198 if(!empty($metacolumns)) {
2199 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2200 $fields = array_intersect($fields_records, $fields_table);
2203 $fields = $fields_records;
2206 fwrite($fp, implode(',', $fields));
2207 fwrite($fp, "\r\n");
2209 foreach($records as $record) {
2210 $array = (array)$record;
2212 foreach($fields as $field) {
2213 if(strpos($array[$field], ',')) {
2214 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2217 $values[] = $array[$field];
2220 fwrite($fp, implode(',', $values)."\r\n");
2229 * Recursively delete the file or folder with path $location. That is,
2230 * if it is a file delete it. If it is a folder, delete all its content
2231 * then delete it. If $location does not exist to start, that is not
2232 * considered an error.
2234 * @param string $location the path to remove.
2237 function fulldelete($location) {
2238 if (empty($location)) {
2239 // extra safety against wrong param
2242 if (is_dir($location)) {
2243 $currdir = opendir($location);
2244 while (false !== ($file = readdir($currdir))) {
2245 if ($file <> ".." && $file <> ".") {
2246 $fullfile = $location."/".$file;
2247 if (is_dir($fullfile)) {
2248 if (!fulldelete($fullfile)) {
2252 if (!unlink($fullfile)) {
2259 if (! rmdir($location)) {
2263 } else if (file_exists($location)) {
2264 if (!unlink($location)) {
2272 * Send requested byterange of file.
2274 * @param object $handle A file handle
2275 * @param string $mimetype The mimetype for the output
2276 * @param array $ranges An array of ranges to send
2277 * @param string $filesize The size of the content if only one range is used
2279 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2280 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2281 if ($handle === false) {
2284 if (count($ranges) == 1) { //only one range requested
2285 $length = $ranges[0][2] - $ranges[0][1] + 1;
2286 header('HTTP/1.1 206 Partial content');
2287 header('Content-Length: '.$length);
2288 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2289 header('Content-Type: '.$mimetype);
2291 //flush the buffers - save memory and disable sid rewrite
2292 //this also disables zlib compression
2293 prepare_file_content_sending();
2296 fseek($handle, $ranges[0][1]);
2297 while (!feof($handle) && $length > 0) {
2298 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2299 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2302 $length -= strlen($buffer);
2306 } else { // multiple ranges requested - not tested much
2308 foreach($ranges as $range) {
2309 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2311 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2312 header('HTTP/1.1 206 Partial content');
2313 header('Content-Length: '.$totallength);
2314 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2315 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2317 //flush the buffers - save memory and disable sid rewrite
2318 //this also disables zlib compression
2319 prepare_file_content_sending();
2321 foreach($ranges as $range) {
2322 $length = $range[2] - $range[1] + 1;
2325 fseek($handle, $range[1]);
2326 while (!feof($handle) && $length > 0) {
2327 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2328 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2331 $length -= strlen($buffer);
2334 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2341 * add includes (js and css) into uploaded files
2342 * before returning them, useful for themes and utf.js includes
2345 * @param string $text text to search and replace
2346 * @return string text with added head includes
2348 function file_modify_html_header($text) {
2349 // first look for <head> tag
2352 $stylesheetshtml = '';
2353 /* foreach ($CFG->stylesheets as $stylesheet) {
2355 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2359 if (filter_is_enabled('filter/mediaplugin')) {
2360 // this script is needed by most media filter plugins.
2361 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2362 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2365 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2367 $replacement = '<head>'.$ufo.$stylesheetshtml;
2368 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2372 // if not, look for <html> tag, and stick <head> right after
2373 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2375 // replace <html> tag with <html><head>includes</head>
2376 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2377 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2381 // if not, look for <body> tag, and stick <head> before body
2382 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2384 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2385 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2389 // if not, just stick a <head> tag at the beginning
2390 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2395 * RESTful cURL class
2397 * This is a wrapper class for curl, it is quite easy to use:
2401 * $c = new curl(array('cache'=>true));
2403 * $c = new curl(array('cookie'=>true));
2405 * $c = new curl(array('proxy'=>true));
2407 * // HTTP GET Method
2408 * $html = $c->get('http://example.com');
2409 * // HTTP POST Method
2410 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2411 * // HTTP PUT Method
2412 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2417 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2418 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2423 public $cache = false;
2424 public $proxy = false;
2426 public $version = '0.4 dev';
2428 public $response = array();
2429 public $header = array();
2437 private $proxy_host = '';
2438 private $proxy_auth = '';
2439 private $proxy_type = '';
2441 private $debug = false;
2442 private $cookie = false;
2446 * @param array $options
2448 public function __construct($options = array()){
2450 if (!function_exists('curl_init')) {
2451 $this->error = 'cURL module must be enabled!';
2452 trigger_error($this->error, E_USER_ERROR);
2455 // the options of curl should be init here.
2457 if (!empty($options['debug'])) {
2458 $this->debug = true;
2460 if(!empty($options['cookie'])) {
2461 if($options['cookie'] === true) {
2462 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2464 $this->cookie = $options['cookie'];
2467 if (!empty($options['cache'])) {
2468 if (class_exists('curl_cache')) {
2469 if (!empty($options['module_cache'])) {
2470 $this->cache = new curl_cache($options['module_cache']);
2472 $this->cache = new curl_cache('misc');
2476 if (!empty($CFG->proxyhost)) {
2477 if (empty($CFG->proxyport)) {
2478 $this->proxy_host = $CFG->proxyhost;
2480 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2482 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2483 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2484 $this->setopt(array(
2485 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2486 'proxyuserpwd'=>$this->proxy_auth));
2488 if (!empty($CFG->proxytype)) {
2489 if ($CFG->proxytype == 'SOCKS5') {
2490 $this->proxy_type = CURLPROXY_SOCKS5;
2492 $this->proxy_type = CURLPROXY_HTTP;
2493 $this->setopt(array('httpproxytunnel'=>false));
2495 $this->setopt(array('proxytype'=>$this->proxy_type));
2498 if (!empty($this->proxy_host)) {
2499 $this->proxy = array('proxy'=>$this->proxy_host);
2503 * Resets the CURL options that have already been set
2505 public function resetopt(){
2506 $this->options = array();
2507 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2508 // True to include the header in the output
2509 $this->options['CURLOPT_HEADER'] = 0;
2510 // True to Exclude the body from the output
2511 $this->options['CURLOPT_NOBODY'] = 0;
2512 // TRUE to follow any "Location: " header that the server
2513 // sends as part of the HTTP header (note this is recursive,
2514 // PHP will follow as many "Location: " headers that it is sent,
2515 // unless CURLOPT_MAXREDIRS is set).
2516 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2517 $this->options['CURLOPT_MAXREDIRS'] = 10;
2518 $this->options['CURLOPT_ENCODING'] = '';
2519 // TRUE to return the transfer as a string of the return
2520 // value of curl_exec() instead of outputting it out directly.
2521 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2522 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2523 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2524 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2525 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2531 public function resetcookie() {
2532 if (!empty($this->cookie)) {
2533 if (is_file($this->cookie)) {
2534 $fp = fopen($this->cookie, 'w');
2546 * @param array $options If array is null, this function will
2547 * reset the options to default value.
2550 public function setopt($options = array()) {
2551 if (is_array($options)) {
2552 foreach($options as $name => $val){
2553 if (stripos($name, 'CURLOPT_') === false) {
2554 $name = strtoupper('CURLOPT_'.$name);
2556 $this->options[$name] = $val;
2564 public function cleanopt(){
2565 unset($this->options['CURLOPT_HTTPGET']);
2566 unset($this->options['CURLOPT_POST']);
2567 unset($this->options['CURLOPT_POSTFIELDS']);
2568 unset($this->options['CURLOPT_PUT']);
2569 unset($this->options['CURLOPT_INFILE']);
2570 unset($this->options['CURLOPT_INFILESIZE']);
2571 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2575 * Set HTTP Request Header
2577 * @param array $headers
2580 public function setHeader($header) {
2581 if (is_array($header)){
2582 foreach ($header as $v) {
2583 $this->setHeader($v);
2586 $this->header[] = $header;
2590 * Set HTTP Response Header
2593 public function getResponse(){
2594 return $this->response;
2597 * private callback function
2598 * Formatting HTTP Response Header
2600 * @param mixed $ch Apparently not used
2601 * @param string $header
2602 * @return int The strlen of the header
2604 private function formatHeader($ch, $header)
2607 if (strlen($header) > 2) {
2608 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2609 $key = rtrim($key, ':');
2610 if (!empty($this->response[$key])) {
2611 if (is_array($this->response[$key])){
2612 $this->response[$key][] = $value;
2614 $tmp = $this->response[$key];
2615 $this->response[$key] = array();
2616 $this->response[$key][] = $tmp;
2617 $this->response[$key][] = $value;
2621 $this->response[$key] = $value;
2624 return strlen($header);
2628 * Set options for individual curl instance
2630 * @param object $curl A curl handle
2631 * @param array $options
2632 * @return object The curl handle
2634 private function apply_opt($curl, $options) {
2638 if (!empty($this->cookie) || !empty($options['cookie'])) {
2639 $this->setopt(array('cookiejar'=>$this->cookie,
2640 'cookiefile'=>$this->cookie
2645 if (!empty($this->proxy) || !empty($options['proxy'])) {
2646 $this->setopt($this->proxy);
2648 $this->setopt($options);
2649 // reset before set options
2650 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2652 if (empty($this->header)){
2653 $this->setHeader(array(
2654 'User-Agent: MoodleBot/1.0',
2655 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2656 'Connection: keep-alive'
2659 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2662 echo '<h1>Options</h1>';
2663 var_dump($this->options);
2664 echo '<h1>Header</h1>';
2665 var_dump($this->header);
2669 foreach($this->options as $name => $val) {
2670 if (is_string($name)) {
2671 $name = constant(strtoupper($name));
2673 curl_setopt($curl, $name, $val);
2678 * Download multiple files in parallel
2680 * Calls {@link multi()} with specific download headers
2684 * $c->download(array(
2685 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2686 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2690 * @param array $requests An array of files to request
2691 * @param array $options An array of options to set
2692 * @return array An array of results
2694 public function download($requests, $options = array()) {
2695 $options['CURLOPT_BINARYTRANSFER'] = 1;
2696 $options['RETURNTRANSFER'] = false;
2697 return $this->multi($requests, $options);
2700 * Mulit HTTP Requests
2701 * This function could run multi-requests in parallel.
2703 * @param array $requests An array of files to request
2704 * @param array $options An array of options to set
2705 * @return array An array of results
2707 protected function multi($requests, $options = array()) {
2708 $count = count($requests);
2711 $main = curl_multi_init();
2712 for ($i = 0; $i < $count; $i++) {
2713 $url = $requests[$i];
2714 foreach($url as $n=>$v){
2715 $options[$n] = $url[$n];
2717 $handles[$i] = curl_init($url['url']);
2718 $this->apply_opt($handles[$i], $options);
2719 curl_multi_add_handle($main, $handles[$i]);
2723 curl_multi_exec($main, $running);
2724 } while($running > 0);
2725 for ($i = 0; $i < $count; $i++) {
2726 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
2729 $results[] = curl_multi_getcontent($handles[$i]);
2731 curl_multi_remove_handle($main, $handles[$i]);
2733 curl_multi_close($main);
2737 * Single HTTP Request
2739 * @param string $url The URL to request
2740 * @param array $options
2743 protected function request($url, $options = array()){
2744 // create curl instance
2745 $curl = curl_init($url);
2746 $options['url'] = $url;
2747 $this->apply_opt($curl, $options);
2748 if ($this->cache && $ret = $this->cache->get($this->options)) {
2751 $ret = curl_exec($curl);
2753 $this->cache->set($this->options, $ret);
2757 $this->info = curl_getinfo($curl);
2758 $this->error = curl_error($curl);
2761 echo '<h1>Return Data</h1>';
2763 echo '<h1>Info</h1>';
2764 var_dump($this->info);
2765 echo '<h1>Error</h1>';
2766 var_dump($this->error);
2771 if (empty($this->error)){
2774 return $this->error;
2775 // exception is not ajax friendly
2776 //throw new moodle_exception($this->error, 'curl');
2785 * @param string $url
2786 * @param array $options
2789 public function head($url, $options = array()){
2790 $options['CURLOPT_HTTPGET'] = 0;
2791 $options['CURLOPT_HEADER'] = 1;
2792 $options['CURLOPT_NOBODY'] = 1;
2793 return $this->request($url, $options);
2799 * @param string $url
2800 * @param array|string $params
2801 * @param array $options
2804 public function post($url, $params = '', $options = array()){
2805 $options['CURLOPT_POST'] = 1;
2806 if (is_array($params)) {
2807 $this->_tmp_file_post_params = array();
2808 foreach ($params as $key => $value) {
2809 if ($value instanceof stored_file) {
2810 $value->add_to_curl_request($this, $key);
2812 $this->_tmp_file_post_params[$key] = $value;
2815 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2816 unset($this->_tmp_file_post_params);
2818 // $params is the raw post data
2819 $options['CURLOPT_POSTFIELDS'] = $params;
2821 return $this->request($url, $options);
2827 * @param string $url
2828 * @param array $params
2829 * @param array $options
2832 public function get($url, $params = array(), $options = array()){
2833 $options['CURLOPT_HTTPGET'] = 1;
2835 if (!empty($params)){
2836 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2837 $url .= http_build_query($params, '', '&');
2839 return $this->request($url, $options);
2845 * @param string $url
2846 * @param array $params
2847 * @param array $options
2850 public function put($url, $params = array(), $options = array()){
2851 $file = $params['file'];
2852 if (!is_file($file)){
2855 $fp = fopen($file, 'r');
2856 $size = filesize($file);
2857 $options['CURLOPT_PUT'] = 1;
2858 $options['CURLOPT_INFILESIZE'] = $size;
2859 $options['CURLOPT_INFILE'] = $fp;
2860 if (!isset($this->options['CURLOPT_USERPWD'])){
2861 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2863 $ret = $this->request($url, $options);
2869 * HTTP DELETE method
2871 * @param string $url
2872 * @param array $params
2873 * @param array $options
2876 public function delete($url, $param = array(), $options = array()){
2877 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2878 if (!isset($options['CURLOPT_USERPWD'])) {
2879 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2881 $ret = $this->request($url, $options);
2887 * @param string $url
2888 * @param array $options
2891 public function trace($url, $options = array()){
2892 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2893 $ret = $this->request($url, $options);
2897 * HTTP OPTIONS method
2899 * @param string $url
2900 * @param array $options
2903 public function options($url, $options = array()){
2904 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2905 $ret = $this->request($url, $options);
2908 public function get_info() {
2914 * This class is used by cURL class, use case:
2917 * $CFG->repositorycacheexpire = 120;
2918 * $CFG->curlcache = 120;
2920 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2921 * $ret = $c->get('http://www.google.com');
2926 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2935 * @param string @module which module is using curl_cache
2938 function __construct($module = 'repository'){
2940 if (!empty($module)) {
2941 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2943 $this->dir = $CFG->dataroot.'/cache/misc/';
2945 if (!file_exists($this->dir)) {
2946 mkdir($this->dir, $CFG->directorypermissions, true);
2948 if ($module == 'repository') {
2949 if (empty($CFG->repositorycacheexpire)) {
2950 $CFG->repositorycacheexpire = 120;
2952 $this->ttl = $CFG->repositorycacheexpire;
2954 if (empty($CFG->curlcache)) {
2955 $CFG->curlcache = 120;
2957 $this->ttl = $CFG->curlcache;
2966 * @param mixed $param
2967 * @return bool|string
2969 public function get($param){
2971 $this->cleanup($this->ttl);
2972 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2973 if(file_exists($this->dir.$filename)) {
2974 $lasttime = filemtime($this->dir.$filename);
2975 if(time()-$lasttime > $this->ttl)
2979 $fp = fopen($this->dir.$filename, 'r');
2980 $size = filesize($this->dir.$filename);
2981 $content = fread($fp, $size);
2982 return unserialize($content);
2991 * @global object $CFG
2992 * @global object $USER
2993 * @param mixed $param
2996 public function set($param, $val){
2998 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2999 $fp = fopen($this->dir.$filename, 'w');
3000 fwrite($fp, serialize($val));
3005 * Remove cache files
3007 * @param int $expire The number os seconds before expiry
3009 public function cleanup($expire){
3010 if($dir = opendir($this->dir)){
3011 while (false !== ($file = readdir($dir))) {
3012 if(!is_dir($file) && $file != '.' && $file != '..') {
3013 $lasttime = @filemtime($this->dir.$file);
3014 if(time() - $lasttime > $expire){
3015 @unlink($this->dir.$file);
3022 * delete current user's cache file
3024 * @global object $CFG
3025 * @global object $USER
3027 public function refresh(){
3029 if($dir = opendir($this->dir)){
3030 while (false !== ($file = readdir($dir))) {
3031 if(!is_dir($file) && $file != '.' && $file != '..') {
3032 if(strpos($file, 'u'.$USER->id.'_')!==false){
3033 @unlink($this->dir.$file);
3042 * This class is used to parse lib/file/file_types.mm which help get file
3043 * extensions by file types.
3044 * The file_types.mm file can be edited by freemind in graphic environment.
3048 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
3049 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3051 class filetype_parser {
3053 * Check file_types.mm file, setup variables
3055 * @global object $CFG
3056 * @param string $file
3058 public function __construct($file = '') {
3061 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
3063 $this->file = $file;
3065 $this->tree = array();
3066 $this->result = array();
3070 * A private function to browse xml nodes
3072 * @param array $parent
3073 * @param array $types
3075 private function _browse_nodes($parent, $types) {
3076 $key = (string)$parent['TEXT'];
3077 if(isset($parent->node)) {
3078 $this->tree[$key] = array();
3079 if (in_array((string)$parent['TEXT'], $types)) {
3080 $this->_select_nodes($parent, $this->result);
3082 foreach($parent->node as $v){
3083 $this->_browse_nodes($v, $types);
3087 $this->tree[] = $key;
3092 * A private function to select text nodes
3094 * @param array $parent
3096 private function _select_nodes($parent){
3097 if(isset($parent->node)) {
3098 foreach($parent->node as $v){
3099 $this->_select_nodes($v, $this->result);
3102 $this->result[] = (string)$parent['TEXT'];
3108 * Get file extensions by file types names.
3110 * @param array $types
3113 public function get_extensions($types) {
3114 if (!is_array($types)) {
3115 $types = array($types);
3117 $this->result = array();
3118 if ((is_array($types) && in_array('*', $types)) ||
3119 $types == '*' || empty($types)) {
3122 foreach ($types as $key=>$value){
3123 if (strpos($value, '.') !== false) {
3124 $this->result[] = $value;
3125 unset($types[$key]);
3128 if (file_exists($this->file)) {
3129 $xml = simplexml_load_file($this->file);
3130 foreach($xml->node->node as $v){
3131 if (in_array((string)$v['TEXT'], $types)) {
3132 $this->_select_nodes($v);
3134 $this->_browse_nodes($v, $types);
3138 exit('Failed to open file lib/filestorage/file_types.mm');
3140 return $this->result;