Revert "MDL-40931 useragent: separated user agent functionality into a lib"
[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 /**
33  * Unlimited area size constant
34  */
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
42 /**
43  * Encodes file serving url
44  *
45  * @deprecated use moodle_url factory methods instead
46  *
47  * @todo MDL-31071 deprecate this function
48  * @global stdClass $CFG
49  * @param string $urlbase
50  * @param string $path /filearea/itemid/dir/dir/file.exe
51  * @param bool $forcedownload
52  * @param bool $https https url required
53  * @return string encoded file url
54  */
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56     global $CFG;
58 //TODO: deprecate this
60     if ($CFG->slasharguments) {
61         $parts = explode('/', $path);
62         $parts = array_map('rawurlencode', $parts);
63         $path  = implode('/', $parts);
64         $return = $urlbase.$path;
65         if ($forcedownload) {
66             $return .= '?forcedownload=1';
67         }
68     } else {
69         $path = rawurlencode($path);
70         $return = $urlbase.'?file='.$path;
71         if ($forcedownload) {
72             $return .= '&amp;forcedownload=1';
73         }
74     }
76     if ($https) {
77         $return = str_replace('http://', 'https://', $return);
78     }
80     return $return;
81 }
83 /**
84  * Prepares 'editor' formslib element from data in database
85  *
86  * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
87  * function then copies the embedded files into draft area (assigning itemids automatically),
88  * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
89  * displayed.
90  * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
91  * your mform's set_data() supplying the object returned by this function.
92  *
93  * @category files
94  * @param stdClass $data database field that holds the html text with embedded media
95  * @param string $field the name of the database field that holds the html text with embedded media
96  * @param array $options editor options (like maxifiles, maxbytes etc.)
97  * @param stdClass $context context of the editor
98  * @param string $component
99  * @param string $filearea file area name
100  * @param int $itemid item id, required if item exists
101  * @return stdClass modified data object
102  */
103 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
104     $options = (array)$options;
105     if (!isset($options['trusttext'])) {
106         $options['trusttext'] = false;
107     }
108     if (!isset($options['forcehttps'])) {
109         $options['forcehttps'] = false;
110     }
111     if (!isset($options['subdirs'])) {
112         $options['subdirs'] = false;
113     }
114     if (!isset($options['maxfiles'])) {
115         $options['maxfiles'] = 0; // no files by default
116     }
117     if (!isset($options['noclean'])) {
118         $options['noclean'] = false;
119     }
121     //sanity check for passed context. This function doesn't expect $option['context'] to be set
122     //But this function is called before creating editor hence, this is one of the best places to check
123     //if context is used properly. This check notify developer that they missed passing context to editor.
124     if (isset($context) && !isset($options['context'])) {
125         //if $context is not null then make sure $option['context'] is also set.
126         debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
127     } else if (isset($options['context']) && isset($context)) {
128         //If both are passed then they should be equal.
129         if ($options['context']->id != $context->id) {
130             $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
131             throw new coding_exception($exceptionmsg);
132         }
133     }
135     if (is_null($itemid) or is_null($context)) {
136         $contextid = null;
137         $itemid = null;
138         if (!isset($data)) {
139             $data = new stdClass();
140         }
141         if (!isset($data->{$field})) {
142             $data->{$field} = '';
143         }
144         if (!isset($data->{$field.'format'})) {
145             $data->{$field.'format'} = editors_get_preferred_format();
146         }
147         if (!$options['noclean']) {
148             $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
149         }
151     } else {
152         if ($options['trusttext']) {
153             // noclean ignored if trusttext enabled
154             if (!isset($data->{$field.'trust'})) {
155                 $data->{$field.'trust'} = 0;
156             }
157             $data = trusttext_pre_edit($data, $field, $context);
158         } else {
159             if (!$options['noclean']) {
160                 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
161             }
162         }
163         $contextid = $context->id;
164     }
166     if ($options['maxfiles'] != 0) {
167         $draftid_editor = file_get_submitted_draft_itemid($field);
168         $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
169         $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
170     } else {
171         $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
172     }
174     return $data;
177 /**
178  * Prepares the content of the 'editor' form element with embedded media files to be saved in database
179  *
180  * This function moves files from draft area to the destination area and
181  * encodes URLs to the draft files so they can be safely saved into DB. The
182  * form has to contain the 'editor' element named foobar_editor, where 'foobar'
183  * is the name of the database field to hold the wysiwyg editor content. The
184  * editor data comes as an array with text, format and itemid properties. This
185  * function automatically adds $data properties foobar, foobarformat and
186  * foobartrust, where foobar has URL to embedded files encoded.
187  *
188  * @category files
189  * @param stdClass $data raw data submitted by the form
190  * @param string $field name of the database field containing the html with embedded media files
191  * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
192  * @param stdClass $context context, required for existing data
193  * @param string $component file component
194  * @param string $filearea file area name
195  * @param int $itemid item id, required if item exists
196  * @return stdClass modified data object
197  */
198 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
199     $options = (array)$options;
200     if (!isset($options['trusttext'])) {
201         $options['trusttext'] = false;
202     }
203     if (!isset($options['forcehttps'])) {
204         $options['forcehttps'] = false;
205     }
206     if (!isset($options['subdirs'])) {
207         $options['subdirs'] = false;
208     }
209     if (!isset($options['maxfiles'])) {
210         $options['maxfiles'] = 0; // no files by default
211     }
212     if (!isset($options['maxbytes'])) {
213         $options['maxbytes'] = 0; // unlimited
214     }
216     if ($options['trusttext']) {
217         $data->{$field.'trust'} = trusttext_trusted($context);
218     } else {
219         $data->{$field.'trust'} = 0;
220     }
222     $editor = $data->{$field.'_editor'};
224     if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
225         $data->{$field} = $editor['text'];
226     } else {
227         $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
228     }
229     $data->{$field.'format'} = $editor['format'];
231     return $data;
234 /**
235  * Saves text and files modified by Editor formslib element
236  *
237  * @category files
238  * @param stdClass $data $database entry field
239  * @param string $field name of data field
240  * @param array $options various options
241  * @param stdClass $context context - must already exist
242  * @param string $component
243  * @param string $filearea file area name
244  * @param int $itemid must already exist, usually means data is in db
245  * @return stdClass modified data obejct
246  */
247 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
248     $options = (array)$options;
249     if (!isset($options['subdirs'])) {
250         $options['subdirs'] = false;
251     }
252     if (is_null($itemid) or is_null($context)) {
253         $itemid = null;
254         $contextid = null;
255     } else {
256         $contextid = $context->id;
257     }
259     $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
260     file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
261     $data->{$field.'_filemanager'} = $draftid_editor;
263     return $data;
266 /**
267  * Saves files modified by File manager formslib element
268  *
269  * @todo MDL-31073 review this function
270  * @category files
271  * @param stdClass $data $database entry field
272  * @param string $field name of data field
273  * @param array $options various options
274  * @param stdClass $context context - must already exist
275  * @param string $component
276  * @param string $filearea file area name
277  * @param int $itemid must already exist, usually means data is in db
278  * @return stdClass modified data obejct
279  */
280 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
281     $options = (array)$options;
282     if (!isset($options['subdirs'])) {
283         $options['subdirs'] = false;
284     }
285     if (!isset($options['maxfiles'])) {
286         $options['maxfiles'] = -1; // unlimited
287     }
288     if (!isset($options['maxbytes'])) {
289         $options['maxbytes'] = 0; // unlimited
290     }
292     if (empty($data->{$field.'_filemanager'})) {
293         $data->$field = '';
295     } else {
296         file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
297         $fs = get_file_storage();
299         if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
300             $data->$field = '1'; // TODO: this is an ugly hack (skodak)
301         } else {
302             $data->$field = '';
303         }
304     }
306     return $data;
309 /**
310  * Generate a draft itemid
311  *
312  * @category files
313  * @global moodle_database $DB
314  * @global stdClass $USER
315  * @return int a random but available draft itemid that can be used to create a new draft
316  * file area.
317  */
318 function file_get_unused_draft_itemid() {
319     global $DB, $USER;
321     if (isguestuser() or !isloggedin()) {
322         // guests and not-logged-in users can not be allowed to upload anything!!!!!!
323         print_error('noguest');
324     }
326     $contextid = context_user::instance($USER->id)->id;
328     $fs = get_file_storage();
329     $draftitemid = rand(1, 999999999);
330     while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
331         $draftitemid = rand(1, 999999999);
332     }
334     return $draftitemid;
337 /**
338  * Initialise a draft file area from a real one by copying the files. A draft
339  * area will be created if one does not already exist. Normally you should
340  * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
341  *
342  * @category files
343  * @global stdClass $CFG
344  * @global stdClass $USER
345  * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
346  * @param int $contextid This parameter and the next two identify the file area to copy files from.
347  * @param string $component
348  * @param string $filearea helps indentify the file area.
349  * @param int $itemid helps identify the file area. Can be null if there are no files yet.
350  * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
351  * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
352  * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
353  */
354 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
355     global $CFG, $USER, $CFG;
357     $options = (array)$options;
358     if (!isset($options['subdirs'])) {
359         $options['subdirs'] = false;
360     }
361     if (!isset($options['forcehttps'])) {
362         $options['forcehttps'] = false;
363     }
365     $usercontext = context_user::instance($USER->id);
366     $fs = get_file_storage();
368     if (empty($draftitemid)) {
369         // create a new area and copy existing files into
370         $draftitemid = file_get_unused_draft_itemid();
371         $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
372         if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
373             foreach ($files as $file) {
374                 if ($file->is_directory() and $file->get_filepath() === '/') {
375                     // we need a way to mark the age of each draft area,
376                     // by not copying the root dir we force it to be created automatically with current timestamp
377                     continue;
378                 }
379                 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
380                     continue;
381                 }
382                 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
383                 // XXX: This is a hack for file manager (MDL-28666)
384                 // File manager needs to know the original file information before copying
385                 // to draft area, so we append these information in mdl_files.source field
386                 // {@link file_storage::search_references()}
387                 // {@link file_storage::search_references_count()}
388                 $sourcefield = $file->get_source();
389                 $newsourcefield = new stdClass;
390                 $newsourcefield->source = $sourcefield;
391                 $original = new stdClass;
392                 $original->contextid = $contextid;
393                 $original->component = $component;
394                 $original->filearea  = $filearea;
395                 $original->itemid    = $itemid;
396                 $original->filename  = $file->get_filename();
397                 $original->filepath  = $file->get_filepath();
398                 $newsourcefield->original = file_storage::pack_reference($original);
399                 $draftfile->set_source(serialize($newsourcefield));
400                 // End of file manager hack
401             }
402         }
403         if (!is_null($text)) {
404             // at this point there should not be any draftfile links yet,
405             // because this is a new text from database that should still contain the @@pluginfile@@ links
406             // this happens when developers forget to post process the text
407             $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
408         }
409     } else {
410         // nothing to do
411     }
413     if (is_null($text)) {
414         return null;
415     }
417     // relink embedded files - editor can not handle @@PLUGINFILE@@ !
418     return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
421 /**
422  * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
423  *
424  * @category files
425  * @global stdClass $CFG
426  * @param string $text The content that may contain ULRs in need of rewriting.
427  * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
428  * @param int $contextid This parameter and the next two identify the file area to use.
429  * @param string $component
430  * @param string $filearea helps identify the file area.
431  * @param int $itemid helps identify the file area.
432  * @param array $options text and file options ('forcehttps'=>false)
433  * @return string the processed text.
434  */
435 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
436     global $CFG;
438     $options = (array)$options;
439     if (!isset($options['forcehttps'])) {
440         $options['forcehttps'] = false;
441     }
443     if (!$CFG->slasharguments) {
444         $file = $file . '?file=';
445     }
447     $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
449     if ($itemid !== null) {
450         $baseurl .= "$itemid/";
451     }
453     if ($options['forcehttps']) {
454         $baseurl = str_replace('http://', 'https://', $baseurl);
455     }
457     return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
460 /**
461  * Returns information about files in a draft area.
462  *
463  * @global stdClass $CFG
464  * @global stdClass $USER
465  * @param int $draftitemid the draft area item id.
466  * @param string $filepath path to the directory from which the information have to be retrieved.
467  * @return array with the following entries:
468  *      'filecount' => number of files in the draft area.
469  *      'filesize' => total size of the files in the draft area.
470  *      'foldercount' => number of folders in the draft area.
471  *      'filesize_without_references' => total size of the area excluding file references.
472  * (more information will be added as needed).
473  */
474 function file_get_draft_area_info($draftitemid, $filepath = '/') {
475     global $CFG, $USER;
477     $usercontext = context_user::instance($USER->id);
478     $fs = get_file_storage();
480     $results = array(
481         'filecount' => 0,
482         'foldercount' => 0,
483         'filesize' => 0,
484         'filesize_without_references' => 0
485     );
487     if ($filepath != '/') {
488         $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
489     } else {
490         $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
491     }
492     foreach ($draftfiles as $file) {
493         if ($file->is_directory()) {
494             $results['foldercount'] += 1;
495         } else {
496             $results['filecount'] += 1;
497         }
499         $filesize = $file->get_filesize();
500         $results['filesize'] += $filesize;
501         if (!$file->is_external_file()) {
502             $results['filesize_without_references'] += $filesize;
503         }
504     }
506     return $results;
509 /**
510  * Returns whether a draft area has exceeded/will exceed its size limit.
511  *
512  * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
513  *
514  * @param int $draftitemid the draft area item id.
515  * @param int $areamaxbytes the maximum size allowed in this draft area.
516  * @param int $newfilesize the size that would be added to the current area.
517  * @param bool $includereferences true to include the size of the references in the area size.
518  * @return bool true if the area will/has exceeded its limit.
519  * @since 2.4
520  */
521 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
522     if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
523         $draftinfo = file_get_draft_area_info($draftitemid);
524         $areasize = $draftinfo['filesize_without_references'];
525         if ($includereferences) {
526             $areasize = $draftinfo['filesize'];
527         }
528         if ($areasize + $newfilesize > $areamaxbytes) {
529             return true;
530         }
531     }
532     return false;
535 /**
536  * Get used space of files
537  * @global moodle_database $DB
538  * @global stdClass $USER
539  * @return int total bytes
540  */
541 function file_get_user_used_space() {
542     global $DB, $USER;
544     $usercontext = context_user::instance($USER->id);
545     $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
546             JOIN (SELECT contenthash, filename, MAX(id) AS id
547             FROM {files}
548             WHERE contextid = ? AND component = ? AND filearea != ?
549             GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
550     $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
551     $record = $DB->get_record_sql($sql, $params);
552     return (int)$record->totalbytes;
555 /**
556  * Convert any string to a valid filepath
557  * @todo review this function
558  * @param string $str
559  * @return string path
560  */
561 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
562     if ($str == '/' or empty($str)) {
563         return '/';
564     } else {
565         return '/'.trim($str, '/').'/';
566     }
569 /**
570  * Generate a folder tree of draft area of current USER recursively
571  *
572  * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
573  * @param int $draftitemid
574  * @param string $filepath
575  * @param mixed $data
576  */
577 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
578     global $USER, $OUTPUT, $CFG;
579     $data->children = array();
580     $context = context_user::instance($USER->id);
581     $fs = get_file_storage();
582     if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
583         foreach ($files as $file) {
584             if ($file->is_directory()) {
585                 $item = new stdClass();
586                 $item->sortorder = $file->get_sortorder();
587                 $item->filepath = $file->get_filepath();
589                 $foldername = explode('/', trim($item->filepath, '/'));
590                 $item->fullname = trim(array_pop($foldername), '/');
592                 $item->id = uniqid();
593                 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
594                 $data->children[] = $item;
595             } else {
596                 continue;
597             }
598         }
599     }
602 /**
603  * Listing all files (including folders) in current path (draft area)
604  * used by file manager
605  * @param int $draftitemid
606  * @param string $filepath
607  * @return stdClass
608  */
609 function file_get_drafarea_files($draftitemid, $filepath = '/') {
610     global $USER, $OUTPUT, $CFG;
612     $context = context_user::instance($USER->id);
613     $fs = get_file_storage();
615     $data = new stdClass();
616     $data->path = array();
617     $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
619     // will be used to build breadcrumb
620     $trail = '/';
621     if ($filepath !== '/') {
622         $filepath = file_correct_filepath($filepath);
623         $parts = explode('/', $filepath);
624         foreach ($parts as $part) {
625             if ($part != '' && $part != null) {
626                 $trail .= ($part.'/');
627                 $data->path[] = array('name'=>$part, 'path'=>$trail);
628             }
629         }
630     }
632     $list = array();
633     $maxlength = 12;
634     if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
635         foreach ($files as $file) {
636             $item = new stdClass();
637             $item->filename = $file->get_filename();
638             $item->filepath = $file->get_filepath();
639             $item->fullname = trim($item->filename, '/');
640             $filesize = $file->get_filesize();
641             $item->size = $filesize ? $filesize : null;
642             $item->filesize = $filesize ? display_size($filesize) : '';
644             $item->sortorder = $file->get_sortorder();
645             $item->author = $file->get_author();
646             $item->license = $file->get_license();
647             $item->datemodified = $file->get_timemodified();
648             $item->datecreated = $file->get_timecreated();
649             $item->isref = $file->is_external_file();
650             if ($item->isref && $file->get_status() == 666) {
651                 $item->originalmissing = true;
652             }
653             // find the file this draft file was created from and count all references in local
654             // system pointing to that file
655             $source = @unserialize($file->get_source());
656             if (isset($source->original)) {
657                 $item->refcount = $fs->search_references_count($source->original);
658             }
660             if ($file->is_directory()) {
661                 $item->filesize = 0;
662                 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
663                 $item->type = 'folder';
664                 $foldername = explode('/', trim($item->filepath, '/'));
665                 $item->fullname = trim(array_pop($foldername), '/');
666                 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
667             } else {
668                 // do NOT use file browser here!
669                 $item->mimetype = get_mimetype_description($file);
670                 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
671                     $item->type = 'zip';
672                 } else {
673                     $item->type = 'file';
674                 }
675                 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
676                 $item->url = $itemurl->out();
677                 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
678                 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
679                 if ($imageinfo = $file->get_imageinfo()) {
680                     $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
681                     $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
682                     $item->image_width = $imageinfo['width'];
683                     $item->image_height = $imageinfo['height'];
684                 }
685             }
686             $list[] = $item;
687         }
688     }
689     $data->itemid = $draftitemid;
690     $data->list = $list;
691     return $data;
694 /**
695  * Returns draft area itemid for a given element.
696  *
697  * @category files
698  * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
699  * @return int the itemid, or 0 if there is not one yet.
700  */
701 function file_get_submitted_draft_itemid($elname) {
702     // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
703     if (!isset($_REQUEST[$elname])) {
704         return 0;
705     }
706     if (is_array($_REQUEST[$elname])) {
707         $param = optional_param_array($elname, 0, PARAM_INT);
708         if (!empty($param['itemid'])) {
709             $param = $param['itemid'];
710         } else {
711             debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
712             return false;
713         }
715     } else {
716         $param = optional_param($elname, 0, PARAM_INT);
717     }
719     if ($param) {
720         require_sesskey();
721     }
723     return $param;
726 /**
727  * Restore the original source field from draft files
728  *
729  * Do not use this function because it makes field files.source inconsistent
730  * for draft area files. This function will be deprecated in 2.6
731  *
732  * @param stored_file $storedfile This only works with draft files
733  * @return stored_file
734  */
735 function file_restore_source_field_from_draft_file($storedfile) {
736     $source = @unserialize($storedfile->get_source());
737     if (!empty($source)) {
738         if (is_object($source)) {
739             $restoredsource = $source->source;
740             $storedfile->set_source($restoredsource);
741         } else {
742             throw new moodle_exception('invalidsourcefield', 'error');
743         }
744     }
745     return $storedfile;
747 /**
748  * Saves files from a draft file area to a real one (merging the list of files).
749  * Can rewrite URLs in some content at the same time if desired.
750  *
751  * @category files
752  * @global stdClass $USER
753  * @param int $draftitemid the id of the draft area to use. Normally obtained
754  *      from file_get_submitted_draft_itemid('elementname') or similar.
755  * @param int $contextid This parameter and the next two identify the file area to save to.
756  * @param string $component
757  * @param string $filearea indentifies the file area.
758  * @param int $itemid helps identifies the file area.
759  * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
760  * @param string $text some html content that needs to have embedded links rewritten
761  *      to the @@PLUGINFILE@@ form for saving in the database.
762  * @param bool $forcehttps force https urls.
763  * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
764  */
765 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
766     global $USER;
768     $usercontext = context_user::instance($USER->id);
769     $fs = get_file_storage();
771     $options = (array)$options;
772     if (!isset($options['subdirs'])) {
773         $options['subdirs'] = false;
774     }
775     if (!isset($options['maxfiles'])) {
776         $options['maxfiles'] = -1; // unlimited
777     }
778     if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
779         $options['maxbytes'] = 0; // unlimited
780     }
781     if (!isset($options['areamaxbytes'])) {
782         $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
783     }
784     $allowreferences = true;
785     if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
786         // we assume that if $options['return_types'] is NOT specified, we DO allow references.
787         // this is not exactly right. BUT there are many places in code where filemanager options
788         // are not passed to file_save_draft_area_files()
789         $allowreferences = false;
790     }
792     // Check if the draft area has exceeded the authorised limit. This should never happen as validation
793     // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
794     // anything at all in the next area.
795     if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
796         return null;
797     }
799     $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
800     $oldfiles   = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
802     // One file in filearea means it is empty (it has only top-level directory '.').
803     if (count($draftfiles) > 1 || count($oldfiles) > 1) {
804         // we have to merge old and new files - we want to keep file ids for files that were not changed
805         // we change time modified for all new and changed files, we keep time created as is
807         $newhashes = array();
808         $filecount = 0;
809         foreach ($draftfiles as $file) {
810             if (!$options['subdirs'] && ($file->get_filepath() !== '/' or $file->is_directory())) {
811                 continue;
812             }
813             if (!$allowreferences && $file->is_external_file()) {
814                 continue;
815             }
816             if (!$file->is_directory()) {
817                 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
818                     // oversized file - should not get here at all
819                     continue;
820                 }
821                 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
822                     // more files - should not get here at all
823                     continue;
824                 }
825                 $filecount++;
826             }
827             $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
828             $newhashes[$newhash] = $file;
829         }
831         // Loop through oldfiles and decide which we need to delete and which to update.
832         // After this cycle the array $newhashes will only contain the files that need to be added.
833         foreach ($oldfiles as $oldfile) {
834             $oldhash = $oldfile->get_pathnamehash();
835             if (!isset($newhashes[$oldhash])) {
836                 // delete files not needed any more - deleted by user
837                 $oldfile->delete();
838                 continue;
839             }
841             $newfile = $newhashes[$oldhash];
842             // Now we know that we have $oldfile and $newfile for the same path.
843             // Let's check if we can update this file or we need to delete and create.
844             if ($newfile->is_directory()) {
845                 // Directories are always ok to just update.
846             } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
847                 // File has the 'original' - we need to update the file (it may even have not been changed at all).
848                 $original = file_storage::unpack_reference($source->original);
849                 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
850                     // Very odd, original points to another file. Delete and create file.
851                     $oldfile->delete();
852                     continue;
853                 }
854             } else {
855                 // The same file name but absence of 'original' means that file was deteled and uploaded again.
856                 // By deleting and creating new file we properly manage all existing references.
857                 $oldfile->delete();
858                 continue;
859             }
861             // status changed, we delete old file, and create a new one
862             if ($oldfile->get_status() != $newfile->get_status()) {
863                 // file was changed, use updated with new timemodified data
864                 $oldfile->delete();
865                 // This file will be added later
866                 continue;
867             }
869             // Updated author
870             if ($oldfile->get_author() != $newfile->get_author()) {
871                 $oldfile->set_author($newfile->get_author());
872             }
873             // Updated license
874             if ($oldfile->get_license() != $newfile->get_license()) {
875                 $oldfile->set_license($newfile->get_license());
876             }
878             // Updated file source
879             // Field files.source for draftarea files contains serialised object with source and original information.
880             // We only store the source part of it for non-draft file area.
881             $newsource = $newfile->get_source();
882             if ($source = @unserialize($newfile->get_source())) {
883                 $newsource = $source->source;
884             }
885             if ($oldfile->get_source() !== $newsource) {
886                 $oldfile->set_source($newsource);
887             }
889             // Updated sort order
890             if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
891                 $oldfile->set_sortorder($newfile->get_sortorder());
892             }
894             // Update file timemodified
895             if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
896                 $oldfile->set_timemodified($newfile->get_timemodified());
897             }
899             // Replaced file content
900             if (!$oldfile->is_directory() &&
901                     ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
902                     $oldfile->get_filesize() != $newfile->get_filesize() ||
903                     $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
904                     $oldfile->get_userid() != $newfile->get_userid())) {
905                 $oldfile->replace_file_with($newfile);
906                 // push changes to all local files that are referencing this file
907                 $fs->update_references_to_storedfile($oldfile);
908             }
910             // unchanged file or directory - we keep it as is
911             unset($newhashes[$oldhash]);
912         }
914         // Add fresh file or the file which has changed status
915         // the size and subdirectory tests are extra safety only, the UI should prevent it
916         foreach ($newhashes as $file) {
917             $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
918             if ($source = @unserialize($file->get_source())) {
919                 // Field files.source for draftarea files contains serialised object with source and original information.
920                 // We only store the source part of it for non-draft file area.
921                 $file_record['source'] = $source->source;
922             }
924             if ($file->is_external_file()) {
925                 $repoid = $file->get_repository_id();
926                 if (!empty($repoid)) {
927                     $file_record['repositoryid'] = $repoid;
928                     $file_record['reference'] = $file->get_reference();
929                 }
930             }
932             $fs->create_file_from_storedfile($file_record, $file);
933         }
934     }
936     // note: do not purge the draft area - we clean up areas later in cron,
937     //       the reason is that user might press submit twice and they would loose the files,
938     //       also sometimes we might want to use hacks that save files into two different areas
940     if (is_null($text)) {
941         return null;
942     } else {
943         return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
944     }
947 /**
948  * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
949  * ready to be saved in the database. Normally, this is done automatically by
950  * {@link file_save_draft_area_files()}.
951  *
952  * @category files
953  * @param string $text the content to process.
954  * @param int $draftitemid the draft file area the content was using.
955  * @param bool $forcehttps whether the content contains https URLs. Default false.
956  * @return string the processed content.
957  */
958 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
959     global $CFG, $USER;
961     $usercontext = context_user::instance($USER->id);
963     $wwwroot = $CFG->wwwroot;
964     if ($forcehttps) {
965         $wwwroot = str_replace('http://', 'https://', $wwwroot);
966     }
968     // relink embedded files if text submitted - no absolute links allowed in database!
969     $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
971     if (strpos($text, 'draftfile.php?file=') !== false) {
972         $matches = array();
973         preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
974         if ($matches) {
975             foreach ($matches[0] as $match) {
976                 $replace = str_ireplace('%2F', '/', $match);
977                 $text = str_replace($match, $replace, $text);
978             }
979         }
980         $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
981     }
983     return $text;
986 /**
987  * Set file sort order
988  *
989  * @global moodle_database $DB
990  * @param int $contextid the context id
991  * @param string $component file component
992  * @param string $filearea file area.
993  * @param int $itemid itemid.
994  * @param string $filepath file path.
995  * @param string $filename file name.
996  * @param int $sortorder the sort order of file.
997  * @return bool
998  */
999 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1000     global $DB;
1001     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1002     if ($file_record = $DB->get_record('files', $conditions)) {
1003         $sortorder = (int)$sortorder;
1004         $file_record->sortorder = $sortorder;
1005         $DB->update_record('files', $file_record);
1006         return true;
1007     }
1008     return false;
1011 /**
1012  * reset file sort order number to 0
1013  * @global moodle_database $DB
1014  * @param int $contextid the context id
1015  * @param string $component
1016  * @param string $filearea file area.
1017  * @param int|bool $itemid itemid.
1018  * @return bool
1019  */
1020 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1021     global $DB;
1023     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1024     if ($itemid !== false) {
1025         $conditions['itemid'] = $itemid;
1026     }
1028     $file_records = $DB->get_records('files', $conditions);
1029     foreach ($file_records as $file_record) {
1030         $file_record->sortorder = 0;
1031         $DB->update_record('files', $file_record);
1032     }
1033     return true;
1036 /**
1037  * Returns description of upload error
1038  *
1039  * @param int $errorcode found in $_FILES['filename.ext']['error']
1040  * @return string error description string, '' if ok
1041  */
1042 function file_get_upload_error($errorcode) {
1044     switch ($errorcode) {
1045     case 0: // UPLOAD_ERR_OK - no error
1046         $errmessage = '';
1047         break;
1049     case 1: // UPLOAD_ERR_INI_SIZE
1050         $errmessage = get_string('uploadserverlimit');
1051         break;
1053     case 2: // UPLOAD_ERR_FORM_SIZE
1054         $errmessage = get_string('uploadformlimit');
1055         break;
1057     case 3: // UPLOAD_ERR_PARTIAL
1058         $errmessage = get_string('uploadpartialfile');
1059         break;
1061     case 4: // UPLOAD_ERR_NO_FILE
1062         $errmessage = get_string('uploadnofilefound');
1063         break;
1065     // Note: there is no error with a value of 5
1067     case 6: // UPLOAD_ERR_NO_TMP_DIR
1068         $errmessage = get_string('uploadnotempdir');
1069         break;
1071     case 7: // UPLOAD_ERR_CANT_WRITE
1072         $errmessage = get_string('uploadcantwrite');
1073         break;
1075     case 8: // UPLOAD_ERR_EXTENSION
1076         $errmessage = get_string('uploadextension');
1077         break;
1079     default:
1080         $errmessage = get_string('uploadproblem');
1081     }
1083     return $errmessage;
1086 /**
1087  * Recursive function formating an array in POST parameter
1088  * @param array $arraydata - the array that we are going to format and add into &$data array
1089  * @param string $currentdata - a row of the final postdata array at instant T
1090  *                when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1091  * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1092  */
1093 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1094         foreach ($arraydata as $k=>$v) {
1095             $newcurrentdata = $currentdata;
1096             if (is_array($v)) { //the value is an array, call the function recursively
1097                 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1098                 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1099             }  else { //add the POST parameter to the $data array
1100                 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1101             }
1102         }
1105 /**
1106  * Transform a PHP array into POST parameter
1107  * (see the recursive function format_array_postdata_for_curlcall)
1108  * @param array $postdata
1109  * @return array containing all POST parameters  (1 row = 1 POST parameter)
1110  */
1111 function format_postdata_for_curlcall($postdata) {
1112         $data = array();
1113         foreach ($postdata as $k=>$v) {
1114             if (is_array($v)) {
1115                 $currentdata = urlencode($k);
1116                 format_array_postdata_for_curlcall($v, $currentdata, $data);
1117             }  else {
1118                 $data[] = urlencode($k).'='.urlencode($v);
1119             }
1120         }
1121         $convertedpostdata = implode('&', $data);
1122         return $convertedpostdata;
1125 /**
1126  * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1127  * Due to security concerns only downloads from http(s) sources are supported.
1128  *
1129  * @category files
1130  * @param string $url file url starting with http(s)://
1131  * @param array $headers http headers, null if none. If set, should be an
1132  *   associative array of header name => value pairs.
1133  * @param array $postdata array means use POST request with given parameters
1134  * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1135  *   (if false, just returns content)
1136  * @param int $timeout timeout for complete download process including all file transfer
1137  *   (default 5 minutes)
1138  * @param int $connecttimeout timeout for connection to server; this is the timeout that
1139  *   usually happens if the remote server is completely down (default 20 seconds);
1140  *   may not work when using proxy
1141  * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1142  *   Only use this when already in a trusted location.
1143  * @param string $tofile store the downloaded content to file instead of returning it.
1144  * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1145  *   filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1146  * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1147  */
1148 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1149     global $CFG;
1151     // Only http and https links supported.
1152     if (!preg_match('|^https?://|i', $url)) {
1153         if ($fullresponse) {
1154             $response = new stdClass();
1155             $response->status        = 0;
1156             $response->headers       = array();
1157             $response->response_code = 'Invalid protocol specified in url';
1158             $response->results       = '';
1159             $response->error         = 'Invalid protocol specified in url';
1160             return $response;
1161         } else {
1162             return false;
1163         }
1164     }
1166     $options = array();
1168     $headers2 = array();
1169     if (is_array($headers)) {
1170         foreach ($headers as $key => $value) {
1171             if (is_numeric($key)) {
1172                 $headers2[] = $value;
1173             } else {
1174                 $headers2[] = "$key: $value";
1175             }
1176         }
1177     }
1179     if ($skipcertverify) {
1180         $options['CURLOPT_SSL_VERIFYPEER'] = false;
1181     } else {
1182         $options['CURLOPT_SSL_VERIFYPEER'] = true;
1183     }
1185     $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1187     $options['CURLOPT_FOLLOWLOCATION'] = 1;
1188     $options['CURLOPT_MAXREDIRS'] = 5;
1190     // Use POST if requested.
1191     if (is_array($postdata)) {
1192         $postdata = format_postdata_for_curlcall($postdata);
1193     } else if (empty($postdata)) {
1194         $postdata = null;
1195     }
1197     // Optionally attempt to get more correct timeout by fetching the file size.
1198     if (!isset($CFG->curltimeoutkbitrate)) {
1199         // Use very slow rate of 56kbps as a timeout speed when not set.
1200         $bitrate = 56;
1201     } else {
1202         $bitrate = $CFG->curltimeoutkbitrate;
1203     }
1204     if ($calctimeout and !isset($postdata)) {
1205         $curl = new curl();
1206         $curl->setHeader($headers2);
1208         $curl->head($url, $postdata, $options);
1210         $info = $curl->get_info();
1211         $error_no = $curl->get_errno();
1212         if (!$error_no && $info['download_content_length'] > 0) {
1213             // No curl errors - adjust for large files only - take max timeout.
1214             $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1215         }
1216     }
1218     $curl = new curl();
1219     $curl->setHeader($headers2);
1221     $options['CURLOPT_RETURNTRANSFER'] = true;
1222     $options['CURLOPT_NOBODY'] = false;
1223     $options['CURLOPT_TIMEOUT'] = $timeout;
1225     if ($tofile) {
1226         $fh = fopen($tofile, 'w');
1227         if (!$fh) {
1228             if ($fullresponse) {
1229                 $response = new stdClass();
1230                 $response->status        = 0;
1231                 $response->headers       = array();
1232                 $response->response_code = 'Can not write to file';
1233                 $response->results       = false;
1234                 $response->error         = 'Can not write to file';
1235                 return $response;
1236             } else {
1237                 return false;
1238             }
1239         }
1240         $options['CURLOPT_FILE'] = $fh;
1241     }
1243     if (isset($postdata)) {
1244         $content = $curl->post($url, $postdata, $options);
1245     } else {
1246         $content = $curl->get($url, null, $options);
1247     }
1249     if ($tofile) {
1250         fclose($fh);
1251         @chmod($tofile, $CFG->filepermissions);
1252     }
1254 /*
1255     // Try to detect encoding problems.
1256     if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1257         curl_setopt($ch, CURLOPT_ENCODING, 'none');
1258         $result = curl_exec($ch);
1259     }
1260 */
1262     $info       = $curl->get_info();
1263     $error_no   = $curl->get_errno();
1264     $rawheaders = $curl->get_raw_response();
1266     if ($error_no) {
1267         $error = $content;
1268         if (!$fullresponse) {
1269             debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1270             return false;
1271         }
1273         $response = new stdClass();
1274         if ($error_no == 28) {
1275             $response->status    = '-100'; // Mimic snoopy.
1276         } else {
1277             $response->status    = '0';
1278         }
1279         $response->headers       = array();
1280         $response->response_code = $error;
1281         $response->results       = false;
1282         $response->error         = $error;
1283         return $response;
1284     }
1286     if ($tofile) {
1287         $content = true;
1288     }
1290     if (empty($info['http_code'])) {
1291         // For security reasons we support only true http connections (Location: file:// exploit prevention).
1292         $response = new stdClass();
1293         $response->status        = '0';
1294         $response->headers       = array();
1295         $response->response_code = 'Unknown cURL error';
1296         $response->results       = false; // do NOT change this, we really want to ignore the result!
1297         $response->error         = 'Unknown cURL error';
1299     } else {
1300         $response = new stdClass();
1301         $response->status        = (string)$info['http_code'];
1302         $response->headers       = $rawheaders;
1303         $response->results       = $content;
1304         $response->error         = '';
1306         // There might be multiple headers on redirect, find the status of the last one.
1307         $firstline = true;
1308         foreach ($rawheaders as $line) {
1309             if ($firstline) {
1310                 $response->response_code = $line;
1311                 $firstline = false;
1312             }
1313             if (trim($line, "\r\n") === '') {
1314                 $firstline = true;
1315             }
1316         }
1317     }
1319     if ($fullresponse) {
1320         return $response;
1321     }
1323     if ($info['http_code'] != 200) {
1324         debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1325         return false;
1326     }
1327     return $response->results;
1330 /**
1331  * Returns a list of information about file types based on extensions.
1332  *
1333  * The following elements expected in value array for each extension:
1334  * 'type' - mimetype
1335  * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1336  *     or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1337  *     also files with bigger sizes under names
1338  *     FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1339  * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1340  *     commonly used in moodle the following groups:
1341  *       - web_image - image that can be included as <img> in HTML
1342  *       - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1343  *       - video - file that can be imported as video in text editor
1344  *       - audio - file that can be imported as audio in text editor
1345  *       - archive - we can extract files from this archive
1346  *       - spreadsheet - used for portfolio format
1347  *       - document - used for portfolio format
1348  *       - presentation - used for portfolio format
1349  * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1350  *     human-readable description for this filetype;
1351  *     Function {@link get_mimetype_description()} first looks at the presence of string for
1352  *     particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1353  *     attribute, if not found returns the value of 'type';
1354  * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1355  *     an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1356  *     this function will return first found icon; Especially usefull for types such as 'text/plain'
1357  *
1358  * @category files
1359  * @return array List of information about file types based on extensions.
1360  *   Associative array of extension (lower-case) to associative array
1361  *   from 'element name' to data. Current element names are 'type' and 'icon'.
1362  *   Unknown types should use the 'xxx' entry which includes defaults.
1363  */
1364 function &get_mimetypes_array() {
1365     static $mimearray = array (
1366         'xxx'  => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1367         '3gp'  => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1368         'aac'  => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1369         'accdb'  => array ('type'=>'application/msaccess', 'icon'=>'base'),
1370         'ai'   => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1371         'aif'  => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1372         'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1373         'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1374         'applescript'  => array ('type'=>'text/plain', 'icon'=>'text'),
1375         'asc'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1376         'asm'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1377         'au'   => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1378         'avi'  => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1379         'bmp'  => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1380         'c'    => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1381         'cct'  => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1382         'cpp'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1383         'cs'   => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1384         'css'  => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1385         'csv'  => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1386         'dv'   => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1387         'dmg'  => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1389         'doc'  => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1390         'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1391         'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1392         'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1393         'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1395         'dcr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1396         'dif'  => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1397         'dir'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1398         'dxr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1399         'eps'  => array ('type'=>'application/postscript', 'icon'=>'eps'),
1400         'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1401         'fdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1402         'flv'  => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1403         'f4v'  => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1405         'gallery'           => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1406         'galleryitem'       => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1407         'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1408         'gif'  => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1409         'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1410         'tgz'  => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1411         'gz'   => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1412         'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1413         'h'    => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1414         'hpp'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1415         'hqx'  => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1416         'htc'  => array ('type'=>'text/x-component', 'icon'=>'markup'),
1417         'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1418         'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1419         'htm'  => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1420         'ico'  => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1421         'ics'  => array ('type'=>'text/calendar', 'icon'=>'text'),
1422         'isf'  => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1423         'ist'  => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1424         'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1425         'jar'  => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1426         'jcb'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1427         'jcl'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1428         'jcw'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1429         'jmt'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1430         'jmx'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1431         'jpe'  => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1432         'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1433         'jpg'  => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1434         'jqz'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1435         'js'   => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1436         'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1437         'm'    => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1438         'mbz'  => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1439         'mdb'  => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1440         'mht'  => array ('type'=>'message/rfc822', 'icon'=>'archive'),
1441         'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
1442         'mov'  => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1443         'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1444         'm3u'  => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1445         'mp3'  => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1446         'mp4'  => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1447         'm4v'  => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1448         'm4a'  => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1449         'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1450         'mpe'  => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1451         'mpg'  => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1452         'mpr'  => array ('type'=>'application/vnd.moodle.profiling', 'icon'=>'moodle'),
1454         'nbk'       => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1455         'notebook'  => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1457         'odt'  => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1458         'ott'  => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1459         'oth'  => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1460         'odm'  => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1461         'odg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1462         'otg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1463         'odp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1464         'otp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1465         'ods'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1466         'ots'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1467         'odc'  => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1468         'odf'  => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1469         'odb'  => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1470         'odi'  => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1471         'oga'  => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1472         'ogg'  => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1473         'ogv'  => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1475         'pct'  => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1476         'pdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1477         'php'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1478         'pic'  => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1479         'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1480         'png'  => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1482         'pps'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1483         'ppt'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1484         'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1485         'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1486         'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1487         'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1488         'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1489         'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1490         'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1492         'ps'   => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1493         'qt'   => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1494         'ra'   => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1495         'ram'  => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1496         'rhb'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1497         'rm'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1498         'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1499         'rtf'  => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1500         'rtx'  => array ('type'=>'text/richtext', 'icon'=>'text'),
1501         'rv'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1502         'sh'   => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1503         'sit'  => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1504         'smi'  => array ('type'=>'application/smil', 'icon'=>'text'),
1505         'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1506         'sqt'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1507         'svg'  => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1508         'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1509         'swa'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1510         'swf'  => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1511         'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1513         'sxw'  => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1514         'stw'  => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1515         'sxc'  => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1516         'stc'  => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1517         'sxd'  => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1518         'std'  => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1519         'sxi'  => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1520         'sti'  => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1521         'sxg'  => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1522         'sxm'  => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1524         'tar'  => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1525         'tif'  => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1526         'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1527         'tex'  => array ('type'=>'application/x-tex', 'icon'=>'text'),
1528         'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1529         'texinfo'  => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1530         'tsv'  => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1531         'txt'  => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1532         'wav'  => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1533         'webm'  => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1534         'wmv'  => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1535         'asf'  => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1537         'xbk'  => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1538         'xdp'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1539         'xfd'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1540         'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1542         'xls'  => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1543         'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1544         'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1545         'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1546         'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1547         'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1548         'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1550         'xml'  => array ('type'=>'application/xml', 'icon'=>'markup'),
1551         'xsl'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1553         'zip'  => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1554     );
1555     return $mimearray;
1558 /**
1559  * Obtains information about a filetype based on its extension. Will
1560  * use a default if no information is present about that particular
1561  * extension.
1562  *
1563  * @category files
1564  * @param string $element Desired information (usually 'icon'
1565  *   for icon filename or 'type' for MIME type. Can also be
1566  *   'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1567  * @param string $filename Filename we're looking up
1568  * @return string Requested piece of information from array
1569  */
1570 function mimeinfo($element, $filename) {
1571     global $CFG;
1572     $mimeinfo = & get_mimetypes_array();
1573     static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1575     $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1576     if (empty($filetype)) {
1577         $filetype = 'xxx'; // file without extension
1578     }
1579     if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1580         $iconsize = max(array(16, (int)$iconsizematch[1]));
1581         $filenames = array($mimeinfo['xxx']['icon']);
1582         if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1583             array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1584         }
1585         // find the file with the closest size, first search for specific icon then for default icon
1586         foreach ($filenames as $filename) {
1587             foreach ($iconpostfixes as $size => $postfix) {
1588                 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1589                 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1590                     return $filename.$postfix;
1591                 }
1592             }
1593         }
1594     } else if (isset($mimeinfo[$filetype][$element])) {
1595         return $mimeinfo[$filetype][$element];
1596     } else if (isset($mimeinfo['xxx'][$element])) {
1597         return $mimeinfo['xxx'][$element];   // By default
1598     } else {
1599         return null;
1600     }
1603 /**
1604  * Obtains information about a filetype based on the MIME type rather than
1605  * the other way around.
1606  *
1607  * @category files
1608  * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1609  * @param string $mimetype MIME type we're looking up
1610  * @return string Requested piece of information from array
1611  */
1612 function mimeinfo_from_type($element, $mimetype) {
1613     /* array of cached mimetype->extension associations */
1614     static $cached = array();
1615     $mimeinfo = & get_mimetypes_array();
1617     if (!array_key_exists($mimetype, $cached)) {
1618         $cached[$mimetype] = null;
1619         foreach($mimeinfo as $filetype => $values) {
1620             if ($values['type'] == $mimetype) {
1621                 if ($cached[$mimetype] === null) {
1622                     $cached[$mimetype] = '.'.$filetype;
1623                 }
1624                 if (!empty($values['defaulticon'])) {
1625                     $cached[$mimetype] = '.'.$filetype;
1626                     break;
1627                 }
1628             }
1629         }
1630         if (empty($cached[$mimetype])) {
1631             $cached[$mimetype] = '.xxx';
1632         }
1633     }
1634     if ($element === 'extension') {
1635         return $cached[$mimetype];
1636     } else {
1637         return mimeinfo($element, $cached[$mimetype]);
1638     }
1641 /**
1642  * Return the relative icon path for a given file
1643  *
1644  * Usage:
1645  * <code>
1646  * // $file - instance of stored_file or file_info
1647  * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1648  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1649  * </code>
1650  * or
1651  * <code>
1652  * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1653  * </code>
1654  *
1655  * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1656  *     and $file->mimetype are expected)
1657  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1658  * @return string
1659  */
1660 function file_file_icon($file, $size = null) {
1661     if (!is_object($file)) {
1662         $file = (object)$file;
1663     }
1664     if (isset($file->filename)) {
1665         $filename = $file->filename;
1666     } else if (method_exists($file, 'get_filename')) {
1667         $filename = $file->get_filename();
1668     } else if (method_exists($file, 'get_visible_name')) {
1669         $filename = $file->get_visible_name();
1670     } else {
1671         $filename = '';
1672     }
1673     if (isset($file->mimetype)) {
1674         $mimetype = $file->mimetype;
1675     } else if (method_exists($file, 'get_mimetype')) {
1676         $mimetype = $file->get_mimetype();
1677     } else {
1678         $mimetype = '';
1679     }
1680     $mimetypes = &get_mimetypes_array();
1681     if ($filename) {
1682         $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1683         if ($extension && !empty($mimetypes[$extension])) {
1684             // if file name has known extension, return icon for this extension
1685             return file_extension_icon($filename, $size);
1686         }
1687     }
1688     return file_mimetype_icon($mimetype, $size);
1691 /**
1692  * Return the relative icon path for a folder image
1693  *
1694  * Usage:
1695  * <code>
1696  * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1697  * echo html_writer::empty_tag('img', array('src' => $icon));
1698  * </code>
1699  * or
1700  * <code>
1701  * echo $OUTPUT->pix_icon(file_folder_icon(32));
1702  * </code>
1703  *
1704  * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1705  * @return string
1706  */
1707 function file_folder_icon($iconsize = null) {
1708     global $CFG;
1709     static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1710     static $cached = array();
1711     $iconsize = max(array(16, (int)$iconsize));
1712     if (!array_key_exists($iconsize, $cached)) {
1713         foreach ($iconpostfixes as $size => $postfix) {
1714             $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1715             if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1716                 $cached[$iconsize] = 'f/folder'.$postfix;
1717                 break;
1718             }
1719         }
1720     }
1721     return $cached[$iconsize];
1724 /**
1725  * Returns the relative icon path for a given mime type
1726  *
1727  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1728  * a return the full path to an icon.
1729  *
1730  * <code>
1731  * $mimetype = 'image/jpg';
1732  * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1733  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1734  * </code>
1735  *
1736  * @category files
1737  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1738  * to conform with that.
1739  * @param string $mimetype The mimetype to fetch an icon for
1740  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1741  * @return string The relative path to the icon
1742  */
1743 function file_mimetype_icon($mimetype, $size = NULL) {
1744     return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1747 /**
1748  * Returns the relative icon path for a given file name
1749  *
1750  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1751  * a return the full path to an icon.
1752  *
1753  * <code>
1754  * $filename = '.jpg';
1755  * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1756  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1757  * </code>
1758  *
1759  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1760  * to conform with that.
1761  * @todo MDL-31074 Implement $size
1762  * @category files
1763  * @param string $filename The filename to get the icon for
1764  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1765  * @return string
1766  */
1767 function file_extension_icon($filename, $size = NULL) {
1768     return 'f/'.mimeinfo('icon'.$size, $filename);
1771 /**
1772  * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1773  * mimetypes.php language file.
1774  *
1775  * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1776  *   'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1777  *   have filename); In case of array/stdClass the field 'mimetype' is optional.
1778  * @param bool $capitalise If true, capitalises first character of result
1779  * @return string Text description
1780  */
1781 function get_mimetype_description($obj, $capitalise=false) {
1782     $filename = $mimetype = '';
1783     if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1784         // this is an instance of stored_file
1785         $mimetype = $obj->get_mimetype();
1786         $filename = $obj->get_filename();
1787     } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1788         // this is an instance of file_info
1789         $mimetype = $obj->get_mimetype();
1790         $filename = $obj->get_visible_name();
1791     } else if (is_array($obj) || is_object ($obj)) {
1792         $obj = (array)$obj;
1793         if (!empty($obj['filename'])) {
1794             $filename = $obj['filename'];
1795         }
1796         if (!empty($obj['mimetype'])) {
1797             $mimetype = $obj['mimetype'];
1798         }
1799     } else {
1800         $mimetype = $obj;
1801     }
1802     $mimetypefromext = mimeinfo('type', $filename);
1803     if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1804         // if file has a known extension, overwrite the specified mimetype
1805         $mimetype = $mimetypefromext;
1806     }
1807     $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1808     if (empty($extension)) {
1809         $mimetypestr = mimeinfo_from_type('string', $mimetype);
1810         $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1811     } else {
1812         $mimetypestr = mimeinfo('string', $filename);
1813     }
1814     $chunks = explode('/', $mimetype, 2);
1815     $chunks[] = '';
1816     $attr = array(
1817         'mimetype' => $mimetype,
1818         'ext' => $extension,
1819         'mimetype1' => $chunks[0],
1820         'mimetype2' => $chunks[1],
1821     );
1822     $a = array();
1823     foreach ($attr as $key => $value) {
1824         $a[$key] = $value;
1825         $a[strtoupper($key)] = strtoupper($value);
1826         $a[ucfirst($key)] = ucfirst($value);
1827     }
1829     // MIME types may include + symbol but this is not permitted in string ids.
1830     $safemimetype = str_replace('+', '_', $mimetype);
1831     $safemimetypestr = str_replace('+', '_', $mimetypestr);
1832     if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1833         $result = get_string($safemimetype, 'mimetypes', (object)$a);
1834     } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1835         $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1836     } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1837         $result = get_string('default', 'mimetypes', (object)$a);
1838     } else {
1839         $result = $mimetype;
1840     }
1841     if ($capitalise) {
1842         $result=ucfirst($result);
1843     }
1844     return $result;
1847 /**
1848  * Returns array of elements of type $element in type group(s)
1849  *
1850  * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1851  * @param string|array $groups one group or array of groups/extensions/mimetypes
1852  * @return array
1853  */
1854 function file_get_typegroup($element, $groups) {
1855     static $cached = array();
1856     if (!is_array($groups)) {
1857         $groups = array($groups);
1858     }
1859     if (!array_key_exists($element, $cached)) {
1860         $cached[$element] = array();
1861     }
1862     $result = array();
1863     foreach ($groups as $group) {
1864         if (!array_key_exists($group, $cached[$element])) {
1865             // retrieive and cache all elements of type $element for group $group
1866             $mimeinfo = & get_mimetypes_array();
1867             $cached[$element][$group] = array();
1868             foreach ($mimeinfo as $extension => $value) {
1869                 $value['extension'] = '.'.$extension;
1870                 if (empty($value[$element])) {
1871                     continue;
1872                 }
1873                 if (($group === '.'.$extension || $group === $value['type'] ||
1874                         (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1875                         !in_array($value[$element], $cached[$element][$group])) {
1876                     $cached[$element][$group][] = $value[$element];
1877                 }
1878             }
1879         }
1880         $result = array_merge($result, $cached[$element][$group]);
1881     }
1882     return array_values(array_unique($result));
1885 /**
1886  * Checks if file with name $filename has one of the extensions in groups $groups
1887  *
1888  * @see get_mimetypes_array()
1889  * @param string $filename name of the file to check
1890  * @param string|array $groups one group or array of groups to check
1891  * @param bool $checktype if true and extension check fails, find the mimetype and check if
1892  * file mimetype is in mimetypes in groups $groups
1893  * @return bool
1894  */
1895 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1896     $extension = pathinfo($filename, PATHINFO_EXTENSION);
1897     if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1898         return true;
1899     }
1900     return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1903 /**
1904  * Checks if mimetype $mimetype belongs to one of the groups $groups
1905  *
1906  * @see get_mimetypes_array()
1907  * @param string $mimetype
1908  * @param string|array $groups one group or array of groups to check
1909  * @return bool
1910  */
1911 function file_mimetype_in_typegroup($mimetype, $groups) {
1912     return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1915 /**
1916  * Requested file is not found or not accessible, does not return, terminates script
1917  *
1918  * @global stdClass $CFG
1919  * @global stdClass $COURSE
1920  */
1921 function send_file_not_found() {
1922     global $CFG, $COURSE;
1923     send_header_404();
1924     print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1926 /**
1927  * Helper function to send correct 404 for server.
1928  */
1929 function send_header_404() {
1930     if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1931         header("Status: 404 Not Found");
1932     } else {
1933         header('HTTP/1.0 404 not found');
1934     }
1937 /**
1938  * Enhanced readfile() with optional acceleration.
1939  * @param string|stored_file $file
1940  * @param string $mimetype
1941  * @param bool $accelerate
1942  * @return void
1943  */
1944 function readfile_accel($file, $mimetype, $accelerate) {
1945     global $CFG;
1947     if ($mimetype === 'text/plain') {
1948         // there is no encoding specified in text files, we need something consistent
1949         header('Content-Type: text/plain; charset=utf-8');
1950     } else {
1951         header('Content-Type: '.$mimetype);
1952     }
1954     $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1955     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1957     if (is_object($file)) {
1958         header('Etag: "' . $file->get_contenthash() . '"');
1959         if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1960             header('HTTP/1.1 304 Not Modified');
1961             return;
1962         }
1963     }
1965     // if etag present for stored file rely on it exclusively
1966     if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1967         // get unixtime of request header; clip extra junk off first
1968         $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1969         if ($since && $since >= $lastmodified) {
1970             header('HTTP/1.1 304 Not Modified');
1971             return;
1972         }
1973     }
1975     if ($accelerate and !empty($CFG->xsendfile)) {
1976         if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1977             header('Accept-Ranges: bytes');
1978         } else {
1979             header('Accept-Ranges: none');
1980         }
1982         if (is_object($file)) {
1983             $fs = get_file_storage();
1984             if ($fs->xsendfile($file->get_contenthash())) {
1985                 return;
1986             }
1988         } else {
1989             require_once("$CFG->libdir/xsendfilelib.php");
1990             if (xsendfile($file)) {
1991                 return;
1992             }
1993         }
1994     }
1996     $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1998     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2000     if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2001         header('Accept-Ranges: bytes');
2003         if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2004             // byteserving stuff - for acrobat reader and download accelerators
2005             // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2006             // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2007             $ranges = false;
2008             if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2009                 foreach ($ranges as $key=>$value) {
2010                     if ($ranges[$key][1] == '') {
2011                         //suffix case
2012                         $ranges[$key][1] = $filesize - $ranges[$key][2];
2013                         $ranges[$key][2] = $filesize - 1;
2014                     } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2015                         //fix range length
2016                         $ranges[$key][2] = $filesize - 1;
2017                     }
2018                     if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2019                         //invalid byte-range ==> ignore header
2020                         $ranges = false;
2021                         break;
2022                     }
2023                     //prepare multipart header
2024                     $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2025                     $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2026                 }
2027             } else {
2028                 $ranges = false;
2029             }
2030             if ($ranges) {
2031                 if (is_object($file)) {
2032                     $handle = $file->get_content_file_handle();
2033                 } else {
2034                     $handle = fopen($file, 'rb');
2035                 }
2036                 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2037             }
2038         }
2039     } else {
2040         // Do not byteserve
2041         header('Accept-Ranges: none');
2042     }
2044     header('Content-Length: '.$filesize);
2046     if ($filesize > 10000000) {
2047         // for large files try to flush and close all buffers to conserve memory
2048         while(@ob_get_level()) {
2049             if (!@ob_end_flush()) {
2050                 break;
2051             }
2052         }
2053     }
2055     // send the whole file content
2056     if (is_object($file)) {
2057         $file->readfile();
2058     } else {
2059         readfile($file);
2060     }
2063 /**
2064  * Similar to readfile_accel() but designed for strings.
2065  * @param string $string
2066  * @param string $mimetype
2067  * @param bool $accelerate
2068  * @return void
2069  */
2070 function readstring_accel($string, $mimetype, $accelerate) {
2071     global $CFG;
2073     if ($mimetype === 'text/plain') {
2074         // there is no encoding specified in text files, we need something consistent
2075         header('Content-Type: text/plain; charset=utf-8');
2076     } else {
2077         header('Content-Type: '.$mimetype);
2078     }
2079     header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2080     header('Accept-Ranges: none');
2082     if ($accelerate and !empty($CFG->xsendfile)) {
2083         $fs = get_file_storage();
2084         if ($fs->xsendfile(sha1($string))) {
2085             return;
2086         }
2087     }
2089     header('Content-Length: '.strlen($string));
2090     echo $string;
2093 /**
2094  * Handles the sending of temporary file to user, download is forced.
2095  * File is deleted after abort or successful sending, does not return, script terminated
2096  *
2097  * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2098  * @param string $filename proposed file name when saving file
2099  * @param bool $pathisstring If the path is string
2100  */
2101 function send_temp_file($path, $filename, $pathisstring=false) {
2102     global $CFG;
2104     if (check_browser_version('Firefox', '1.5')) {
2105         // only FF is known to correctly save to disk before opening...
2106         $mimetype = mimeinfo('type', $filename);
2107     } else {
2108         $mimetype = 'application/x-forcedownload';
2109     }
2111     // close session - not needed anymore
2112     session_get_instance()->write_close();
2114     if (!$pathisstring) {
2115         if (!file_exists($path)) {
2116             send_header_404();
2117             print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2118         }
2119         // executed after normal finish or abort
2120         @register_shutdown_function('send_temp_file_finished', $path);
2121     }
2123     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2124     if (check_browser_version('MSIE')) {
2125         $filename = urlencode($filename);
2126     }
2128     header('Content-Disposition: attachment; filename="'.$filename.'"');
2129     if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2130         header('Cache-Control: max-age=10');
2131         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2132         header('Pragma: ');
2133     } else { //normal http - prevent caching at all cost
2134         header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2135         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2136         header('Pragma: no-cache');
2137     }
2139     // send the contents - we can not accelerate this because the file will be deleted asap
2140     if ($pathisstring) {
2141         readstring_accel($path, $mimetype, false);
2142     } else {
2143         readfile_accel($path, $mimetype, false);
2144         @unlink($path);
2145     }
2147     die; //no more chars to output
2150 /**
2151  * Internal callback function used by send_temp_file()
2152  *
2153  * @param string $path
2154  */
2155 function send_temp_file_finished($path) {
2156     if (file_exists($path)) {
2157         @unlink($path);
2158     }
2161 /**
2162  * Handles the sending of file data to the user's browser, including support for
2163  * byteranges etc.
2164  *
2165  * @category files
2166  * @param string $path Path of file on disk (including real filename), or actual content of file as string
2167  * @param string $filename Filename to send
2168  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2169  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2170  * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2171  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2172  * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2173  * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2174  *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2175  *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
2176  *                        and should not be reopened.
2177  * @return null script execution stopped unless $dontdie is true
2178  */
2179 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2180     global $CFG, $COURSE;
2182     if ($dontdie) {
2183         ignore_user_abort(true);
2184     }
2186     // MDL-11789, apply $CFG->filelifetime here
2187     if ($lifetime === 'default') {
2188         if (!empty($CFG->filelifetime)) {
2189             $lifetime = $CFG->filelifetime;
2190         } else {
2191             $lifetime = 86400;
2192         }
2193     }
2195     session_get_instance()->write_close(); // unlock session during fileserving
2197     // Use given MIME type if specified, otherwise guess it using mimeinfo.
2198     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2199     // only Firefox saves all files locally before opening when content-disposition: attachment stated
2200     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2201     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2202                          ($mimetype ? $mimetype : mimeinfo('type', $filename));
2204     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2205     if (check_browser_version('MSIE')) {
2206         $filename = rawurlencode($filename);
2207     }
2209     if ($forcedownload) {
2210         header('Content-Disposition: attachment; filename="'.$filename.'"');
2211     } else {
2212         header('Content-Disposition: inline; filename="'.$filename.'"');
2213     }
2215     if ($lifetime > 0) {
2216         $nobyteserving = false;
2217         header('Cache-Control: max-age='.$lifetime);
2218         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2219         header('Pragma: ');
2221     } else { // Do not cache files in proxies and browsers
2222         $nobyteserving = true;
2223         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2224             header('Cache-Control: max-age=10');
2225             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2226             header('Pragma: ');
2227         } else { //normal http - prevent caching at all cost
2228             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2229             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2230             header('Pragma: no-cache');
2231         }
2232     }
2234     if (empty($filter)) {
2235         // send the contents
2236         if ($pathisstring) {
2237             readstring_accel($path, $mimetype, !$dontdie);
2238         } else {
2239             readfile_accel($path, $mimetype, !$dontdie);
2240         }
2242     } else {
2243         // Try to put the file through filters
2244         if ($mimetype == 'text/html') {
2245             $options = new stdClass();
2246             $options->noclean = true;
2247             $options->nocache = true; // temporary workaround for MDL-5136
2248             $text = $pathisstring ? $path : implode('', file($path));
2250             $text = file_modify_html_header($text);
2251             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2253             readstring_accel($output, $mimetype, false);
2255         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2256             // only filter text if filter all files is selected
2257             $options = new stdClass();
2258             $options->newlines = false;
2259             $options->noclean = true;
2260             $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2261             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2263             readstring_accel($output, $mimetype, false);
2265         } else {
2266             // send the contents
2267             if ($pathisstring) {
2268                 readstring_accel($path, $mimetype, !$dontdie);
2269             } else {
2270                 readfile_accel($path, $mimetype, !$dontdie);
2271             }
2272         }
2273     }
2274     if ($dontdie) {
2275         return;
2276     }
2277     die; //no more chars to output!!!
2280 /**
2281  * Handles the sending of file data to the user's browser, including support for
2282  * byteranges etc.
2283  *
2284  * The $options parameter supports the following keys:
2285  *  (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2286  *  (string|null) filename - overrides the implicit filename
2287  *  (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2288  *      if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2289  *      you must detect this case when control is returned using connection_aborted. Please not that session is closed
2290  *      and should not be reopened.
2291  *
2292  * @category files
2293  * @param stored_file $stored_file local file object
2294  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2295  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2296  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2297  * @param array $options additional options affecting the file serving
2298  * @return null script execution stopped unless $options['dontdie'] is true
2299  */
2300 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2301     global $CFG, $COURSE;
2303     if (empty($options['filename'])) {
2304         $filename = null;
2305     } else {
2306         $filename = $options['filename'];
2307     }
2309     if (empty($options['dontdie'])) {
2310         $dontdie = false;
2311     } else {
2312         $dontdie = true;
2313     }
2315     if (!empty($options['preview'])) {
2316         // replace the file with its preview
2317         $fs = get_file_storage();
2318         $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2319         if (!$preview_file) {
2320             // unable to create a preview of the file, send its default mime icon instead
2321             if ($options['preview'] === 'tinyicon') {
2322                 $size = 24;
2323             } else if ($options['preview'] === 'thumb') {
2324                 $size = 90;
2325             } else {
2326                 $size = 256;
2327             }
2328             $fileicon = file_file_icon($stored_file, $size);
2329             send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2330         } else {
2331             // preview images have fixed cache lifetime and they ignore forced download
2332             // (they are generated by GD and therefore they are considered reasonably safe).
2333             $stored_file = $preview_file;
2334             $lifetime = DAYSECS;
2335             $filter = 0;
2336             $forcedownload = false;
2337         }
2338     }
2340     // handle external resource
2341     if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2342         $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2343         die;
2344     }
2346     if (!$stored_file or $stored_file->is_directory()) {
2347         // nothing to serve
2348         if ($dontdie) {
2349             return;
2350         }
2351         die;
2352     }
2354     if ($dontdie) {
2355         ignore_user_abort(true);
2356     }
2358     session_get_instance()->write_close(); // unlock session during fileserving
2360     // Use given MIME type if specified, otherwise guess it using mimeinfo.
2361     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2362     // only Firefox saves all files locally before opening when content-disposition: attachment stated
2363     $filename     = is_null($filename) ? $stored_file->get_filename() : $filename;
2364     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2365     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2366                          ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2368     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2369     if (check_browser_version('MSIE')) {
2370         $filename = rawurlencode($filename);
2371     }
2373     if ($forcedownload) {
2374         header('Content-Disposition: attachment; filename="'.$filename.'"');
2375     } else {
2376         header('Content-Disposition: inline; filename="'.$filename.'"');
2377     }
2379     if ($lifetime > 0) {
2380         header('Cache-Control: max-age='.$lifetime);
2381         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2382         header('Pragma: ');
2384     } else { // Do not cache files in proxies and browsers
2385         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2386             header('Cache-Control: max-age=10');
2387             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2388             header('Pragma: ');
2389         } else { //normal http - prevent caching at all cost
2390             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2391             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2392             header('Pragma: no-cache');
2393         }
2394     }
2396     if (empty($filter)) {
2397         // send the contents
2398         readfile_accel($stored_file, $mimetype, !$dontdie);
2400     } else {     // Try to put the file through filters
2401         if ($mimetype == 'text/html') {
2402             $options = new stdClass();
2403             $options->noclean = true;
2404             $options->nocache = true; // temporary workaround for MDL-5136
2405             $text = $stored_file->get_content();
2406             $text = file_modify_html_header($text);
2407             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2409             readstring_accel($output, $mimetype, false);
2411         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2412             // only filter text if filter all files is selected
2413             $options = new stdClass();
2414             $options->newlines = false;
2415             $options->noclean = true;
2416             $text = $stored_file->get_content();
2417             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2419             readstring_accel($output, $mimetype, false);
2421         } else {    // Just send it out raw
2422             readfile_accel($stored_file, $mimetype, !$dontdie);
2423         }
2424     }
2425     if ($dontdie) {
2426         return;
2427     }
2428     die; //no more chars to output!!!
2431 /**
2432  * Retrieves an array of records from a CSV file and places
2433  * them into a given table structure
2434  *
2435  * @global stdClass $CFG
2436  * @global moodle_database $DB
2437  * @param string $file The path to a CSV file
2438  * @param string $table The table to retrieve columns from
2439  * @return bool|array Returns an array of CSV records or false
2440  */
2441 function get_records_csv($file, $table) {
2442     global $CFG, $DB;
2444     if (!$metacolumns = $DB->get_columns($table)) {
2445         return false;
2446     }
2448     if(!($handle = @fopen($file, 'r'))) {
2449         print_error('get_records_csv failed to open '.$file);
2450     }
2452     $fieldnames = fgetcsv($handle, 4096);
2453     if(empty($fieldnames)) {
2454         fclose($handle);
2455         return false;
2456     }
2458     $columns = array();
2460     foreach($metacolumns as $metacolumn) {
2461         $ord = array_search($metacolumn->name, $fieldnames);
2462         if(is_int($ord)) {
2463             $columns[$metacolumn->name] = $ord;
2464         }
2465     }
2467     $rows = array();
2469     while (($data = fgetcsv($handle, 4096)) !== false) {
2470         $item = new stdClass;
2471         foreach($columns as $name => $ord) {
2472             $item->$name = $data[$ord];
2473         }
2474         $rows[] = $item;
2475     }
2477     fclose($handle);
2478     return $rows;
2481 /**
2482  * Create a file with CSV contents
2483  *
2484  * @global stdClass $CFG
2485  * @global moodle_database $DB
2486  * @param string $file The file to put the CSV content into
2487  * @param array $records An array of records to write to a CSV file
2488  * @param string $table The table to get columns from
2489  * @return bool success
2490  */
2491 function put_records_csv($file, $records, $table = NULL) {
2492     global $CFG, $DB;
2494     if (empty($records)) {
2495         return true;
2496     }
2498     $metacolumns = NULL;
2499     if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2500         return false;
2501     }
2503     echo "x";
2505     if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2506         print_error('put_records_csv failed to open '.$file);
2507     }
2509     $proto = reset($records);
2510     if(is_object($proto)) {
2511         $fields_records = array_keys(get_object_vars($proto));
2512     }
2513     else if(is_array($proto)) {
2514         $fields_records = array_keys($proto);
2515     }
2516     else {
2517         return false;
2518     }
2519     echo "x";
2521     if(!empty($metacolumns)) {
2522         $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2523         $fields = array_intersect($fields_records, $fields_table);
2524     }
2525     else {
2526         $fields = $fields_records;
2527     }
2529     fwrite($fp, implode(',', $fields));
2530     fwrite($fp, "\r\n");
2532     foreach($records as $record) {
2533         $array  = (array)$record;
2534         $values = array();
2535         foreach($fields as $field) {
2536             if(strpos($array[$field], ',')) {
2537                 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2538             }
2539             else {
2540                 $values[] = $array[$field];
2541             }
2542         }
2543         fwrite($fp, implode(',', $values)."\r\n");
2544     }
2546     fclose($fp);
2547     @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
2548     return true;
2552 /**
2553  * Recursively delete the file or folder with path $location. That is,
2554  * if it is a file delete it. If it is a folder, delete all its content
2555  * then delete it. If $location does not exist to start, that is not
2556  * considered an error.
2557  *
2558  * @param string $location the path to remove.
2559  * @return bool
2560  */
2561 function fulldelete($location) {
2562     if (empty($location)) {
2563         // extra safety against wrong param
2564         return false;
2565     }
2566     if (is_dir($location)) {
2567         if (!$currdir = opendir($location)) {
2568             return false;
2569         }
2570         while (false !== ($file = readdir($currdir))) {
2571             if ($file <> ".." && $file <> ".") {
2572                 $fullfile = $location."/".$file;
2573                 if (is_dir($fullfile)) {
2574                     if (!fulldelete($fullfile)) {
2575                         return false;
2576                     }
2577                 } else {
2578                     if (!unlink($fullfile)) {
2579                         return false;
2580                     }
2581                 }
2582             }
2583         }
2584         closedir($currdir);
2585         if (! rmdir($location)) {
2586             return false;
2587         }
2589     } else if (file_exists($location)) {
2590         if (!unlink($location)) {
2591             return false;
2592         }
2593     }
2594     return true;
2597 /**
2598  * Send requested byterange of file.
2599  *
2600  * @param resource $handle A file handle
2601  * @param string $mimetype The mimetype for the output
2602  * @param array $ranges An array of ranges to send
2603  * @param string $filesize The size of the content if only one range is used
2604  */
2605 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2606     // better turn off any kind of compression and buffering
2607     @ini_set('zlib.output_compression', 'Off');
2609     $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2610     if ($handle === false) {
2611         die;
2612     }
2613     if (count($ranges) == 1) { //only one range requested
2614         $length = $ranges[0][2] - $ranges[0][1] + 1;
2615         header('HTTP/1.1 206 Partial content');
2616         header('Content-Length: '.$length);
2617         header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2618         header('Content-Type: '.$mimetype);
2620         while(@ob_get_level()) {
2621             if (!@ob_end_flush()) {
2622                 break;
2623             }
2624         }
2626         fseek($handle, $ranges[0][1]);
2627         while (!feof($handle) && $length > 0) {
2628             @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2629             $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2630             echo $buffer;
2631             flush();
2632             $length -= strlen($buffer);
2633         }
2634         fclose($handle);
2635         die;
2636     } else { // multiple ranges requested - not tested much
2637         $totallength = 0;
2638         foreach($ranges as $range) {
2639             $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2640         }
2641         $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2642         header('HTTP/1.1 206 Partial content');
2643         header('Content-Length: '.$totallength);
2644         header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2646         while(@ob_get_level()) {
2647             if (!@ob_end_flush()) {
2648                 break;
2649             }
2650         }
2652         foreach($ranges as $range) {
2653             $length = $range[2] - $range[1] + 1;
2654             echo $range[0];
2655             fseek($handle, $range[1]);
2656             while (!feof($handle) && $length > 0) {
2657                 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2658                 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2659                 echo $buffer;
2660                 flush();
2661                 $length -= strlen($buffer);
2662             }
2663         }
2664         echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2665         fclose($handle);
2666         die;
2667     }
2670 /**
2671  * add includes (js and css) into uploaded files
2672  * before returning them, useful for themes and utf.js includes
2673  *
2674  * @global stdClass $CFG
2675  * @param string $text text to search and replace
2676  * @return string text with added head includes
2677  * @todo MDL-21120
2678  */
2679 function file_modify_html_header($text) {
2680     // first look for <head> tag
2681     global $CFG;
2683     $stylesheetshtml = '';
2684 /*    foreach ($CFG->stylesheets as $stylesheet) {
2685         //TODO: MDL-21120
2686         $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2687     }*/
2689     $ufo = '';
2690     if (filter_is_enabled('mediaplugin')) {
2691         // this script is needed by most media filter plugins.
2692         $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2693         $ufo = html_writer::tag('script', '', $attributes) . "\n";
2694     }
2696     preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2697     if ($matches) {
2698         $replacement = '<head>'.$ufo.$stylesheetshtml;
2699         $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2700         return $text;
2701     }
2703     // if not, look for <html> tag, and stick <head> right after
2704     preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2705     if ($matches) {
2706         // replace <html> tag with <html><head>includes</head>
2707         $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2708         $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2709         return $text;
2710     }
2712     // if not, look for <body> tag, and stick <head> before body
2713     preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2714     if ($matches) {
2715         $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2716         $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2717         return $text;
2718     }
2720     // if not, just stick a <head> tag at the beginning
2721     $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2722     return $text;
2725 /**
2726  * RESTful cURL class
2727  *
2728  * This is a wrapper class for curl, it is quite easy to use:
2729  * <code>
2730  * $c = new curl;
2731  * // enable cache
2732  * $c = new curl(array('cache'=>true));
2733  * // enable cookie
2734  * $c = new curl(array('cookie'=>true));
2735  * // enable proxy
2736  * $c = new curl(array('proxy'=>true));
2737  *
2738  * // HTTP GET Method
2739  * $html = $c->get('http://example.com');
2740  * // HTTP POST Method
2741  * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2742  * // HTTP PUT Method
2743  * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2744  * </code>
2745  *
2746  * @package   core_files
2747  * @category files
2748  * @copyright Dongsheng Cai <dongsheng@moodle.com>
2749  * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
2750  */
2751 class curl {
2752     /** @var bool Caches http request contents */
2753     public  $cache    = false;
2754     /** @var bool Uses proxy, null means automatic based on URL */
2755     public  $proxy    = null;
2756     /** @var string library version */
2757     public  $version  = '0.4 dev';
2758     /** @var array http's response */
2759     public  $response = array();
2760     /** @var array Raw response headers, needed for BC in download_file_content(). */
2761     public $rawresponse = array();
2762     /** @var array http header */
2763     public  $header   = array();
2764     /** @var string cURL information */
2765     public  $info;
2766     /** @var string error */
2767     public  $error;
2768     /** @var int error code */
2769     public  $errno;
2770     /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2771     public $emulateredirects = null;
2773     /** @var array cURL options */
2774     private $options;
2775     /** @var string Proxy host */
2776     private $proxy_host = '';
2777     /** @var string Proxy auth */
2778     private $proxy_auth = '';
2779     /** @var string Proxy type */
2780     private $proxy_type = '';
2781     /** @var bool Debug mode on */
2782     private $debug    = false;
2783     /** @var bool|string Path to cookie file */
2784     private $cookie   = false;
2785     /** @var bool tracks multiple headers in response - redirect detection */
2786     private $responsefinished = false;
2788     /**
2789      * Curl constructor.
2790      *
2791      * Allowed settings are:
2792      *  proxy: (bool) use proxy server, null means autodetect non-local from url
2793      *  debug: (bool) use debug output
2794      *  cookie: (string) path to cookie file, false if none
2795      *  cache: (bool) use cache
2796      *  module_cache: (string) type of cache
2797      *
2798      * @param array $settings
2799      */
2800     public function __construct($settings = array()) {
2801         global $CFG;
2802         if (!function_exists('curl_init')) {
2803             $this->error = 'cURL module must be enabled!';
2804             trigger_error($this->error, E_USER_ERROR);
2805             return false;
2806         }
2808         // All settings of this class should be init here.
2809         $this->resetopt();
2810         if (!empty($settings['debug'])) {
2811             $this->debug = true;
2812         }
2813         if (!empty($settings['cookie'])) {
2814             if($settings['cookie'] === true) {
2815                 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2816             } else {
2817                 $this->cookie = $settings['cookie'];
2818             }
2819         }
2820         if (!empty($settings['cache'])) {
2821             if (class_exists('curl_cache')) {
2822                 if (!empty($settings['module_cache'])) {
2823                     $this->cache = new curl_cache($settings['module_cache']);
2824                 } else {
2825                     $this->cache = new curl_cache('misc');
2826                 }
2827             }
2828         }
2829         if (!empty($CFG->proxyhost)) {
2830             if (empty($CFG->proxyport)) {
2831                 $this->proxy_host = $CFG->proxyhost;
2832             } else {
2833                 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2834             }
2835             if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2836                 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2837                 $this->setopt(array(
2838                             'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2839                             'proxyuserpwd'=>$this->proxy_auth));
2840             }
2841             if (!empty($CFG->proxytype)) {
2842                 if ($CFG->proxytype == 'SOCKS5') {
2843                     $this->proxy_type = CURLPROXY_SOCKS5;
2844                 } else {
2845                     $this->proxy_type = CURLPROXY_HTTP;
2846                     $this->setopt(array('httpproxytunnel'=>false));
2847                 }
2848                 $this->setopt(array('proxytype'=>$this->proxy_type));
2849             }
2851             if (isset($settings['proxy'])) {
2852                 $this->proxy = $settings['proxy'];
2853             }
2854         } else {
2855             $this->proxy = false;
2856         }
2858         if (!isset($this->emulateredirects)) {
2859             $this->emulateredirects = (ini_get('open_basedir') or ini_get('safe_mode'));
2860         }
2861     }
2863     /**
2864      * Resets the CURL options that have already been set
2865      */
2866     public function resetopt() {
2867         $this->options = array();
2868         $this->options['CURLOPT_USERAGENT']         = 'MoodleBot/1.0';
2869         // True to include the header in the output
2870         $this->options['CURLOPT_HEADER']            = 0;
2871         // True to Exclude the body from the output
2872         $this->options['CURLOPT_NOBODY']            = 0;
2873         // Redirect ny default.
2874         $this->options['CURLOPT_FOLLOWLOCATION']    = 1;
2875         $this->options['CURLOPT_MAXREDIRS']         = 10;
2876         $this->options['CURLOPT_ENCODING']          = '';
2877         // TRUE to return the transfer as a string of the return
2878         // value of curl_exec() instead of outputting it out directly.
2879         $this->options['CURLOPT_RETURNTRANSFER']    = 1;
2880         $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
2881         $this->options['CURLOPT_SSL_VERIFYHOST']    = 2;
2882         $this->options['CURLOPT_CONNECTTIMEOUT']    = 30;
2884         if ($cacert = self::get_cacert()) {
2885             $this->options['CURLOPT_CAINFO'] = $cacert;
2886         }
2887     }
2889     /**
2890      * Get the location of ca certificates.
2891      * @return string absolute file path or empty if default used
2892      */
2893     public static function get_cacert() {
2894         global $CFG;
2896         // Bundle in dataroot always wins.
2897         if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2898             return realpath("$CFG->dataroot/moodleorgca.crt");
2899         }
2901         // Next comes the default from php.ini
2902         $cacert = ini_get('curl.cainfo');
2903         if (!empty($cacert) and is_readable($cacert)) {
2904             return realpath($cacert);
2905         }
2907         // Windows PHP does not have any certs, we need to use something.
2908         if ($CFG->ostype === 'WINDOWS') {
2909             if (is_readable("$CFG->libdir/cacert.pem")) {
2910                 return realpath("$CFG->libdir/cacert.pem");
2911             }
2912         }
2914         // Use default, this should work fine on all properly configured *nix systems.
2915         return null;
2916     }
2918     /**
2919      * Reset Cookie
2920      */
2921     public function resetcookie() {
2922         if (!empty($this->cookie)) {
2923             if (is_file($this->cookie)) {
2924                 $fp = fopen($this->cookie, 'w');
2925                 if (!empty($fp)) {
2926                     fwrite($fp, '');
2927                     fclose($fp);
2928                 }
2929             }
2930         }
2931     }
2933     /**
2934      * Set curl options.
2935      *
2936      * Do not use the curl constants to define the options, pass a string
2937      * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2938      * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2939      *
2940      * @param array $options If array is null, this function will reset the options to default value.
2941      * @return void
2942      * @throws coding_exception If an option uses constant value instead of option name.
2943      */
2944     public function setopt($options = array()) {
2945         if (is_array($options)) {
2946             foreach ($options as $name => $val) {
2947                 if (!is_string($name)) {
2948                     throw new coding_exception('Curl options should be defined using strings, not constant values.');
2949                 }
2950                 if (stripos($name, 'CURLOPT_') === false) {
2951                     $name = strtoupper('CURLOPT_'.$name);
2952                 } else {
2953                     $name = strtoupper($name);
2954                 }
2955                 $this->options[$name] = $val;
2956             }
2957         }
2958     }
2960     /**
2961      * Reset http method
2962      */
2963     public function cleanopt() {
2964         unset($this->options['CURLOPT_HTTPGET']);
2965         unset($this->options['CURLOPT_POST']);
2966         unset($this->options['CURLOPT_POSTFIELDS']);
2967         unset($this->options['CURLOPT_PUT']);
2968         unset($this->options['CURLOPT_INFILE']);
2969         unset($this->options['CURLOPT_INFILESIZE']);
2970         unset($this->options['CURLOPT_CUSTOMREQUEST']);
2971         unset($this->options['CURLOPT_FILE']);
2972     }
2974     /**
2975      * Resets the HTTP Request headers (to prepare for the new request)
2976      */
2977     public function resetHeader() {
2978         $this->header = array();
2979     }
2981     /**
2982      * Set HTTP Request Header
2983      *
2984      * @param array $header
2985      */
2986     public function setHeader($header) {
2987         if (is_array($header)) {
2988             foreach ($header as $v) {
2989                 $this->setHeader($v);
2990             }
2991         } else {
2992             // Remove newlines, they are not allowed in headers.
2993             $this->header[] = preg_replace('/[\r\n]/', '', $header);
2994         }
2995     }
2997     /**
2998      * Get HTTP Response Headers
2999      * @return array of arrays
3000      */
3001     public function getResponse() {
3002         return $this->response;
3003     }
3005     /**
3006      * Get raw HTTP Response Headers
3007      * @return array of strings
3008      */
3009     public function get_raw_response() {
3010         return $this->rawresponse;
3011     }
3013     /**
3014      * private callback function
3015      * Formatting HTTP Response Header
3016      *
3017      * @param resource $ch Apparently not used
3018      * @param string $header
3019      * @return int The strlen of the header
3020      */
3021     private function formatHeader($ch, $header) {
3022         $this->rawresponse[] = $header;
3024         if (trim($header, "\r\n") === '') {
3025             if ($this->responsefinished) {
3026                 // Multiple headers means redirect, keep just the latest one.
3027                 $this->response = array();
3028                 return strlen($header);
3029             }
3030             $this->responsefinished = true;
3031         }
3033         if (strlen($header) > 2) {
3034             list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3035             $key = rtrim($key, ':');
3036             if (!empty($this->response[$key])) {
3037                 if (is_array($this->response[$key])) {
3038                     $this->response[$key][] = $value;
3039                 } else {
3040                     $tmp = $this->response[$key];
3041                     $this->response[$key] = array();
3042                     $this->response[$key][] = $tmp;
3043                     $this->response[$key][] = $value;
3045                 }
3046             } else {
3047                 $this->response[$key] = $value;
3048             }
3049         }
3050         return strlen($header);
3051     }
3053     /**
3054      * Set options for individual curl instance
3055      *
3056      * @param resource $curl A curl handle
3057      * @param array $options
3058      * @return resource The curl handle
3059      */
3060     private function apply_opt($curl, $options) {
3061         // Some more security first.
3062         if (defined('CURLOPT_PROTOCOLS')) {
3063             $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3064         }
3065         if (defined('CURLOPT_REDIR_PROTOCOLS')) {
3066             $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3067         }
3069         // Clean up
3070         $this->cleanopt();
3071         // set cookie
3072         if (!empty($this->cookie) || !empty($options['cookie'])) {
3073             $this->setopt(array('cookiejar'=>$this->cookie,
3074                             'cookiefile'=>$this->cookie
3075                              ));
3076         }
3078         // Bypass proxy if required.
3079         if ($this->proxy === null) {
3080             if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3081                 $proxy = false;
3082             } else {
3083                 $proxy = true;
3084             }
3085         } else {
3086             $proxy = (bool)$this->proxy;
3087         }
3089         // Set proxy.
3090         if ($proxy) {
3091             $options['CURLOPT_PROXY'] = $this->proxy_host;
3092         } else {
3093             unset($this->options['CURLOPT_PROXY']);
3094         }
3096         $this->setopt($options);
3097         // reset before set options
3098         curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3099         // set headers
3100         if (empty($this->header)) {
3101             $this->setHeader(array(
3102                 'User-Agent: MoodleBot/1.0',
3103                 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3104                 'Connection: keep-alive'
3105                 ));
3106         }
3107         curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3109         if ($this->debug) {
3110             echo '<h1>Options</h1>';
3111             var_dump($this->options);
3112             echo '<h1>Header</h1>';
3113             var_dump($this->header);
3114         }
3116         // Do not allow infinite redirects.
3117         if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3118             $this->options['CURLOPT_MAXREDIRS'] = 0;
3119         } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3120             $this->options['CURLOPT_MAXREDIRS'] = 100;
3121         } else {
3122             $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3123         }
3125         // Make sure we always know if redirects expected.
3126         if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3127             $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3128         }
3130         // Set options.
3131         foreach($this->options as $name => $val) {
3132             if ($name === 'CURLOPT_PROTOCOLS' or $name === 'CURLOPT_REDIR_PROTOCOLS') {
3133                 // These can not be changed, sorry.
3134                 continue;
3135             }
3136             if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3137                 // The redirects are emulated elsewhere.
3138                 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3139                 continue;
3140             }
3141             $name = constant($name);
3142             curl_setopt($curl, $name, $val);
3143         }
3145         return $curl;
3146     }
3148     /**
3149      * Download multiple files in parallel
3150      *
3151      * Calls {@link multi()} with specific download headers
3152      *
3153      * <code>
3154      * $c = new curl();
3155      * $file1 = fopen('a', 'wb');
3156      * $file2 = fopen('b', 'wb');
3157      * $c->download(array(
3158      *     array('url'=>'http://localhost/', 'file'=>$file1),
3159      *     array('url'=>'http://localhost/20/', 'file'=>$file2)
3160      * ));
3161      * fclose($file1);
3162      * fclose($file2);
3163      * </code>
3164      *
3165      * or
3166      *
3167      * <code>
3168      * $c = new curl();
3169      * $c->download(array(
3170      *              array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3171      *              array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3172      *              ));
3173      * </code>
3174      *
3175      * @param array $requests An array of files to request {
3176      *                  url => url to download the file [required]
3177      *                  file => file handler, or
3178      *                  filepath => file path
3179      * }
3180      * If 'file' and 'filepath' parameters are both specified in one request, the
3181      * open file handle in the 'file' parameter will take precedence and 'filepath'
3182      * will be ignored.
3183      *
3184      * @param array $options An array of options to set
3185      * @return array An array of results
3186      */
3187     public function download($requests, $options = array()) {
3188         $options['RETURNTRANSFER'] = false;
3189         return $this->multi($requests, $options);
3190     }
3192     /**
3193      * Multi HTTP Requests
3194      * This function could run multi-requests in parallel.
3195      *
3196      * @param array $requests An array of files to request
3197      * @param array $options An array of options to set
3198      * @return array An array of results
3199      */
3200     protected function multi($requests, $options = array()) {
3201         $count   = count($requests);
3202         $handles = array();
3203         $results = array();
3204         $main    = curl_multi_init();
3205         for ($i = 0; $i < $count; $i++) {
3206             if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3207                 // open file
3208                 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3209                 $requests[$i]['auto-handle'] = true;
3210             }
3211             foreach($requests[$i] as $n=>$v) {
3212                 $options[$n] = $v;
3213             }
3214             $handles[$i] = curl_init($requests[$i]['url']);
3215             $this->apply_opt($handles[$i], $options);
3216             curl_multi_add_handle($main, $handles[$i]);
3217         }
3218         $running = 0;
3219         do {
3220             curl_multi_exec($main, $running);
3221         } while($running > 0);
3222         for ($i = 0; $i < $count; $i++) {
3223             if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3224                 $results[] = true;
3225             } else {
3226                 $results[] = curl_multi_getcontent($handles[$i]);
3227             }
3228             curl_multi_remove_handle($main, $handles[$i]);
3229         }
3230         curl_multi_close($main);
3232         for ($i = 0; $i < $count; $i++) {
3233             if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3234                 // close file handler if file is opened in this function
3235                 fclose($requests[$i]['file']);
3236             }
3237         }
3238         return $results;
3239     }
3241     /**
3242      * Single HTTP Request
3243      *
3244      * @param string $url The URL to request
3245      * @param array $options
3246      * @return bool
3247      */
3248     protected function request($url, $options = array()) {
3249         // create curl instance
3250         $curl = curl_init($url);
3251         $options['url'] = $url;
3253         // Reset here so that the data is valid when result returned from cache.
3254         $this->info             = array();
3255         $this->error            = '';
3256         $this->errno            = 0;
3257         $this->response         = array();
3258         $this->rawresponse      = array();
3259         $this->responsefinished = false;
3261         $this->apply_opt($curl, $options);
3262         if ($this->cache && $ret = $this->cache->get($this->options)) {
3263             return $ret;
3264         }
3266         $ret = curl_exec($curl);
3267         $this->info  = curl_getinfo($curl);
3268         $this->error = curl_error($curl);
3269         $this->errno = curl_errno($curl);
3270         // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3272         if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3273             $redirects = 0;
3275             while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3277                 if ($this->info['http_code'] == 301) {
3278                     // Moved Permanently - repeat the same request on new URL.
3280                 } else if ($this->info['http_code'] == 302) {
3281                     // Found - the standard redirect - repeat the same request on new URL.
3283                 } else if ($this->info['http_code'] == 303) {
3284                     // 303 See Other - repeat only if GET, do not bother with POSTs.
3285                     if (empty($this->options['CURLOPT_HTTPGET'])) {
3286                         break;
3287                     }
3289                 } else if ($this->info['http_code'] == 307) {
3290                     // Temporary Redirect - must repeat using the same request type.
3292                 } else if ($this->info['http_code'] == 308) {
3293                     // Permanent Redirect - must repeat using the same request type.
3295                 } else {
3296                     // Some other http code means do not retry!
3297                     break;
3298                 }
3300                 $redirects++;
3302                 $redirecturl = null;
3303                 if (isset($this->info['redirect_url'])) {
3304                     if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3305                         $redirecturl = $this->info['redirect_url'];
3306                     }
3307                 }
3308                 if (!$redirecturl) {
3309                     foreach ($this->response as $k => $v) {
3310                         if (strtolower($k) === 'location') {
3311                             $redirecturl = $v;
3312                             break;
3313                         }
3314                     }
3315                     if (preg_match('|^https?://|i', $redirecturl)) {
3316                         // Great, this is the correct location format!
3318                     } else if ($redirecturl) {
3319                         $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3320                         if (strpos($redirecturl, '/') === 0) {
3321                             // Relative to server root - just guess.
3322                             $pos = strpos('/', $current, 8);
3323                             if ($pos === false) {
3324                                 $redirecturl = $current.$redirecturl;
3325                             } else {
3326                                 $redirecturl = substr($current, 0, $pos).$redirecturl;
3327                             }
3328                         } else {
3329                             // Relative to current script.
3330                             $redirecturl = dirname($current).'/'.$redirecturl;
3331                         }
3332                     }
3333                 }
3335                 $this->responsefinished = false;
3336                 $this->response = array();
3338                 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3339                 $ret = curl_exec($curl);
3341                 $this->info  = curl_getinfo($curl);
3342                 $this->error = curl_error($curl);
3343                 $this->errno = curl_errno($curl);
3345                 $this->info['redirect_count'] = $redirects;
3347                 if ($this->info['http_code'] === 200) {
3348                     // Finally this is what we wanted.
3349                     break;
3350                 }
3351                 if ($this->errno != CURLE_OK) {
3352                     // Something wrong is going on.
3353                     break;
3354                 }
3355             }
3356             if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3357                 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3358                 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3359             }
3360         }
3362         if ($this->cache) {
3363             $this->cache->set($this->options, $ret);
3364         }
3366         if ($this->debug) {
3367             echo '<h1>Return Data</h1>';
3368             var_dump($ret);
3369             echo '<h1>Info</h1>';
3370             var_dump($this->info);
3371             echo '<h1>Error</h1>';
3372             var_dump($this->error);
3373         }
3375         curl_close($curl);
3377         if (empty($this->error)) {
3378             return $ret;
3379         } else {
3380             return $this->error;
3381             // exception is not ajax friendly
3382             //throw new moodle_exception($this->error, 'curl');
3383         }
3384     }
3386     /**
3387      * HTTP HEAD method
3388      *
3389      * @see request()
3390      *
3391      * @param string $url
3392      * @param array $options
3393      * @return bool
3394      */
3395     public function head($url, $options = array()) {
3396         $options['CURLOPT_HTTPGET'] = 0;
3397         $options['CURLOPT_HEADER']  = 1;
3398         $options['CURLOPT_NOBODY']  = 1;
3399         return $this->request($url, $options);
3400     }
3402     /**
3403      * HTTP POST method
3404      *
3405      * @param string $url
3406      * @param array|string $params
3407      * @param array $options
3408      * @return bool
3409      */
3410     public function post($url, $params = '', $options = array()) {
3411         $options['CURLOPT_POST']       = 1;
3412         if (is_array($params)) {
3413             $this->_tmp_file_post_params = array();
3414             foreach ($params as $key => $value) {
3415                 if ($value instanceof stored_file) {
3416                     $value->add_to_curl_request($this, $key);
3417                 } else {
3418                     $this->_tmp_file_post_params[$key] = $value;
3419                 }
3420             }
3421             $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3422             unset($this->_tmp_file_post_params);
3423         } else {
3424             // $params is the raw post data
3425             $options['CURLOPT_POSTFIELDS'] = $params;
3426         }
3427         return $this->request($url, $options);
3428     }
3430     /**
3431      * HTTP GET method
3432      *
3433      * @param string $url
3434      * @param array $params
3435      * @param array $options
3436      * @return bool
3437      */
3438     public function get($url, $params = array(), $options = array()) {
3439         $options['CURLOPT_HTTPGET'] = 1;
3441         if (!empty($params)) {
3442             $url .= (stripos($url, '?') !== false) ? '&' : '?';
3443             $url .= http_build_query($params, '', '&');
3444         }
3445         return $this->request($url, $options);
3446     }
3448     /**
3449      * Downloads one file and writes it to the specified file handler
3450      *
3451      * <code>
3452      * $c = new curl();
3453      * $file = fopen('savepath', 'w');
3454      * $result = $c->download_one('http://localhost/', null,
3455      *   array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3456      * fclose($file);
3457      * $download_info = $c->get_info();
3458      * if ($result === true) {
3459      *   // file downloaded successfully
3460      * } else {
3461      *   $error_text = $result;
3462      *   $error_code = $c->get_errno();
3463      * }
3464      * </code>
3465      *
3466      * <code>
3467      * $c = new curl();
3468      * $result = $c->download_one('http://localhost/', null,
3469      *   array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3470      * // ... see above, no need to close handle and remove file if unsuccessful
3471      * </code>
3472      *
3473      * @param string $url
3474      * @param array|null $params key-value pairs to be added to $url as query string
3475      * @param array $options request options. Must include either 'file' or 'filepath'
3476      * @return bool|string true on success or error string on failure
3477      */
3478     public function download_one($url, $params, $options = array()) {
3479         $options['CURLOPT_HTTPGET'] = 1;
3480         if (!empty($params)) {
3481             $url .= (stripos($url, '?') !== false) ? '&' : '?';
3482             $url .= http_build_query($params, '', '&');
3483         }
3484         if (!empty($options['filepath']) && empty($options['file'])) {
3485             // open file
3486             if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3487                 $this->errno = 100;
3488                 return get_string('cannotwritefile', 'error', $options['filepath']);
3489             }
3490             $filepath = $options['filepath'];
3491         }
3492         unset($options['filepath']);
3493         $result = $this->request($url, $options);
3494         if (isset($filepath)) {
3495             fclose($options['file']);
3496             if ($result !== true) {
3497                 unlink($filepath);
3498             }
3499         }
3500         return $result;
3501     }
3503     /**
3504      * HTTP PUT method
3505      *
3506      * @param string $url
3507      * @param array $params
3508      * @param array $options