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 if (is_null($itemid) or is_null($context)) {
117 if (!isset($data->{$field})) {
118 $data->{$field} = '';
120 if (!isset($data->{$field.'format'})) {
121 $data->{$field.'format'} = editors_get_preferred_format();
123 if (!$options['noclean']) {
124 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
128 if ($options['trusttext']) {
129 // noclean ignored if trusttext enabled
130 if (!isset($data->{$field.'trust'})) {
131 $data->{$field.'trust'} = 0;
133 $data = trusttext_pre_edit($data, $field, $context);
135 if (!$options['noclean']) {
136 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
139 $contextid = $context->id
;
142 if ($options['maxfiles'] != 0) {
143 $draftid_editor = file_get_submitted_draft_itemid($field);
144 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
145 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
147 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
154 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
156 * This function moves files from draft area to the destination area and
157 * encodes URLs to the draft files so they can be safely saved into DB. The
158 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
159 * is the name of the database field to hold the wysiwyg editor content. The
160 * editor data comes as an array with text, format and itemid properties. This
161 * function automatically adds $data properties foobar, foobarformat and
162 * foobartrust, where foobar has URL to embedded files encoded.
164 * @param object $data raw data submitted by the form
165 * @param string $field name of the database field containing the html with embedded media files
166 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
167 * @param object $context context, required for existing data
168 * @param string component
169 * @param string $filearea file area name
170 * @param int $itemid item id, required if item exists
171 * @return object modified data object
173 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
174 $options = (array)$options;
175 if (!isset($options['trusttext'])) {
176 $options['trusttext'] = false;
178 if (!isset($options['forcehttps'])) {
179 $options['forcehttps'] = false;
181 if (!isset($options['subdirs'])) {
182 $options['subdirs'] = false;
184 if (!isset($options['maxfiles'])) {
185 $options['maxfiles'] = 0; // no files by default
187 if (!isset($options['maxbytes'])) {
188 $options['maxbytes'] = 0; // unlimited
191 if ($options['trusttext']) {
192 $data->{$field.'trust'} = trusttext_trusted($context);
194 $data->{$field.'trust'} = 0;
197 $editor = $data->{$field.'_editor'};
199 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
200 $data->{$field} = $editor['text'];
202 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id
, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
204 $data->{$field.'format'} = $editor['format'];
210 * Saves text and files modified by Editor formslib element
212 * @param object $data $database entry field
213 * @param string $field name of data field
214 * @param array $options various options
215 * @param object $context context - must already exist
216 * @param string $component
217 * @param string $filearea file area name
218 * @param int $itemid must already exist, usually means data is in db
219 * @return object modified data obejct
221 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
222 $options = (array)$options;
223 if (!isset($options['subdirs'])) {
224 $options['subdirs'] = false;
226 if (is_null($itemid) or is_null($context)) {
230 $contextid = $context->id
;
233 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
234 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
235 $data->{$field.'_filemanager'} = $draftid_editor;
241 * Saves files modified by File manager formslib element
243 * @param object $data $database entry field
244 * @param string $field name of data field
245 * @param array $options various options
246 * @param object $context context - must already exist
247 * @param string $component
248 * @param string $filearea file area name
249 * @param int $itemid must already exist, usually means data is in db
250 * @return object modified data obejct
252 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
253 $options = (array)$options;
254 if (!isset($options['subdirs'])) {
255 $options['subdirs'] = false;
257 if (!isset($options['maxfiles'])) {
258 $options['maxfiles'] = -1; // unlimited
260 if (!isset($options['maxbytes'])) {
261 $options['maxbytes'] = 0; // unlimited
264 if (empty($data->{$field.'_filemanager'})) {
268 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id
, $component, $filearea, $itemid, $options);
269 $fs = get_file_storage();
271 if ($fs->get_area_files($context->id
, $component, $filearea, $itemid)) {
272 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
285 * @return int a random but available draft itemid that can be used to create a new draft
288 function file_get_unused_draft_itemid() {
291 if (isguestuser() or !isloggedin()) {
292 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
293 print_error('noguest');
296 $contextid = get_context_instance(CONTEXT_USER
, $USER->id
)->id
;
298 $fs = get_file_storage();
299 $draftitemid = rand(1, 999999999);
300 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
301 $draftitemid = rand(1, 999999999);
308 * Initialise a draft file area from a real one by copying the files. A draft
309 * area will be created if one does not already exist. Normally you should
310 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
314 * @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.
315 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
316 * @param string $component
317 * @param string $filearea helps indentify the file area.
318 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
319 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
320 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
321 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
323 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
326 $options = (array)$options;
327 if (!isset($options['subdirs'])) {
328 $options['subdirs'] = false;
330 if (!isset($options['forcehttps'])) {
331 $options['forcehttps'] = false;
334 $usercontext = get_context_instance(CONTEXT_USER
, $USER->id
);
335 $fs = get_file_storage();
337 if (empty($draftitemid)) {
338 // create a new area and copy existing files into
339 $draftitemid = file_get_unused_draft_itemid();
340 $file_record = array('contextid'=>$usercontext->id
, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
341 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
342 foreach ($files as $file) {
343 if ($file->is_directory() and $file->get_filepath() === '/') {
344 // we need a way to mark the age of each draft area,
345 // by not copying the root dir we force it to be created automatically with current timestamp
348 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
351 $fs->create_file_from_storedfile($file_record, $file);
358 if (is_null($text)) {
362 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
363 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id
, 'user', 'draft', $draftitemid, $options);
367 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
370 * @param string $text The content that may contain ULRs in need of rewriting.
371 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
372 * @param integer $contextid This parameter and the next two identify the file area to use.
373 * @param string $component
374 * @param string $filearea helps identify the file area.
375 * @param integer $itemid helps identify the file area.
376 * @param array $options text and file options ('forcehttps'=>false)
377 * @return string the processed text.
379 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
382 $options = (array)$options;
383 if (!isset($options['forcehttps'])) {
384 $options['forcehttps'] = false;
387 if (!$CFG->slasharguments
) {
388 $file = $file . '?file=';
391 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
393 if ($itemid !== null) {
394 $baseurl .= "$itemid/";
397 if ($options['forcehttps']) {
398 $baseurl = str_replace('http://', 'https://', $baseurl);
401 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
405 * Returns information about files in a draft area.
409 * @param integer $draftitemid the draft area item id.
410 * @return array with the following entries:
411 * 'filecount' => number of files in the draft area.
412 * (more information will be added as needed).
414 function file_get_draft_area_info($draftitemid) {
417 $usercontext = get_context_instance(CONTEXT_USER
, $USER->id
);
418 $fs = get_file_storage();
422 // The number of files
423 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id', false);
424 $results['filecount'] = count($draftfiles);
425 $results['filesize'] = 0;
426 foreach ($draftfiles as $file) {
427 $results['filesize'] +
= $file->get_filesize();
434 * Get used space of files
435 * @return int total bytes
437 function file_get_user_used_space() {
440 $usercontext = get_context_instance(CONTEXT_USER
, $USER->id
);
441 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
442 JOIN (SELECT contenthash, filename, MAX(id) AS id
444 WHERE contextid = ? AND component = ? AND filearea != ?
445 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
446 $params = array('contextid'=>$usercontext->id
, 'component'=>'user', 'filearea'=>'draft');
447 $record = $DB->get_record_sql($sql, $params);
448 return (int)$record->totalbytes
;
452 * Convert any string to a valid filepath
454 * @return string path
456 function file_correct_filepath($str) { //TODO: what is this? (skodak)
457 if ($str == '/' or empty($str)) {
460 return '/'.trim($str, './@#$ ').'/';
465 * Generate a folder tree of draft area of current USER recursively
467 * @param string $filepath
468 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
470 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
471 global $USER, $OUTPUT, $CFG;
472 $data->children
= array();
473 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
474 $fs = get_file_storage();
475 if ($files = $fs->get_directory_files($context->id
, 'user', 'draft', $draftitemid, $filepath, false)) {
476 foreach ($files as $file) {
477 if ($file->is_directory()) {
478 $item = new stdclass
;
479 $item->sortorder
= $file->get_sortorder();
480 $item->filepath
= $file->get_filepath();
482 $foldername = explode('/', trim($item->filepath
, '/'));
483 $item->fullname
= trim(array_pop($foldername), '/');
485 $item->id
= uniqid();
486 file_get_drafarea_folders($draftitemid, $item->filepath
, $item);
487 $data->children
[] = $item;
496 * Listing all files (including folders) in current path (draft area)
497 * used by file manager
498 * @param int $draftitemid
499 * @param string $filepath
502 function file_get_drafarea_files($draftitemid, $filepath = '/') {
503 global $USER, $OUTPUT, $CFG;
505 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
506 $fs = get_file_storage();
508 $data = new stdclass
;
509 $data->path
= array();
510 $data->path
[] = array('name'=>get_string('files'), 'path'=>'/');
512 // will be used to build breadcrumb
514 if ($filepath !== '/') {
515 $filepath = file_correct_filepath($filepath);
516 $parts = explode('/', $filepath);
517 foreach ($parts as $part) {
518 if ($part != '' && $part != null) {
519 $trail .= ('/'.$part.'/');
520 $data->path
[] = array('name'=>$part, 'path'=>$trail);
527 if ($files = $fs->get_directory_files($context->id
, 'user', 'draft', $draftitemid, $filepath, false)) {
528 foreach ($files as $file) {
529 $item = new stdclass
;
530 $item->filename
= $file->get_filename();
531 $item->filepath
= $file->get_filepath();
532 $item->fullname
= trim($item->filename
, '/');
533 $filesize = $file->get_filesize();
534 $item->filesize
= $filesize ?
display_size($filesize) : '';
536 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
537 $item->icon
= $OUTPUT->pix_url('f/' . $icon)->out();
538 $item->sortorder
= $file->get_sortorder();
540 if ($icon == 'zip') {
543 $item->type
= 'file';
546 if ($file->is_directory()) {
548 $item->icon
= $OUTPUT->pix_url('f/folder')->out();
549 $item->type
= 'folder';
550 $foldername = explode('/', trim($item->filepath
, '/'));
551 $item->fullname
= trim(array_pop($foldername), '/');
553 // do NOT use file browser here!
554 $item->url
= moodle_url
::make_draftfile_url($draftitemid, $item->filepath
, $item->filename
)->out();
559 $data->itemid
= $draftitemid;
565 * Returns draft area itemid for a given element.
567 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
568 * @return integer the itemid, or 0 if there is not one yet.
570 function file_get_submitted_draft_itemid($elname) {
571 $param = optional_param($elname, 0, PARAM_INT
);
575 if (is_array($param)) {
576 if (!empty($param['itemid'])) {
577 $param = $param['itemid'];
579 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER
);
587 * Saves files from a draft file area to a real one (merging the list of files).
588 * Can rewrite URLs in some content at the same time if desired.
592 * @param integer $draftitemid the id of the draft area to use. Normally obtained
593 * from file_get_submitted_draft_itemid('elementname') or similar.
594 * @param integer $contextid This parameter and the next two identify the file area to save to.
595 * @param string $component
596 * @param string $filearea indentifies the file area.
597 * @param integer $itemid helps identifies the file area.
598 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
599 * @param string $text some html content that needs to have embedded links rewritten
600 * to the @@PLUGINFILE@@ form for saving in the database.
601 * @param boolean $forcehttps force https urls.
602 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
604 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
607 $usercontext = get_context_instance(CONTEXT_USER
, $USER->id
);
608 $fs = get_file_storage();
610 $options = (array)$options;
611 if (!isset($options['subdirs'])) {
612 $options['subdirs'] = false;
614 if (!isset($options['maxfiles'])) {
615 $options['maxfiles'] = -1; // unlimited
617 if (!isset($options['maxbytes'])) {
618 $options['maxbytes'] = 0; // unlimited
621 $draftfiles = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftitemid, 'id');
622 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
624 if (count($draftfiles) < 2) {
625 // means there are no files - one file means root dir only ;-)
626 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
628 } else if (count($oldfiles) < 2) {
630 // there were no files before - one file means root dir only ;-)
631 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
632 foreach ($draftfiles as $file) {
633 if (!$options['subdirs']) {
634 if ($file->get_filepath() !== '/' or $file->is_directory()) {
638 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
639 // oversized file - should not get here at all
642 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
643 // more files - should not get here at all
646 if (!$file->is_directory()) {
649 $fs->create_file_from_storedfile($file_record, $file);
653 // we have to merge old and new files - we want to keep file ids for files that were not changed
654 // we change time modified for all new and changed files, we keep time created as is
655 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
657 $newhashes = array();
658 foreach ($draftfiles as $file) {
659 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
660 $newhashes[$newhash] = $file;
663 foreach ($oldfiles as $oldfile) {
664 $oldhash = $oldfile->get_pathnamehash();
665 if (!isset($newhashes[$oldhash])) {
666 // delete files not needed any more - deleted by user
670 $newfile = $newhashes[$oldhash];
671 if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
672 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
673 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
674 // file was changed, use updated with new timemodified data
678 // unchanged file or directory - we keep it as is
679 unset($newhashes[$oldhash]);
680 if (!$file->is_directory()) {
685 // now add new/changed files
686 // the size and subdirectory tests are extra safety only, the UI should prevent it
687 foreach ($newhashes as $file) {
688 if (!$options['subdirs']) {
689 if ($file->get_filepath() !== '/' or $file->is_directory()) {
693 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
694 // oversized file - should not get here at all
697 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
698 // more files - should not get here at all
701 if (!$file->is_directory()) {
704 $fs->create_file_from_storedfile($file_record, $file);
708 // note: do not purge the draft area - we clean up areas later in cron,
709 // the reason is that user might press submit twice and they would loose the files,
710 // also sometimes we might want to use hacks that save files into two different areas
712 if (is_null($text)) {
716 // relink embedded files if text submitted - no absolute links allowed in database!
717 if ($CFG->slasharguments
) {
718 $draftbase = "$CFG->wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/";
720 $draftbase = "$CFG->wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/";
724 $draftbase = str_replace('http://', 'https://', $draftbase);
727 $text = str_ireplace($draftbase, '@@PLUGINFILE@@/', $text);
733 * Set file sort order
735 * @param integer $contextid the context id
736 * @param string $component
737 * @param string $filearea file area.
738 * @param integer $itemid itemid.
739 * @param string $filepath file path.
740 * @param string $filename file name.
741 * @param integer $sortorer the sort order of file.
744 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
746 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
747 if ($file_record = $DB->get_record('files', $conditions)) {
748 $sortorder = (int)$sortorder;
749 $file_record->sortorder
= $sortorder;
750 $DB->update_record('files', $file_record);
757 * reset file sort order number to 0
759 * @param integer $contextid the context id
760 * @param string $component
761 * @param string $filearea file area.
762 * @param integer $itemid itemid.
765 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
768 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
769 if ($itemid !== false) {
770 $conditions['itemid'] = $itemid;
773 $file_records = $DB->get_records('files', $conditions);
774 foreach ($file_records as $file_record) {
775 $file_record->sortorder
= 0;
776 $DB->update_record('files', $file_record);
782 * Returns description of upload error
784 * @param int $errorcode found in $_FILES['filename.ext']['error']
785 * @return string error description string, '' if ok
787 function file_get_upload_error($errorcode) {
789 switch ($errorcode) {
790 case 0: // UPLOAD_ERR_OK - no error
794 case 1: // UPLOAD_ERR_INI_SIZE
795 $errmessage = get_string('uploadserverlimit');
798 case 2: // UPLOAD_ERR_FORM_SIZE
799 $errmessage = get_string('uploadformlimit');
802 case 3: // UPLOAD_ERR_PARTIAL
803 $errmessage = get_string('uploadpartialfile');
806 case 4: // UPLOAD_ERR_NO_FILE
807 $errmessage = get_string('uploadnofilefound');
810 // Note: there is no error with a value of 5
812 case 6: // UPLOAD_ERR_NO_TMP_DIR
813 $errmessage = get_string('uploadnotempdir');
816 case 7: // UPLOAD_ERR_CANT_WRITE
817 $errmessage = get_string('uploadcantwrite');
820 case 8: // UPLOAD_ERR_EXTENSION
821 $errmessage = get_string('uploadextension');
825 $errmessage = get_string('uploadproblem');
832 * Recursive function formating an array in POST parameter
833 * @param array $arraydata - the array that we are going to format and add into &$data array
834 * @param string $currentdata - a row of the final postdata array at instant T
835 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
836 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
838 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
839 foreach ($arraydata as $k=>$v) {
840 $newcurrentdata = $currentdata;
841 if (is_array($v)) { //the value is an array, call the function recursively
842 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
843 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
844 } else { //add the POST parameter to the $data array
845 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
851 * Transform a PHP array into POST parameter
852 * (see the recursive function format_array_postdata_for_curlcall)
853 * @param array $postdata
854 * @return array containing all POST parameters (1 row = 1 POST parameter)
856 function format_postdata_for_curlcall($postdata) {
858 foreach ($postdata as $k=>$v) {
860 $currentdata = urlencode($k);
861 format_array_postdata_for_curlcall($v, $currentdata, $data);
863 $data[] = urlencode($k).'='.urlencode($v);
866 $convertedpostdata = implode('&', $data);
867 return $convertedpostdata;
874 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
875 * Due to security concerns only downloads from http(s) sources are supported.
878 * @param string $url file url starting with http(s)://
879 * @param array $headers http headers, null if none. If set, should be an
880 * associative array of header name => value pairs.
881 * @param array $postdata array means use POST request with given parameters
882 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
883 * (if false, just returns content)
884 * @param int $timeout timeout for complete download process including all file transfer
885 * (default 5 minutes)
886 * @param int $connecttimeout timeout for connection to server; this is the timeout that
887 * usually happens if the remote server is completely down (default 20 seconds);
888 * may not work when using proxy
889 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
890 * @param string $tofile store the downloaded content to file instead of returning it
891 * @return mixed false if request failed or content of the file as string if ok. true if file downloaded into $tofile successfully.
893 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL) {
896 // some extra security
897 $newlines = array("\r", "\n");
898 if (is_array($headers) ) {
899 foreach ($headers as $key => $value) {
900 $headers[$key] = str_replace($newlines, '', $value);
903 $url = str_replace($newlines, '', $url);
904 if (!preg_match('|^https?://|i', $url)) {
906 $response = new object();
907 $response->status
= 0;
908 $response->headers
= array();
909 $response->response_code
= 'Invalid protocol specified in url';
910 $response->results
= '';
911 $response->error
= 'Invalid protocol specified in url';
918 // check if proxy (if used) should be bypassed for this url
919 $proxybypass = is_proxybypass($url);
921 if (!$ch = curl_init($url)) {
922 debugging('Can not init curl.');
927 if (is_array($headers) ) {
929 foreach ($headers as $key => $value) {
930 $headers2[] = "$key: $value";
932 curl_setopt($ch, CURLOPT_HTTPHEADER
, $headers2);
936 if ($skipcertverify) {
937 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
940 // use POST if requested
941 if (is_array($postdata)) {
942 $postdata = format_postdata_for_curlcall($postdata);
943 curl_setopt($ch, CURLOPT_POST
, true);
944 curl_setopt($ch, CURLOPT_POSTFIELDS
, $postdata);
947 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
948 curl_setopt($ch, CURLOPT_HEADER
, false);
949 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, $connecttimeout);
950 curl_setopt($ch, CURLOPT_TIMEOUT
, $timeout);
951 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
952 // TODO: add version test for '7.10.5'
953 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
954 curl_setopt($ch, CURLOPT_MAXREDIRS
, 5);
957 if (!empty($CFG->proxyhost
) and !$proxybypass) {
958 // SOCKS supported in PHP5 only
959 if (!empty($CFG->proxytype
) and ($CFG->proxytype
== 'SOCKS5')) {
960 if (defined('CURLPROXY_SOCKS5')) {
961 curl_setopt($ch, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
965 $response = new object();
966 $response->status
= '0';
967 $response->headers
= array();
968 $response->response_code
= 'SOCKS5 proxy is not supported in PHP4';
969 $response->results
= '';
970 $response->error
= 'SOCKS5 proxy is not supported in PHP4';
973 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL
);
979 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, false);
981 if (empty($CFG->proxyport
)) {
982 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
);
984 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
.':'.$CFG->proxyport
);
987 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
988 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
989 if (defined('CURLOPT_PROXYAUTH')) {
990 // any proxy authentication if PHP 5.1
991 curl_setopt($ch, CURLOPT_PROXYAUTH
, CURLAUTH_BASIC | CURLAUTH_NTLM
);
996 // set up header and content handlers
997 $received = new object();
998 $received->headers
= array(); // received headers array
999 $received->tofile
= $tofile;
1000 $received->fh
= null;
1001 curl_setopt($ch, CURLOPT_HEADERFUNCTION
, partial('download_file_content_header_handler', $received));
1003 curl_setopt($ch, CURLOPT_WRITEFUNCTION
, partial('download_file_content_write_handler', $received));
1006 $result = curl_exec($ch);
1008 // try to detect encoding problems
1009 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1010 curl_setopt($ch, CURLOPT_ENCODING
, 'none');
1011 $result = curl_exec($ch);
1014 if ($received->fh
) {
1015 fclose($received->fh
);
1018 if (curl_errno($ch)) {
1019 $error = curl_error($ch);
1020 $error_no = curl_errno($ch);
1023 if ($fullresponse) {
1024 $response = new object();
1025 if ($error_no == 28) {
1026 $response->status
= '-100'; // mimic snoopy
1028 $response->status
= '0';
1030 $response->headers
= array();
1031 $response->response_code
= $error;
1032 $response->results
= false;
1033 $response->error
= $error;
1036 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
1041 $info = curl_getinfo($ch);
1044 if (empty($info['http_code'])) {
1045 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1046 $response = new object();
1047 $response->status
= '0';
1048 $response->headers
= array();
1049 $response->response_code
= 'Unknown cURL error';
1050 $response->results
= false; // do NOT change this, we really want to ignore the result!
1051 $response->error
= 'Unknown cURL error';
1054 $response = new object();;
1055 $response->status
= (string)$info['http_code'];
1056 $response->headers
= $received->headers
;
1057 $response->response_code
= $received->headers
[0];
1058 $response->results
= $result;
1059 $response->error
= '';
1062 if ($fullresponse) {
1064 } else if ($info['http_code'] != 200) {
1065 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
1068 return $response->results
;
1074 * internal implementation
1076 function download_file_content_header_handler($received, $ch, $header) {
1077 $received->headers
[] = $header;
1078 return strlen($header);
1082 * internal implementation
1084 function download_file_content_write_handler($received, $ch, $data) {
1085 if (!$received->fh
) {
1086 $received->fh
= fopen($received->tofile
, 'w');
1087 if ($received->fh
=== false) {
1088 // bad luck, file creation or overriding failed
1092 if (fwrite($received->fh
, $data) === false) {
1093 // bad luck, write failed, let's abort completely
1096 return strlen($data);
1100 * @return array List of information about file types based on extensions.
1101 * Associative array of extension (lower-case) to associative array
1102 * from 'element name' to data. Current element names are 'type' and 'icon'.
1103 * Unknown types should use the 'xxx' entry which includes defaults.
1105 function get_mimetypes_array() {
1106 static $mimearray = array (
1107 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1108 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1109 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1110 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1111 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1112 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1113 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1114 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1115 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1116 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1117 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1118 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1119 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1120 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1121 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1122 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1123 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1124 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1125 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1126 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1128 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1129 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1130 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1131 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1132 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1134 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1135 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1136 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1137 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1138 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1139 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1140 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1141 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1142 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1143 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1144 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1145 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1146 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1147 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1148 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1149 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1150 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1151 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1152 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1153 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1154 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1155 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1156 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1157 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1158 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1159 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1160 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1161 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1162 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1163 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1164 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1165 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1166 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1167 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1168 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1169 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1170 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1171 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1172 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1173 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1174 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1175 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1176 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1177 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1178 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1179 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1180 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1182 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1183 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1184 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1185 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1186 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1187 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1188 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1189 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1190 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1191 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1192 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1193 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1194 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1195 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1197 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1198 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1199 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1200 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1201 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1202 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1204 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1205 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1206 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1207 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1208 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1209 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1210 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1211 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1212 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1214 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1215 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1216 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1217 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1218 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1219 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1220 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1221 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1222 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1223 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1224 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1225 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1226 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1227 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1228 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1229 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1230 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1231 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1233 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1234 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1235 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1236 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1237 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1238 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1239 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1240 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1241 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1242 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1244 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1245 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1246 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1247 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1248 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1249 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1250 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1251 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1252 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1253 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1254 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1255 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1256 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1257 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1259 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1260 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1261 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1262 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1263 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1264 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1265 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1267 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1268 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1269 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1275 * Obtains information about a filetype based on its extension. Will
1276 * use a default if no information is present about that particular
1279 * @param string $element Desired information (usually 'icon'
1280 * for icon filename or 'type' for MIME type)
1281 * @param string $filename Filename we're looking up
1282 * @return string Requested piece of information from array
1284 function mimeinfo($element, $filename) {
1286 $mimeinfo = get_mimetypes_array();
1288 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1289 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1290 return $mimeinfo[strtolower($match[1])][$element];
1292 if ($element == 'icon32') {
1293 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1294 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1296 $filename = 'unknown';
1299 if (file_exists($CFG->dirroot
.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot
.'/pix/f/'.$filename.'.gif')) {
1302 return 'unknown-32';
1305 return $mimeinfo['xxx'][$element]; // By default
1309 if ($element == 'icon32') {
1310 return 'unknown-32';
1312 return $mimeinfo['xxx'][$element]; // By default
1317 * Obtains information about a filetype based on the MIME type rather than
1318 * the other way around.
1320 * @param string $element Desired information (usually 'icon')
1321 * @param string $mimetype MIME type we're looking up
1322 * @return string Requested piece of information from array
1324 function mimeinfo_from_type($element, $mimetype) {
1325 $mimeinfo = get_mimetypes_array();
1327 foreach($mimeinfo as $values) {
1328 if ($values['type']==$mimetype) {
1329 if (isset($values[$element])) {
1330 return $values[$element];
1335 return $mimeinfo['xxx'][$element]; // Default
1339 * Get information about a filetype based on the icon file.
1341 * @param string $element Desired information (usually 'icon')
1342 * @param string $icon Icon file name without extension
1343 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1344 * @return string Requested piece of information from array
1346 function mimeinfo_from_icon($element, $icon, $all=false) {
1347 $mimeinfo = get_mimetypes_array();
1349 if (preg_match("/\/(.*)/", $icon, $matches)) {
1350 $icon = $matches[1];
1352 // Try to get the extension
1354 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1355 $extension = substr($icon, $cutat +
1);
1357 $info = array($mimeinfo['xxx'][$element]); // Default
1358 foreach($mimeinfo as $key => $values) {
1359 if ($values['icon']==$icon) {
1360 if (isset($values[$element])) {
1361 $info[$key] = $values[$element];
1363 //No break, for example for 'excel' we don't want 'csv'!
1367 if (count($info) > 1) {
1368 array_shift($info); // take off document/unknown if we have better options
1370 return array_values($info); // Keep keys out when requesting all
1373 // Requested only one, try to get the best by extension coincidence, else return the last
1374 if ($extension && isset($info[$extension])) {
1375 return $info[$extension];
1378 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1382 * Returns the relative icon path for a given mime type
1384 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1385 * a return the full path to an icon.
1388 * $mimetype = 'image/jpg';
1389 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1390 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1393 * @todo When an $OUTPUT->icon method is available this function should be altered
1394 * to conform with that.
1396 * @param string $mimetype The mimetype to fetch an icon for
1397 * @param int $size The size of the icon. Not yet implemented
1398 * @return string The relative path to the icon
1400 function file_mimetype_icon($mimetype, $size = NULL) {
1403 $icon = mimeinfo_from_type('icon', $mimetype);
1405 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1406 $icon = "$icon-$size";
1413 * Returns the relative icon path for a given file name
1415 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1416 * a return the full path to an icon.
1419 * $filename = 'jpg';
1420 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1421 * echo '<img src="'.$icon.'" alt="blah" />';
1424 * @todo When an $OUTPUT->icon method is available this function should be altered
1425 * to conform with that.
1426 * @todo Implement $size
1428 * @param string filename The filename to get the icon for
1429 * @param int $size The size of the icon. Defaults to null can also be 32
1432 function file_extension_icon($filename, $size = NULL) {
1435 $icon = mimeinfo('icon', $filename);
1437 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1438 $icon = "$icon-$size";
1445 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1446 * mimetypes.php language file.
1448 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1449 * @param bool $capitalise If true, capitalises first character of result
1450 * @return string Text description
1452 function get_mimetype_description($mimetype, $capitalise=false) {
1453 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1454 $result = get_string($mimetype, 'mimetypes');
1456 $result = get_string('document/unknown','mimetypes');
1459 $result=ucfirst($result);
1465 * Requested file is not found or not accessible
1467 * @return does not return, terminates script
1469 function send_file_not_found() {
1470 global $CFG, $COURSE;
1471 header('HTTP/1.0 404 not found');
1472 print_error('filenotfound', 'error', $CFG->wwwroot
.'/course/view.php?id='.$COURSE->id
); //this is not displayed on IIS??
1476 * Handles the sending of temporary file to user, download is forced.
1477 * File is deleted after abort or successful sending.
1480 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1481 * @param string $filename proposed file name when saving file
1482 * @param bool $path is content of file
1483 * @return does not return, script terminated
1485 function send_temp_file($path, $filename, $pathisstring=false) {
1488 // close session - not needed anymore
1489 @session_get_instance
()->write_close();
1491 if (!$pathisstring) {
1492 if (!file_exists($path)) {
1493 header('HTTP/1.0 404 not found');
1494 print_error('filenotfound', 'error', $CFG->wwwroot
.'/');
1496 // executed after normal finish or abort
1497 @register_shutdown_function
('send_temp_file_finished', $path);
1500 //IE compatibility HACK!
1501 if (ini_get('zlib.output_compression')) {
1502 ini_set('zlib.output_compression', 'Off');
1505 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1506 if (check_browser_version('MSIE')) {
1507 $filename = urlencode($filename);
1510 $filesize = $pathisstring ?
strlen($path) : filesize($path);
1512 @header
('Content-Disposition: attachment; filename='.$filename);
1513 @header
('Content-Length: '.$filesize);
1514 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1515 @header
('Cache-Control: max-age=10');
1516 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1517 @header
('Pragma: ');
1518 } else { //normal http - prevent caching at all cost
1519 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1520 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1521 @header
('Pragma: no-cache');
1523 @header
('Accept-Ranges: none'); // Do not allow byteserving
1525 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1526 if ($pathisstring) {
1532 die; //no more chars to output
1536 * Internal callback function used by send_temp_file()
1538 function send_temp_file_finished($path) {
1539 if (file_exists($path)) {
1545 * Handles the sending of file data to the user's browser, including support for
1551 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1552 * @param string $filename Filename to send
1553 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1554 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1555 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1556 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1557 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1558 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1559 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1560 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1561 * and should not be reopened.
1562 * @return no return or void, script execution stopped unless $dontdie is true
1564 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1565 global $CFG, $COURSE, $SESSION;
1568 ignore_user_abort(true);
1571 // MDL-11789, apply $CFG->filelifetime here
1572 if ($lifetime === 'default') {
1573 if (!empty($CFG->filelifetime
)) {
1574 $lifetime = $CFG->filelifetime
;
1580 session_get_instance()->write_close(); // unlock session during fileserving
1582 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1583 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1584 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1585 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1586 $mimetype = ($forcedownload and !$isFF) ?
'application/x-forcedownload' :
1587 ($mimetype ?
$mimetype : mimeinfo('type', $filename));
1589 $lastmodified = $pathisstring ?
time() : filemtime($path);
1590 $filesize = $pathisstring ?
strlen($path) : filesize($path);
1593 //Adobe Acrobat Reader XSS prevention
1594 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1595 //please note that it prevents opening of pdfs in browser when http referer disabled
1596 //or file linked from another site; browser caching of pdfs is now disabled too
1597 if (!empty($_SERVER['HTTP_RANGE'])) {
1598 //already byteserving
1599 $lifetime = 1; // >0 needed for byteserving
1600 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1601 $mimetype = 'application/x-forcedownload';
1602 $forcedownload = true;
1605 $lifetime = 1; // >0 needed for byteserving
1610 //IE compatibiltiy HACK!
1611 if (ini_get('zlib.output_compression')) {
1612 ini_set('zlib.output_compression', 'Off');
1615 //try to disable automatic sid rewrite in cookieless mode
1616 @ini_set
("session.use_trans_sid", "false");
1618 //do not put '@' before the next header to detect incorrect moodle configurations,
1619 //error should be better than "weird" empty lines for admins/users
1620 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1621 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1623 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1624 if (check_browser_version('MSIE')) {
1625 $filename = rawurlencode($filename);
1628 if ($forcedownload) {
1629 @header
('Content-Disposition: attachment; filename="'.$filename.'"');
1631 @header
('Content-Disposition: inline; filename="'.$filename.'"');
1634 if ($lifetime > 0) {
1635 @header
('Cache-Control: max-age='.$lifetime);
1636 @header
('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
1637 @header
('Pragma: ');
1639 if (empty($CFG->disablebyteserving
) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1641 @header
('Accept-Ranges: bytes');
1643 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1644 // byteserving stuff - for acrobat reader and download accelerators
1645 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1646 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1648 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
1649 foreach ($ranges as $key=>$value) {
1650 if ($ranges[$key][1] == '') {
1652 $ranges[$key][1] = $filesize - $ranges[$key][2];
1653 $ranges[$key][2] = $filesize - 1;
1654 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
1656 $ranges[$key][2] = $filesize - 1;
1658 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1659 //invalid byte-range ==> ignore header
1663 //prepare multipart header
1664 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
1665 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1671 $handle = fopen($filename, 'rb');
1672 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1676 /// Do not byteserve (disabled, strings, text and html files).
1677 @header
('Accept-Ranges: none');
1679 } else { // Do not cache files in proxies and browsers
1680 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1681 @header
('Cache-Control: max-age=10');
1682 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1683 @header
('Pragma: ');
1684 } else { //normal http - prevent caching at all cost
1685 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1686 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1687 @header
('Pragma: no-cache');
1689 @header
('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1692 if (empty($filter)) {
1693 if ($mimetype == 'text/html' && !empty($CFG->usesid
)) {
1694 //cookieless mode - rewrite links
1695 @header
('Content-Type: text/html');
1696 $path = $pathisstring ?
$path : implode('', file($path));
1697 $path = sid_ob_rewrite($path);
1698 $filesize = strlen($path);
1699 $pathisstring = true;
1700 } else if ($mimetype == 'text/plain') {
1701 @header
('Content-Type: Text/plain; charset=utf-8'); //add encoding
1703 @header
('Content-Type: '.$mimetype);
1705 @header
('Content-Length: '.$filesize);
1706 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1707 if ($pathisstring) {
1712 } else { // Try to put the file through filters
1713 if ($mimetype == 'text/html') {
1714 $options = new object();
1715 $options->noclean
= true;
1716 $options->nocache
= true; // temporary workaround for MDL-5136
1717 $text = $pathisstring ?
$path : implode('', file($path));
1719 $text = file_modify_html_header($text);
1720 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
1721 if (!empty($CFG->usesid
)) {
1722 //cookieless mode - rewrite links
1723 $output = sid_ob_rewrite($output);
1726 @header
('Content-Length: '.strlen($output));
1727 @header
('Content-Type: text/html');
1728 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1730 // only filter text if filter all files is selected
1731 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1732 $options = new object();
1733 $options->newlines
= false;
1734 $options->noclean
= true;
1735 $text = htmlentities($pathisstring ?
$path : implode('', file($path)));
1736 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
1737 if (!empty($CFG->usesid
)) {
1738 //cookieless mode - rewrite links
1739 $output = sid_ob_rewrite($output);
1742 @header
('Content-Length: '.strlen($output));
1743 @header
('Content-Type: text/html; charset=utf-8'); //add encoding
1744 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1746 } else { // Just send it out raw
1747 @header
('Content-Length: '.$filesize);
1748 @header
('Content-Type: '.$mimetype);
1749 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1750 if ($pathisstring) {
1760 die; //no more chars to output!!!
1764 * Handles the sending of file data to the user's browser, including support for
1770 * @param object $stored_file local file object
1771 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1772 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1773 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1774 * @param string $filename Override filename
1775 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1776 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1777 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1778 * and should not be reopened.
1779 * @return void no return or void, script execution stopped unless $dontdie is true
1781 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1782 global $CFG, $COURSE, $SESSION;
1785 ignore_user_abort(true);
1788 session_get_instance()->write_close(); // unlock session during fileserving
1790 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1791 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1792 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1793 $filename = is_null($filename) ?
$stored_file->get_filename() : $filename;
1794 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1795 $mimetype = ($forcedownload and !$isFF) ?
'application/x-forcedownload' :
1796 ($stored_file->get_mimetype() ?
$stored_file->get_mimetype() : mimeinfo('type', $filename));
1798 $lastmodified = $stored_file->get_timemodified();
1799 $filesize = $stored_file->get_filesize();
1801 //IE compatibiltiy HACK!
1802 if (ini_get('zlib.output_compression')) {
1803 ini_set('zlib.output_compression', 'Off');
1806 //try to disable automatic sid rewrite in cookieless mode
1807 @ini_set
("session.use_trans_sid", "false");
1809 //do not put '@' before the next header to detect incorrect moodle configurations,
1810 //error should be better than "weird" empty lines for admins/users
1811 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1812 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1814 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1815 if (check_browser_version('MSIE')) {
1816 $filename = rawurlencode($filename);
1819 if ($forcedownload) {
1820 @header
('Content-Disposition: attachment; filename="'.$filename.'"');
1822 @header
('Content-Disposition: inline; filename="'.$filename.'"');
1825 if ($lifetime > 0) {
1826 @header
('Cache-Control: max-age='.$lifetime);
1827 @header
('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
1828 @header
('Pragma: ');
1830 if (empty($CFG->disablebyteserving
) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1832 @header
('Accept-Ranges: bytes');
1834 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1835 // byteserving stuff - for acrobat reader and download accelerators
1836 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1837 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1839 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
1840 foreach ($ranges as $key=>$value) {
1841 if ($ranges[$key][1] == '') {
1843 $ranges[$key][1] = $filesize - $ranges[$key][2];
1844 $ranges[$key][2] = $filesize - 1;
1845 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
1847 $ranges[$key][2] = $filesize - 1;
1849 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1850 //invalid byte-range ==> ignore header
1854 //prepare multipart header
1855 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
1856 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1862 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1866 /// Do not byteserve (disabled, strings, text and html files).
1867 @header
('Accept-Ranges: none');
1869 } else { // Do not cache files in proxies and browsers
1870 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1871 @header
('Cache-Control: max-age=10');
1872 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1873 @header
('Pragma: ');
1874 } else { //normal http - prevent caching at all cost
1875 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1876 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1877 @header
('Pragma: no-cache');
1879 @header
('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1882 if (empty($filter)) {
1884 if ($mimetype == 'text/html' && !empty($CFG->usesid
)) {
1885 //cookieless mode - rewrite links
1886 @header
('Content-Type: text/html');
1887 $text = $stored_file->get_content();
1888 $text = sid_ob_rewrite($text);
1889 $filesize = strlen($text);
1891 } else if ($mimetype == 'text/plain') {
1892 @header
('Content-Type: Text/plain; charset=utf-8'); //add encoding
1894 @header
('Content-Type: '.$mimetype);
1896 @header
('Content-Length: '.$filesize);
1897 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1901 $stored_file->readfile();
1904 } else { // Try to put the file through filters
1905 if ($mimetype == 'text/html') {
1906 $options = new object();
1907 $options->noclean
= true;
1908 $options->nocache
= true; // temporary workaround for MDL-5136
1909 $text = $stored_file->get_content();
1910 $text = file_modify_html_header($text);
1911 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
1912 if (!empty($CFG->usesid
)) {
1913 //cookieless mode - rewrite links
1914 $output = sid_ob_rewrite($output);
1917 @header
('Content-Length: '.strlen($output));
1918 @header
('Content-Type: text/html');
1919 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1921 // only filter text if filter all files is selected
1922 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1923 $options = new object();
1924 $options->newlines
= false;
1925 $options->noclean
= true;
1926 $text = $stored_file->get_content();
1927 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
1928 if (!empty($CFG->usesid
)) {
1929 //cookieless mode - rewrite links
1930 $output = sid_ob_rewrite($output);
1933 @header
('Content-Length: '.strlen($output));
1934 @header
('Content-Type: text/html; charset=utf-8'); //add encoding
1935 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1937 } else { // Just send it out raw
1938 @header
('Content-Length: '.$filesize);
1939 @header
('Content-Type: '.$mimetype);
1940 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1941 $stored_file->readfile();
1947 die; //no more chars to output!!!
1951 * Retrieves an array of records from a CSV file and places
1952 * them into a given table structure
1956 * @param string $file The path to a CSV file
1957 * @param string $table The table to retrieve columns from
1958 * @return bool|array Returns an array of CSV records or false
1960 function get_records_csv($file, $table) {
1963 if (!$metacolumns = $DB->get_columns($table)) {
1967 if(!($handle = @fopen
($file, 'r'))) {
1968 print_error('get_records_csv failed to open '.$file);
1971 $fieldnames = fgetcsv($handle, 4096);
1972 if(empty($fieldnames)) {
1979 foreach($metacolumns as $metacolumn) {
1980 $ord = array_search($metacolumn->name
, $fieldnames);
1982 $columns[$metacolumn->name
] = $ord;
1988 while (($data = fgetcsv($handle, 4096)) !== false) {
1989 $item = new stdClass
;
1990 foreach($columns as $name => $ord) {
1991 $item->$name = $data[$ord];
2004 * @param string $file The file to put the CSV content into
2005 * @param array $records An array of records to write to a CSV file
2006 * @param string $table The table to get columns from
2007 * @return bool success
2009 function put_records_csv($file, $records, $table = NULL) {
2012 if (empty($records)) {
2016 $metacolumns = NULL;
2017 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2023 if(!($fp = @fopen
($CFG->dataroot
.'/temp/'.$file, 'w'))) {
2024 print_error('put_records_csv failed to open '.$file);
2027 $proto = reset($records);
2028 if(is_object($proto)) {
2029 $fields_records = array_keys(get_object_vars($proto));
2031 else if(is_array($proto)) {
2032 $fields_records = array_keys($proto);
2039 if(!empty($metacolumns)) {
2040 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2041 $fields = array_intersect($fields_records, $fields_table);
2044 $fields = $fields_records;
2047 fwrite($fp, implode(',', $fields));
2048 fwrite($fp, "\r\n");
2050 foreach($records as $record) {
2051 $array = (array)$record;
2053 foreach($fields as $field) {
2054 if(strpos($array[$field], ',')) {
2055 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2058 $values[] = $array[$field];
2061 fwrite($fp, implode(',', $values)."\r\n");
2070 * Recursively delete the file or folder with path $location. That is,
2071 * if it is a file delete it. If it is a folder, delete all its content
2072 * then delete it. If $location does not exist to start, that is not
2073 * considered an error.
2075 * @param $location the path to remove.
2078 function fulldelete($location) {
2079 if (empty($location)) {
2080 // extra safety against wrong param
2083 if (is_dir($location)) {
2084 $currdir = opendir($location);
2085 while (false !== ($file = readdir($currdir))) {
2086 if ($file <> ".." && $file <> ".") {
2087 $fullfile = $location."/".$file;
2088 if (is_dir($fullfile)) {
2089 if (!fulldelete($fullfile)) {
2093 if (!unlink($fullfile)) {
2100 if (! rmdir($location)) {
2104 } else if (file_exists($location)) {
2105 if (!unlink($location)) {
2113 * Send requested byterange of file.
2115 * @param object $handle A file handle
2116 * @param string $mimetype The mimetype for the output
2117 * @param array $ranges An array of ranges to send
2118 * @param string $filesize The size of the content if only one range is used
2120 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2121 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2122 if ($handle === false) {
2125 if (count($ranges) == 1) { //only one range requested
2126 $length = $ranges[0][2] - $ranges[0][1] +
1;
2127 @header
('HTTP/1.1 206 Partial content');
2128 @header
('Content-Length: '.$length);
2129 @header
('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2130 @header
('Content-Type: '.$mimetype);
2131 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
2133 fseek($handle, $ranges[0][1]);
2134 while (!feof($handle) && $length > 0) {
2135 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2136 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2139 $length -= strlen($buffer);
2143 } else { // multiple ranges requested - not tested much
2145 foreach($ranges as $range) {
2146 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
2148 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
2149 @header
('HTTP/1.1 206 Partial content');
2150 @header
('Content-Length: '.$totallength);
2151 @header
('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
2152 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2153 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
2154 foreach($ranges as $range) {
2155 $length = $range[2] - $range[1] +
1;
2158 fseek($handle, $range[1]);
2159 while (!feof($handle) && $length > 0) {
2160 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2161 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
2164 $length -= strlen($buffer);
2167 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
2174 * add includes (js and css) into uploaded files
2175 * before returning them, useful for themes and utf.js includes
2178 * @param string $text text to search and replace
2179 * @return string text with added head includes
2181 function file_modify_html_header($text) {
2182 // first look for <head> tag
2185 $stylesheetshtml = '';
2186 /* foreach ($CFG->stylesheets as $stylesheet) {
2188 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2192 if (filter_is_enabled('filter/mediaplugin')) {
2193 // this script is needed by most media filter plugins.
2194 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot
. '/lib/ufo.js');
2195 $ufo = html_writer
::tag('script', '', $attributes) . "\n";
2198 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2200 $replacement = '<head>'.$ufo.$stylesheetshtml;
2201 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2205 // if not, look for <html> tag, and stick <head> right after
2206 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2208 // replace <html> tag with <html><head>includes</head>
2209 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2210 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2214 // if not, look for <body> tag, and stick <head> before body
2215 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2217 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2218 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2222 // if not, just stick a <head> tag at the beginning
2223 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2228 * RESTful cURL class
2230 * This is a wrapper class for curl, it is quite easy to use:
2234 * $c = new curl(array('cache'=>true));
2236 * $c = new curl(array('cookie'=>true));
2238 * $c = new curl(array('proxy'=>true));
2240 * // HTTP GET Method
2241 * $html = $c->get('http://example.com');
2242 * // HTTP POST Method
2243 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2244 * // HTTP PUT Method
2245 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2250 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2251 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2256 public $cache = false;
2257 public $proxy = false;
2259 public $version = '0.4 dev';
2261 public $response = array();
2262 public $header = array();
2270 private $proxy_host = '';
2271 private $proxy_auth = '';
2272 private $proxy_type = '';
2274 private $debug = false;
2275 private $cookie = false;
2279 * @param array $options
2281 public function __construct($options = array()){
2283 if (!function_exists('curl_init')) {
2284 $this->error
= 'cURL module must be enabled!';
2285 trigger_error($this->error
, E_USER_ERROR
);
2288 // the options of curl should be init here.
2290 if (!empty($options['debug'])) {
2291 $this->debug
= true;
2293 if(!empty($options['cookie'])) {
2294 if($options['cookie'] === true) {
2295 $this->cookie
= $CFG->dataroot
.'/curl_cookie.txt';
2297 $this->cookie
= $options['cookie'];
2300 if (!empty($options['cache'])) {
2301 if (class_exists('curl_cache')) {
2302 if (!empty($options['module_cache'])) {
2303 $this->cache
= new curl_cache($options['module_cache']);
2305 $this->cache
= new curl_cache('misc');
2309 if (!empty($CFG->proxyhost
)) {
2310 if (empty($CFG->proxyport
)) {
2311 $this->proxy_host
= $CFG->proxyhost
;
2313 $this->proxy_host
= $CFG->proxyhost
.':'.$CFG->proxyport
;
2315 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
2316 $this->proxy_auth
= $CFG->proxyuser
.':'.$CFG->proxypassword
;
2317 $this->setopt(array(
2318 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM
,
2319 'proxyuserpwd'=>$this->proxy_auth
));
2321 if (!empty($CFG->proxytype
)) {
2322 if ($CFG->proxytype
== 'SOCKS5') {
2323 $this->proxy_type
= CURLPROXY_SOCKS5
;
2325 $this->proxy_type
= CURLPROXY_HTTP
;
2326 $this->setopt(array('httpproxytunnel'=>false));
2328 $this->setopt(array('proxytype'=>$this->proxy_type
));
2331 if (!empty($this->proxy_host
)) {
2332 $this->proxy
= array('proxy'=>$this->proxy_host
);
2336 * Resets the CURL options that have already been set
2338 public function resetopt(){
2339 $this->options
= array();
2340 $this->options
['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2341 // True to include the header in the output
2342 $this->options
['CURLOPT_HEADER'] = 0;
2343 // True to Exclude the body from the output
2344 $this->options
['CURLOPT_NOBODY'] = 0;
2345 // TRUE to follow any "Location: " header that the server
2346 // sends as part of the HTTP header (note this is recursive,
2347 // PHP will follow as many "Location: " headers that it is sent,
2348 // unless CURLOPT_MAXREDIRS is set).
2349 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2350 $this->options
['CURLOPT_MAXREDIRS'] = 10;
2351 $this->options
['CURLOPT_ENCODING'] = '';
2352 // TRUE to return the transfer as a string of the return
2353 // value of curl_exec() instead of outputting it out directly.
2354 $this->options
['CURLOPT_RETURNTRANSFER'] = 1;
2355 $this->options
['CURLOPT_BINARYTRANSFER'] = 0;
2356 $this->options
['CURLOPT_SSL_VERIFYPEER'] = 0;
2357 $this->options
['CURLOPT_SSL_VERIFYHOST'] = 2;
2358 $this->options
['CURLOPT_CONNECTTIMEOUT'] = 30;
2364 public function resetcookie() {
2365 if (!empty($this->cookie
)) {
2366 if (is_file($this->cookie
)) {
2367 $fp = fopen($this->cookie
, 'w');
2379 * @param array $options If array is null, this function will
2380 * reset the options to default value.
2383 public function setopt($options = array()) {
2384 if (is_array($options)) {
2385 foreach($options as $name => $val){
2386 if (stripos($name, 'CURLOPT_') === false) {
2387 $name = strtoupper('CURLOPT_'.$name);
2389 $this->options
[$name] = $val;
2397 public function cleanopt(){
2398 unset($this->options
['CURLOPT_HTTPGET']);
2399 unset($this->options
['CURLOPT_POST']);
2400 unset($this->options
['CURLOPT_POSTFIELDS']);
2401 unset($this->options
['CURLOPT_PUT']);
2402 unset($this->options
['CURLOPT_INFILE']);
2403 unset($this->options
['CURLOPT_INFILESIZE']);
2404 unset($this->options
['CURLOPT_CUSTOMREQUEST']);
2408 * Set HTTP Request Header
2410 * @param array $headers
2413 public function setHeader($header) {
2414 if (is_array($header)){
2415 foreach ($header as $v) {
2416 $this->setHeader($v);
2419 $this->header
[] = $header;
2423 * Set HTTP Response Header
2426 public function getResponse(){
2427 return $this->response
;
2430 * private callback function
2431 * Formatting HTTP Response Header
2433 * @param mixed $ch Apparently not used
2434 * @param string $header
2435 * @return int The strlen of the header
2437 private function formatHeader($ch, $header)
2440 if (strlen($header) > 2) {
2441 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2442 $key = rtrim($key, ':');
2443 if (!empty($this->response
[$key])) {
2444 if (is_array($this->response
[$key])){
2445 $this->response
[$key][] = $value;
2447 $tmp = $this->response
[$key];
2448 $this->response
[$key] = array();
2449 $this->response
[$key][] = $tmp;
2450 $this->response
[$key][] = $value;
2454 $this->response
[$key] = $value;
2457 return strlen($header);
2461 * Set options for individual curl instance
2463 * @param object $curl A curl handle
2464 * @param array $options
2465 * @return object The curl handle
2467 private function apply_opt($curl, $options) {
2471 if (!empty($this->cookie
) ||
!empty($options['cookie'])) {
2472 $this->setopt(array('cookiejar'=>$this->cookie
,
2473 'cookiefile'=>$this->cookie
2478 if (!empty($this->proxy
) ||
!empty($options['proxy'])) {
2479 $this->setopt($this->proxy
);
2481 $this->setopt($options);
2482 // reset before set options
2483 curl_setopt($curl, CURLOPT_HEADERFUNCTION
, array(&$this,'formatHeader'));
2485 if (empty($this->header
)){
2486 $this->setHeader(array(
2487 'User-Agent: MoodleBot/1.0',
2488 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2489 'Connection: keep-alive'
2492 curl_setopt($curl, CURLOPT_HTTPHEADER
, $this->header
);
2495 echo '<h1>Options</h1>';
2496 var_dump($this->options
);
2497 echo '<h1>Header</h1>';
2498 var_dump($this->header
);
2502 foreach($this->options
as $name => $val) {
2503 if (is_string($name)) {
2504 $name = constant(strtoupper($name));
2506 curl_setopt($curl, $name, $val);
2511 * Download multiple files in parallel
2513 * Calls {@link multi()} with specific download headers
2517 * $c->download(array(
2518 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2519 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2523 * @param array $requests An array of files to request
2524 * @param array $options An array of options to set
2525 * @return array An array of results
2527 public function download($requests, $options = array()) {
2528 $options['CURLOPT_BINARYTRANSFER'] = 1;
2529 $options['RETURNTRANSFER'] = false;
2530 return $this->multi($requests, $options);
2533 * Mulit HTTP Requests
2534 * This function could run multi-requests in parallel.
2536 * @param array $requests An array of files to request
2537 * @param array $options An array of options to set
2538 * @return array An array of results
2540 protected function multi($requests, $options = array()) {
2541 $count = count($requests);
2544 $main = curl_multi_init();
2545 for ($i = 0; $i < $count; $i++
) {
2546 $url = $requests[$i];
2547 foreach($url as $n=>$v){
2548 $options[$n] = $url[$n];
2550 $handles[$i] = curl_init($url['url']);
2551 $this->apply_opt($handles[$i], $options);
2552 curl_multi_add_handle($main, $handles[$i]);
2556 curl_multi_exec($main, $running);
2557 } while($running > 0);
2558 for ($i = 0; $i < $count; $i++
) {
2559 if (!empty($optins['CURLOPT_RETURNTRANSFER'])) {
2562 $results[] = curl_multi_getcontent($handles[$i]);
2564 curl_multi_remove_handle($main, $handles[$i]);
2566 curl_multi_close($main);
2570 * Single HTTP Request
2572 * @param string $url The URL to request
2573 * @param array $options
2576 protected function request($url, $options = array()){
2577 // create curl instance
2578 $curl = curl_init($url);
2579 $options['url'] = $url;
2580 $this->apply_opt($curl, $options);
2581 if ($this->cache
&& $ret = $this->cache
->get($this->options
)) {
2584 $ret = curl_exec($curl);
2586 $this->cache
->set($this->options
, $ret);
2590 $this->info
= curl_getinfo($curl);
2591 $this->error
= curl_error($curl);
2594 echo '<h1>Return Data</h1>';
2596 echo '<h1>Info</h1>';
2597 var_dump($this->info
);
2598 echo '<h1>Error</h1>';
2599 var_dump($this->error
);
2604 if (empty($this->error
)){
2607 return $this->error
;
2608 // exception is not ajax friendly
2609 //throw new moodle_exception($this->error, 'curl');
2618 * @param string $url
2619 * @param array $options
2622 public function head($url, $options = array()){
2623 $options['CURLOPT_HTTPGET'] = 0;
2624 $options['CURLOPT_HEADER'] = 1;
2625 $options['CURLOPT_NOBODY'] = 1;
2626 return $this->request($url, $options);
2632 * @param string $url
2633 * @param array|string $params
2634 * @param array $options
2637 public function post($url, $params = '', $options = array()){
2638 $options['CURLOPT_POST'] = 1;
2639 if (is_array($params)) {
2640 $this->_tmp_file_post_params
= array();
2641 foreach ($params as $key => $value) {
2642 if ($value instanceof stored_file
) {
2643 $value->add_to_curl_request($this, $key);
2645 $this->_tmp_file_post_params
[$key] = $value;
2648 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params
;
2649 unset($this->_tmp_file_post_params
);
2651 // $params is the raw post data
2652 $options['CURLOPT_POSTFIELDS'] = $params;
2654 return $this->request($url, $options);
2660 * @param string $url
2661 * @param array $params
2662 * @param array $options
2665 public function get($url, $params = array(), $options = array()){
2666 $options['CURLOPT_HTTPGET'] = 1;
2668 if (!empty($params)){
2669 $url .= (stripos($url, '?') !== false) ?
'&' : '?';
2670 $url .= http_build_query($params, '', '&');
2672 return $this->request($url, $options);
2678 * @param string $url
2679 * @param array $params
2680 * @param array $options
2683 public function put($url, $params = array(), $options = array()){
2684 $file = $params['file'];
2685 if (!is_file($file)){
2688 $fp = fopen($file, 'r');
2689 $size = filesize($file);
2690 $options['CURLOPT_PUT'] = 1;
2691 $options['CURLOPT_INFILESIZE'] = $size;
2692 $options['CURLOPT_INFILE'] = $fp;
2693 if (!isset($this->options
['CURLOPT_USERPWD'])){
2694 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2696 $ret = $this->request($url, $options);
2702 * HTTP DELETE method
2704 * @param string $url
2705 * @param array $params
2706 * @param array $options
2709 public function delete($url, $param = array(), $options = array()){
2710 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2711 if (!isset($options['CURLOPT_USERPWD'])) {
2712 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2714 $ret = $this->request($url, $options);
2720 * @param string $url
2721 * @param array $options
2724 public function trace($url, $options = array()){
2725 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2726 $ret = $this->request($url, $options);
2730 * HTTP OPTIONS method
2732 * @param string $url
2733 * @param array $options
2736 public function options($url, $options = array()){
2737 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2738 $ret = $this->request($url, $options);
2741 public function get_info() {
2747 * This class is used by cURL class, use case:
2750 * $CFG->repositorycacheexpire = 120;
2751 * $CFG->curlcache = 120;
2753 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2754 * $ret = $c->get('http://www.google.com');
2759 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2760 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2768 * @param string @module which module is using curl_cache
2771 function __construct($module = 'repository'){
2773 if (!empty($module)) {
2774 $this->dir
= $CFG->dataroot
.'/cache/'.$module.'/';
2776 $this->dir
= $CFG->dataroot
.'/cache/misc/';
2778 if (!file_exists($this->dir
)) {
2779 mkdir($this->dir
, $CFG->directorypermissions
, true);
2781 if ($module == 'repository') {
2782 if (empty($CFG->repositorycacheexpire
)) {
2783 $CFG->repositorycacheexpire
= 120;
2785 $this->ttl
= $CFG->repositorycacheexpire
;
2787 if (empty($CFG->curlcache
)) {
2788 $CFG->curlcache
= 120;
2790 $this->ttl
= $CFG->curlcache
;
2799 * @param mixed $param
2800 * @return bool|string
2802 public function get($param){
2804 $this->cleanup($this->ttl
);
2805 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
2806 if(file_exists($this->dir
.$filename)) {
2807 $lasttime = filemtime($this->dir
.$filename);
2808 if(time()-$lasttime > $this->ttl
)
2812 $fp = fopen($this->dir
.$filename, 'r');
2813 $size = filesize($this->dir
.$filename);
2814 $content = fread($fp, $size);
2815 return unserialize($content);
2824 * @global object $CFG
2825 * @global object $USER
2826 * @param mixed $param
2829 public function set($param, $val){
2831 $filename = 'u'.$USER->id
.'_'.md5(serialize($param));
2832 $fp = fopen($this->dir
.$filename, 'w');
2833 fwrite($fp, serialize($val));
2838 * Remove cache files
2840 * @param int $expire The number os seconds before expiry
2842 public function cleanup($expire){
2843 if($dir = opendir($this->dir
)){
2844 while (false !== ($file = readdir($dir))) {
2845 if(!is_dir($file) && $file != '.' && $file != '..') {
2846 $lasttime = @filemtime
($this->dir
.$file);
2847 if(time() - $lasttime > $expire){
2848 @unlink
($this->dir
.$file);
2855 * delete current user's cache file
2857 * @global object $CFG
2858 * @global object $USER
2860 public function refresh(){
2862 if($dir = opendir($this->dir
)){
2863 while (false !== ($file = readdir($dir))) {
2864 if(!is_dir($file) && $file != '.' && $file != '..') {
2865 if(strpos($file, 'u'.$USER->id
.'_')!==false){
2866 @unlink
($this->dir
.$file);
2875 * This class is used to parse lib/file/file_types.mm which help get file
2876 * extensions by file types.
2877 * The file_types.mm file can be edited by freemind in graphic environment.
2881 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
2882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2884 class filetype_parser
{
2886 * Check file_types.mm file, setup variables
2888 * @global object $CFG
2889 * @param string $file
2891 public function __construct($file = '') {
2894 $this->file
= $CFG->libdir
.'/filestorage/file_types.mm';
2896 $this->file
= $file;
2898 $this->tree
= array();
2899 $this->result
= array();
2903 * A private function to browse xml nodes
2905 * @param array $parent
2906 * @param array $types
2908 private function _browse_nodes($parent, $types) {
2909 $key = (string)$parent['TEXT'];
2910 if(isset($parent->node
)) {
2911 $this->tree
[$key] = array();
2912 if (in_array((string)$parent['TEXT'], $types)) {
2913 $this->_select_nodes($parent, $this->result
);
2915 foreach($parent->node
as $v){
2916 $this->_browse_nodes($v, $types);
2920 $this->tree
[] = $key;
2925 * A private function to select text nodes
2927 * @param array $parent
2929 private function _select_nodes($parent){
2930 if(isset($parent->node
)) {
2931 foreach($parent->node
as $v){
2932 $this->_select_nodes($v, $this->result
);
2935 $this->result
[] = (string)$parent['TEXT'];
2941 * Get file extensions by file types names.
2943 * @param array $types
2946 public function get_extensions($types) {
2947 if (!is_array($types)) {
2948 $types = array($types);
2950 $this->result
= array();
2951 if ((is_array($types) && in_array('*', $types)) ||
2952 $types == '*' ||
empty($types)) {
2955 foreach ($types as $key=>$value){
2956 if (strpos($value, '.') !== false) {
2957 $this->result
[] = $value;
2958 unset($types[$key]);
2961 if (file_exists($this->file
)) {
2962 $xml = simplexml_load_file($this->file
);
2963 foreach($xml->node
->node
as $v){
2964 if (in_array((string)$v['TEXT'], $types)) {
2965 $this->_select_nodes($v);
2967 $this->_browse_nodes($v, $types);
2971 exit('Failed to open file lib/filestorage/file_types.mm');
2973 return $this->result
;