MDL-32147 - use correct 404 for server type
[moodle.git] / lib / filelib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Functions for file handling.
19  *
20  * @package   core_files
21  * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 defined('MOODLE_INTERNAL') || die();
27 /**
28  * BYTESERVING_BOUNDARY - string unique string constant.
29  */
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38  * Encodes file serving url
39  *
40  * @deprecated use moodle_url factory methods instead
41  *
42  * @todo MDL-31071 deprecate this function
43  * @global stdClass $CFG
44  * @param string $urlbase
45  * @param string $path /filearea/itemid/dir/dir/file.exe
46  * @param bool $forcedownload
47  * @param bool $https https url required
48  * @return string encoded file url
49  */
50 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
51     global $CFG;
53 //TODO: deprecate this
55     if ($CFG->slasharguments) {
56         $parts = explode('/', $path);
57         $parts = array_map('rawurlencode', $parts);
58         $path  = implode('/', $parts);
59         $return = $urlbase.$path;
60         if ($forcedownload) {
61             $return .= '?forcedownload=1';
62         }
63     } else {
64         $path = rawurlencode($path);
65         $return = $urlbase.'?file='.$path;
66         if ($forcedownload) {
67             $return .= '&amp;forcedownload=1';
68         }
69     }
71     if ($https) {
72         $return = str_replace('http://', 'https://', $return);
73     }
75     return $return;
76 }
78 /**
79  * Prepares 'editor' formslib element from data in database
80  *
81  * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
82  * function then copies the embedded files into draft area (assigning itemids automatically),
83  * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
84  * displayed.
85  * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
86  * your mform's set_data() supplying the object returned by this function.
87  *
88  * @category files
89  * @param stdClass $data database field that holds the html text with embedded media
90  * @param string $field the name of the database field that holds the html text with embedded media
91  * @param array $options editor options (like maxifiles, maxbytes etc.)
92  * @param stdClass $context context of the editor
93  * @param string $component
94  * @param string $filearea file area name
95  * @param int $itemid item id, required if item exists
96  * @return stdClass modified data object
97  */
98 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
99     $options = (array)$options;
100     if (!isset($options['trusttext'])) {
101         $options['trusttext'] = false;
102     }
103     if (!isset($options['forcehttps'])) {
104         $options['forcehttps'] = false;
105     }
106     if (!isset($options['subdirs'])) {
107         $options['subdirs'] = false;
108     }
109     if (!isset($options['maxfiles'])) {
110         $options['maxfiles'] = 0; // no files by default
111     }
112     if (!isset($options['noclean'])) {
113         $options['noclean'] = false;
114     }
116     //sanity check for passed context. This function doesn't expect $option['context'] to be set
117     //But this function is called before creating editor hence, this is one of the best places to check
118     //if context is used properly. This check notify developer that they missed passing context to editor.
119     if (isset($context) && !isset($options['context'])) {
120         //if $context is not null then make sure $option['context'] is also set.
121         debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
122     } else if (isset($options['context']) && isset($context)) {
123         //If both are passed then they should be equal.
124         if ($options['context']->id != $context->id) {
125             $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
126             throw new coding_exception($exceptionmsg);
127         }
128     }
130     if (is_null($itemid) or is_null($context)) {
131         $contextid = null;
132         $itemid = null;
133         if (!isset($data)) {
134             $data = new stdClass();
135         }
136         if (!isset($data->{$field})) {
137             $data->{$field} = '';
138         }
139         if (!isset($data->{$field.'format'})) {
140             $data->{$field.'format'} = editors_get_preferred_format();
141         }
142         if (!$options['noclean']) {
143             $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
144         }
146     } else {
147         if ($options['trusttext']) {
148             // noclean ignored if trusttext enabled
149             if (!isset($data->{$field.'trust'})) {
150                 $data->{$field.'trust'} = 0;
151             }
152             $data = trusttext_pre_edit($data, $field, $context);
153         } else {
154             if (!$options['noclean']) {
155                 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
156             }
157         }
158         $contextid = $context->id;
159     }
161     if ($options['maxfiles'] != 0) {
162         $draftid_editor = file_get_submitted_draft_itemid($field);
163         $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
164         $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
165     } else {
166         $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
167     }
169     return $data;
172 /**
173  * Prepares the content of the 'editor' form element with embedded media files to be saved in database
174  *
175  * This function moves files from draft area to the destination area and
176  * encodes URLs to the draft files so they can be safely saved into DB. The
177  * form has to contain the 'editor' element named foobar_editor, where 'foobar'
178  * is the name of the database field to hold the wysiwyg editor content. The
179  * editor data comes as an array with text, format and itemid properties. This
180  * function automatically adds $data properties foobar, foobarformat and
181  * foobartrust, where foobar has URL to embedded files encoded.
182  *
183  * @category files
184  * @param stdClass $data raw data submitted by the form
185  * @param string $field name of the database field containing the html with embedded media files
186  * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
187  * @param stdClass $context context, required for existing data
188  * @param string $component file component
189  * @param string $filearea file area name
190  * @param int $itemid item id, required if item exists
191  * @return stdClass modified data object
192  */
193 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
194     $options = (array)$options;
195     if (!isset($options['trusttext'])) {
196         $options['trusttext'] = false;
197     }
198     if (!isset($options['forcehttps'])) {
199         $options['forcehttps'] = false;
200     }
201     if (!isset($options['subdirs'])) {
202         $options['subdirs'] = false;
203     }
204     if (!isset($options['maxfiles'])) {
205         $options['maxfiles'] = 0; // no files by default
206     }
207     if (!isset($options['maxbytes'])) {
208         $options['maxbytes'] = 0; // unlimited
209     }
211     if ($options['trusttext']) {
212         $data->{$field.'trust'} = trusttext_trusted($context);
213     } else {
214         $data->{$field.'trust'} = 0;
215     }
217     $editor = $data->{$field.'_editor'};
219     if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
220         $data->{$field} = $editor['text'];
221     } else {
222         $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
223     }
224     $data->{$field.'format'} = $editor['format'];
226     return $data;
229 /**
230  * Saves text and files modified by Editor formslib element
231  *
232  * @category files
233  * @param stdClass $data $database entry field
234  * @param string $field name of data field
235  * @param array $options various options
236  * @param stdClass $context context - must already exist
237  * @param string $component
238  * @param string $filearea file area name
239  * @param int $itemid must already exist, usually means data is in db
240  * @return stdClass modified data obejct
241  */
242 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
243     $options = (array)$options;
244     if (!isset($options['subdirs'])) {
245         $options['subdirs'] = false;
246     }
247     if (is_null($itemid) or is_null($context)) {
248         $itemid = null;
249         $contextid = null;
250     } else {
251         $contextid = $context->id;
252     }
254     $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
255     file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
256     $data->{$field.'_filemanager'} = $draftid_editor;
258     return $data;
261 /**
262  * Saves files modified by File manager formslib element
263  *
264  * @todo MDL-31073 review this function
265  * @category files
266  * @param stdClass $data $database entry field
267  * @param string $field name of data field
268  * @param array $options various options
269  * @param stdClass $context context - must already exist
270  * @param string $component
271  * @param string $filearea file area name
272  * @param int $itemid must already exist, usually means data is in db
273  * @return stdClass modified data obejct
274  */
275 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
276     $options = (array)$options;
277     if (!isset($options['subdirs'])) {
278         $options['subdirs'] = false;
279     }
280     if (!isset($options['maxfiles'])) {
281         $options['maxfiles'] = -1; // unlimited
282     }
283     if (!isset($options['maxbytes'])) {
284         $options['maxbytes'] = 0; // unlimited
285     }
287     if (empty($data->{$field.'_filemanager'})) {
288         $data->$field = '';
290     } else {
291         file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
292         $fs = get_file_storage();
294         if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
295             $data->$field = '1'; // TODO: this is an ugly hack (skodak)
296         } else {
297             $data->$field = '';
298         }
299     }
301     return $data;
304 /**
305  * Generate a draft itemid
306  *
307  * @category files
308  * @global moodle_database $DB
309  * @global stdClass $USER
310  * @return int a random but available draft itemid that can be used to create a new draft
311  * file area.
312  */
313 function file_get_unused_draft_itemid() {
314     global $DB, $USER;
316     if (isguestuser() or !isloggedin()) {
317         // guests and not-logged-in users can not be allowed to upload anything!!!!!!
318         print_error('noguest');
319     }
321     $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
323     $fs = get_file_storage();
324     $draftitemid = rand(1, 999999999);
325     while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
326         $draftitemid = rand(1, 999999999);
327     }
329     return $draftitemid;
332 /**
333  * Initialise a draft file area from a real one by copying the files. A draft
334  * area will be created if one does not already exist. Normally you should
335  * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
336  *
337  * @category files
338  * @global stdClass $CFG
339  * @global stdClass $USER
340  * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
341  * @param int $contextid This parameter and the next two identify the file area to copy files from.
342  * @param string $component
343  * @param string $filearea helps indentify the file area.
344  * @param int $itemid helps identify the file area. Can be null if there are no files yet.
345  * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
346  * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
347  * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
348  */
349 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
350     global $CFG, $USER, $CFG;
352     $options = (array)$options;
353     if (!isset($options['subdirs'])) {
354         $options['subdirs'] = false;
355     }
356     if (!isset($options['forcehttps'])) {
357         $options['forcehttps'] = false;
358     }
360     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
361     $fs = get_file_storage();
363     if (empty($draftitemid)) {
364         // create a new area and copy existing files into
365         $draftitemid = file_get_unused_draft_itemid();
366         $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
367         if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
368             foreach ($files as $file) {
369                 if ($file->is_directory() and $file->get_filepath() === '/') {
370                     // we need a way to mark the age of each draft area,
371                     // by not copying the root dir we force it to be created automatically with current timestamp
372                     continue;
373                 }
374                 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
375                     continue;
376                 }
377                 $fs->create_file_from_storedfile($file_record, $file);
378             }
379         }
380         if (!is_null($text)) {
381             // at this point there should not be any draftfile links yet,
382             // because this is a new text from database that should still contain the @@pluginfile@@ links
383             // this happens when developers forget to post process the text
384             $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
385         }
386     } else {
387         // nothing to do
388     }
390     if (is_null($text)) {
391         return null;
392     }
394     // relink embedded files - editor can not handle @@PLUGINFILE@@ !
395     return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
398 /**
399  * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
400  *
401  * @category files
402  * @global stdClass $CFG
403  * @param string $text The content that may contain ULRs in need of rewriting.
404  * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
405  * @param int $contextid This parameter and the next two identify the file area to use.
406  * @param string $component
407  * @param string $filearea helps identify the file area.
408  * @param int $itemid helps identify the file area.
409  * @param array $options text and file options ('forcehttps'=>false)
410  * @return string the processed text.
411  */
412 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
413     global $CFG;
415     $options = (array)$options;
416     if (!isset($options['forcehttps'])) {
417         $options['forcehttps'] = false;
418     }
420     if (!$CFG->slasharguments) {
421         $file = $file . '?file=';
422     }
424     $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
426     if ($itemid !== null) {
427         $baseurl .= "$itemid/";
428     }
430     if ($options['forcehttps']) {
431         $baseurl = str_replace('http://', 'https://', $baseurl);
432     }
434     return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
437 /**
438  * Returns information about files in a draft area.
439  *
440  * @global stdClass $CFG
441  * @global stdClass $USER
442  * @param int $draftitemid the draft area item id.
443  * @return array with the following entries:
444  *      'filecount' => number of files in the draft area.
445  * (more information will be added as needed).
446  */
447 function file_get_draft_area_info($draftitemid) {
448     global $CFG, $USER;
450     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
451     $fs = get_file_storage();
453     $results = array();
455     // The number of files
456     $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
457     $results['filecount'] = count($draftfiles);
458     $results['filesize'] = 0;
459     foreach ($draftfiles as $file) {
460         $results['filesize'] += $file->get_filesize();
461     }
463     return $results;
466 /**
467  * Get used space of files
468  * @global moodle_database $DB
469  * @global stdClass $USER
470  * @return int total bytes
471  */
472 function file_get_user_used_space() {
473     global $DB, $USER;
475     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
476     $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
477             JOIN (SELECT contenthash, filename, MAX(id) AS id
478             FROM {files}
479             WHERE contextid = ? AND component = ? AND filearea != ?
480             GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
481     $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
482     $record = $DB->get_record_sql($sql, $params);
483     return (int)$record->totalbytes;
486 /**
487  * Convert any string to a valid filepath
488  * @todo review this function
489  * @param string $str
490  * @return string path
491  */
492 function file_correct_filepath($str) { //TODO: what is this? (skodak)
493     if ($str == '/' or empty($str)) {
494         return '/';
495     } else {
496         return '/'.trim($str, './@#$ ').'/';
497     }
500 /**
501  * Generate a folder tree of draft area of current USER recursively
502  *
503  * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
504  * @param int $draftitemid
505  * @param string $filepath
506  * @param mixed $data
507  */
508 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
509     global $USER, $OUTPUT, $CFG;
510     $data->children = array();
511     $context = get_context_instance(CONTEXT_USER, $USER->id);
512     $fs = get_file_storage();
513     if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
514         foreach ($files as $file) {
515             if ($file->is_directory()) {
516                 $item = new stdClass();
517                 $item->sortorder = $file->get_sortorder();
518                 $item->filepath = $file->get_filepath();
520                 $foldername = explode('/', trim($item->filepath, '/'));
521                 $item->fullname = trim(array_pop($foldername), '/');
523                 $item->id = uniqid();
524                 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
525                 $data->children[] = $item;
526             } else {
527                 continue;
528             }
529         }
530     }
533 /**
534  * Listing all files (including folders) in current path (draft area)
535  * used by file manager
536  * @param int $draftitemid
537  * @param string $filepath
538  * @return stdClass
539  */
540 function file_get_drafarea_files($draftitemid, $filepath = '/') {
541     global $USER, $OUTPUT, $CFG;
543     $context = get_context_instance(CONTEXT_USER, $USER->id);
544     $fs = get_file_storage();
546     $data = new stdClass();
547     $data->path = array();
548     $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
550     // will be used to build breadcrumb
551     $trail = '';
552     if ($filepath !== '/') {
553         $filepath = file_correct_filepath($filepath);
554         $parts = explode('/', $filepath);
555         foreach ($parts as $part) {
556             if ($part != '' && $part != null) {
557                 $trail .= ('/'.$part.'/');
558                 $data->path[] = array('name'=>$part, 'path'=>$trail);
559             }
560         }
561     }
563     $list = array();
564     $maxlength = 12;
565     if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
566         foreach ($files as $file) {
567             $item = new stdClass();
568             $item->filename = $file->get_filename();
569             $item->filepath = $file->get_filepath();
570             $item->fullname = trim($item->filename, '/');
571             $filesize = $file->get_filesize();
572             $item->filesize = $filesize ? display_size($filesize) : '';
574             $icon = mimeinfo_from_type('icon', $file->get_mimetype());
575             $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
576             $item->sortorder = $file->get_sortorder();
578             if ($icon == 'zip') {
579                 $item->type = 'zip';
580             } else {
581                 $item->type = 'file';
582             }
584             if ($file->is_directory()) {
585                 $item->filesize = 0;
586                 $item->icon = $OUTPUT->pix_url('f/folder')->out();
587                 $item->type = 'folder';
588                 $foldername = explode('/', trim($item->filepath, '/'));
589                 $item->fullname = trim(array_pop($foldername), '/');
590             } else {
591                 // do NOT use file browser here!
592                 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
593             }
594             $list[] = $item;
595         }
596     }
597     $data->itemid = $draftitemid;
598     $data->list = $list;
599     return $data;
602 /**
603  * Returns draft area itemid for a given element.
604  *
605  * @category files
606  * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
607  * @return int the itemid, or 0 if there is not one yet.
608  */
609 function file_get_submitted_draft_itemid($elname) {
610     // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
611     if (!isset($_REQUEST[$elname])) {
612         return 0;
613     }
614     if (is_array($_REQUEST[$elname])) {
615         $param = optional_param_array($elname, 0, PARAM_INT);
616         if (!empty($param['itemid'])) {
617             $param = $param['itemid'];
618         } else {
619             debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
620             return false;
621         }
623     } else {
624         $param = optional_param($elname, 0, PARAM_INT);
625     }
627     if ($param) {
628         require_sesskey();
629     }
631     return $param;
634 /**
635  * Saves files from a draft file area to a real one (merging the list of files).
636  * Can rewrite URLs in some content at the same time if desired.
637  *
638  * @category files
639  * @global stdClass $USER
640  * @param int $draftitemid the id of the draft area to use. Normally obtained
641  *      from file_get_submitted_draft_itemid('elementname') or similar.
642  * @param int $contextid This parameter and the next two identify the file area to save to.
643  * @param string $component
644  * @param string $filearea indentifies the file area.
645  * @param int $itemid helps identifies the file area.
646  * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
647  * @param string $text some html content that needs to have embedded links rewritten
648  *      to the @@PLUGINFILE@@ form for saving in the database.
649  * @param bool $forcehttps force https urls.
650  * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
651  */
652 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
653     global $USER;
655     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
656     $fs = get_file_storage();
658     $options = (array)$options;
659     if (!isset($options['subdirs'])) {
660         $options['subdirs'] = false;
661     }
662     if (!isset($options['maxfiles'])) {
663         $options['maxfiles'] = -1; // unlimited
664     }
665     if (!isset($options['maxbytes'])) {
666         $options['maxbytes'] = 0; // unlimited
667     }
669     $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
670     $oldfiles   = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
672     if (count($draftfiles) < 2) {
673         // means there are no files - one file means root dir only ;-)
674         $fs->delete_area_files($contextid, $component, $filearea, $itemid);
676     } else if (count($oldfiles) < 2) {
677         $filecount = 0;
678         // there were no files before - one file means root dir only ;-)
679         $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
680         foreach ($draftfiles as $file) {
681             if (!$options['subdirs']) {
682                 if ($file->get_filepath() !== '/' or $file->is_directory()) {
683                     continue;
684                 }
685             }
686             if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
687                 // oversized file - should not get here at all
688                 continue;
689             }
690             if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
691                 // more files - should not get here at all
692                 break;
693             }
694             if (!$file->is_directory()) {
695                 $filecount++;
696             }
697             $fs->create_file_from_storedfile($file_record, $file);
698         }
700     } else {
701         // we have to merge old and new files - we want to keep file ids for files that were not changed
702         // we change time modified for all new and changed files, we keep time created as is
703         $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
705         $newhashes = array();
706         foreach ($draftfiles as $file) {
707             $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
708             $newhashes[$newhash] = $file;
709         }
710         $filecount = 0;
711         foreach ($oldfiles as $oldfile) {
712             $oldhash = $oldfile->get_pathnamehash();
713             if (!isset($newhashes[$oldhash])) {
714                 // delete files not needed any more - deleted by user
715                 $oldfile->delete();
716                 continue;
717             }
718             $newfile = $newhashes[$oldhash];
719             if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
720                 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
721                 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
722                 // file was changed, use updated with new timemodified data
723                 $oldfile->delete();
724                 continue;
725             }
726             // unchanged file or directory - we keep it as is
727             unset($newhashes[$oldhash]);
728             if (!$oldfile->is_directory()) {
729                 $filecount++;
730             }
731         }
733         // now add new/changed files
734         // the size and subdirectory tests are extra safety only, the UI should prevent it
735         foreach ($newhashes as $file) {
736             if (!$options['subdirs']) {
737                 if ($file->get_filepath() !== '/' or $file->is_directory()) {
738                     continue;
739                 }
740             }
741             if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
742                 // oversized file - should not get here at all
743                 continue;
744             }
745             if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
746                 // more files - should not get here at all
747                 break;
748             }
749             if (!$file->is_directory()) {
750                 $filecount++;
751             }
752             $fs->create_file_from_storedfile($file_record, $file);
753         }
754     }
756     // note: do not purge the draft area - we clean up areas later in cron,
757     //       the reason is that user might press submit twice and they would loose the files,
758     //       also sometimes we might want to use hacks that save files into two different areas
760     if (is_null($text)) {
761         return null;
762     } else {
763         return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
764     }
767 /**
768  * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
769  * ready to be saved in the database. Normally, this is done automatically by
770  * {@link file_save_draft_area_files()}.
771  *
772  * @category files
773  * @param string $text the content to process.
774  * @param int $draftitemid the draft file area the content was using.
775  * @param bool $forcehttps whether the content contains https URLs. Default false.
776  * @return string the processed content.
777  */
778 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
779     global $CFG, $USER;
781     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
783     $wwwroot = $CFG->wwwroot;
784     if ($forcehttps) {
785         $wwwroot = str_replace('http://', 'https://', $wwwroot);
786     }
788     // relink embedded files if text submitted - no absolute links allowed in database!
789     $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
791     if (strpos($text, 'draftfile.php?file=') !== false) {
792         $matches = array();
793         preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
794         if ($matches) {
795             foreach ($matches[0] as $match) {
796                 $replace = str_ireplace('%2F', '/', $match);
797                 $text = str_replace($match, $replace, $text);
798             }
799         }
800         $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
801     }
803     return $text;
806 /**
807  * Set file sort order
808  *
809  * @global moodle_database $DB
810  * @param int $contextid the context id
811  * @param string $component file component
812  * @param string $filearea file area.
813  * @param int $itemid itemid.
814  * @param string $filepath file path.
815  * @param string $filename file name.
816  * @param int $sortorder the sort order of file.
817  * @return bool
818  */
819 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
820     global $DB;
821     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
822     if ($file_record = $DB->get_record('files', $conditions)) {
823         $sortorder = (int)$sortorder;
824         $file_record->sortorder = $sortorder;
825         $DB->update_record('files', $file_record);
826         return true;
827     }
828     return false;
831 /**
832  * reset file sort order number to 0
833  * @global moodle_database $DB
834  * @param int $contextid the context id
835  * @param string $component
836  * @param string $filearea file area.
837  * @param int|bool $itemid itemid.
838  * @return bool
839  */
840 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
841     global $DB;
843     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
844     if ($itemid !== false) {
845         $conditions['itemid'] = $itemid;
846     }
848     $file_records = $DB->get_records('files', $conditions);
849     foreach ($file_records as $file_record) {
850         $file_record->sortorder = 0;
851         $DB->update_record('files', $file_record);
852     }
853     return true;
856 /**
857  * Returns description of upload error
858  *
859  * @param int $errorcode found in $_FILES['filename.ext']['error']
860  * @return string error description string, '' if ok
861  */
862 function file_get_upload_error($errorcode) {
864     switch ($errorcode) {
865     case 0: // UPLOAD_ERR_OK - no error
866         $errmessage = '';
867         break;
869     case 1: // UPLOAD_ERR_INI_SIZE
870         $errmessage = get_string('uploadserverlimit');
871         break;
873     case 2: // UPLOAD_ERR_FORM_SIZE
874         $errmessage = get_string('uploadformlimit');
875         break;
877     case 3: // UPLOAD_ERR_PARTIAL
878         $errmessage = get_string('uploadpartialfile');
879         break;
881     case 4: // UPLOAD_ERR_NO_FILE
882         $errmessage = get_string('uploadnofilefound');
883         break;
885     // Note: there is no error with a value of 5
887     case 6: // UPLOAD_ERR_NO_TMP_DIR
888         $errmessage = get_string('uploadnotempdir');
889         break;
891     case 7: // UPLOAD_ERR_CANT_WRITE
892         $errmessage = get_string('uploadcantwrite');
893         break;
895     case 8: // UPLOAD_ERR_EXTENSION
896         $errmessage = get_string('uploadextension');
897         break;
899     default:
900         $errmessage = get_string('uploadproblem');
901     }
903     return $errmessage;
906 /**
907  * Recursive function formating an array in POST parameter
908  * @param array $arraydata - the array that we are going to format and add into &$data array
909  * @param string $currentdata - a row of the final postdata array at instant T
910  *                when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
911  * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
912  */
913 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
914         foreach ($arraydata as $k=>$v) {
915             $newcurrentdata = $currentdata;
916             if (is_array($v)) { //the value is an array, call the function recursively
917                 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
918                 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
919             }  else { //add the POST parameter to the $data array
920                 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
921             }
922         }
925 /**
926  * Transform a PHP array into POST parameter
927  * (see the recursive function format_array_postdata_for_curlcall)
928  * @param array $postdata
929  * @return array containing all POST parameters  (1 row = 1 POST parameter)
930  */
931 function format_postdata_for_curlcall($postdata) {
932         $data = array();
933         foreach ($postdata as $k=>$v) {
934             if (is_array($v)) {
935                 $currentdata = urlencode($k);
936                 format_array_postdata_for_curlcall($v, $currentdata, $data);
937             }  else {
938                 $data[] = urlencode($k).'='.urlencode($v);
939             }
940         }
941         $convertedpostdata = implode('&', $data);
942         return $convertedpostdata;
945 /**
946  * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
947  * Due to security concerns only downloads from http(s) sources are supported.
948  *
949  * @todo MDL-31073 add version test for '7.10.5'
950  * @category files
951  * @param string $url file url starting with http(s)://
952  * @param array $headers http headers, null if none. If set, should be an
953  *   associative array of header name => value pairs.
954  * @param array $postdata array means use POST request with given parameters
955  * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
956  *   (if false, just returns content)
957  * @param int $timeout timeout for complete download process including all file transfer
958  *   (default 5 minutes)
959  * @param int $connecttimeout timeout for connection to server; this is the timeout that
960  *   usually happens if the remote server is completely down (default 20 seconds);
961  *   may not work when using proxy
962  * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
963  *   Only use this when already in a trusted location.
964  * @param string $tofile store the downloaded content to file instead of returning it.
965  * @param bool $calctimeout false by default, true enables an extra head request to try and determine
966  *   filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
967  * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
968  */
969 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
970     global $CFG;
972     // some extra security
973     $newlines = array("\r", "\n");
974     if (is_array($headers) ) {
975         foreach ($headers as $key => $value) {
976             $headers[$key] = str_replace($newlines, '', $value);
977         }
978     }
979     $url = str_replace($newlines, '', $url);
980     if (!preg_match('|^https?://|i', $url)) {
981         if ($fullresponse) {
982             $response = new stdClass();
983             $response->status        = 0;
984             $response->headers       = array();
985             $response->response_code = 'Invalid protocol specified in url';
986             $response->results       = '';
987             $response->error         = 'Invalid protocol specified in url';
988             return $response;
989         } else {
990             return false;
991         }
992     }
994     // check if proxy (if used) should be bypassed for this url
995     $proxybypass = is_proxybypass($url);
997     if (!$ch = curl_init($url)) {
998         debugging('Can not init curl.');
999         return false;
1000     }
1002     // set extra headers
1003     if (is_array($headers) ) {
1004         $headers2 = array();
1005         foreach ($headers as $key => $value) {
1006             $headers2[] = "$key: $value";
1007         }
1008         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1009     }
1011     if ($skipcertverify) {
1012         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1013     }
1015     // use POST if requested
1016     if (is_array($postdata)) {
1017         $postdata = format_postdata_for_curlcall($postdata);
1018         curl_setopt($ch, CURLOPT_POST, true);
1019         curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1020     }
1022     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1023     curl_setopt($ch, CURLOPT_HEADER, false);
1024     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1026     if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1027         // TODO: add version test for '7.10.5'
1028         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1029         curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1030     }
1032     if (!empty($CFG->proxyhost) and !$proxybypass) {
1033         // SOCKS supported in PHP5 only
1034         if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1035             if (defined('CURLPROXY_SOCKS5')) {
1036                 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1037             } else {
1038                 curl_close($ch);
1039                 if ($fullresponse) {
1040                     $response = new stdClass();
1041                     $response->status        = '0';
1042                     $response->headers       = array();
1043                     $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1044                     $response->results       = '';
1045                     $response->error         = 'SOCKS5 proxy is not supported in PHP4';
1046                     return $response;
1047                 } else {
1048                     debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1049                     return false;
1050                 }
1051             }
1052         }
1054         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1056         if (empty($CFG->proxyport)) {
1057             curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1058         } else {
1059             curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1060         }
1062         if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1063             curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1064             if (defined('CURLOPT_PROXYAUTH')) {
1065                 // any proxy authentication if PHP 5.1
1066                 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1067             }
1068         }
1069     }
1071     // set up header and content handlers
1072     $received = new stdClass();
1073     $received->headers = array(); // received headers array
1074     $received->tofile  = $tofile;
1075     $received->fh      = null;
1076     curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1077     if ($tofile) {
1078         curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1079     }
1081     if (!isset($CFG->curltimeoutkbitrate)) {
1082         //use very slow rate of 56kbps as a timeout speed when not set
1083         $bitrate = 56;
1084     } else {
1085         $bitrate = $CFG->curltimeoutkbitrate;
1086     }
1088     // try to calculate the proper amount for timeout from remote file size.
1089     // if disabled or zero, we won't do any checks nor head requests.
1090     if ($calctimeout && $bitrate > 0) {
1091         //setup header request only options
1092         curl_setopt_array ($ch, array(
1093             CURLOPT_RETURNTRANSFER => false,
1094             CURLOPT_NOBODY         => true)
1095         );
1097         curl_exec($ch);
1098         $info = curl_getinfo($ch);
1099         $err = curl_error($ch);
1101         if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1102             $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1103         }
1104         //reinstate affected curl options
1105         curl_setopt_array ($ch, array(
1106             CURLOPT_RETURNTRANSFER => true,
1107             CURLOPT_NOBODY         => false)
1108         );
1109     }
1111     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1112     $result = curl_exec($ch);
1114     // try to detect encoding problems
1115     if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1116         curl_setopt($ch, CURLOPT_ENCODING, 'none');
1117         $result = curl_exec($ch);
1118     }
1120     if ($received->fh) {
1121         fclose($received->fh);
1122     }
1124     if (curl_errno($ch)) {
1125         $error    = curl_error($ch);
1126         $error_no = curl_errno($ch);
1127         curl_close($ch);
1129         if ($fullresponse) {
1130             $response = new stdClass();
1131             if ($error_no == 28) {
1132                 $response->status    = '-100'; // mimic snoopy
1133             } else {
1134                 $response->status    = '0';
1135             }
1136             $response->headers       = array();
1137             $response->response_code = $error;
1138             $response->results       = false;
1139             $response->error         = $error;
1140             return $response;
1141         } else {
1142             debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1143             return false;
1144         }
1146     } else {
1147         $info = curl_getinfo($ch);
1148         curl_close($ch);
1150         if (empty($info['http_code'])) {
1151             // for security reasons we support only true http connections (Location: file:// exploit prevention)
1152             $response = new stdClass();
1153             $response->status        = '0';
1154             $response->headers       = array();
1155             $response->response_code = 'Unknown cURL error';
1156             $response->results       = false; // do NOT change this, we really want to ignore the result!
1157             $response->error         = 'Unknown cURL error';
1159         } else {
1160             $response = new stdClass();;
1161             $response->status        = (string)$info['http_code'];
1162             $response->headers       = $received->headers;
1163             $response->response_code = $received->headers[0];
1164             $response->results       = $result;
1165             $response->error         = '';
1166         }
1168         if ($fullresponse) {
1169             return $response;
1170         } else if ($info['http_code'] != 200) {
1171             debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1172             return false;
1173         } else {
1174             return $response->results;
1175         }
1176     }
1179 /**
1180  * internal implementation
1181  * @param stdClass $received
1182  * @param resource $ch
1183  * @param mixed $header
1184  * @return int header length
1185  */
1186 function download_file_content_header_handler($received, $ch, $header) {
1187     $received->headers[] = $header;
1188     return strlen($header);
1191 /**
1192  * internal implementation
1193  * @param stdClass $received
1194  * @param resource $ch
1195  * @param mixed $data
1196  */
1197 function download_file_content_write_handler($received, $ch, $data) {
1198     if (!$received->fh) {
1199         $received->fh = fopen($received->tofile, 'w');
1200         if ($received->fh === false) {
1201             // bad luck, file creation or overriding failed
1202             return 0;
1203         }
1204     }
1205     if (fwrite($received->fh, $data) === false) {
1206         // bad luck, write failed, let's abort completely
1207         return 0;
1208     }
1209     return strlen($data);
1212 /**
1213  * Returns a list of information about file t ypes based on extensions
1214  *
1215  * @category files
1216  * @return array List of information about file types based on extensions.
1217  *   Associative array of extension (lower-case) to associative array
1218  *   from 'element name' to data. Current element names are 'type' and 'icon'.
1219  *   Unknown types should use the 'xxx' entry which includes defaults.
1220  */
1221 function get_mimetypes_array() {
1222     static $mimearray = array (
1223         'xxx'  => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1224         '3gp'  => array ('type'=>'video/quicktime', 'icon'=>'video'),
1225         'aac'  => array ('type'=>'audio/aac', 'icon'=>'audio'),
1226         'ai'   => array ('type'=>'application/postscript', 'icon'=>'image'),
1227         'aif'  => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1228         'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1229         'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1230         'applescript'  => array ('type'=>'text/plain', 'icon'=>'text'),
1231         'asc'  => array ('type'=>'text/plain', 'icon'=>'text'),
1232         'asm'  => array ('type'=>'text/plain', 'icon'=>'text'),
1233         'au'   => array ('type'=>'audio/au', 'icon'=>'audio'),
1234         'avi'  => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1235         'bmp'  => array ('type'=>'image/bmp', 'icon'=>'image'),
1236         'c'    => array ('type'=>'text/plain', 'icon'=>'text'),
1237         'cct'  => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1238         'cpp'  => array ('type'=>'text/plain', 'icon'=>'text'),
1239         'cs'   => array ('type'=>'application/x-csh', 'icon'=>'text'),
1240         'css'  => array ('type'=>'text/css', 'icon'=>'text'),
1241         'csv'  => array ('type'=>'text/csv', 'icon'=>'excel'),
1242         'dv'   => array ('type'=>'video/x-dv', 'icon'=>'video'),
1243         'dmg'  => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1245         'doc'  => array ('type'=>'application/msword', 'icon'=>'word'),
1246         'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1247         'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1248         'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1249         'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1251         'dcr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1252         'dif'  => array ('type'=>'video/x-dv', 'icon'=>'video'),
1253         'dir'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1254         'dxr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1255         'eps'  => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1256         'fdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1257         'flv'  => array ('type'=>'video/x-flv', 'icon'=>'video'),
1258         'f4v'  => array ('type'=>'video/mp4', 'icon'=>'video'),
1259         'gif'  => array ('type'=>'image/gif', 'icon'=>'image'),
1260         'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1261         'tgz'  => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1262         'gz'   => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1263         'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1264         'h'    => array ('type'=>'text/plain', 'icon'=>'text'),
1265         'hpp'  => array ('type'=>'text/plain', 'icon'=>'text'),
1266         'hqx'  => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1267         'htc'  => array ('type'=>'text/x-component', 'icon'=>'text'),
1268         'html' => array ('type'=>'text/html', 'icon'=>'html'),
1269         'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1270         'htm'  => array ('type'=>'text/html', 'icon'=>'html'),
1271         'ico'  => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1272         'ics'  => array ('type'=>'text/calendar', 'icon'=>'text'),
1273         'isf'  => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1274         'ist'  => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1275         'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1276         'jcb'  => array ('type'=>'text/xml', 'icon'=>'jcb'),
1277         'jcl'  => array ('type'=>'text/xml', 'icon'=>'jcl'),
1278         'jcw'  => array ('type'=>'text/xml', 'icon'=>'jcw'),
1279         'jmt'  => array ('type'=>'text/xml', 'icon'=>'jmt'),
1280         'jmx'  => array ('type'=>'text/xml', 'icon'=>'jmx'),
1281         'jpe'  => array ('type'=>'image/jpeg', 'icon'=>'image'),
1282         'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1283         'jpg'  => array ('type'=>'image/jpeg', 'icon'=>'image'),
1284         'jqz'  => array ('type'=>'text/xml', 'icon'=>'jqz'),
1285         'js'   => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1286         'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1287         'm'    => array ('type'=>'text/plain', 'icon'=>'text'),
1288         'mbz'  => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1289         'mov'  => array ('type'=>'video/quicktime', 'icon'=>'video'),
1290         'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1291         'm3u'  => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1292         'mp3'  => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1293         'mp4'  => array ('type'=>'video/mp4', 'icon'=>'video'),
1294         'm4v'  => array ('type'=>'video/mp4', 'icon'=>'video'),
1295         'm4a'  => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1296         'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1297         'mpe'  => array ('type'=>'video/mpeg', 'icon'=>'video'),
1298         'mpg'  => array ('type'=>'video/mpeg', 'icon'=>'video'),
1300         'odt'  => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1301         'ott'  => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1302         'oth'  => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1303         'odm'  => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1304         'odg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1305         'otg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1306         'odp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1307         'otp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1308         'ods'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1309         'ots'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1310         'odc'  => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1311         'odf'  => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1312         'odb'  => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1313         'odi'  => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1314         'oga'  => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1315         'ogg'  => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1316         'ogv'  => array ('type'=>'video/ogg', 'icon'=>'video'),
1318         'pct'  => array ('type'=>'image/pict', 'icon'=>'image'),
1319         'pdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1320         'php'  => array ('type'=>'text/plain', 'icon'=>'text'),
1321         'pic'  => array ('type'=>'image/pict', 'icon'=>'image'),
1322         'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1323         'png'  => array ('type'=>'image/png', 'icon'=>'image'),
1325         'pps'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1326         'ppt'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1327         'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1328         'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1329         'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1330         'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1331         'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1332         'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1333         'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1335         'ps'   => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1336         'qt'   => array ('type'=>'video/quicktime', 'icon'=>'video'),
1337         'ra'   => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1338         'ram'  => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1339         'rhb'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1340         'rm'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1341         'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
1342         'rtf'  => array ('type'=>'text/rtf', 'icon'=>'text'),
1343         'rtx'  => array ('type'=>'text/richtext', 'icon'=>'text'),
1344         'rv'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
1345         'sh'   => array ('type'=>'application/x-sh', 'icon'=>'text'),
1346         'sit'  => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1347         'smi'  => array ('type'=>'application/smil', 'icon'=>'text'),
1348         'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1349         'sqt'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1350         'svg'  => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1351         'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1352         'swa'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1353         'swf'  => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1354         'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1356         'sxw'  => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1357         'stw'  => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1358         'sxc'  => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1359         'stc'  => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1360         'sxd'  => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1361         'std'  => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1362         'sxi'  => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1363         'sti'  => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1364         'sxg'  => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1365         'sxm'  => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1367         'tar'  => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1368         'tif'  => array ('type'=>'image/tiff', 'icon'=>'image'),
1369         'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1370         'tex'  => array ('type'=>'application/x-tex', 'icon'=>'text'),
1371         'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1372         'texinfo'  => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1373         'tsv'  => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1374         'txt'  => array ('type'=>'text/plain', 'icon'=>'text'),
1375         'wav'  => array ('type'=>'audio/wav', 'icon'=>'audio'),
1376         'webm'  => array ('type'=>'video/webm', 'icon'=>'video'),
1377         'wmv'  => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1378         'asf'  => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1379         'xdp'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1380         'xfd'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1381         'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1383         'xls'  => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1384         'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1385         'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1386         'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1387         'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1388         'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1389         'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1391         'xml'  => array ('type'=>'application/xml', 'icon'=>'xml'),
1392         'xsl'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1393         'zip'  => array ('type'=>'application/zip', 'icon'=>'zip')
1394     );
1395     return $mimearray;
1398 /**
1399  * Obtains information about a filetype based on its extension. Will
1400  * use a default if no information is present about that particular
1401  * extension.
1402  *
1403  * @category files
1404  * @param string $element Desired information (usually 'icon'
1405  *   for icon filename or 'type' for MIME type)
1406  * @param string $filename Filename we're looking up
1407  * @return string Requested piece of information from array
1408  */
1409 function mimeinfo($element, $filename) {
1410     global $CFG;
1411     $mimeinfo = get_mimetypes_array();
1413     if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1414         if (isset($mimeinfo[strtolower($match[1])][$element])) {
1415             return $mimeinfo[strtolower($match[1])][$element];
1416         } else {
1417             if ($element == 'icon32') {
1418                 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1419                     $filename = $mimeinfo[strtolower($match[1])]['icon'];
1420                 } else {
1421                     $filename = 'unknown';
1422                 }
1423                 $filename .= '-32';
1424                 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1425                     return $filename;
1426                 } else {
1427                     return 'unknown-32';
1428                 }
1429             } else {
1430                 return $mimeinfo['xxx'][$element];   // By default
1431             }
1432         }
1433     } else {
1434         if ($element == 'icon32') {
1435             return 'unknown-32';
1436         }
1437         return $mimeinfo['xxx'][$element];   // By default
1438     }
1441 /**
1442  * Obtains information about a filetype based on the MIME type rather than
1443  * the other way around.
1444  *
1445  * @category files
1446  * @param string $element Desired information (usually 'icon')
1447  * @param string $mimetype MIME type we're looking up
1448  * @return string Requested piece of information from array
1449  */
1450 function mimeinfo_from_type($element, $mimetype) {
1451     $mimeinfo = get_mimetypes_array();
1453     foreach($mimeinfo as $values) {
1454         if ($values['type']==$mimetype) {
1455             if (isset($values[$element])) {
1456                 return $values[$element];
1457             }
1458             break;
1459         }
1460     }
1461     return $mimeinfo['xxx'][$element]; // Default
1464 /**
1465  * Get information about a filetype based on the icon file.
1466  *
1467  * @category files
1468  * @param string $element Desired information (usually 'icon')
1469  * @param string $icon Icon file name without extension
1470  * @param bool $all return all matching entries (defaults to false - best (by ext)/last match)
1471  * @return string Requested piece of information from array
1472  */
1473 function mimeinfo_from_icon($element, $icon, $all=false) {
1474     $mimeinfo = get_mimetypes_array();
1476     if (preg_match("/\/(.*)/", $icon, $matches)) {
1477         $icon = $matches[1];
1478     }
1479     // Try to get the extension
1480     $extension = '';
1481     if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1482         $extension = substr($icon, $cutat + 1);
1483     }
1484     $info = array($mimeinfo['xxx'][$element]); // Default
1485     foreach($mimeinfo as $key => $values) {
1486         if ($values['icon']==$icon) {
1487             if (isset($values[$element])) {
1488                 $info[$key] = $values[$element];
1489             }
1490             //No break, for example for 'excel' we don't want 'csv'!
1491         }
1492     }
1493     if ($all) {
1494         if (count($info) > 1) {
1495             array_shift($info); // take off document/unknown if we have better options
1496         }
1497         return array_values($info); // Keep keys out when requesting all
1498     }
1500     // Requested only one, try to get the best by extension coincidence, else return the last
1501     if ($extension && isset($info[$extension])) {
1502         return $info[$extension];
1503     }
1505     return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1508 /**
1509  * Returns the relative icon path for a given mime type
1510  *
1511  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1512  * a return the full path to an icon.
1513  *
1514  * <code>
1515  * $mimetype = 'image/jpg';
1516  * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1517  * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1518  * </code>
1519  *
1520  * @category files
1521  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1522  * to conform with that.
1523  * @param string $mimetype The mimetype to fetch an icon for
1524  * @param int $size The size of the icon. Not yet implemented
1525  * @return string The relative path to the icon
1526  */
1527 function file_mimetype_icon($mimetype, $size = NULL) {
1528     global $CFG;
1530     $icon = mimeinfo_from_type('icon', $mimetype);
1531     if ($size) {
1532         if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1533             $icon = "$icon-$size";
1534         }
1535     }
1536     return 'f/'.$icon;
1539 /**
1540  * Returns the relative icon path for a given file name
1541  *
1542  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1543  * a return the full path to an icon.
1544  *
1545  * <code>
1546  * $filename = 'jpg';
1547  * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1548  * echo '<img src="'.$icon.'" alt="blah" />';
1549  * </code>
1550  *
1551  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1552  * to conform with that.
1553  * @todo MDL-31074 Implement $size
1554  * @category files
1555  * @param string $filename The filename to get the icon for
1556  * @param int $size The size of the icon. Defaults to null can also be 32
1557  * @return string
1558  */
1559 function file_extension_icon($filename, $size = NULL) {
1560     global $CFG;
1562     $icon = mimeinfo('icon', $filename);
1563     if ($size) {
1564         if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1565             $icon = "$icon-$size";
1566         }
1567     }
1568     return 'f/'.$icon;
1571 /**
1572  * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1573  * mimetypes.php language file.
1574  *
1575  * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1576  * @param bool $capitalise If true, capitalises first character of result
1577  * @return string Text description
1578  */
1579 function get_mimetype_description($mimetype, $capitalise=false) {
1580     if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1581         $result = get_string($mimetype, 'mimetypes');
1582     } else {
1583         $result = get_string('document/unknown','mimetypes');
1584     }
1585     if ($capitalise) {
1586         $result=ucfirst($result);
1587     }
1588     return $result;
1591 /**
1592  * Requested file is not found or not accessible, does not return, terminates script
1593  *
1594  * @global stdClass $CFG
1595  * @global stdClass $COURSE
1596  */
1597 function send_file_not_found() {
1598     global $CFG, $COURSE;
1599     send_header_404();
1600     print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1602 /**
1603  * Helper function to send correct 404 for server.
1604  */
1605 function send_header_404() {
1606     if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1607         header("Status: 404 Not Found");
1608     } else {
1609         header('HTTP/1.0 404 not found');
1610     }
1613 /**
1614  * Check output buffering settings before sending file.
1615  * Please note you should not send any other headers after calling this function.
1616  *
1617  * To be called only from lib/filelib.php !
1618  */
1619 function prepare_file_content_sending() {
1620     // We needed to be able to send headers up until now
1621     if (headers_sent()) {
1622         throw new file_serving_exception('Headers already sent, can not serve file.');
1623     }
1625     $olddebug = error_reporting(0);
1627     // IE compatibility HACK - it does not like zlib compression much
1628     // there is also a problem with the length header in older PHP versions
1629     if (ini_get_bool('zlib.output_compression')) {
1630         ini_set('zlib.output_compression', 'Off');
1631     }
1633     // flush and close all buffers if possible
1634     while(ob_get_level()) {
1635         if (!ob_end_flush()) {
1636             // prevent infinite loop when buffer can not be closed
1637             break;
1638         }
1639     }
1641     error_reporting($olddebug);
1643     //NOTE: we can not reliable test headers_sent() here because
1644     //      the headers might be sent which trying to close the buffers,
1645     //      this happens especially if browser does not support gzip or deflate
1648 /**
1649  * Handles the sending of temporary file to user, download is forced.
1650  * File is deleted after abort or successful sending, does not return, script terminated
1651  *
1652  * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1653  * @param string $filename proposed file name when saving file
1654  * @param bool $pathisstring If the path is string
1655  */
1656 function send_temp_file($path, $filename, $pathisstring=false) {
1657     global $CFG;
1659     // close session - not needed anymore
1660     @session_get_instance()->write_close();
1662     if (!$pathisstring) {
1663         if (!file_exists($path)) {
1664             send_header_404();
1665             print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1666         }
1667         // executed after normal finish or abort
1668         @register_shutdown_function('send_temp_file_finished', $path);
1669     }
1671     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1672     if (check_browser_version('MSIE')) {
1673         $filename = urlencode($filename);
1674     }
1676     $filesize = $pathisstring ? strlen($path) : filesize($path);
1678     header('Content-Disposition: attachment; filename='.$filename);
1679     header('Content-Length: '.$filesize);
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');
1688     }
1689     header('Accept-Ranges: none'); // Do not allow byteserving
1691     //flush the buffers - save memory and disable sid rewrite
1692     // this also disables zlib compression
1693     prepare_file_content_sending();
1695     // send the contents
1696     if ($pathisstring) {
1697         echo $path;
1698     } else {
1699         @readfile($path);
1700     }
1702     die; //no more chars to output
1705 /**
1706  * Internal callback function used by send_temp_file()
1707  *
1708  * @param string $path
1709  */
1710 function send_temp_file_finished($path) {
1711     if (file_exists($path)) {
1712         @unlink($path);
1713     }
1716 /**
1717  * Handles the sending of file data to the user's browser, including support for
1718  * byteranges etc.
1719  *
1720  * @category files
1721  * @global stdClass $CFG
1722  * @global stdClass $COURSE
1723  * @global moodle_session $SESSION
1724  * @param string $path Path of file on disk (including real filename), or actual content of file as string
1725  * @param string $filename Filename to send
1726  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1727  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1728  * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1729  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1730  * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1731  * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1732  *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
1733  *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
1734  *                        and should not be reopened.
1735  * @return null script execution stopped unless $dontdie is true
1736  */
1737 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1738     global $CFG, $COURSE, $SESSION;
1740     if ($dontdie) {
1741         ignore_user_abort(true);
1742     }
1744     // MDL-11789, apply $CFG->filelifetime here
1745     if ($lifetime === 'default') {
1746         if (!empty($CFG->filelifetime)) {
1747             $lifetime = $CFG->filelifetime;
1748         } else {
1749             $lifetime = 86400;
1750         }
1751     }
1753     session_get_instance()->write_close(); // unlock session during fileserving
1755     // Use given MIME type if specified, otherwise guess it using mimeinfo.
1756     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1757     // only Firefox saves all files locally before opening when content-disposition: attachment stated
1758     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1759     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1760                          ($mimetype ? $mimetype : mimeinfo('type', $filename));
1762     $lastmodified = $pathisstring ? time() : filemtime($path);
1763     $filesize     = $pathisstring ? strlen($path) : filesize($path);
1765 /* - MDL-13949
1766     //Adobe Acrobat Reader XSS prevention
1767     if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1768         //please note that it prevents opening of pdfs in browser when http referer disabled
1769         //or file linked from another site; browser caching of pdfs is now disabled too
1770         if (!empty($_SERVER['HTTP_RANGE'])) {
1771             //already byteserving
1772             $lifetime = 1; // >0 needed for byteserving
1773         } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1774             $mimetype = 'application/x-forcedownload';
1775             $forcedownload = true;
1776             $lifetime = 0;
1777         } else {
1778             $lifetime = 1; // >0 needed for byteserving
1779         }
1780     }
1781 */
1783     if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1784         // get unixtime of request header; clip extra junk off first
1785         $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1786         if ($since && $since >= $lastmodified) {
1787             header('HTTP/1.1 304 Not Modified');
1788             header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1789             header('Cache-Control: max-age='.$lifetime);
1790             header('Content-Type: '.$mimetype);
1791             if ($dontdie) {
1792                 return;
1793             }
1794             die;
1795         }
1796     }
1798     //do not put '@' before the next header to detect incorrect moodle configurations,
1799     //error should be better than "weird" empty lines for admins/users
1800     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1802     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1803     if (check_browser_version('MSIE')) {
1804         $filename = rawurlencode($filename);
1805     }
1807     if ($forcedownload) {
1808         header('Content-Disposition: attachment; filename="'.$filename.'"');
1809     } else {
1810         header('Content-Disposition: inline; filename="'.$filename.'"');
1811     }
1813     if ($lifetime > 0) {
1814         header('Cache-Control: max-age='.$lifetime);
1815         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1816         header('Pragma: ');
1818         if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1820             header('Accept-Ranges: bytes');
1822             if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1823                 // byteserving stuff - for acrobat reader and download accelerators
1824                 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1825                 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1826                 $ranges = false;
1827                 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1828                     foreach ($ranges as $key=>$value) {
1829                         if ($ranges[$key][1] == '') {
1830                             //suffix case
1831                             $ranges[$key][1] = $filesize - $ranges[$key][2];
1832                             $ranges[$key][2] = $filesize - 1;
1833                         } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1834                             //fix range length
1835                             $ranges[$key][2] = $filesize - 1;
1836                         }
1837                         if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1838                             //invalid byte-range ==> ignore header
1839                             $ranges = false;
1840                             break;
1841                         }
1842                         //prepare multipart header
1843                         $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1844                         $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1845                     }
1846                 } else {
1847                     $ranges = false;
1848                 }
1849                 if ($ranges) {
1850                     $handle = fopen($path, 'rb');
1851                     byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1852                 }
1853             }
1854         } else {
1855             /// Do not byteserve (disabled, strings, text and html files).
1856             header('Accept-Ranges: none');
1857         }
1858     } else { // Do not cache files in proxies and browsers
1859         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1860             header('Cache-Control: max-age=10');
1861             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1862             header('Pragma: ');
1863         } else { //normal http - prevent caching at all cost
1864             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1865             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1866             header('Pragma: no-cache');
1867         }
1868         header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1869     }
1871     if (empty($filter)) {
1872         if ($mimetype == 'text/plain') {
1873             header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1874         } else {
1875             header('Content-Type: '.$mimetype);
1876         }
1877         header('Content-Length: '.$filesize);
1879         //flush the buffers - save memory and disable sid rewrite
1880         //this also disables zlib compression
1881         prepare_file_content_sending();
1883         // send the contents
1884         if ($pathisstring) {
1885             echo $path;
1886         } else {
1887             @readfile($path);
1888         }
1890     } else {     // Try to put the file through filters
1891         if ($mimetype == 'text/html') {
1892             $options = new stdClass();
1893             $options->noclean = true;
1894             $options->nocache = true; // temporary workaround for MDL-5136
1895             $text = $pathisstring ? $path : implode('', file($path));
1897             $text = file_modify_html_header($text);
1898             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1900             header('Content-Length: '.strlen($output));
1901             header('Content-Type: text/html');
1903             //flush the buffers - save memory and disable sid rewrite
1904             //this also disables zlib compression
1905             prepare_file_content_sending();
1907             // send the contents
1908             echo $output;
1909         // only filter text if filter all files is selected
1910         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1911             $options = new stdClass();
1912             $options->newlines = false;
1913             $options->noclean = true;
1914             $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1915             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1917             header('Content-Length: '.strlen($output));
1918             header('Content-Type: text/html; charset=utf-8'); //add encoding
1920             //flush the buffers - save memory and disable sid rewrite
1921             //this also disables zlib compression
1922             prepare_file_content_sending();
1924             // send the contents
1925             echo $output;
1927         } else {    // Just send it out raw
1928             header('Content-Length: '.$filesize);
1929             header('Content-Type: '.$mimetype);
1931             //flush the buffers - save memory and disable sid rewrite
1932             //this also disables zlib compression
1933             prepare_file_content_sending();
1935             // send the contents
1936             if ($pathisstring) {
1937                 echo $path;
1938             }else {
1939                 @readfile($path);
1940             }
1941         }
1942     }
1943     if ($dontdie) {
1944         return;
1945     }
1946     die; //no more chars to output!!!
1949 /**
1950  * Handles the sending of file data to the user's browser, including support for
1951  * byteranges etc.
1952  *
1953  * @category files
1954  * @global stdClass $CFG
1955  * @global stdClass $COURSE
1956  * @global moodle_session $SESSION
1957  * @param stored_file $stored_file local file object
1958  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1959  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1960  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1961  * @param string $filename Override filename
1962  * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1963  *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
1964  *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
1965  *                        and should not be reopened.
1966  * @return null script execution stopped unless $dontdie is true
1967  */
1968 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1969     global $CFG, $COURSE, $SESSION;
1971     if (!$stored_file or $stored_file->is_directory()) {
1972         // nothing to serve
1973         if ($dontdie) {
1974             return;
1975         }
1976         die;
1977     }
1979     if ($dontdie) {
1980         ignore_user_abort(true);
1981     }
1983     session_get_instance()->write_close(); // unlock session during fileserving
1985     // Use given MIME type if specified, otherwise guess it using mimeinfo.
1986     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1987     // only Firefox saves all files locally before opening when content-disposition: attachment stated
1988     $filename     = is_null($filename) ? $stored_file->get_filename() : $filename;
1989     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1990     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1991                          ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1993     $lastmodified = $stored_file->get_timemodified();
1994     $filesize     = $stored_file->get_filesize();
1996     if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1997         // get unixtime of request header; clip extra junk off first
1998         $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1999         if ($since && $since >= $lastmodified) {
2000             header('HTTP/1.1 304 Not Modified');
2001             header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2002             header('Cache-Control: max-age='.$lifetime);
2003             header('Content-Type: '.$mimetype);
2004             if ($dontdie) {
2005                 return;
2006             }
2007             die;
2008         }
2009     }
2011     //do not put '@' before the next header to detect incorrect moodle configurations,
2012     //error should be better than "weird" empty lines for admins/users
2013     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2015     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2016     if (check_browser_version('MSIE')) {
2017         $filename = rawurlencode($filename);
2018     }
2020     if ($forcedownload) {
2021         header('Content-Disposition: attachment; filename="'.$filename.'"');
2022     } else {
2023         header('Content-Disposition: inline; filename="'.$filename.'"');
2024     }
2026     if ($lifetime > 0) {
2027         header('Cache-Control: max-age='.$lifetime);
2028         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2029         header('Pragma: ');
2031         if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
2033             header('Accept-Ranges: bytes');
2035             if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2036                 // byteserving stuff - for acrobat reader and download accelerators
2037                 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2038                 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2039                 $ranges = false;
2040                 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2041                     foreach ($ranges as $key=>$value) {
2042                         if ($ranges[$key][1] == '') {
2043                             //suffix case
2044                             $ranges[$key][1] = $filesize - $ranges[$key][2];
2045                             $ranges[$key][2] = $filesize - 1;
2046                         } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2047                             //fix range length
2048                             $ranges[$key][2] = $filesize - 1;
2049                         }
2050                         if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2051                             //invalid byte-range ==> ignore header
2052                             $ranges = false;
2053                             break;
2054                         }
2055                         //prepare multipart header
2056                         $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2057                         $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2058                     }
2059                 } else {
2060                     $ranges = false;
2061                 }
2062                 if ($ranges) {
2063                     byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
2064                 }
2065             }
2066         } else {
2067             /// Do not byteserve (disabled, strings, text and html files).
2068             header('Accept-Ranges: none');
2069         }
2070     } else { // Do not cache files in proxies and browsers
2071         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2072             header('Cache-Control: max-age=10');
2073             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2074             header('Pragma: ');
2075         } else { //normal http - prevent caching at all cost
2076             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2077             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2078             header('Pragma: no-cache');
2079         }
2080         header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
2081     }
2083     if (empty($filter)) {
2084         if ($mimetype == 'text/plain') {
2085             header('Content-Type: Text/plain; charset=utf-8'); //add encoding
2086         } else {
2087             header('Content-Type: '.$mimetype);
2088         }
2089         header('Content-Length: '.$filesize);
2091         //flush the buffers - save memory and disable sid rewrite
2092         //this also disables zlib compression
2093         prepare_file_content_sending();
2095         // send the contents
2096         $stored_file->readfile();
2098     } else {     // Try to put the file through filters
2099         if ($mimetype == 'text/html') {
2100             $options = new stdClass();
2101             $options->noclean = true;
2102             $options->nocache = true; // temporary workaround for MDL-5136
2103             $text = $stored_file->get_content();
2104             $text = file_modify_html_header($text);
2105             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2107             header('Content-Length: '.strlen($output));
2108             header('Content-Type: text/html');
2110             //flush the buffers - save memory and disable sid rewrite
2111             //this also disables zlib compression
2112             prepare_file_content_sending();
2114             // send the contents
2115             echo $output;
2117         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2118             // only filter text if filter all files is selected
2119             $options = new stdClass();
2120             $options->newlines = false;
2121             $options->noclean = true;
2122             $text = $stored_file->get_content();
2123             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2125             header('Content-Length: '.strlen($output));
2126             header('Content-Type: text/html; charset=utf-8'); //add encoding
2128             //flush the buffers - save memory and disable sid rewrite
2129             //this also disables zlib compression
2130             prepare_file_content_sending();
2132             // send the contents
2133             echo $output;
2135         } else {    // Just send it out raw
2136             header('Content-Length: '.$filesize);
2137             header('Content-Type: '.$mimetype);
2139             //flush the buffers - save memory and disable sid rewrite
2140             //this also disables zlib compression
2141             prepare_file_content_sending();
2143             // send the contents
2144             $stored_file->readfile();
2145         }
2146     }
2147     if ($dontdie) {
2148         return;
2149     }
2150     die; //no more chars to output!!!
2153 /**
2154  * Retrieves an array of records from a CSV file and places
2155  * them into a given table structure
2156  *
2157  * @global stdClass $CFG
2158  * @global moodle_database $DB
2159  * @param string $file The path to a CSV file
2160  * @param string $table The table to retrieve columns from
2161  * @return bool|array Returns an array of CSV records or false
2162  */
2163 function get_records_csv($file, $table) {
2164     global $CFG, $DB;
2166     if (!$metacolumns = $DB->get_columns($table)) {
2167         return false;
2168     }
2170     if(!($handle = @fopen($file, 'r'))) {
2171         print_error('get_records_csv failed to open '.$file);
2172     }
2174     $fieldnames = fgetcsv($handle, 4096);
2175     if(empty($fieldnames)) {
2176         fclose($handle);
2177         return false;
2178     }
2180     $columns = array();
2182     foreach($metacolumns as $metacolumn) {
2183         $ord = array_search($metacolumn->name, $fieldnames);
2184         if(is_int($ord)) {
2185             $columns[$metacolumn->name] = $ord;
2186         }
2187     }
2189     $rows = array();
2191     while (($data = fgetcsv($handle, 4096)) !== false) {
2192         $item = new stdClass;
2193         foreach($columns as $name => $ord) {
2194             $item->$name = $data[$ord];
2195         }
2196         $rows[] = $item;
2197     }
2199     fclose($handle);
2200     return $rows;
2203 /**
2204  * Create a file with CSV contents
2205  *
2206  * @global stdClass $CFG
2207  * @global moodle_database $DB
2208  * @param string $file The file to put the CSV content into
2209  * @param array $records An array of records to write to a CSV file
2210  * @param string $table The table to get columns from
2211  * @return bool success
2212  */
2213 function put_records_csv($file, $records, $table = NULL) {
2214     global $CFG, $DB;
2216     if (empty($records)) {
2217         return true;
2218     }
2220     $metacolumns = NULL;
2221     if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2222         return false;
2223     }
2225     echo "x";
2227     if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2228         print_error('put_records_csv failed to open '.$file);
2229     }
2231     $proto = reset($records);
2232     if(is_object($proto)) {
2233         $fields_records = array_keys(get_object_vars($proto));
2234     }
2235     else if(is_array($proto)) {
2236         $fields_records = array_keys($proto);
2237     }
2238     else {
2239         return false;
2240     }
2241     echo "x";
2243     if(!empty($metacolumns)) {
2244         $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2245         $fields = array_intersect($fields_records, $fields_table);
2246     }
2247     else {
2248         $fields = $fields_records;
2249     }
2251     fwrite($fp, implode(',', $fields));
2252     fwrite($fp, "\r\n");
2254     foreach($records as $record) {
2255         $array  = (array)$record;
2256         $values = array();
2257         foreach($fields as $field) {
2258             if(strpos($array[$field], ',')) {
2259                 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2260             }
2261             else {
2262                 $values[] = $array[$field];
2263             }
2264         }
2265         fwrite($fp, implode(',', $values)."\r\n");
2266     }
2268     fclose($fp);
2269     return true;
2273 /**
2274  * Recursively delete the file or folder with path $location. That is,
2275  * if it is a file delete it. If it is a folder, delete all its content
2276  * then delete it. If $location does not exist to start, that is not
2277  * considered an error.
2278  *
2279  * @param string $location the path to remove.
2280  * @return bool
2281  */
2282 function fulldelete($location) {
2283     if (empty($location)) {
2284         // extra safety against wrong param
2285         return false;
2286     }
2287     if (is_dir($location)) {
2288         $currdir = opendir($location);
2289         while (false !== ($file = readdir($currdir))) {
2290             if ($file <> ".." && $file <> ".") {
2291                 $fullfile = $location."/".$file;
2292                 if (is_dir($fullfile)) {
2293                     if (!fulldelete($fullfile)) {
2294                         return false;
2295                     }
2296                 } else {
2297                     if (!unlink($fullfile)) {
2298                         return false;
2299                     }
2300                 }
2301             }
2302         }
2303         closedir($currdir);
2304         if (! rmdir($location)) {
2305             return false;
2306         }
2308     } else if (file_exists($location)) {
2309         if (!unlink($location)) {
2310             return false;
2311         }
2312     }
2313     return true;
2316 /**
2317  * Send requested byterange of file.
2318  *
2319  * @param resource $handle A file handle
2320  * @param string $mimetype The mimetype for the output
2321  * @param array $ranges An array of ranges to send
2322  * @param string $filesize The size of the content if only one range is used
2323  * @todo MDL-31088 check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2324  */
2325 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2326     $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2327     if ($handle === false) {
2328         die;
2329     }
2330     if (count($ranges) == 1) { //only one range requested
2331         $length = $ranges[0][2] - $ranges[0][1] + 1;
2332         header('HTTP/1.1 206 Partial content');
2333         header('Content-Length: '.$length);
2334         header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2335         header('Content-Type: '.$mimetype);
2337         //flush the buffers - save memory and disable sid rewrite
2338         //this also disables zlib compression
2339         prepare_file_content_sending();
2341         $buffer = '';
2342         fseek($handle, $ranges[0][1]);
2343         while (!feof($handle) && $length > 0) {
2344             @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2345             $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2346             echo $buffer;
2347             flush();
2348             $length -= strlen($buffer);
2349         }
2350         fclose($handle);
2351         die;
2352     } else { // multiple ranges requested - not tested much
2353         $totallength = 0;
2354         foreach($ranges as $range) {
2355             $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2356         }
2357         $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2358         header('HTTP/1.1 206 Partial content');
2359         header('Content-Length: '.$totallength);
2360         header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2361         //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2363         //flush the buffers - save memory and disable sid rewrite
2364         //this also disables zlib compression
2365         prepare_file_content_sending();
2367         foreach($ranges as $range) {
2368             $length = $range[2] - $range[1] + 1;
2369             echo $range[0];
2370             $buffer = '';
2371             fseek($handle, $range[1]);
2372             while (!feof($handle) && $length > 0) {
2373                 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2374                 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2375                 echo $buffer;
2376                 flush();
2377                 $length -= strlen($buffer);
2378             }
2379         }
2380         echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2381         fclose($handle);
2382         die;
2383     }
2386 /**
2387  * add includes (js and css) into uploaded files
2388  * before returning them, useful for themes and utf.js includes
2389  *
2390  * @global stdClass $CFG
2391  * @param string $text text to search and replace
2392  * @return string text with added head includes
2393  * @todo MDL-21120
2394  */
2395 function file_modify_html_header($text) {
2396     // first look for <head> tag
2397     global $CFG;
2399     $stylesheetshtml = '';
2400 /*    foreach ($CFG->stylesheets as $stylesheet) {
2401         //TODO: MDL-21120
2402         $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2403     }*/
2405     $ufo = '';
2406     if (filter_is_enabled('filter/mediaplugin')) {
2407         // this script is needed by most media filter plugins.
2408         $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2409         $ufo = html_writer::tag('script', '', $attributes) . "\n";
2410     }
2412     preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2413     if ($matches) {
2414         $replacement = '<head>'.$ufo.$stylesheetshtml;
2415         $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2416         return $text;
2417     }
2419     // if not, look for <html> tag, and stick <head> right after
2420     preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2421     if ($matches) {
2422         // replace <html> tag with <html><head>includes</head>
2423         $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2424         $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2425         return $text;
2426     }
2428     // if not, look for <body> tag, and stick <head> before body
2429     preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2430     if ($matches) {
2431         $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2432         $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2433         return $text;
2434     }
2436     // if not, just stick a <head> tag at the beginning
2437     $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2438     return $text;
2441 /**
2442  * RESTful cURL class
2443  *
2444  * This is a wrapper class for curl, it is quite easy to use:
2445  * <code>
2446  * $c = new curl;
2447  * // enable cache
2448  * $c = new curl(array('cache'=>true));
2449  * // enable cookie
2450  * $c = new curl(array('cookie'=>true));
2451  * // enable proxy
2452  * $c = new curl(array('proxy'=>true));
2453  *
2454  * // HTTP GET Method
2455  * $html = $c->get('http://example.com');
2456  * // HTTP POST Method
2457  * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2458  * // HTTP PUT Method
2459  * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2460  * </code>
2461  *
2462  * @package   core_files
2463  * @category files
2464  * @copyright Dongsheng Cai <dongsheng@moodle.com>
2465  * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
2466  */
2467 class curl {
2468     /** @var bool Caches http request contents */
2469     public  $cache    = false;
2470     /** @var bool Uses proxy */
2471     public  $proxy    = false;
2472     /** @var string library version */
2473     public  $version  = '0.4 dev';
2474     /** @var array http's response */
2475     public  $response = array();
2476     /** @var array http header */
2477     public  $header   = array();
2478     /** @var string cURL information */
2479     public  $info;
2480     /** @var string error */
2481     public  $error;
2483     /** @var array cURL options */
2484     private $options;
2485     /** @var string Proxy host */
2486     private $proxy_host = '';
2487     /** @var string Proxy auth */
2488     private $proxy_auth = '';
2489     /** @var string Proxy type */
2490     private $proxy_type = '';
2491     /** @var bool Debug mode on */
2492     private $debug    = false;
2493     /** @var bool|string Path to cookie file */
2494     private $cookie   = false;
2496     /**
2497      * Constructor
2498      *
2499      * @global stdClass $CFG
2500      * @param array $options
2501      */
2502     public function __construct($options = array()){
2503         global $CFG;
2504         if (!function_exists('curl_init')) {
2505             $this->error = 'cURL module must be enabled!';
2506             trigger_error($this->error, E_USER_ERROR);
2507             return false;
2508         }
2509         // the options of curl should be init here.
2510         $this->resetopt();
2511         if (!empty($options['debug'])) {
2512             $this->debug = true;
2513         }
2514         if(!empty($options['cookie'])) {
2515             if($options['cookie'] === true) {
2516                 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2517             } else {
2518                 $this->cookie = $options['cookie'];
2519             }
2520         }
2521         if (!empty($options['cache'])) {
2522             if (class_exists('curl_cache')) {
2523                 if (!empty($options['module_cache'])) {
2524                     $this->cache = new curl_cache($options['module_cache']);
2525                 } else {
2526                     $this->cache = new curl_cache('misc');
2527                 }
2528             }
2529         }
2530         if (!empty($CFG->proxyhost)) {
2531             if (empty($CFG->proxyport)) {
2532                 $this->proxy_host = $CFG->proxyhost;
2533             } else {
2534                 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2535             }
2536             if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2537                 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2538                 $this->setopt(array(
2539                             'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2540                             'proxyuserpwd'=>$this->proxy_auth));
2541             }
2542             if (!empty($CFG->proxytype)) {
2543                 if ($CFG->proxytype == 'SOCKS5') {
2544                     $this->proxy_type = CURLPROXY_SOCKS5;
2545                 } else {
2546                     $this->proxy_type = CURLPROXY_HTTP;
2547                     $this->setopt(array('httpproxytunnel'=>false));
2548                 }
2549                 $this->setopt(array('proxytype'=>$this->proxy_type));
2550             }
2551         }
2552         if (!empty($this->proxy_host)) {
2553             $this->proxy = array('proxy'=>$this->proxy_host);
2554         }
2555     }
2556     /**
2557      * Resets the CURL options that have already been set
2558      */
2559     public function resetopt(){
2560         $this->options = array();
2561         $this->options['CURLOPT_USERAGENT']         = 'MoodleBot/1.0';
2562         // True to include the header in the output
2563         $this->options['CURLOPT_HEADER']            = 0;
2564         // True to Exclude the body from the output
2565         $this->options['CURLOPT_NOBODY']            = 0;
2566         // TRUE to follow any "Location: " header that the server
2567         // sends as part of the HTTP header (note this is recursive,
2568         // PHP will follow as many "Location: " headers that it is sent,
2569         // unless CURLOPT_MAXREDIRS is set).
2570         //$this->options['CURLOPT_FOLLOWLOCATION']    = 1;
2571         $this->options['CURLOPT_MAXREDIRS']         = 10;
2572         $this->options['CURLOPT_ENCODING']          = '';
2573         // TRUE to return the transfer as a string of the return
2574         // value of curl_exec() instead of outputting it out directly.
2575         $this->options['CURLOPT_RETURNTRANSFER']    = 1;
2576         $this->options['CURLOPT_BINARYTRANSFER']    = 0;
2577         $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
2578         $this->options['CURLOPT_SSL_VERIFYHOST']    = 2;
2579         $this->options['CURLOPT_CONNECTTIMEOUT']    = 30;
2580     }
2582     /**
2583      * Reset Cookie
2584      */
2585     public function resetcookie() {
2586         if (!empty($this->cookie)) {
2587             if (is_file($this->cookie)) {
2588                 $fp = fopen($this->cookie, 'w');
2589                 if (!empty($fp)) {
2590                     fwrite($fp, '');
2591                     fclose($fp);
2592                 }
2593             }
2594         }
2595     }
2597     /**
2598      * Set curl options
2599      *
2600      * @param array $options If array is null, this function will
2601      * reset the options to default value.
2602      */
2603     public function setopt($options = array()) {
2604         if (is_array($options)) {
2605             foreach($options as $name => $val){
2606                 if (stripos($name, 'CURLOPT_') === false) {
2607                     $name = strtoupper('CURLOPT_'.$name);
2608                 }
2609                 $this->options[$name] = $val;
2610             }
2611         }
2612     }
2614     /**
2615      * Reset http method
2616      */
2617     public function cleanopt(){
2618         unset($this->options['CURLOPT_HTTPGET']);
2619         unset($this->options['CURLOPT_POST']);
2620         unset($this->options['CURLOPT_POSTFIELDS']);
2621         unset($this->options['CURLOPT_PUT']);
2622         unset($this->options['CURLOPT_INFILE']);
2623         unset($this->options['CURLOPT_INFILESIZE']);
2624         unset($this->options['CURLOPT_CUSTOMREQUEST']);
2625     }
2627     /**
2628      * Set HTTP Request Header
2629      *
2630      * @param array $header
2631      */
2632     public function setHeader($header) {
2633         if (is_array($header)){
2634             foreach ($header as $v) {
2635                 $this->setHeader($v);
2636             }
2637         } else {
2638             $this->header[] = $header;
2639         }
2640     }
2642     /**
2643      * Set HTTP Response Header
2644      *
2645      */
2646     public function getResponse(){
2647         return $this->response;
2648     }
2650     /**
2651      * private callback function
2652      * Formatting HTTP Response Header
2653      *
2654      * @param resource $ch Apparently not used
2655      * @param string $header
2656      * @return int The strlen of the header
2657      */
2658     private function formatHeader($ch, $header)
2659     {
2660         $this->count++;
2661         if (strlen($header) > 2) {
2662             list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2663             $key = rtrim($key, ':');
2664             if (!empty($this->response[$key])) {
2665                 if (is_array($this->response[$key])){
2666                     $this->response[$key][] = $value;
2667                 } else {
2668                     $tmp = $this->response[$key];
2669                     $this->response[$key] = array();
2670                     $this->response[$key][] = $tmp;
2671                     $this->response[$key][] = $value;
2673                 }
2674             } else {
2675                 $this->response[$key] = $value;
2676             }
2677         }
2678         return strlen($header);
2679     }
2681     /**
2682      * Set options for individual curl instance
2683      *
2684      * @param resource $curl A curl handle
2685      * @param array $options
2686      * @return resource The curl handle
2687      */
2688     private function apply_opt($curl, $options) {
2689         // Clean up
2690         $this->cleanopt();
2691         // set cookie
2692         if (!empty($this->cookie) || !empty($options['cookie'])) {
2693             $this->setopt(array('cookiejar'=>$this->cookie,
2694                             'cookiefile'=>$this->cookie
2695                              ));
2696         }
2698         // set proxy
2699         if (!empty($this->proxy) || !empty($options['proxy'])) {
2700             $this->setopt($this->proxy);
2701         }
2702         $this->setopt($options);
2703         // reset before set options
2704         curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2705         // set headers
2706         if (empty($this->header)){
2707             $this->setHeader(array(
2708                 'User-Agent: MoodleBot/1.0',
2709                 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2710                 'Connection: keep-alive'
2711                 ));
2712         }
2713         curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2715         if ($this->debug){
2716             echo '<h1>Options</h1>';
2717             var_dump($this->options);
2718             echo '<h1>Header</h1>';
2719             var_dump($this->header);
2720         }
2722         // set options
2723         foreach($this->options as $name => $val) {
2724             if (is_string($name)) {
2725                 $name = constant(strtoupper($name));
2726             }
2727             curl_setopt($curl, $name, $val);
2728         }
2729         return $curl;
2730     }
2732     /**
2733      * Download multiple files in parallel
2734      *
2735      * Calls {@link multi()} with specific download headers
2736      *
2737      * <code>
2738      * $c = new curl;
2739      * $c->download(array(
2740      *              array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2741      *              array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2742      *              ));
2743      * </code>
2744      *
2745      * @param array $requests An array of files to request
2746      * @param array $options An array of options to set
2747      * @return array An array of results
2748      */
2749     public function download($requests, $options = array()) {
2750         $options['CURLOPT_BINARYTRANSFER'] = 1;
2751         $options['RETURNTRANSFER'] = false;
2752         return $this->multi($requests, $options);
2753     }
2755     /**
2756      * Mulit HTTP Requests
2757      * This function could run multi-requests in parallel.
2758      *
2759      * @param array $requests An array of files to request
2760      * @param array $options An array of options to set
2761      * @return array An array of results
2762      */
2763     protected function multi($requests, $options = array()) {
2764         $count   = count($requests);
2765         $handles = array();
2766         $results = array();
2767         $main    = curl_multi_init();
2768         for ($i = 0; $i < $count; $i++) {
2769             $url = $requests[$i];
2770             foreach($url as $n=>$v){
2771                 $options[$n] = $url[$n];
2772             }
2773             $handles[$i] = curl_init($url['url']);
2774             $this->apply_opt($handles[$i], $options);
2775             curl_multi_add_handle($main, $handles[$i]);
2776         }
2777         $running = 0;
2778         do {
2779             curl_multi_exec($main, $running);
2780         } while($running > 0);
2781         for ($i = 0; $i < $count; $i++) {
2782             if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
2783                 $results[] = true;
2784             } else {
2785                 $results[] = curl_multi_getcontent($handles[$i]);
2786             }
2787             curl_multi_remove_handle($main, $handles[$i]);
2788         }
2789         curl_multi_close($main);
2790         return $results;
2791     }
2793     /**
2794      * Single HTTP Request
2795      *
2796      * @param string $url The URL to request
2797      * @param array $options
2798      * @return bool
2799      */
2800     protected function request($url, $options = array()){
2801         // create curl instance
2802         $curl = curl_init($url);
2803         $options['url'] = $url;
2804         $this->apply_opt($curl, $options);
2805         if ($this->cache && $ret = $this->cache->get($this->options)) {
2806             return $ret;
2807         } else {
2808             $ret = curl_exec($curl);
2809             if ($this->cache) {
2810                 $this->cache->set($this->options, $ret);
2811             }
2812         }
2814         $this->info  = curl_getinfo($curl);
2815         $this->error = curl_error($curl);
2817         if ($this->debug){
2818             echo '<h1>Return Data</h1>';
2819             var_dump($ret);
2820             echo '<h1>Info</h1>';
2821             var_dump($this->info);
2822             echo '<h1>Error</h1>';
2823             var_dump($this->error);
2824         }
2826         curl_close($curl);
2828         if (empty($this->error)){
2829             return $ret;
2830         } else {
2831             return $this->error;
2832             // exception is not ajax friendly
2833             //throw new moodle_exception($this->error, 'curl');
2834         }
2835     }
2837     /**
2838      * HTTP HEAD method
2839      *
2840      * @see request()
2841      *
2842      * @param string $url
2843      * @param array $options
2844      * @return bool
2845      */
2846     public function head($url, $options = array()){
2847         $options['CURLOPT_HTTPGET'] = 0;
2848         $options['CURLOPT_HEADER']  = 1;
2849         $options['CURLOPT_NOBODY']  = 1;
2850         return $this->request($url, $options);
2851     }
2853     /**
2854      * HTTP POST method
2855      *
2856      * @param string $url
2857      * @param array|string $params
2858      * @param array $options
2859      * @return bool
2860      */
2861     public function post($url, $params = '', $options = array()){
2862         $options['CURLOPT_POST']       = 1;
2863         if (is_array($params)) {
2864             $this->_tmp_file_post_params = array();
2865             foreach ($params as $key => $value) {
2866                 if ($value instanceof stored_file) {
2867                     $value->add_to_curl_request($this, $key);
2868                 } else {
2869                     $this->_tmp_file_post_params[$key] = $value;
2870                 }
2871             }
2872             $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2873             unset($this->_tmp_file_post_params);
2874         } else {
2875             // $params is the raw post data
2876             $options['CURLOPT_POSTFIELDS'] = $params;
2877         }
2878         return $this->request($url, $options);
2879     }
2881     /**
2882      * HTTP GET method
2883      *
2884      * @param string $url
2885      * @param array $params
2886      * @param array $options
2887      * @return bool
2888      */
2889     public function get($url, $params = array(), $options = array()){
2890         $options['CURLOPT_HTTPGET'] = 1;
2892         if (!empty($params)){
2893             $url .= (stripos($url, '?') !== false) ? '&' : '?';
2894             $url .= http_build_query($params, '', '&');
2895         }
2896         return $this->request($url, $options);
2897     }
2899     /**
2900      * HTTP PUT method
2901      *
2902      * @param string $url
2903      * @param array $params
2904      * @param array $options
2905      * @return bool
2906      */
2907     public function put($url, $params = array(), $options = array()){
2908         $file = $params['file'];
2909         if (!is_file($file)){
2910             return null;
2911         }
2912         $fp   = fopen($file, 'r');
2913         $size = filesize($file);
2914         $options['CURLOPT_PUT']        = 1;
2915         $options['CURLOPT_INFILESIZE'] = $size;
2916         $options['CURLOPT_INFILE']     = $fp;
2917         if (!isset($this->options['CURLOPT_USERPWD'])){
2918             $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2919         }
2920         $ret = $this->request($url, $options);
2921         fclose($fp);
2922         return $ret;
2923     }
2925     /**
2926      * HTTP DELETE method
2927      *
2928      * @param string $url
2929      * @param array $param
2930      * @param array $options
2931      * @return bool
2932      */
2933     public function delete($url, $param = array(), $options = array()){
2934         $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2935         if (!isset($options['CURLOPT_USERPWD'])) {
2936             $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2937         }
2938         $ret = $this->request($url, $options);
2939         return $ret;
2940     }
2942     /**
2943      * HTTP TRACE method
2944      *
2945      * @param string $url
2946      * @param array $options
2947      * @return bool
2948      */
2949     public function trace($url, $options = array()){
2950         $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2951         $ret = $this->request($url, $options);
2952         return $ret;
2953     }
2955     /**
2956      * HTTP OPTIONS method
2957      *
2958      * @param string $url
2959      * @param array $options
2960      * @return bool
2961      */
2962     public function options($url, $options = array()){
2963         $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2964         $ret = $this->request($url, $options);
2965         return $ret;
2966     }
2968     /**
2969      * Get curl information
2970      *
2971      * @return string
2972      */
2973     public function get_info() {
2974         return $this->info;
2975     }
2978 /**
2979  * This class is used by cURL class, use case:
2980  *
2981  * <code>
2982  * $CFG->repositorycacheexpire = 120;
2983  * $CFG->curlcache = 120;
2984  *
2985  * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2986  * $ret = $c->get('http://www.google.com');
2987  * </code>
2988  *
2989  * @package   core_files
2990  * @copyright Dongsheng Cai <dongsheng@moodle.com>
2991  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2992  */
2993 class curl_cache {
2994     /** @var string Path to cache directory */
2995     public $dir = '';
2997     /**
2998      * Constructor
2999      *
3000      * @global stdClass $CFG
3001      * @param string $module which module is using curl_cache
3002      */
3003     function __construct($module = 'repository'){
3004         global $CFG;
3005         if (!empty($module)) {
3006             $this->dir = $CFG->cachedir.'/'.$module.'/';
3007         } else {
3008             $this->dir = $CFG->cachedir.'/misc/';
3009         }
3010         if (!file_exists($this->dir)) {
3011             mkdir($this->dir, $CFG->directorypermissions, true);
3012         }
3013         if ($module == 'repository') {
3014             if (empty($CFG->repositorycacheexpire)) {
3015                 $CFG->repositorycacheexpire = 120;
3016             }
3017             $this->ttl = $CFG->repositorycacheexpire;
3018         } else {
3019             if (empty($CFG->curlcache)) {
3020                 $CFG->curlcache = 120;
3021             }
3022             $this->ttl = $CFG->curlcache;
3023         }
3024     }
3026     /**
3027      * Get cached value
3028      *
3029      * @global stdClass $CFG
3030      * @global stdClass $USER
3031      * @param mixed $param
3032      * @return bool|string
3033      */
3034     public function get($param){
3035         global $CFG, $USER;
3036         $this->cleanup($this->ttl);
3037         $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3038         if(file_exists($this->dir.$filename)) {
3039             $lasttime = filemtime($this->dir.$filename);
3040             if(time()-$lasttime > $this->ttl)
3041             {
3042                 return false;
3043             } else {
3044                 $fp = fopen($this->dir.$filename, 'r');
3045                 $size = filesize($this->dir.$filename);
3046                 $content = fread($fp, $size);
3047                 return unserialize($content);
3048             }
3049         }
3050         return false;
3051     }
3053     /**
3054      * Set cache value
3055      *
3056      * @global object $CFG
3057      * @global object $USER
3058      * @param mixed $param
3059      * @param mixed $val
3060      */
3061     public function set($param, $val){
3062         global $CFG, $USER;
3063         $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3064         $fp = fopen($this->dir.$filename, 'w');
3065         fwrite($fp, serialize($val));
3066         fclose($fp);
3067     }
3069     /**
3070      * Remove cache files
3071      *
3072      * @param int $expire The number os seconds before expiry
3073      */
3074     public function cleanup($expire){
3075         if($dir = opendir($this->dir)){
3076             while (false !== ($file = readdir($dir))) {
3077                 if(!is_dir($file) && $file != '.' && $file != '..') {
3078                     $lasttime = @filemtime($this->dir.$file);
3079                     if(time() - $lasttime > $expire){
3080                         @unlink($this->dir.$file);
3081                     }
3082                 }
3083             }
3084         }
3085     }
3086     /**
3087      * delete current user's cache file
3088      *
3089      * @global object $CFG
3090      * @global object $USER
3091      */
3092     public function refresh(){
3093         global $CFG, $USER;
3094         if($dir = opendir($this->dir)){
3095             while (false !== ($file = readdir($dir))) {
3096                 if(!is_dir($file) && $file != '.' && $file != '..') {
3097                     if(strpos($file, 'u'.$USER->id.'_')!==false){
3098                         @unlink($this->dir.$file);
3099                     }
3100                 }
3101             }
3102         }
3103     }
3106 /**
3107  * This class is used to parse lib/file/file_types.mm which help get file extensions by file types.
3108  *
3109  * The file_types.mm file can be edited by freemind in graphic environment.
3110  *
3111  * @package   core_files
3112  * @category  files
3113  * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
3114  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3115  */
3116 class filetype_parser {
3117     /**
3118      * Check file_types.mm file, setup variables
3119      *
3120      * @global stdClass $CFG
3121      * @param string $file
3122      */
3123     public function __construct($file = '') {
3124         global $CFG;
3125         if (empty($file)) {
3126             $this->file = $CFG->libdir.'/filestorage/file_types.mm';
3127         } else {
3128             $this->file = $file;
3129         }
3130         $this->tree = array();
3131         $this->result = array();
3132     }
3134     /**
3135      * A private function to browse xml nodes
3136      *
3137      * @param array $parent
3138      * @param array $types
3139      */
3140     private function _browse_nodes($parent, $types) {
3141         $key = (string)$parent['TEXT'];
3142         if(isset($parent->node)) {
3143             $this->tree[$key] = array();
3144             if (in_array((string)$parent['TEXT'], $types)) {
3145                 $this->_select_nodes($parent, $this->result);
3146             } else {
3147                 foreach($parent->node as $v){
3148                     $this->_browse_nodes($v, $types);
3149                 }
3150             }
3151         } else {
3152             $this->tree[] = $key;
3153         }
3154     }
3156     /**
3157      * A private function to select text nodes
3158      *
3159      * @param array $parent
3160      */
3161     private function _select_nodes($parent){
3162         if(isset($parent->node)) {
3163             foreach($parent->node as $v){
3164                 $this->_select_nodes($v, $this->result);
3165             }
3166         } else {
3167             $this->result[] = (string)$parent['TEXT'];
3168         }
3169     }
3172     /**
3173      * Get file extensions by file types names.
3174      *
3175      * @param array $types
3176      * @return mixed
3177      */
3178     public function get_extensions($types) {
3179         if (!is_array($types)) {
3180             $types = array($types);
3181         }
3182         $this->result = array();
3183         if ((is_array($types) && in_array('*', $types)) ||
3184             $types == '*' || empty($types)) {
3185             return array('*');
3186         }
3187         foreach ($types as $key=>$value){
3188             if (strpos($value, '.') !== false) {
3189                 $this->result[] = $value;
3190                 unset($types[$key]);
3191             }
3192         }
3193         if (file_exists($this->file)) {
3194             $xml = simplexml_load_file($this->file);
3195             foreach($xml->node->node as $v){
3196                 if (in_array((string)$v['TEXT'], $types)) {
3197                     $this->_select_nodes($v);
3198                 } else {
3199                     $this->_browse_nodes($v, $types);
3200                 }
3201             }
3202         } else {
3203             exit('Failed to open file lib/filestorage/file_types.mm');
3204         }
3205         return $this->result;
3206     }
3209 /**
3210  * This function delegates file serving to individual plugins
3211  *
3212  * @param string $relativepath
3213  * @param bool $forcedownload
3214  * @todo MDL-31088 file serving improments
3215  */
3216 function file_pluginfile($relativepath, $forcedownload) {
3217     global $DB, $CFG, $USER;
3218     // relative path must start with '/'
3219     if (!$relativepath) {
3220         print_error('invalidargorconf');
3221     } else if ($relativepath[0] != '/') {
3222         print_error('pathdoesnotstartslash');
3223     }
3225     // extract relative path components
3226     $args = explode('/', ltrim($relativepath, '/'));
3228     if (count($args) < 3) { // always at least context, component and filearea
3229         print_error('invalidarguments');
3230     }
3232     $contextid = (int)array_shift($args);
3233     $component = clean_param(array_shift($args), PARAM_COMPONENT);
3234     $filearea  = clean_param(array_shift($args), PARAM_AREA);
3236     list($context, $course, $cm) = get_context_info_array($contextid);
3238     $fs = get_file_storage();
3240     // ========================================================================================================================
3241     if ($component === 'blog') {
3242         // Blog file serving
3243         if ($context->contextlevel != CONTEXT_SYSTEM) {
3244             send_file_not_found();
3245         }
3246         if ($filearea !== 'attachment' and $filearea !== 'post') {
3247             send_file_not_found();
3248         }
3250         if (empty($CFG->bloglevel)) {
3251             print_error('siteblogdisable', 'blog');
3252         }
3254         $entryid = (int)array_shift($args);
3255         if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3256             send_file_not_found();
3257         }
3258         if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3259             require_login();
3260             if (isguestuser()) {
3261                 print_error('noguest');
3262             }
3263             if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3264                 if ($USER->id != $entry->userid) {
3265                     send_file_not_found();
3266                 }
3267             }
3268         }
3270         if ('publishstate' === 'public') {
3271             if ($CFG->forcelogin) {
3272                 require_login();
3273             }
3275         } else if ('publishstate' === 'site') {
3276             require_login();
3277             //ok
3278         } else if ('publishstate' === 'draft') {
3279             require_login();
3280             if ($USER->id != $entry->userid) {
3281                 send_file_not_found();
3282             }
3283         }
3285         $filename = array_pop($args);
3286         $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3288         if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3289             send_file_not_found();
3290         }
3292         send_stored_file($file, 10*60, 0, true); // download MUST be forced - security!
3294     // ========================================================================================================================
3295     } else if ($component === 'grade') {
3296         if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3297             // Global gradebook files
3298             if ($CFG->forcelogin) {
3299                 require_login();
3300             }
3302             $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3304             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3305                 send_file_not_found();
3306             }
3308             session_get_instance()->write_close(); // unlock session during fileserving
3309             send_stored_file($file, 60*60, 0, $forcedownload);
3311         } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3312             //TODO: nobody implemented this yet in grade edit form!!
3313             send_file_not_found();
3315             if ($CFG->forcelogin || $course->id != SITEID) {
3316                 require_login($course);
3317             }
3319             $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3321             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3322                 send_file_not_found();
3323             }
3325             session_get_instance()->write_close(); // unlock session during fileserving
3326             send_stored_file($file, 60*60, 0, $forcedownload);
3327         } else {
3328             send_file_not_found();
3329         }
3331     // ========================================================================================================================
3332     } else if ($component === 'tag') {
3333         if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3335             // All tag descriptions are going to be public but we still need to respect forcelogin
3336             if ($CFG->forcelogin) {
3337                 require_login();
3338             }
3340             $fullpath = "/$context->id/tag/description/".implode('/', $args);
3342             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3343                 send_file_not_found();
3344             }
3346             session_get_instance()->write_close(); // unlock session during fileserving
3347             send_stored_file($file, 60*60, 0, true);
3349         } else {
3350             send_file_not_found();
3351         }
3353     // ========================================================================================================================
3354     } else if ($component === 'calendar') {
3355         if ($filearea === 'event_description'  and $context->contextlevel == CONTEXT_SYSTEM) {
3357             // All events here are public the one requirement is that we respect forcelogin
3358             if ($CFG->forcelogin) {
3359                 require_login();
3360             }
3362             // Get the event if from the args array
3363             $eventid = array_shift($args);
3365             // Load the event from the database
3366             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3367                 send_file_not_found();
3368             }
3369             // Check that we got an event and that it's userid is that of the user
3371             // Get the file and serve if successful
3372             $filename = array_pop($args);
3373             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3374             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3375                 send_file_not_found();
3376             }
3378             session_get_instance()->write_close(); // unlock session during fileserving
3379             send_stored_file($file, 60*60, 0, $forcedownload);
3381         } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3383             // Must be logged in, if they are not then they obviously can't be this user
3384             require_login();
3386             // Don't want guests here, potentially saves a DB call
3387             if (isguestuser()) {
3388                 send_file_not_found();
3389             }
3391             // Get the event if from the args array
3392             $eventid = array_shift($args);
3394             // Load the event from the database - user id must match
3395             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3396                 send_file_not_found();
3397             }
3399             // Get the file and serve if successful
3400             $filename = array_pop($args);
3401             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3402             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3403                 send_file_not_found();
3404             }
3406             session_get_instance()->write_close(); // unlock session during fileserving
3407             send_stored_file($file, 60*60, 0, $forcedownload);
3409         } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3411             // Respect forcelogin and require login unless this is the site.... it probably
3412             // should NEVER be the site
3413             if ($CFG->forcelogin || $course->id != SITEID) {
3414                 require_login($course);
3415             }
3417             // Must be able to at least view the course
3418             if (!is_enrolled($context) and !is_viewing($context)) {
3419                 //TODO: hmm, do we really want to block guests here?
3420                 send_file_not_found();
3421             }
3423             // Get the event id
3424             $eventid = array_shift($args);
3426             // Load the event from the database we need to check whether it is
3427             // a) valid course event
3428             // b) a group event
3429             // Group events use the course context (there is no group context)
3430             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3431                 send_file_not_found();
3432             }
3434             // If its a group event require either membership of view all groups capability
3435             if ($event->eventtype === 'group') {
3436                 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3437                     send_file_not_found();
3438                 }
3439             } else if ($event->eventtype === 'course') {
3440                 //ok
3441             } else {
3442                 // some other type
3443                 send_file_not_found();
3444             }
3446             // If we get this far we can serve the file
3447             $filename = array_pop($args);
3448             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3449             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3450                 send_file_not_found();
3451             }
3453             session_get_instance()->write_close(); // unlock session during fileserving
3454             send_stored_file($file, 60*60, 0, $forcedownload);
3456         } else {
3457             send_file_not_found();
3458         }
3460     // ========================================================================================================================
3461     } else if ($component === 'user') {
3462         if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3463             $redirect = false;
3464             if (count($args) == 1) {
3465                 $themename = theme_config::DEFAULT_THEME;
3466                 $filename = array_shift($args);
3467             } else {
3468                 $themename = array_shift($args);
3469                 $filename = array_shift($args);
3470             }
3471             if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3472                     (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3473                 // protect images if login required and not logged in;
3474                 // also if login is required for profile images and is not logged in or guest
3475                 // do not use require_login() because it is expensive and not suitable here anyway
3476                 $redirect = true;
3477             }
3478             if (!$redirect and ($filename !== 'f1' and $filename !== 'f2')) {
3479                 $filename = 'f1';
3480                 $redirect = true;
3481             }
3482             if (!$redirect && !$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'/.png')) {
3483                 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg')) {
3484                     $redirect = true;
3485                 }
3486             }
3487             if ($redirect) {
3488                 $theme = theme_config::load($themename);
3489                 redirect($theme->pix_url('u/'.$filename, 'moodle'));
3490             }
3491             send_stored_file($file, 60*60*24); // enable long caching, there are many images on each page
3493         } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3494             require_login();
3496             if (isguestuser()) {
3497                 send_file_not_found();
3498             }
3500             if ($USER->id !== $context->instanceid) {
3501                 send_file_not_found();
3502             }
3504             $filename = array_pop($args);
3505             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3506             if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3507                 send_file_not_found();
3508             }
3510             session_get_instance()->write_close(); // unlock session during fileserving
3511             send_stored_file($file, 0, 0, true); // must force download - security!
3513         } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3515             if ($CFG->forcelogin) {
3516                 require_login();
3517             }
3519             $userid = $context->instanceid;
3521             if ($USER->id == $userid) {
3522                 // always can access own
3524             } else if (!empty($CFG->forceloginforprofiles)) {
3525                 require_login();
3527                 if (isguestuser()) {
3528                     send_file_not_found();
3529                 }
3531                 // we allow access to site profile of all course contacts (usually teachers)
3532                 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3533                     send_file_not_found();
3534                 }
3536                 $canview = false;
3537                 if (has_capability('moodle/user:viewdetails', $context)) {
3538                     $canview = true;
3539                 } else {
3540                     $courses = enrol_get_my_courses();
3541                 }
3543                 while (!$canview && count($courses) > 0) {
3544                     $course = array_shift($courses);
3545                     if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) {
3546                         $canview = true;
3547                     }
3548                 }
3549             }
3551             $filename = array_pop($args);
3552             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3553             if (!$file =