8a35373b8c3a70935370e09d76f04c95f214d290
[moodle.git] / lib / filelib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Functions for file handling.
19  *
20  * @package   core_files
21  * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 defined('MOODLE_INTERNAL') || die();
27 /**
28  * BYTESERVING_BOUNDARY - string unique string constant.
29  */
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38  * Encodes file serving url
39  *
40  * @deprecated use moodle_url factory methods instead
41  *
42  * @todo MDL-31071 deprecate this function
43  * @global stdClass $CFG
44  * @param string $urlbase
45  * @param string $path /filearea/itemid/dir/dir/file.exe
46  * @param bool $forcedownload
47  * @param bool $https https url required
48  * @return string encoded file url
49  */
50 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
51     global $CFG;
53 //TODO: deprecate this
55     if ($CFG->slasharguments) {
56         $parts = explode('/', $path);
57         $parts = array_map('rawurlencode', $parts);
58         $path  = implode('/', $parts);
59         $return = $urlbase.$path;
60         if ($forcedownload) {
61             $return .= '?forcedownload=1';
62         }
63     } else {
64         $path = rawurlencode($path);
65         $return = $urlbase.'?file='.$path;
66         if ($forcedownload) {
67             $return .= '&amp;forcedownload=1';
68         }
69     }
71     if ($https) {
72         $return = str_replace('http://', 'https://', $return);
73     }
75     return $return;
76 }
78 /**
79  * Prepares 'editor' formslib element from data in database
80  *
81  * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
82  * function then copies the embedded files into draft area (assigning itemids automatically),
83  * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
84  * displayed.
85  * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
86  * your mform's set_data() supplying the object returned by this function.
87  *
88  * @category files
89  * @param stdClass $data database field that holds the html text with embedded media
90  * @param string $field the name of the database field that holds the html text with embedded media
91  * @param array $options editor options (like maxifiles, maxbytes etc.)
92  * @param stdClass $context context of the editor
93  * @param string $component
94  * @param string $filearea file area name
95  * @param int $itemid item id, required if item exists
96  * @return stdClass modified data object
97  */
98 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
99     $options = (array)$options;
100     if (!isset($options['trusttext'])) {
101         $options['trusttext'] = false;
102     }
103     if (!isset($options['forcehttps'])) {
104         $options['forcehttps'] = false;
105     }
106     if (!isset($options['subdirs'])) {
107         $options['subdirs'] = false;
108     }
109     if (!isset($options['maxfiles'])) {
110         $options['maxfiles'] = 0; // no files by default
111     }
112     if (!isset($options['noclean'])) {
113         $options['noclean'] = false;
114     }
116     //sanity check for passed context. This function doesn't expect $option['context'] to be set
117     //But this function is called before creating editor hence, this is one of the best places to check
118     //if context is used properly. This check notify developer that they missed passing context to editor.
119     if (isset($context) && !isset($options['context'])) {
120         //if $context is not null then make sure $option['context'] is also set.
121         debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
122     } else if (isset($options['context']) && isset($context)) {
123         //If both are passed then they should be equal.
124         if ($options['context']->id != $context->id) {
125             $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
126             throw new coding_exception($exceptionmsg);
127         }
128     }
130     if (is_null($itemid) or is_null($context)) {
131         $contextid = null;
132         $itemid = null;
133         if (!isset($data)) {
134             $data = new stdClass();
135         }
136         if (!isset($data->{$field})) {
137             $data->{$field} = '';
138         }
139         if (!isset($data->{$field.'format'})) {
140             $data->{$field.'format'} = editors_get_preferred_format();
141         }
142         if (!$options['noclean']) {
143             $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
144         }
146     } else {
147         if ($options['trusttext']) {
148             // noclean ignored if trusttext enabled
149             if (!isset($data->{$field.'trust'})) {
150                 $data->{$field.'trust'} = 0;
151             }
152             $data = trusttext_pre_edit($data, $field, $context);
153         } else {
154             if (!$options['noclean']) {
155                 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
156             }
157         }
158         $contextid = $context->id;
159     }
161     if ($options['maxfiles'] != 0) {
162         $draftid_editor = file_get_submitted_draft_itemid($field);
163         $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
164         $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
165     } else {
166         $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
167     }
169     return $data;
172 /**
173  * Prepares the content of the 'editor' form element with embedded media files to be saved in database
174  *
175  * This function moves files from draft area to the destination area and
176  * encodes URLs to the draft files so they can be safely saved into DB. The
177  * form has to contain the 'editor' element named foobar_editor, where 'foobar'
178  * is the name of the database field to hold the wysiwyg editor content. The
179  * editor data comes as an array with text, format and itemid properties. This
180  * function automatically adds $data properties foobar, foobarformat and
181  * foobartrust, where foobar has URL to embedded files encoded.
182  *
183  * @category files
184  * @param stdClass $data raw data submitted by the form
185  * @param string $field name of the database field containing the html with embedded media files
186  * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
187  * @param stdClass $context context, required for existing data
188  * @param string $component file component
189  * @param string $filearea file area name
190  * @param int $itemid item id, required if item exists
191  * @return stdClass modified data object
192  */
193 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
194     $options = (array)$options;
195     if (!isset($options['trusttext'])) {
196         $options['trusttext'] = false;
197     }
198     if (!isset($options['forcehttps'])) {
199         $options['forcehttps'] = false;
200     }
201     if (!isset($options['subdirs'])) {
202         $options['subdirs'] = false;
203     }
204     if (!isset($options['maxfiles'])) {
205         $options['maxfiles'] = 0; // no files by default
206     }
207     if (!isset($options['maxbytes'])) {
208         $options['maxbytes'] = 0; // unlimited
209     }
211     if ($options['trusttext']) {
212         $data->{$field.'trust'} = trusttext_trusted($context);
213     } else {
214         $data->{$field.'trust'} = 0;
215     }
217     $editor = $data->{$field.'_editor'};
219     if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
220         $data->{$field} = $editor['text'];
221     } else {
222         $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
223     }
224     $data->{$field.'format'} = $editor['format'];
226     return $data;
229 /**
230  * Saves text and files modified by Editor formslib element
231  *
232  * @category files
233  * @param stdClass $data $database entry field
234  * @param string $field name of data field
235  * @param array $options various options
236  * @param stdClass $context context - must already exist
237  * @param string $component
238  * @param string $filearea file area name
239  * @param int $itemid must already exist, usually means data is in db
240  * @return stdClass modified data obejct
241  */
242 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
243     $options = (array)$options;
244     if (!isset($options['subdirs'])) {
245         $options['subdirs'] = false;
246     }
247     if (is_null($itemid) or is_null($context)) {
248         $itemid = null;
249         $contextid = null;
250     } else {
251         $contextid = $context->id;
252     }
254     $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
255     file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
256     $data->{$field.'_filemanager'} = $draftid_editor;
258     return $data;
261 /**
262  * Saves files modified by File manager formslib element
263  *
264  * @todo MDL-31073 review this function
265  * @category files
266  * @param stdClass $data $database entry field
267  * @param string $field name of data field
268  * @param array $options various options
269  * @param stdClass $context context - must already exist
270  * @param string $component
271  * @param string $filearea file area name
272  * @param int $itemid must already exist, usually means data is in db
273  * @return stdClass modified data obejct
274  */
275 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
276     $options = (array)$options;
277     if (!isset($options['subdirs'])) {
278         $options['subdirs'] = false;
279     }
280     if (!isset($options['maxfiles'])) {
281         $options['maxfiles'] = -1; // unlimited
282     }
283     if (!isset($options['maxbytes'])) {
284         $options['maxbytes'] = 0; // unlimited
285     }
287     if (empty($data->{$field.'_filemanager'})) {
288         $data->$field = '';
290     } else {
291         file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
292         $fs = get_file_storage();
294         if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
295             $data->$field = '1'; // TODO: this is an ugly hack (skodak)
296         } else {
297             $data->$field = '';
298         }
299     }
301     return $data;
304 /**
305  * Generate a draft itemid
306  *
307  * @category files
308  * @global moodle_database $DB
309  * @global stdClass $USER
310  * @return int a random but available draft itemid that can be used to create a new draft
311  * file area.
312  */
313 function file_get_unused_draft_itemid() {
314     global $DB, $USER;
316     if (isguestuser() or !isloggedin()) {
317         // guests and not-logged-in users can not be allowed to upload anything!!!!!!
318         print_error('noguest');
319     }
321     $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
323     $fs = get_file_storage();
324     $draftitemid = rand(1, 999999999);
325     while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
326         $draftitemid = rand(1, 999999999);
327     }
329     return $draftitemid;
332 /**
333  * Initialise a draft file area from a real one by copying the files. A draft
334  * area will be created if one does not already exist. Normally you should
335  * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
336  *
337  * @category files
338  * @global stdClass $CFG
339  * @global stdClass $USER
340  * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
341  * @param int $contextid This parameter and the next two identify the file area to copy files from.
342  * @param string $component
343  * @param string $filearea helps indentify the file area.
344  * @param int $itemid helps identify the file area. Can be null if there are no files yet.
345  * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
346  * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
347  * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
348  */
349 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
350     global $CFG, $USER, $CFG;
352     $options = (array)$options;
353     if (!isset($options['subdirs'])) {
354         $options['subdirs'] = false;
355     }
356     if (!isset($options['forcehttps'])) {
357         $options['forcehttps'] = false;
358     }
360     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
361     $fs = get_file_storage();
363     if (empty($draftitemid)) {
364         // create a new area and copy existing files into
365         $draftitemid = file_get_unused_draft_itemid();
366         $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
367         if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
368             foreach ($files as $file) {
369                 if ($file->is_directory() and $file->get_filepath() === '/') {
370                     // we need a way to mark the age of each draft area,
371                     // by not copying the root dir we force it to be created automatically with current timestamp
372                     continue;
373                 }
374                 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
375                     continue;
376                 }
377                 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
378                 // XXX: This is a hack for file manager (MDL-28666)
379                 // File manager needs to know the original file information before copying
380                 // to draft area, so we append these information in mdl_files.source field
381                 // {@link file_storage::search_references()}
382                 // {@link file_storage::search_references_count()}
383                 $sourcefield = $file->get_source();
384                 $newsourcefield = new stdClass;
385                 $newsourcefield->source = $sourcefield;
386                 $original = new stdClass;
387                 $original->contextid = $contextid;
388                 $original->component = $component;
389                 $original->filearea  = $filearea;
390                 $original->itemid    = $itemid;
391                 $original->filename  = $file->get_filename();
392                 $original->filepath  = $file->get_filepath();
393                 $newsourcefield->original = file_storage::pack_reference($original);
394                 $draftfile->set_source(serialize($newsourcefield));
395                 // End of file manager hack
396             }
397         }
398         if (!is_null($text)) {
399             // at this point there should not be any draftfile links yet,
400             // because this is a new text from database that should still contain the @@pluginfile@@ links
401             // this happens when developers forget to post process the text
402             $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
403         }
404     } else {
405         // nothing to do
406     }
408     if (is_null($text)) {
409         return null;
410     }
412     // relink embedded files - editor can not handle @@PLUGINFILE@@ !
413     return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
416 /**
417  * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
418  *
419  * @category files
420  * @global stdClass $CFG
421  * @param string $text The content that may contain ULRs in need of rewriting.
422  * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
423  * @param int $contextid This parameter and the next two identify the file area to use.
424  * @param string $component
425  * @param string $filearea helps identify the file area.
426  * @param int $itemid helps identify the file area.
427  * @param array $options text and file options ('forcehttps'=>false)
428  * @return string the processed text.
429  */
430 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
431     global $CFG;
433     $options = (array)$options;
434     if (!isset($options['forcehttps'])) {
435         $options['forcehttps'] = false;
436     }
438     if (!$CFG->slasharguments) {
439         $file = $file . '?file=';
440     }
442     $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
444     if ($itemid !== null) {
445         $baseurl .= "$itemid/";
446     }
448     if ($options['forcehttps']) {
449         $baseurl = str_replace('http://', 'https://', $baseurl);
450     }
452     return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
455 /**
456  * Returns information about files in a draft area.
457  *
458  * @global stdClass $CFG
459  * @global stdClass $USER
460  * @param int $draftitemid the draft area item id.
461  * @return array with the following entries:
462  *      'filecount' => number of files in the draft area.
463  * (more information will be added as needed).
464  */
465 function file_get_draft_area_info($draftitemid) {
466     global $CFG, $USER;
468     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
469     $fs = get_file_storage();
471     $results = array();
473     // The number of files
474     $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
475     $results['filecount'] = count($draftfiles);
476     $results['filesize'] = 0;
477     foreach ($draftfiles as $file) {
478         $results['filesize'] += $file->get_filesize();
479     }
481     return $results;
484 /**
485  * Get used space of files
486  * @global moodle_database $DB
487  * @global stdClass $USER
488  * @return int total bytes
489  */
490 function file_get_user_used_space() {
491     global $DB, $USER;
493     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
494     $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
495             JOIN (SELECT contenthash, filename, MAX(id) AS id
496             FROM {files}
497             WHERE contextid = ? AND component = ? AND filearea != ?
498             GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
499     $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
500     $record = $DB->get_record_sql($sql, $params);
501     return (int)$record->totalbytes;
504 /**
505  * Convert any string to a valid filepath
506  * @todo review this function
507  * @param string $str
508  * @return string path
509  */
510 function file_correct_filepath($str) { //TODO: what is this? (skodak)
511     if ($str == '/' or empty($str)) {
512         return '/';
513     } else {
514         return '/'.trim($str, './@#$ ').'/';
515     }
518 /**
519  * Generate a folder tree of draft area of current USER recursively
520  *
521  * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
522  * @param int $draftitemid
523  * @param string $filepath
524  * @param mixed $data
525  */
526 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
527     global $USER, $OUTPUT, $CFG;
528     $data->children = array();
529     $context = get_context_instance(CONTEXT_USER, $USER->id);
530     $fs = get_file_storage();
531     if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
532         foreach ($files as $file) {
533             if ($file->is_directory()) {
534                 $item = new stdClass();
535                 $item->sortorder = $file->get_sortorder();
536                 $item->filepath = $file->get_filepath();
538                 $foldername = explode('/', trim($item->filepath, '/'));
539                 $item->fullname = trim(array_pop($foldername), '/');
541                 $item->id = uniqid();
542                 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
543                 $data->children[] = $item;
544             } else {
545                 continue;
546             }
547         }
548     }
551 /**
552  * Listing all files (including folders) in current path (draft area)
553  * used by file manager
554  * @param int $draftitemid
555  * @param string $filepath
556  * @return stdClass
557  */
558 function file_get_drafarea_files($draftitemid, $filepath = '/') {
559     global $USER, $OUTPUT, $CFG;
561     $context = get_context_instance(CONTEXT_USER, $USER->id);
562     $fs = get_file_storage();
564     $data = new stdClass();
565     $data->path = array();
566     $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
568     // will be used to build breadcrumb
569     $trail = '/';
570     if ($filepath !== '/') {
571         $filepath = file_correct_filepath($filepath);
572         $parts = explode('/', $filepath);
573         foreach ($parts as $part) {
574             if ($part != '' && $part != null) {
575                 $trail .= ($part.'/');
576                 $data->path[] = array('name'=>$part, 'path'=>$trail);
577             }
578         }
579     }
581     $list = array();
582     $maxlength = 12;
583     if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
584         foreach ($files as $file) {
585             $item = new stdClass();
586             $item->filename = $file->get_filename();
587             $item->filepath = $file->get_filepath();
588             $item->fullname = trim($item->filename, '/');
589             $filesize = $file->get_filesize();
590             $item->size = $filesize ? $filesize : null;
591             $item->filesize = $filesize ? display_size($filesize) : '';
593             $item->sortorder = $file->get_sortorder();
594             $item->author = $file->get_author();
595             $item->license = $file->get_license();
596             $item->datemodified = $file->get_timemodified();
597             $item->datecreated = $file->get_timecreated();
598             $item->isref = $file->is_external_file();
599             // find the file this draft file was created from and count all references in local
600             // system pointing to that file
601             $source = unserialize($file->get_source());
602             if (isset($source->original)) {
603                 $item->refcount = $fs->search_references_count($source->original);
604             }
606             if ($file->is_directory()) {
607                 $item->filesize = 0;
608                 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
609                 $item->type = 'folder';
610                 $foldername = explode('/', trim($item->filepath, '/'));
611                 $item->fullname = trim(array_pop($foldername), '/');
612                 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
613             } else {
614                 // do NOT use file browser here!
615                 $item->mimetype = get_mimetype_description($file);
616                 if (file_mimetype_in_typegroup($item->mimetype, 'archive')) {
617                     $item->type = 'zip';
618                 } else {
619                     $item->type = 'file';
620                 }
621                 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
622                 $item->url = $itemurl->out();
623                 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
624                 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
625                 if ($imageinfo = $file->get_imageinfo()) {
626                     $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
627                     $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
628                     $item->image_width = $imageinfo['width'];
629                     $item->image_height = $imageinfo['height'];
630                 }
631             }
632             $list[] = $item;
633         }
634     }
635     $data->itemid = $draftitemid;
636     $data->list = $list;
637     return $data;
640 /**
641  * Returns draft area itemid for a given element.
642  *
643  * @category files
644  * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
645  * @return int the itemid, or 0 if there is not one yet.
646  */
647 function file_get_submitted_draft_itemid($elname) {
648     // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
649     if (!isset($_REQUEST[$elname])) {
650         return 0;
651     }
652     if (is_array($_REQUEST[$elname])) {
653         $param = optional_param_array($elname, 0, PARAM_INT);
654         if (!empty($param['itemid'])) {
655             $param = $param['itemid'];
656         } else {
657             debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
658             return false;
659         }
661     } else {
662         $param = optional_param($elname, 0, PARAM_INT);
663     }
665     if ($param) {
666         require_sesskey();
667     }
669     return $param;
672 /**
673  * Restore the original source field from draft files
674  *
675  * @param stored_file $storedfile This only works with draft files
676  * @return stored_file
677  */
678 function file_restore_source_field_from_draft_file($storedfile) {
679     $source = unserialize($storedfile->get_source());
680     if (!empty($source)) {
681         if (is_object($source)) {
682             $restoredsource = $source->source;
683             $storedfile->set_source($restoredsource);
684         } else {
685             throw new moodle_exception('invalidsourcefield', 'error');
686         }
687     }
688     return $storedfile;
690 /**
691  * Saves files from a draft file area to a real one (merging the list of files).
692  * Can rewrite URLs in some content at the same time if desired.
693  *
694  * @category files
695  * @global stdClass $USER
696  * @param int $draftitemid the id of the draft area to use. Normally obtained
697  *      from file_get_submitted_draft_itemid('elementname') or similar.
698  * @param int $contextid This parameter and the next two identify the file area to save to.
699  * @param string $component
700  * @param string $filearea indentifies the file area.
701  * @param int $itemid helps identifies the file area.
702  * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
703  * @param string $text some html content that needs to have embedded links rewritten
704  *      to the @@PLUGINFILE@@ form for saving in the database.
705  * @param bool $forcehttps force https urls.
706  * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
707  */
708 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
709     global $USER;
711     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
712     $fs = get_file_storage();
714     $options = (array)$options;
715     if (!isset($options['subdirs'])) {
716         $options['subdirs'] = false;
717     }
718     if (!isset($options['maxfiles'])) {
719         $options['maxfiles'] = -1; // unlimited
720     }
721     if (!isset($options['maxbytes'])) {
722         $options['maxbytes'] = 0; // unlimited
723     }
725     $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
726     $oldfiles   = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
728     if (count($draftfiles) < 2) {
729         // means there are no files - one file means root dir only ;-)
730         $fs->delete_area_files($contextid, $component, $filearea, $itemid);
732     } else if (count($oldfiles) < 2) {
733         $filecount = 0;
734         // there were no files before - one file means root dir only ;-)
735         $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
736         foreach ($draftfiles as $file) {
737             if (!$options['subdirs']) {
738                 if ($file->get_filepath() !== '/' or $file->is_directory()) {
739                     continue;
740                 }
741             }
742             if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
743                 // oversized file - should not get here at all
744                 continue;
745             }
746             if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
747                 // more files - should not get here at all
748                 break;
749             }
750             if (!$file->is_directory()) {
751                 $filecount++;
752             }
754             if ($file->is_external_file()) {
755                 $repoid = $file->get_repository_id();
756                 if (!empty($repoid)) {
757                     $file_record['repositoryid'] = $repoid;
758                     $file_record['reference'] = $file->get_reference();
759                 }
760             }
761             file_restore_source_field_from_draft_file($file);
763             $fs->create_file_from_storedfile($file_record, $file);
764         }
766     } else {
767         // we have to merge old and new files - we want to keep file ids for files that were not changed
768         // we change time modified for all new and changed files, we keep time created as is
769         $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
771         $newhashes = array();
772         foreach ($draftfiles as $file) {
773             $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
774             $newhashes[$newhash] = $file;
775         }
776         $filecount = 0;
777         foreach ($oldfiles as $oldfile) {
778             $oldhash = $oldfile->get_pathnamehash();
779             if (!isset($newhashes[$oldhash])) {
780                 // delete files not needed any more - deleted by user
781                 $oldfile->delete();
782                 continue;
783             }
785             $newfile = $newhashes[$oldhash];
786             // status changed, we delete old file, and create a new one
787             if ($oldfile->get_status() != $newfile->get_status()) {
788                 // file was changed, use updated with new timemodified data
789                 $oldfile->delete();
790                 // This file will be added later
791                 continue;
792             }
794             file_restore_source_field_from_draft_file($newfile);
795             // Replaced file content
796             if ($oldfile->get_contenthash() != $newfile->get_contenthash()) {
797                 $oldfile->replace_content_with($newfile);
798             }
799             // Updated author
800             if ($oldfile->get_author() != $newfile->get_author()) {
801                 $oldfile->set_author($newfile->get_author());
802             }
803             // Updated license
804             if ($oldfile->get_license() != $newfile->get_license()) {
805                 $oldfile->set_license($newfile->get_license());
806             }
808             // Updated file source
809             if ($oldfile->get_source() != $newfile->get_source()) {
810                 $oldfile->set_source($newfile->get_source());
811             }
813             // Updated sort order
814             if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
815                 $oldfile->set_sortorder($newfile->get_sortorder());
816             }
818             // Update file size
819             if ($oldfile->get_filesize() != $newfile->get_filesize()) {
820                 $oldfile->set_filesize($newfile->get_filesize());
821             }
823             // Update file timemodified
824             if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
825                 $oldfile->set_timemodified($newfile->get_timemodified());
826             }
828             // unchanged file or directory - we keep it as is
829             unset($newhashes[$oldhash]);
830             if (!$oldfile->is_directory()) {
831                 $filecount++;
832             }
833         }
835         // Add fresh file or the file which has changed status
836         // the size and subdirectory tests are extra safety only, the UI should prevent it
837         foreach ($newhashes as $file) {
838             if (!$options['subdirs']) {
839                 if ($file->get_filepath() !== '/' or $file->is_directory()) {
840                     continue;
841                 }
842             }
843             if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
844                 // oversized file - should not get here at all
845                 continue;
846             }
847             if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
848                 // more files - should not get here at all
849                 break;
850             }
851             if (!$file->is_directory()) {
852                 $filecount++;
853             }
855             if ($file->is_external_file()) {
856                 $repoid = $file->get_repository_id();
857                 if (!empty($repoid)) {
858                     $file_record['repositoryid'] = $repoid;
859                     $file_record['reference'] = $file->get_reference();
860                 }
861             }
863             $fs->create_file_from_storedfile($file_record, $file);
864         }
865     }
867     // note: do not purge the draft area - we clean up areas later in cron,
868     //       the reason is that user might press submit twice and they would loose the files,
869     //       also sometimes we might want to use hacks that save files into two different areas
871     if (is_null($text)) {
872         return null;
873     } else {
874         return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
875     }
878 /**
879  * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
880  * ready to be saved in the database. Normally, this is done automatically by
881  * {@link file_save_draft_area_files()}.
882  *
883  * @category files
884  * @param string $text the content to process.
885  * @param int $draftitemid the draft file area the content was using.
886  * @param bool $forcehttps whether the content contains https URLs. Default false.
887  * @return string the processed content.
888  */
889 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
890     global $CFG, $USER;
892     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
894     $wwwroot = $CFG->wwwroot;
895     if ($forcehttps) {
896         $wwwroot = str_replace('http://', 'https://', $wwwroot);
897     }
899     // relink embedded files if text submitted - no absolute links allowed in database!
900     $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
902     if (strpos($text, 'draftfile.php?file=') !== false) {
903         $matches = array();
904         preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
905         if ($matches) {
906             foreach ($matches[0] as $match) {
907                 $replace = str_ireplace('%2F', '/', $match);
908                 $text = str_replace($match, $replace, $text);
909             }
910         }
911         $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
912     }
914     return $text;
917 /**
918  * Set file sort order
919  *
920  * @global moodle_database $DB
921  * @param int $contextid the context id
922  * @param string $component file component
923  * @param string $filearea file area.
924  * @param int $itemid itemid.
925  * @param string $filepath file path.
926  * @param string $filename file name.
927  * @param int $sortorder the sort order of file.
928  * @return bool
929  */
930 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
931     global $DB;
932     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
933     if ($file_record = $DB->get_record('files', $conditions)) {
934         $sortorder = (int)$sortorder;
935         $file_record->sortorder = $sortorder;
936         $DB->update_record('files', $file_record);
937         return true;
938     }
939     return false;
942 /**
943  * reset file sort order number to 0
944  * @global moodle_database $DB
945  * @param int $contextid the context id
946  * @param string $component
947  * @param string $filearea file area.
948  * @param int|bool $itemid itemid.
949  * @return bool
950  */
951 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
952     global $DB;
954     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
955     if ($itemid !== false) {
956         $conditions['itemid'] = $itemid;
957     }
959     $file_records = $DB->get_records('files', $conditions);
960     foreach ($file_records as $file_record) {
961         $file_record->sortorder = 0;
962         $DB->update_record('files', $file_record);
963     }
964     return true;
967 /**
968  * Returns description of upload error
969  *
970  * @param int $errorcode found in $_FILES['filename.ext']['error']
971  * @return string error description string, '' if ok
972  */
973 function file_get_upload_error($errorcode) {
975     switch ($errorcode) {
976     case 0: // UPLOAD_ERR_OK - no error
977         $errmessage = '';
978         break;
980     case 1: // UPLOAD_ERR_INI_SIZE
981         $errmessage = get_string('uploadserverlimit');
982         break;
984     case 2: // UPLOAD_ERR_FORM_SIZE
985         $errmessage = get_string('uploadformlimit');
986         break;
988     case 3: // UPLOAD_ERR_PARTIAL
989         $errmessage = get_string('uploadpartialfile');
990         break;
992     case 4: // UPLOAD_ERR_NO_FILE
993         $errmessage = get_string('uploadnofilefound');
994         break;
996     // Note: there is no error with a value of 5
998     case 6: // UPLOAD_ERR_NO_TMP_DIR
999         $errmessage = get_string('uploadnotempdir');
1000         break;
1002     case 7: // UPLOAD_ERR_CANT_WRITE
1003         $errmessage = get_string('uploadcantwrite');
1004         break;
1006     case 8: // UPLOAD_ERR_EXTENSION
1007         $errmessage = get_string('uploadextension');
1008         break;
1010     default:
1011         $errmessage = get_string('uploadproblem');
1012     }
1014     return $errmessage;
1017 /**
1018  * Recursive function formating an array in POST parameter
1019  * @param array $arraydata - the array that we are going to format and add into &$data array
1020  * @param string $currentdata - a row of the final postdata array at instant T
1021  *                when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1022  * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1023  */
1024 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1025         foreach ($arraydata as $k=>$v) {
1026             $newcurrentdata = $currentdata;
1027             if (is_array($v)) { //the value is an array, call the function recursively
1028                 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1029                 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1030             }  else { //add the POST parameter to the $data array
1031                 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1032             }
1033         }
1036 /**
1037  * Transform a PHP array into POST parameter
1038  * (see the recursive function format_array_postdata_for_curlcall)
1039  * @param array $postdata
1040  * @return array containing all POST parameters  (1 row = 1 POST parameter)
1041  */
1042 function format_postdata_for_curlcall($postdata) {
1043         $data = array();
1044         foreach ($postdata as $k=>$v) {
1045             if (is_array($v)) {
1046                 $currentdata = urlencode($k);
1047                 format_array_postdata_for_curlcall($v, $currentdata, $data);
1048             }  else {
1049                 $data[] = urlencode($k).'='.urlencode($v);
1050             }
1051         }
1052         $convertedpostdata = implode('&', $data);
1053         return $convertedpostdata;
1056 /**
1057  * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1058  * Due to security concerns only downloads from http(s) sources are supported.
1059  *
1060  * @todo MDL-31073 add version test for '7.10.5'
1061  * @category files
1062  * @param string $url file url starting with http(s)://
1063  * @param array $headers http headers, null if none. If set, should be an
1064  *   associative array of header name => value pairs.
1065  * @param array $postdata array means use POST request with given parameters
1066  * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1067  *   (if false, just returns content)
1068  * @param int $timeout timeout for complete download process including all file transfer
1069  *   (default 5 minutes)
1070  * @param int $connecttimeout timeout for connection to server; this is the timeout that
1071  *   usually happens if the remote server is completely down (default 20 seconds);
1072  *   may not work when using proxy
1073  * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1074  *   Only use this when already in a trusted location.
1075  * @param string $tofile store the downloaded content to file instead of returning it.
1076  * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1077  *   filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1078  * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1079  */
1080 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1081     global $CFG;
1083     // some extra security
1084     $newlines = array("\r", "\n");
1085     if (is_array($headers) ) {
1086         foreach ($headers as $key => $value) {
1087             $headers[$key] = str_replace($newlines, '', $value);
1088         }
1089     }
1090     $url = str_replace($newlines, '', $url);
1091     if (!preg_match('|^https?://|i', $url)) {
1092         if ($fullresponse) {
1093             $response = new stdClass();
1094             $response->status        = 0;
1095             $response->headers       = array();
1096             $response->response_code = 'Invalid protocol specified in url';
1097             $response->results       = '';
1098             $response->error         = 'Invalid protocol specified in url';
1099             return $response;
1100         } else {
1101             return false;
1102         }
1103     }
1105     // check if proxy (if used) should be bypassed for this url
1106     $proxybypass = is_proxybypass($url);
1108     if (!$ch = curl_init($url)) {
1109         debugging('Can not init curl.');
1110         return false;
1111     }
1113     // set extra headers
1114     if (is_array($headers) ) {
1115         $headers2 = array();
1116         foreach ($headers as $key => $value) {
1117             $headers2[] = "$key: $value";
1118         }
1119         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1120     }
1122     if ($skipcertverify) {
1123         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1124     }
1126     // use POST if requested
1127     if (is_array($postdata)) {
1128         $postdata = format_postdata_for_curlcall($postdata);
1129         curl_setopt($ch, CURLOPT_POST, true);
1130         curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1131     }
1133     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1134     curl_setopt($ch, CURLOPT_HEADER, false);
1135     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1137     if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1138         // TODO: add version test for '7.10.5'
1139         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1140         curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1141     }
1143     if (!empty($CFG->proxyhost) and !$proxybypass) {
1144         // SOCKS supported in PHP5 only
1145         if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1146             if (defined('CURLPROXY_SOCKS5')) {
1147                 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1148             } else {
1149                 curl_close($ch);
1150                 if ($fullresponse) {
1151                     $response = new stdClass();
1152                     $response->status        = '0';
1153                     $response->headers       = array();
1154                     $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1155                     $response->results       = '';
1156                     $response->error         = 'SOCKS5 proxy is not supported in PHP4';
1157                     return $response;
1158                 } else {
1159                     debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1160                     return false;
1161                 }
1162             }
1163         }
1165         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1167         if (empty($CFG->proxyport)) {
1168             curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1169         } else {
1170             curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1171         }
1173         if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1174             curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1175             if (defined('CURLOPT_PROXYAUTH')) {
1176                 // any proxy authentication if PHP 5.1
1177                 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1178             }
1179         }
1180     }
1182     // set up header and content handlers
1183     $received = new stdClass();
1184     $received->headers = array(); // received headers array
1185     $received->tofile  = $tofile;
1186     $received->fh      = null;
1187     curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1188     if ($tofile) {
1189         curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1190     }
1192     if (!isset($CFG->curltimeoutkbitrate)) {
1193         //use very slow rate of 56kbps as a timeout speed when not set
1194         $bitrate = 56;
1195     } else {
1196         $bitrate = $CFG->curltimeoutkbitrate;
1197     }
1199     // try to calculate the proper amount for timeout from remote file size.
1200     // if disabled or zero, we won't do any checks nor head requests.
1201     if ($calctimeout && $bitrate > 0) {
1202         //setup header request only options
1203         curl_setopt_array ($ch, array(
1204             CURLOPT_RETURNTRANSFER => false,
1205             CURLOPT_NOBODY         => true)
1206         );
1208         curl_exec($ch);
1209         $info = curl_getinfo($ch);
1210         $err = curl_error($ch);
1212         if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1213             $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1214         }
1215         //reinstate affected curl options
1216         curl_setopt_array ($ch, array(
1217             CURLOPT_RETURNTRANSFER => true,
1218             CURLOPT_NOBODY         => false)
1219         );
1220     }
1222     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1223     $result = curl_exec($ch);
1225     // try to detect encoding problems
1226     if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1227         curl_setopt($ch, CURLOPT_ENCODING, 'none');
1228         $result = curl_exec($ch);
1229     }
1231     if ($received->fh) {
1232         fclose($received->fh);
1233     }
1235     if (curl_errno($ch)) {
1236         $error    = curl_error($ch);
1237         $error_no = curl_errno($ch);
1238         curl_close($ch);
1240         if ($fullresponse) {
1241             $response = new stdClass();
1242             if ($error_no == 28) {
1243                 $response->status    = '-100'; // mimic snoopy
1244             } else {
1245                 $response->status    = '0';
1246             }
1247             $response->headers       = array();
1248             $response->response_code = $error;
1249             $response->results       = false;
1250             $response->error         = $error;
1251             return $response;
1252         } else {
1253             debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1254             return false;
1255         }
1257     } else {
1258         $info = curl_getinfo($ch);
1259         curl_close($ch);
1261         if (empty($info['http_code'])) {
1262             // for security reasons we support only true http connections (Location: file:// exploit prevention)
1263             $response = new stdClass();
1264             $response->status        = '0';
1265             $response->headers       = array();
1266             $response->response_code = 'Unknown cURL error';
1267             $response->results       = false; // do NOT change this, we really want to ignore the result!
1268             $response->error         = 'Unknown cURL error';
1270         } else {
1271             $response = new stdClass();;
1272             $response->status        = (string)$info['http_code'];
1273             $response->headers       = $received->headers;
1274             $response->response_code = $received->headers[0];
1275             $response->results       = $result;
1276             $response->error         = '';
1277         }
1279         if ($fullresponse) {
1280             return $response;
1281         } else if ($info['http_code'] != 200) {
1282             debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1283             return false;
1284         } else {
1285             return $response->results;
1286         }
1287     }
1290 /**
1291  * internal implementation
1292  * @param stdClass $received
1293  * @param resource $ch
1294  * @param mixed $header
1295  * @return int header length
1296  */
1297 function download_file_content_header_handler($received, $ch, $header) {
1298     $received->headers[] = $header;
1299     return strlen($header);
1302 /**
1303  * internal implementation
1304  * @param stdClass $received
1305  * @param resource $ch
1306  * @param mixed $data
1307  */
1308 function download_file_content_write_handler($received, $ch, $data) {
1309     if (!$received->fh) {
1310         $received->fh = fopen($received->tofile, 'w');
1311         if ($received->fh === false) {
1312             // bad luck, file creation or overriding failed
1313             return 0;
1314         }
1315     }
1316     if (fwrite($received->fh, $data) === false) {
1317         // bad luck, write failed, let's abort completely
1318         return 0;
1319     }
1320     return strlen($data);
1323 /**
1324  * Returns a list of information about file types based on extensions.
1325  *
1326  * The following elements expected in value array for each extension:
1327  * 'type' - mimetype
1328  * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1329  *     or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1330  *     also files with bigger sizes under names
1331  *     FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1332  * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1333  *     commonly used in moodle the following groups:
1334  *       - web_image - image that can be included as <img> in HTML
1335  *       - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1336  *       - video - file that can be imported as video in text editor
1337  *       - audio - file that can be imported as audio in text editor
1338  *       - archive - we can extract files from this archive
1339  *       - spreadsheet - used for portfolio format
1340  *       - document - used for portfolio format
1341  *       - presentation - used for portfolio format
1342  * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1343  *     human-readable description for this filetype;
1344  *     Function {@link get_mimetype_description()} first looks at the presence of string for
1345  *     particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1346  *     attribute, if not found returns the value of 'type';
1347  * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1348  *     an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1349  *     this function will return first found icon; Especially usefull for types such as 'text/plain'
1350  *
1351  * @category files
1352  * @return array List of information about file types based on extensions.
1353  *   Associative array of extension (lower-case) to associative array
1354  *   from 'element name' to data. Current element names are 'type' and 'icon'.
1355  *   Unknown types should use the 'xxx' entry which includes defaults.
1356  */
1357 function &get_mimetypes_array() {
1358     static $mimearray = array (
1359         'xxx'  => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1360         '3gp'  => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1361         'aac'  => array ('type'=>'audio/aac', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1362         'ai'   => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1363         'aif'  => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1364         'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1365         'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1366         'applescript'  => array ('type'=>'text/plain', 'icon'=>'text'),
1367         'asc'  => array ('type'=>'text/plain', 'icon'=>'text'),
1368         'asm'  => array ('type'=>'text/plain', 'icon'=>'text'),
1369         'au'   => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1370         'avi'  => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video'), 'string'=>'video'),
1371         'bmp'  => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1372         'c'    => array ('type'=>'text/plain', 'icon'=>'text'),
1373         'cct'  => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1374         'cpp'  => array ('type'=>'text/plain', 'icon'=>'text'),
1375         'cs'   => array ('type'=>'application/x-csh', 'icon'=>'text'),
1376         'css'  => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1377         'csv'  => array ('type'=>'text/csv', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1378         'dv'   => array ('type'=>'video/x-dv', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1379         'dmg'  => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1381         'doc'  => array ('type'=>'application/msword', 'icon'=>'docx', 'groups'=>array('document')),
1382         'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx', 'groups'=>array('document')),
1383         'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docx'),
1384         'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'docx'),
1385         'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'docx'),
1387         'dcr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1388         'dif'  => array ('type'=>'video/x-dv', 'icon'=>'video', 'groups'=>array('mov'), 'string'=>'video'),
1389         'dir'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1390         'dxr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1391         'eps'  => array ('type'=>'application/postscript', 'icon'=>'eps'),
1392         'fdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1393         'flv'  => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video'), 'string'=>'video'),
1394         'f4v'  => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video'), 'string'=>'video'),
1395         'gif'  => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1396         'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1397         'tgz'  => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1398         'gz'   => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1399         'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1400         'h'    => array ('type'=>'text/plain', 'icon'=>'text'),
1401         'hpp'  => array ('type'=>'text/plain', 'icon'=>'text'),
1402         'hqx'  => array ('type'=>'application/mac-binhex40', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1403         'htc'  => array ('type'=>'text/x-component', 'icon'=>'html'),
1404         'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1405         'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1406         'htm'  => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1407         'ico'  => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1408         'ics'  => array ('type'=>'text/calendar', 'icon'=>'text'),
1409         'isf'  => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1410         'ist'  => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1411         'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1412         'jcb'  => array ('type'=>'text/xml', 'icon'=>'text'),
1413         'jcl'  => array ('type'=>'text/xml', 'icon'=>'text'),
1414         'jcw'  => array ('type'=>'text/xml', 'icon'=>'text'),
1415         'jmt'  => array ('type'=>'text/xml', 'icon'=>'text'),
1416         'jmx'  => array ('type'=>'text/xml', 'icon'=>'text'),
1417         'jpe'  => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1418         'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1419         'jpg'  => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1420         'jqz'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1421         'js'   => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1422         'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1423         'm'    => array ('type'=>'text/plain', 'icon'=>'text'),
1424         'mbz'  => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1425         'mov'  => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1426         'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1427         'm3u'  => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1428         'mp3'  => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1429         'mp4'  => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video'), 'string'=>'video'),
1430         'm4v'  => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video'), 'string'=>'video'),
1431         'm4a'  => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1432         'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video'), 'string'=>'video'),
1433         'mpe'  => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video'), 'string'=>'video'),
1434         'mpg'  => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video'), 'string'=>'video'),
1436         'odt'  => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt', 'groups'=>array('odt')),
1437         'ott'  => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt', 'groups'=>array('odt')),
1438         'oth'  => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt', 'groups'=>array('odh')),
1439         'odm'  => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odh'),
1440         'odg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1441         'otg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1442         'odp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1443         'otp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1444         'ods'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods', 'groups'=>array('spreadsheet')),
1445         'ots'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods', 'groups'=>array('spreadsheet')),
1446         'odc'  => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1447         'odf'  => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1448         'odb'  => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1449         'odi'  => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odg'),
1450         'oga'  => array ('type'=>'audio/ogg', 'icon'=>'wma', 'groups'=>array('audio'), 'string'=>'audio'),
1451         'ogg'  => array ('type'=>'audio/ogg', 'icon'=>'wma', 'groups'=>array('audio'), 'string'=>'audio'),
1452         'ogv'  => array ('type'=>'video/ogg', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1454         'pct'  => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1455         'pdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1456         'php'  => array ('type'=>'text/plain', 'icon'=>'text'),
1457         'pic'  => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1458         'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1459         'png'  => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1461         'pps'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx', 'groups'=>array('presentation')),
1462         'ppt'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx', 'groups'=>array('presentation')),
1463         'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1464         'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptx'),
1465         'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'pptx'),
1466         'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'pptx'),
1467         'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'pptx'),
1468         'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'pptx'),
1469         'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'pptx'),
1471         'ps'   => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1472         'qt'   => array ('type'=>'video/quicktime', 'icon'=>'mov', 'groups'=>array('video'), 'string'=>'video'),
1473         'ra'   => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1474         'ram'  => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1475         'rhb'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1476         'rm'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1477         'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1478         'rtf'  => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1479         'rtx'  => array ('type'=>'text/richtext', 'icon'=>'text'),
1480         'rv'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1481         'sh'   => array ('type'=>'application/x-sh', 'icon'=>'text'),
1482         'sit'  => array ('type'=>'application/x-stuffit', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1483         'smi'  => array ('type'=>'application/smil', 'icon'=>'text'),
1484         'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1485         'sqt'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1486         'svg'  => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1487         'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1488         'swa'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1489         'swf'  => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1490         'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1492         'sxw'  => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1493         'stw'  => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1494         'sxc'  => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'ods'),
1495         'stc'  => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'ods'),
1496         'sxd'  => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odg'),
1497         'std'  => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odg'),
1498         'sxi'  => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odp'),
1499         'sti'  => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odp'),
1500         'sxg'  => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1501         'sxm'  => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odf'),
1503         'tar'  => array ('type'=>'application/x-tar', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive'),
1504         'tif'  => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1505         'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1506         'tex'  => array ('type'=>'application/x-tex', 'icon'=>'text'),
1507         'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1508         'texinfo'  => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1509         'tsv'  => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1510         'txt'  => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1511         'wav'  => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1512         'webm'  => array ('type'=>'video/webm', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1513         'wmv'  => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1514         'asf'  => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1515         'xdp'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1516         'xfd'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1517         'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1519         'xls'  => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1520         'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1521         'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsx', 'groups'=>array('spreadsheet')),
1522         'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xlsx'),
1523         'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xlsx'),
1524         'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsx'),
1525         'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlsx'),
1527         'xml'  => array ('type'=>'application/xml', 'icon'=>'xml'),
1528         'xsl'  => array ('type'=>'text/xml', 'icon'=>'xml'),
1529         'zip'  => array ('type'=>'application/zip', 'icon'=>'zip', 'groups'=>array('archive'), 'string'=>'archive')
1530     );
1531     return $mimearray;
1534 /**
1535  * Obtains information about a filetype based on its extension. Will
1536  * use a default if no information is present about that particular
1537  * extension.
1538  *
1539  * @category files
1540  * @param string $element Desired information (usually 'icon'
1541  *   for icon filename or 'type' for MIME type. Can also be
1542  *   'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1543  * @param string $filename Filename we're looking up
1544  * @return string Requested piece of information from array
1545  */
1546 function mimeinfo($element, $filename) {
1547     global $CFG;
1548     $mimeinfo = & get_mimetypes_array();
1549     static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1551     $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1552     if (empty($filetype)) {
1553         $filetype = 'xxx'; // file without extension
1554     }
1555     if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1556         $iconsize = max(array(16, (int)$iconsizematch[1]));
1557         $filenames = array($mimeinfo['xxx']['icon']);
1558         if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1559             array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1560         }
1561         // find the file with the closest size, first search for specific icon then for default icon
1562         foreach ($filenames as $filename) {
1563             foreach ($iconpostfixes as $size => $postfix) {
1564                 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1565                 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1566                     return $filename.$postfix;
1567                 }
1568             }
1569         }
1570     } else if (isset($mimeinfo[$filetype][$element])) {
1571         return $mimeinfo[$filetype][$element];
1572     } else if (isset($mimeinfo['xxx'][$element])) {
1573         return $mimeinfo['xxx'][$element];   // By default
1574     } else {
1575         return null;
1576     }
1579 /**
1580  * Obtains information about a filetype based on the MIME type rather than
1581  * the other way around.
1582  *
1583  * @category files
1584  * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1585  * @param string $mimetype MIME type we're looking up
1586  * @return string Requested piece of information from array
1587  */
1588 function mimeinfo_from_type($element, $mimetype) {
1589     /* array of cached mimetype->extension associations */
1590     static $cached = array();
1591     $mimeinfo = & get_mimetypes_array();
1593     if (!array_key_exists($mimetype, $cached)) {
1594         $cached[$mimetype] = null;    
1595         foreach($mimeinfo as $filetype => $values) {
1596             if ($values['type'] == $mimetype) {
1597                 if ($cached[$mimetype] === null) {
1598                     $cached[$mimetype] = $filetype;
1599                 }
1600                 if (!empty($values['defaulticon'])) {
1601                     $cached[$mimetype] = $filetype;
1602                     break;
1603                 }
1604             }
1605         }
1606         if (empty($cached[$mimetype])) {
1607             $cached[$mimetype] = 'xxx';
1608         }
1609     }
1610     if ($element === 'extension') {
1611         return $cached[$mimetype];
1612     } else {
1613         return mimeinfo($element, '.'.$cached[$mimetype]);
1614     }
1617 /**
1618  * Return the relative icon path for a given file
1619  *
1620  * Usage:
1621  * <code>
1622  * // $file - instance of stored_file or file_info
1623  * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1624  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1625  * </code>
1626  * or
1627  * <code>
1628  * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1629  * </code>
1630  *
1631  * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1632  *     and $file->mimetype are expected)
1633  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1634  * @return string
1635  */
1636 function file_file_icon($file, $size = null) {
1637     if (!is_object($file)) {
1638         $file = (object)$file;
1639     }
1640     if (isset($file->filename)) {
1641         $filename = $file->filename;
1642     } else if (method_exists($file, 'get_filename')) {
1643         $filename = $file->get_filename();
1644     } else if (method_exists($file, 'get_visible_name')) {
1645         $filename = $file->get_visible_name();
1646     } else {
1647         $filename = '';
1648     }
1649     if (isset($file->mimetype)) {
1650         $mimetype = $file->mimetype;
1651     } else if (method_exists($file, 'get_mimetype')) {
1652         $mimetype = $file->get_mimetype();
1653     } else {
1654         $mimetype = '';
1655     }
1656     if ($filename && pathinfo($filename, PATHINFO_EXTENSION) &&
1657             (!$mimetype || mimeinfo('type', $filename) === $mimetype)) {
1658         // files with different extensions sharing the same mimetype (i.e. 'text/plain') may have different icons
1659         return file_extension_icon($filename, $size);
1660     } else {
1661         // if mimetype and extension do not match we assume that mimetype is more correct
1662         return file_mimetype_icon($mimetype, $size);
1663     }
1666 /**
1667  * Return the relative icon path for a folder image
1668  *
1669  * Usage:
1670  * <code>
1671  * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1672  * echo html_writer::empty_tag('img', array('src' => $icon));
1673  * </code>
1674  * or
1675  * <code>
1676  * echo $OUTPUT->pix_icon(file_folder_icon(32));
1677  * </code>
1678  *
1679  * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1680  * @return string
1681  */
1682 function file_folder_icon($iconsize = null) {
1683     global $CFG;
1684     static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1685     $iconsize = max(array(16, (int)$iconsize));
1686     foreach ($iconpostfixes as $size => $postfix) {
1687         $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1688         if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1689             return 'f/folder'.$postfix;
1690         }
1691     }
1694 /**
1695  * Returns the relative icon path for a given mime type
1696  *
1697  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1698  * a return the full path to an icon.
1699  *
1700  * <code>
1701  * $mimetype = 'image/jpg';
1702  * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1703  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1704  * </code>
1705  *
1706  * @category files
1707  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1708  * to conform with that.
1709  * @param string $mimetype The mimetype to fetch an icon for
1710  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1711  * @return string The relative path to the icon
1712  */
1713 function file_mimetype_icon($mimetype, $size = NULL) {
1714     return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1717 /**
1718  * Returns the relative icon path for a given file name
1719  *
1720  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1721  * a return the full path to an icon.
1722  *
1723  * <code>
1724  * $filename = '.jpg';
1725  * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1726  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1727  * </code>
1728  *
1729  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1730  * to conform with that.
1731  * @todo MDL-31074 Implement $size
1732  * @category files
1733  * @param string $filename The filename to get the icon for
1734  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1735  * @return string
1736  */
1737 function file_extension_icon($filename, $size = NULL) {
1738     return 'f/'.mimeinfo('icon'.$size, $filename);
1741 /**
1742  * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1743  * mimetypes.php language file.
1744  *
1745  * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1746  *   'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1747  *   have filename); In case of array/stdClass the field 'mimetype' is optional.
1748  * @param bool $capitalise If true, capitalises first character of result
1749  * @return string Text description
1750  */
1751 function get_mimetype_description($obj, $capitalise=false) {
1752     if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1753         // this is an instance of stored_file
1754         $mimetype = $obj->get_mimetype();
1755         $filename = $obj->get_filename();
1756     } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1757         // this is an instance of file_info
1758         $mimetype = $obj->get_mimetype();
1759         $filename = $obj->get_visible_name();
1760     } else if (is_array($obj) || is_object ($obj)) {
1761         $obj = (array)$obj;
1762         if (!empty($obj['filename'])) {
1763             $filename = $obj['filename'];
1764         } else {
1765             $filename = '';
1766         }
1767         if (!empty($obj['mimetype'])) {
1768             $mimetype = $obj['mimetype'];
1769         } else {
1770             $mimetype = mimeinfo('type', $filename);
1771         }
1772     } else {
1773         $mimetype = $obj;
1774         $filename = '';
1775     }
1776     $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1777     if (empty($extension)) {
1778         $mimetypestr = mimeinfo_from_type('string', $mimetype);
1779         $extension = mimeinfo_from_type('extension', $mimetype);
1780     } else {
1781         $mimetypestr = mimeinfo('string', $filename);
1782     }
1783     $chunks = explode('/', $mimetype, 2);
1784     $chunks[] = '';
1785     $attr = array(
1786         'mimetype' => $mimetype,
1787         'ext' => $extension,
1788         'mimetype1' => $chunks[0],
1789         'mimetype2' => $chunks[1],
1790     );
1791     $a = array();
1792     foreach ($attr as $key => $value) {
1793         $a[$key] = $value;
1794         $a[strtoupper($key)] = strtoupper($value);
1795         $a[ucfirst($key)] = ucfirst($value);
1796     }
1797     if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1798         $result = get_string($mimetype, 'mimetypes', (object)$a);
1799     } else if (get_string_manager()->string_exists($mimetypestr, 'mimetypes')) {
1800         $result = get_string($mimetypestr, 'mimetypes', (object)$a);
1801     } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1802         $result = get_string('default', 'mimetypes', (object)$a);
1803     } else {
1804         $result = $mimetype;
1805     }
1806     if ($capitalise) {
1807         $result=ucfirst($result);
1808     }
1809     return $result;
1812 /**
1813  * Returns array of elements of type $element in type group(s)
1814  *
1815  * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1816  * @param string|array $groups one group or array of groups/extensions/mimetypes
1817  * @return array
1818  */
1819 function file_get_typegroup($element, $groups) {
1820     static $cached = array();
1821     if (!is_array($groups)) {
1822         $groups = array($groups);
1823     }
1824     if (!array_key_exists($element, $cached)) {
1825         $cached[$element] = array();
1826     }
1827     $result = array();
1828     foreach ($groups as $group) {
1829         if (!array_key_exists($group, $cached[$element])) {
1830             // retrieive and cache all elements of type $element for group $group
1831             $mimeinfo = & get_mimetypes_array();
1832             $cached[$element][$group] = array();
1833             foreach ($mimeinfo as $extension => $value) {
1834                 $value['extension'] = $extension;
1835                 if (empty($value[$element])) {
1836                     continue;
1837                 }
1838                 if (($group === $extension || $group === $value['type'] ||
1839                         (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1840                         !in_array($value[$element], $cached[$element][$group])) {
1841                     $cached[$element][$group][] = $value[$element];
1842                 }
1843             }
1844         }
1845         $result = array_merge($result, $cached[$element][$group]);
1846     }
1847     return array_unique($result);
1850 /**
1851  * Checks if file with name $filename has one of the extensions in groups $groups
1852  *
1853  * @see get_mimetypes_array()
1854  * @param string $filename name of the file to check
1855  * @param string|array $groups one group or array of groups to check
1856  * @param bool $checktype if true and extension check fails, find the mimetype and check if
1857  * file mimetype is in mimetypes in groups $groups
1858  * @return bool
1859  */
1860 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1861     $extension = pathinfo($filename, PATHINFO_EXTENSION);
1862     if (!empty($extension) && in_array(strtolower($extension), file_get_typegroup('extension', $groups))) {
1863         return true;
1864     }
1865     return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1868 /**
1869  * Checks if mimetype $mimetype belongs to one of the groups $groups
1870  *
1871  * @see get_mimetypes_array()
1872  * @param string $mimetype
1873  * @param string|array $groups one group or array of groups to check
1874  * @return bool
1875  */
1876 function file_mimetype_in_typegroup($mimetype, $groups) {
1877     return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1880 /**
1881  * Requested file is not found or not accessible, does not return, terminates script
1882  *
1883  * @global stdClass $CFG
1884  * @global stdClass $COURSE
1885  */
1886 function send_file_not_found() {
1887     global $CFG, $COURSE;
1888     send_header_404();
1889     print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1891 /**
1892  * Helper function to send correct 404 for server.
1893  */
1894 function send_header_404() {
1895     if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1896         header("Status: 404 Not Found");
1897     } else {
1898         header('HTTP/1.0 404 not found');
1899     }
1902 /**
1903  * Enhanced readfile() with optional acceleration.
1904  * @param string|stored_file $file
1905  * @param string $mimetype
1906  * @param bool $accelerate
1907  * @return void
1908  */
1909 function readfile_accel($file, $mimetype, $accelerate) {
1910     global $CFG;
1912     if ($mimetype === 'text/plain') {
1913         // there is no encoding specified in text files, we need something consistent
1914         header('Content-Type: text/plain; charset=utf-8');
1915     } else {
1916         header('Content-Type: '.$mimetype);
1917     }
1919     $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1920     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1922     if (is_object($file)) {
1923         header('ETag: ' . $file->get_contenthash());
1924         if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1925             header('HTTP/1.1 304 Not Modified');
1926             return;
1927         }
1928     }
1930     // if etag present for stored file rely on it exclusively
1931     if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1932         // get unixtime of request header; clip extra junk off first
1933         $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1934         if ($since && $since >= $lastmodified) {
1935             header('HTTP/1.1 304 Not Modified');
1936             return;
1937         }
1938     }
1940     if ($accelerate and !empty($CFG->xsendfile)) {
1941         if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1942             header('Accept-Ranges: bytes');
1943         } else {
1944             header('Accept-Ranges: none');
1945         }
1947         if (is_object($file)) {
1948             $fs = get_file_storage();
1949             if ($fs->xsendfile($file->get_contenthash())) {
1950                 return;
1951             }
1953         } else {
1954             require_once("$CFG->libdir/xsendfilelib.php");
1955             if (xsendfile($file)) {
1956                 return;
1957             }
1958         }
1959     }
1961     $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1963     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1965     if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1966         header('Accept-Ranges: bytes');
1968         if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1969             // byteserving stuff - for acrobat reader and download accelerators
1970             // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1971             // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1972             $ranges = false;
1973             if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1974                 foreach ($ranges as $key=>$value) {
1975                     if ($ranges[$key][1] == '') {
1976                         //suffix case
1977                         $ranges[$key][1] = $filesize - $ranges[$key][2];
1978                         $ranges[$key][2] = $filesize - 1;
1979                     } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1980                         //fix range length
1981                         $ranges[$key][2] = $filesize - 1;
1982                     }
1983                     if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1984                         //invalid byte-range ==> ignore header
1985                         $ranges = false;
1986                         break;
1987                     }
1988                     //prepare multipart header
1989                     $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1990                     $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1991                 }
1992             } else {
1993                 $ranges = false;
1994             }
1995             if ($ranges) {
1996                 if (is_object($file)) {
1997                     $handle = $file->get_content_file_handle();
1998                 } else {
1999                     $handle = fopen($file, 'rb');
2000                 }
2001                 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2002             }
2003         }
2004     } else {
2005         // Do not byteserve
2006         header('Accept-Ranges: none');
2007     }
2009     header('Content-Length: '.$filesize);
2011     if ($filesize > 10000000) {
2012         // for large files try to flush and close all buffers to conserve memory
2013         while(@ob_get_level()) {
2014             if (!@ob_end_flush()) {
2015                 break;
2016             }
2017         }
2018     }
2020     // send the whole file content
2021     if (is_object($file)) {
2022         $file->readfile();
2023     } else {
2024         readfile($file);
2025     }
2028 /**
2029  * Similar to readfile_accel() but designed for strings.
2030  * @param string $string
2031  * @param string $mimetype
2032  * @param bool $accelerate
2033  * @return void
2034  */
2035 function readstring_accel($string, $mimetype, $accelerate) {
2036     global $CFG;
2038     if ($mimetype === 'text/plain') {
2039         // there is no encoding specified in text files, we need something consistent
2040         header('Content-Type: text/plain; charset=utf-8');
2041     } else {
2042         header('Content-Type: '.$mimetype);
2043     }
2044     header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2045     header('Accept-Ranges: none');
2047     if ($accelerate and !empty($CFG->xsendfile)) {
2048         $fs = get_file_storage();
2049         if ($fs->xsendfile(sha1($string))) {
2050             return;
2051         }
2052     }
2054     header('Content-Length: '.strlen($string));
2055     echo $string;
2058 /**
2059  * Handles the sending of temporary file to user, download is forced.
2060  * File is deleted after abort or successful sending, does not return, script terminated
2061  *
2062  * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2063  * @param string $filename proposed file name when saving file
2064  * @param bool $pathisstring If the path is string
2065  */
2066 function send_temp_file($path, $filename, $pathisstring=false) {
2067     global $CFG;
2069     if (check_browser_version('Firefox', '1.5')) {
2070         // only FF is known to correctly save to disk before opening...
2071         $mimetype = mimeinfo('type', $filename);
2072     } else {
2073         $mimetype = 'application/x-forcedownload';
2074     }
2076     // close session - not needed anymore
2077     session_get_instance()->write_close();
2079     if (!$pathisstring) {
2080         if (!file_exists($path)) {
2081             send_header_404();
2082             print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2083         }
2084         // executed after normal finish or abort
2085         @register_shutdown_function('send_temp_file_finished', $path);
2086     }
2088     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2089     if (check_browser_version('MSIE')) {
2090         $filename = urlencode($filename);
2091     }
2093     header('Content-Disposition: attachment; filename="'.$filename.'"');
2094     if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2095         header('Cache-Control: max-age=10');
2096         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2097         header('Pragma: ');
2098     } else { //normal http - prevent caching at all cost
2099         header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2100         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2101         header('Pragma: no-cache');
2102     }
2104     // send the contents - we can not accelerate this because the file will be deleted asap
2105     if ($pathisstring) {
2106         readstring_accel($path, $mimetype, false);
2107     } else {
2108         readfile_accel($path, $mimetype, false);
2109         @unlink($path);
2110     }
2112     die; //no more chars to output
2115 /**
2116  * Internal callback function used by send_temp_file()
2117  *
2118  * @param string $path
2119  */
2120 function send_temp_file_finished($path) {
2121     if (file_exists($path)) {
2122         @unlink($path);
2123     }
2126 /**
2127  * Handles the sending of file data to the user's browser, including support for
2128  * byteranges etc.
2129  *
2130  * @category files
2131  * @param string $path Path of file on disk (including real filename), or actual content of file as string
2132  * @param string $filename Filename to send
2133  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2134  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2135  * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2136  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2137  * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2138  * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2139  *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2140  *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
2141  *                        and should not be reopened.
2142  * @return null script execution stopped unless $dontdie is true
2143  */
2144 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2145     global $CFG, $COURSE;
2147     if ($dontdie) {
2148         ignore_user_abort(true);
2149     }
2151     // MDL-11789, apply $CFG->filelifetime here
2152     if ($lifetime === 'default') {
2153         if (!empty($CFG->filelifetime)) {
2154             $lifetime = $CFG->filelifetime;
2155         } else {
2156             $lifetime = 86400;
2157         }
2158     }
2160     session_get_instance()->write_close(); // unlock session during fileserving
2162     // Use given MIME type if specified, otherwise guess it using mimeinfo.
2163     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2164     // only Firefox saves all files locally before opening when content-disposition: attachment stated
2165     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2166     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2167                          ($mimetype ? $mimetype : mimeinfo('type', $filename));
2169     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2170     if (check_browser_version('MSIE')) {
2171         $filename = rawurlencode($filename);
2172     }
2174     if ($forcedownload) {
2175         header('Content-Disposition: attachment; filename="'.$filename.'"');
2176     } else {
2177         header('Content-Disposition: inline; filename="'.$filename.'"');
2178     }
2180     if ($lifetime > 0) {
2181         $nobyteserving = false;
2182         header('Cache-Control: max-age='.$lifetime);
2183         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2184         header('Pragma: ');
2186     } else { // Do not cache files in proxies and browsers
2187         $nobyteserving = true;
2188         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2189             header('Cache-Control: max-age=10');
2190             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2191             header('Pragma: ');
2192         } else { //normal http - prevent caching at all cost
2193             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2194             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2195             header('Pragma: no-cache');
2196         }
2197     }
2199     if (empty($filter)) {
2200         // send the contents
2201         if ($pathisstring) {
2202             readstring_accel($path, $mimetype, !$dontdie);
2203         } else {
2204             readfile_accel($path, $mimetype, !$dontdie);
2205         }
2207     } else {
2208         // Try to put the file through filters
2209         if ($mimetype == 'text/html') {
2210             $options = new stdClass();
2211             $options->noclean = true;
2212             $options->nocache = true; // temporary workaround for MDL-5136
2213             $text = $pathisstring ? $path : implode('', file($path));
2215             $text = file_modify_html_header($text);
2216             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2218             readstring_accel($output, $mimetype, false);
2220         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2221             // only filter text if filter all files is selected
2222             $options = new stdClass();
2223             $options->newlines = false;
2224             $options->noclean = true;
2225             $text = htmlentities($pathisstring ? $path : implode('', file($path)));
2226             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2228             readstring_accel($output, $mimetype, false);
2230         } else {
2231             // send the contents
2232             if ($pathisstring) {
2233                 readstring_accel($path, $mimetype, !$dontdie);
2234             } else {
2235                 readfile_accel($path, $mimetype, !$dontdie);
2236             }
2237         }
2238     }
2239     if ($dontdie) {
2240         return;
2241     }
2242     die; //no more chars to output!!!
2245 /**
2246  * Handles the sending of file data to the user's browser, including support for
2247  * byteranges etc.
2248  *
2249  * The $options parameter supports the following keys:
2250  *  (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2251  *  (string|null) filename - overrides the implicit filename
2252  *  (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2253  *      if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2254  *      you must detect this case when control is returned using connection_aborted. Please not that session is closed
2255  *      and should not be reopened.
2256  *
2257  * @category files
2258  * @param stored_file $stored_file local file object
2259  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2260  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2261  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2262  * @param array $options additional options affecting the file serving
2263  * @return null script execution stopped unless $options['dontdie'] is true
2264  */
2265 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2266     global $CFG, $COURSE;
2268     if (empty($options['filename'])) {
2269         $filename = null;
2270     } else {
2271         $filename = $options['filename'];
2272     }
2274     if (empty($options['dontdie'])) {
2275         $dontdie = false;
2276     } else {
2277         $dontdie = true;
2278     }
2280     if (!empty($options['preview'])) {
2281         // replace the file with its preview
2282         $fs = get_file_storage();
2283         $stored_file = $fs->get_file_preview($stored_file, $options['preview']);
2284         if (!$stored_file) {
2285             // unable to create a preview of the file
2286             send_header_404();
2287             die();
2288         } else {
2289             // preview images have fixed cache lifetime and they ignore forced download
2290             // (they are generated by GD and therefore they are considered reasonably safe).
2291             $lifetime = DAYSECS;
2292             $filter = 0;
2293             $forcedownload = false;
2294         }
2295     }
2297     // handle external resource
2298     if ($stored_file->is_external_file()) {
2299         $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2300         die;
2301     }
2303     if (!$stored_file or $stored_file->is_directory()) {
2304         // nothing to serve
2305         if ($dontdie) {
2306             return;
2307         }
2308         die;
2309     }
2311     if ($dontdie) {
2312         ignore_user_abort(true);
2313     }
2315     session_get_instance()->write_close(); // unlock session during fileserving
2317     // Use given MIME type if specified, otherwise guess it using mimeinfo.
2318     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2319     // only Firefox saves all files locally before opening when content-disposition: attachment stated
2320     $filename     = is_null($filename) ? $stored_file->get_filename() : $filename;
2321     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2322     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2323                          ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2325     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2326     if (check_browser_version('MSIE')) {
2327         $filename = rawurlencode($filename);
2328     }
2330     if ($forcedownload) {
2331         header('Content-Disposition: attachment; filename="'.$filename.'"');
2332     } else {
2333         header('Content-Disposition: inline; filename="'.$filename.'"');
2334     }
2336     if ($lifetime > 0) {
2337         header('Cache-Control: max-age='.$lifetime);
2338         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2339         header('Pragma: ');
2341     } else { // Do not cache files in proxies and browsers
2342         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2343             header('Cache-Control: max-age=10');
2344             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2345             header('Pragma: ');
2346         } else { //normal http - prevent caching at all cost
2347             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2348             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2349             header('Pragma: no-cache');
2350         }
2351     }
2353     if (empty($filter)) {
2354         // send the contents
2355         readfile_accel($stored_file, $mimetype, !$dontdie);
2357     } else {     // Try to put the file through filters
2358         if ($mimetype == 'text/html') {
2359             $options = new stdClass();
2360             $options->noclean = true;
2361             $options->nocache = true; // temporary workaround for MDL-5136
2362             $text = $stored_file->get_content();
2363             $text = file_modify_html_header($text);
2364             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2366             readstring_accel($output, $mimetype, false);
2368         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2369             // only filter text if filter all files is selected
2370             $options = new stdClass();
2371             $options->newlines = false;
2372             $options->noclean = true;
2373             $text = $stored_file->get_content();
2374             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2376             readstring_accel($output, $mimetype, false);
2378         } else {    // Just send it out raw
2379             readfile_accel($stored_file, $mimetype, !$dontdie);
2380         }
2381     }
2382     if ($dontdie) {
2383         return;
2384     }
2385     die; //no more chars to output!!!
2388 /**
2389  * Retrieves an array of records from a CSV file and places
2390  * them into a given table structure
2391  *
2392  * @global stdClass $CFG
2393  * @global moodle_database $DB
2394  * @param string $file The path to a CSV file
2395  * @param string $table The table to retrieve columns from
2396  * @return bool|array Returns an array of CSV records or false
2397  */
2398 function get_records_csv($file, $table) {
2399     global $CFG, $DB;
2401     if (!$metacolumns = $DB->get_columns($table)) {
2402         return false;
2403     }
2405     if(!($handle = @fopen($file, 'r'))) {
2406         print_error('get_records_csv failed to open '.$file);
2407     }
2409     $fieldnames = fgetcsv($handle, 4096);
2410     if(empty($fieldnames)) {
2411         fclose($handle);
2412         return false;
2413     }
2415     $columns = array();
2417     foreach($metacolumns as $metacolumn) {
2418         $ord = array_search($metacolumn->name, $fieldnames);
2419         if(is_int($ord)) {
2420             $columns[$metacolumn->name] = $ord;
2421         }
2422     }
2424     $rows = array();
2426     while (($data = fgetcsv($handle, 4096)) !== false) {
2427         $item = new stdClass;
2428         foreach($columns as $name => $ord) {
2429             $item->$name = $data[$ord];
2430         }
2431         $rows[] = $item;
2432     }
2434     fclose($handle);
2435     return $rows;
2438 /**
2439  * Create a file with CSV contents
2440  *
2441  * @global stdClass $CFG
2442  * @global moodle_database $DB
2443  * @param string $file The file to put the CSV content into
2444  * @param array $records An array of records to write to a CSV file
2445  * @param string $table The table to get columns from
2446  * @return bool success
2447  */
2448 function put_records_csv($file, $records, $table = NULL) {
2449     global $CFG, $DB;
2451     if (empty($records)) {
2452         return true;
2453     }
2455     $metacolumns = NULL;
2456     if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2457         return false;
2458     }
2460     echo "x";
2462     if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2463         print_error('put_records_csv failed to open '.$file);
2464     }
2466     $proto = reset($records);
2467     if(is_object($proto)) {
2468         $fields_records = array_keys(get_object_vars($proto));
2469     }
2470     else if(is_array($proto)) {
2471         $fields_records = array_keys($proto);
2472     }
2473     else {
2474         return false;
2475     }
2476     echo "x";
2478     if(!empty($metacolumns)) {
2479         $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2480         $fields = array_intersect($fields_records, $fields_table);
2481     }
2482     else {
2483         $fields = $fields_records;
2484     }
2486     fwrite($fp, implode(',', $fields));
2487     fwrite($fp, "\r\n");
2489     foreach($records as $record) {
2490         $array  = (array)$record;
2491         $values = array();
2492         foreach($fields as $field) {
2493             if(strpos($array[$field], ',')) {
2494                 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2495             }
2496             else {
2497                 $values[] = $array[$field];
2498             }
2499         }
2500         fwrite($fp, implode(',', $values)."\r\n");
2501     }
2503     fclose($fp);
2504     return true;
2508 /**
2509  * Recursively delete the file or folder with path $location. That is,
2510  * if it is a file delete it. If it is a folder, delete all its content
2511  * then delete it. If $location does not exist to start, that is not
2512  * considered an error.
2513  *
2514  * @param string $location the path to remove.
2515  * @return bool
2516  */
2517 function fulldelete($location) {
2518     if (empty($location)) {
2519         // extra safety against wrong param
2520         return false;
2521     }
2522     if (is_dir($location)) {
2523         $currdir = opendir($location);
2524         while (false !== ($file = readdir($currdir))) {
2525             if ($file <> ".." && $file <> ".") {
2526                 $fullfile = $location."/".$file;
2527                 if (is_dir($fullfile)) {
2528                     if (!fulldelete($fullfile)) {
2529                         return false;
2530                     }
2531                 } else {
2532                     if (!unlink($fullfile)) {
2533                         return false;
2534                     }
2535                 }
2536             }
2537         }
2538         closedir($currdir);
2539         if (! rmdir($location)) {
2540             return false;
2541         }
2543     } else if (file_exists($location)) {
2544         if (!unlink($location)) {
2545             return false;
2546         }
2547     }
2548     return true;
2551 /**
2552  * Send requested byterange of file.
2553  *
2554  * @param resource $handle A file handle
2555  * @param string $mimetype The mimetype for the output
2556  * @param array $ranges An array of ranges to send
2557  * @param string $filesize The size of the content if only one range is used
2558  */
2559 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2560     // better turn off any kind of compression and buffering
2561     @ini_set('zlib.output_compression', 'Off');
2563     $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2564     if ($handle === false) {
2565         die;
2566     }
2567     if (count($ranges) == 1) { //only one range requested
2568         $length = $ranges[0][2] - $ranges[0][1] + 1;
2569         header('HTTP/1.1 206 Partial content');
2570         header('Content-Length: '.$length);
2571         header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2572         header('Content-Type: '.$mimetype);
2574         while(@ob_get_level()) {
2575             if (!@ob_end_flush()) {
2576                 break;
2577             }
2578         }
2580         fseek($handle, $ranges[0][1]);
2581         while (!feof($handle) && $length > 0) {
2582             @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2583             $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2584             echo $buffer;
2585             flush();
2586             $length -= strlen($buffer);
2587         }
2588         fclose($handle);
2589         die;
2590     } else { // multiple ranges requested - not tested much
2591         $totallength = 0;
2592         foreach($ranges as $range) {
2593             $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2594         }
2595         $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2596         header('HTTP/1.1 206 Partial content');
2597         header('Content-Length: '.$totallength);
2598         header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2600         while(@ob_get_level()) {
2601             if (!@ob_end_flush()) {
2602                 break;
2603             }
2604         }
2606         foreach($ranges as $range) {
2607             $length = $range[2] - $range[1] + 1;
2608             echo $range[0];
2609             fseek($handle, $range[1]);
2610             while (!feof($handle) && $length > 0) {
2611                 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2612                 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2613                 echo $buffer;
2614                 flush();
2615                 $length -= strlen($buffer);
2616             }
2617         }
2618         echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2619         fclose($handle);
2620         die;
2621     }
2624 /**
2625  * add includes (js and css) into uploaded files
2626  * before returning them, useful for themes and utf.js includes
2627  *
2628  * @global stdClass $CFG
2629  * @param string $text text to search and replace
2630  * @return string text with added head includes
2631  * @todo MDL-21120
2632  */
2633 function file_modify_html_header($text) {
2634     // first look for <head> tag
2635     global $CFG;
2637     $stylesheetshtml = '';
2638 /*    foreach ($CFG->stylesheets as $stylesheet) {
2639         //TODO: MDL-21120
2640         $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2641     }*/
2643     $ufo = '';
2644     if (filter_is_enabled('filter/mediaplugin')) {
2645         // this script is needed by most media filter plugins.
2646         $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2647         $ufo = html_writer::tag('script', '', $attributes) . "\n";
2648     }
2650     preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2651     if ($matches) {
2652         $replacement = '<head>'.$ufo.$stylesheetshtml;
2653         $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2654         return $text;
2655     }
2657     // if not, look for <html> tag, and stick <head> right after
2658     preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2659     if ($matches) {
2660         // replace <html> tag with <html><head>includes</head>
2661         $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2662         $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2663         return $text;
2664     }
2666     // if not, look for <body> tag, and stick <head> before body
2667     preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2668     if ($matches) {
2669         $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2670         $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2671         return $text;
2672     }
2674     // if not, just stick a <head> tag at the beginning
2675     $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2676     return $text;
2679 /**
2680  * RESTful cURL class
2681  *
2682  * This is a wrapper class for curl, it is quite easy to use:
2683  * <code>
2684  * $c = new curl;
2685  * // enable cache
2686  * $c = new curl(array('cache'=>true));
2687  * // enable cookie
2688  * $c = new curl(array('cookie'=>true));
2689  * // enable proxy
2690  * $c = new curl(array('proxy'=>true));
2691  *
2692  * // HTTP GET Method
2693  * $html = $c->get('http://example.com');
2694  * // HTTP POST Method
2695  * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2696  * // HTTP PUT Method
2697  * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2698  * </code>
2699  *
2700  * @package   core_files
2701  * @category files
2702  * @copyright Dongsheng Cai <dongsheng@moodle.com>
2703  * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
2704  */
2705 class curl {
2706     /** @var bool Caches http request contents */
2707     public  $cache    = false;
2708     /** @var bool Uses proxy */
2709     public  $proxy    = false;
2710     /** @var string library version */
2711     public  $version  = '0.4 dev';
2712     /** @var array http's response */
2713     public  $response = array();
2714     /** @var array http header */
2715     public  $header   = array();
2716     /** @var string cURL information */
2717     public  $info;
2718     /** @var string error */
2719     public  $error;
2721     /** @var array cURL options */
2722     private $options;
2723     /** @var string Proxy host */
2724     private $proxy_host = '';
2725     /** @var string Proxy auth */
2726     private $proxy_auth = '';
2727     /** @var string Proxy type */
2728     private $proxy_type = '';
2729     /** @var bool Debug mode on */
2730     private $debug    = false;
2731     /** @var bool|string Path to cookie file */
2732     private $cookie   = false;
2734     /**
2735      * Constructor
2736      *
2737      * @global stdClass $CFG
2738      * @param array $options
2739      */
2740     public function __construct($options = array()){
2741         global $CFG;
2742         if (!function_exists('curl_init')) {
2743             $this->error = 'cURL module must be enabled!';
2744             trigger_error($this->error, E_USER_ERROR);
2745             return false;
2746         }
2747         // the options of curl should be init here.
2748         $this->resetopt();
2749         if (!empty($options['debug'])) {
2750             $this->debug = true;
2751         }
2752         if(!empty($options['cookie'])) {
2753             if($options['cookie'] === true) {
2754                 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2755             } else {
2756                 $this->cookie = $options['cookie'];
2757             }
2758         }
2759         if (!empty($options['cache'])) {
2760             if (class_exists('curl_cache')) {
2761                 if (!empty($options['module_cache'])) {
2762                     $this->cache = new curl_cache($options['module_cache']);
2763                 } else {
2764                     $this->cache = new curl_cache('misc');
2765                 }
2766             }
2767         }
2768         if (!empty($CFG->proxyhost)) {
2769             if (empty($CFG->proxyport)) {
2770                 $this->proxy_host = $CFG->proxyhost;
2771             } else {
2772                 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2773             }
2774             if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2775                 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2776                 $this->setopt(array(
2777                             'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2778                             'proxyuserpwd'=>$this->proxy_auth));
2779             }
2780             if (!empty($CFG->proxytype)) {
2781                 if ($CFG->proxytype == 'SOCKS5') {
2782                     $this->proxy_type = CURLPROXY_SOCKS5;
2783                 } else {
2784                     $this->proxy_type = CURLPROXY_HTTP;
2785                     $this->setopt(array('httpproxytunnel'=>false));
2786                 }
2787                 $this->setopt(array('proxytype'=>$this->proxy_type));
2788             }
2789         }
2790         if (!empty($this->proxy_host)) {
2791             $this->proxy = array('proxy'=>$this->proxy_host);
2792         }
2793     }
2794     /**
2795      * Resets the CURL options that have already been set
2796      */
2797     public function resetopt(){
2798         $this->options = array();
2799         $this->options['CURLOPT_USERAGENT']         = 'MoodleBot/1.0';
2800         // True to include the header in the output
2801         $this->options['CURLOPT_HEADER']            = 0;
2802         // True to Exclude the body from the output
2803         $this->options['CURLOPT_NOBODY']            = 0;
2804         // TRUE to follow any "Location: " header that the server
2805         // sends as part of the HTTP header (note this is recursive,
2806         // PHP will follow as many "Location: " headers that it is sent,
2807         // unless CURLOPT_MAXREDIRS is set).
2808         //$this->options['CURLOPT_FOLLOWLOCATION']    = 1;
2809         $this->options['CURLOPT_MAXREDIRS']         = 10;
2810         $this->options['CURLOPT_ENCODING']          = '';
2811         // TRUE to return the transfer as a string of the return
2812         // value of curl_exec() instead of outputting it out directly.
2813         $this->options['CURLOPT_RETURNTRANSFER']    = 1;
2814         $this->options['CURLOPT_BINARYTRANSFER']    = 0;
2815         $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
2816         $this->options['CURLOPT_SSL_VERIFYHOST']    = 2;
2817         $this->options['CURLOPT_CONNECTTIMEOUT']    = 30;
2818     }
2820     /**
2821      * Reset Cookie
2822      */
2823     public function resetcookie() {
2824         if (!empty($this->cookie)) {
2825             if (is_file($this->cookie)) {
2826                 $fp = fopen($this->cookie, 'w');
2827                 if (!empty($fp)) {
2828                     fwrite($fp, '');
2829                     fclose($fp);
2830                 }
2831             }
2832         }
2833     }
2835     /**
2836      * Set curl options
2837      *
2838      * @param array $options If array is null, this function will
2839      * reset the options to default value.
2840      */
2841     public function setopt($options = array()) {
2842         if (is_array($options)) {
2843             foreach($options as $name => $val){
2844                 if (stripos($name, 'CURLOPT_') === false) {
2845                     $name = strtoupper('CURLOPT_'.$name);
2846                 }
2847                 $this->options[$name] = $val;
2848             }
2849         }
2850     }
2852     /**
2853      * Reset http method
2854      */
2855     public function cleanopt(){
2856         unset($this->options['CURLOPT_HTTPGET']);
2857         unset($this->options['CURLOPT_POST']);
2858         unset($this->options['CURLOPT_POSTFIELDS']);
2859         unset($this->options['CURLOPT_PUT']);
2860         unset($this->options['CURLOPT_INFILE']);
2861         unset($this->options['CURLOPT_INFILESIZE']);
2862         unset($this->options['CURLOPT_CUSTOMREQUEST']);
2863     }
2865     /**
2866      * Set HTTP Request Header
2867      *
2868      * @param array $header
2869      */
2870     public function setHeader($header) {
2871         if (is_array($header)){
2872             foreach ($header as $v) {
2873                 $this->setHeader($v);
2874             }
2875         } else {
2876             $this->header[] = $header;
2877         }
2878     }
2880     /**
2881      * Set HTTP Response Header
2882      *
2883      */
2884     public function getResponse(){
2885         return $this->response;
2886     }
2888     /**
2889      * private callback function
2890      * Formatting HTTP Response Header
2891      *
2892      * @param resource $ch Apparently not used
2893      * @param string $header
2894      * @return int The strlen of the header
2895      */
2896     private function formatHeader($ch, $header)
2897     {
2898         $this->count++;
2899         if (strlen($header) > 2) {
2900             list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2901             $key = rtrim($key, ':');
2902             if (!empty($this->response[$key])) {
2903                 if (is_array($this->response[$key])){
2904                     $this->response[$key][] = $value;
2905                 } else {
2906                     $tmp = $this->response[$key];
2907                     $this->response[$key] = array();
2908                     $this->response[$key][] = $tmp;
2909                     $this->response[$key][] = $value;
2911                 }
2912             } else {
2913                 $this->response[$key] = $value;
2914             }
2915         }
2916         return strlen($header);
2917     }
2919     /**
2920      * Set options for individual curl instance
2921      *
2922      * @param resource $curl A curl handle
2923      * @param array $options
2924      * @return resource The curl handle
2925      */
2926     private function apply_opt($curl, $options) {
2927         // Clean up
2928         $this->cleanopt();
2929         // set cookie
2930         if (!empty($this->cookie) || !empty($options['cookie'])) {
2931             $this->setopt(array('cookiejar'=>$this->cookie,
2932                             'cookiefile'=>$this->cookie
2933                              ));
2934         }
2936         // set proxy
2937         if (!empty($this->proxy) || !empty($options['proxy'])) {
2938             $this->setopt($this->proxy);
2939         }
2940         $this->setopt($options);
2941         // reset before set options
2942         curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2943         // set headers
2944         if (empty($this->header)){
2945             $this->setHeader(array(
2946                 'User-Agent: MoodleBot/1.0',
2947                 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2948                 'Connection: keep-alive'
2949                 ));
2950         }
2951         curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2953         if ($this->debug){
2954             echo '<h1>Options</h1>';
2955             var_dump($this->options);
2956             echo '<h1>Header</h1>';
2957             var_dump($this->header);
2958         }
2960         // set options
2961         foreach($this->options as $name => $val) {
2962             if (is_string($name)) {
2963                 $name = constant(strtoupper($name));
2964             }
2965             curl_setopt($curl, $name, $val);
2966         }
2967         return $curl;
2968     }
2970     /**
2971      * Download multiple files in parallel
2972      *
2973      * Calls {@link multi()} with specific download headers
2974      *
2975      * <code>
2976      * $c = new curl;
2977      * $c->download(array(
2978      *              array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2979      *              array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2980      *              ));
2981      * </code>
2982      *
2983      * @param array $requests An array of files to request
2984      * @param array $options An array of options to set
2985      * @return array An array of results
2986      */
2987     public function download($requests, $options = array()) {
2988         $options['CURLOPT_BINARYTRANSFER'] = 1;
2989         $options['RETURNTRANSFER'] = false;
2990         return $this->multi($requests, $options);
2991     }
2993     /**
2994      * Mulit HTTP Requests
2995      * This function could run multi-requests in parallel.
2996      *
2997      * @param array $requests An array of files to request
2998      * @param array $options An array of options to set
2999      * @return array An array of results
3000      */
3001     protected function multi($requests, $options = array()) {
3002         $count   = count($requests);
3003         $handles = array();
3004         $results = array();
3005         $main    = curl_multi_init();
3006         for ($i = 0; $i < $count; $i++) {
3007             $url = $requests[$i];
3008             foreach($url as $n=>$v){
3009                 $options[$n] = $url[$n];
3010             }
3011             $handles[$i] = curl_init($url['url']);
3012             $this->apply_opt($handles[$i], $options);
3013             curl_multi_add_handle($main, $handles[$i]);
3014         }
3015         $running = 0;
3016         do {
3017             curl_multi_exec($main, $running);
3018         } while($running > 0);
3019         for ($i = 0; $i < $count; $i++) {
3020             if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3021                 $results[] = true;
3022             } else {
3023                 $results[] = curl_multi_getcontent($handles[$i]);
3024             }
3025             curl_multi_remove_handle($main, $handles[$i]);
3026         }
3027         curl_multi_close($main);
3028         return $results;
3029     }
3031     /**
3032      * Single HTTP Request
3033      *
3034      * @param string $url The URL to request
3035      * @param array $options
3036      * @return bool
3037      */
3038     protected function request($url, $options = array()){
3039         // create curl instance
3040         $curl = curl_init($url);
3041         $options['url'] = $url;
3042         $this->apply_opt($curl, $options);
3043         if ($this->cache && $ret = $this->cache->get($this->options)) {
3044             return $ret;
3045         } else {
3046             $ret = curl_exec($curl);
3047             if ($this->cache) {
3048                 $this->cache->set($this->options, $ret);
3049             }
3050         }
3052         $this->info  = curl_getinfo($curl);
3053         $this->error = curl_error($curl);
3055         if ($this->debug){
3056             echo '<h1>Return Data</h1>';
3057             var_dump($ret);
3058             echo '<h1>Info</h1>';
3059             var_dump($this->info);
3060             echo '<h1>Error</h1>';
3061             var_dump($this->error);
3062         }
3064         curl_close($curl);
3066         if (empty($this->error)){
3067             return $ret;
3068         } else {
3069             return $this->error;
3070             // exception is not ajax friendly
3071             //throw new moodle_exception($this->error, 'curl');
3072         }
3073     }
3075     /**
3076      * HTTP HEAD method
3077      *
3078      * @see request()
3079      *
3080      * @param string $url
3081      * @param array $options
3082      * @return bool
3083      */
3084     public function head($url, $options = array()){
3085         $options['CURLOPT_HTTPGET'] = 0;
3086         $options['CURLOPT_HEADER']  = 1;
3087         $options['CURLOPT_NOBODY']  = 1;
3088         return $this->request($url, $options);
3089     }
3091     /**
3092      * HTTP POST method
3093      *
3094      * @param string $url
3095      * @param array|string $params
3096      * @param array $options
3097      * @return bool
3098      */
3099     public function post($url, $params = '', $options = array()){
3100         $options['CURLOPT_POST']       = 1;
3101         if (is_array($params)) {
3102             $this->_tmp_file_post_params = array();
3103             foreach ($params as $key => $value) {
3104                 if ($value instanceof stored_file) {
3105                     $value->add_to_curl_request($this, $key);
3106                 } else {
3107                     $this->_tmp_file_post_params[$key] = $value;
3108                 }
3109             }
3110             $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3111             unset($this->_tmp_file_post_params);
3112         } else {
3113             // $params is the raw post data
3114             $options['CURLOPT_POSTFIELDS'] = $params;
3115         }
3116         return $this->request($url, $options);
3117     }
3119     /**
3120      * HTTP GET method
3121      *
3122      * @param string $url
3123      * @param array $params
3124      * @param array $options
3125      * @return bool
3126      */
3127     public function get($url, $params = array(), $options = array()){
3128         $options['CURLOPT_HTTPGET'] = 1;
3130         if (!empty($params)){
3131             $url .= (stripos($url, '?') !== false) ? '&' : '?';
3132             $url .= http_build_query($params, '', '&');
3133         }
3134         return $this->request($url, $options);
3135     }
3137     /**
3138      * HTTP PUT method
3139      *
3140      * @param string $url
3141      * @param array $params
3142      * @param array $options
3143      * @return bool
3144      */
3145     public function put($url, $params = array(), $options = array()){
3146         $file = $params['file'];
3147         if (!is_file($file)){
3148             return null;
3149         }
3150         $fp   = fopen($file, 'r');
3151         $size = filesize($file);
3152         $options['CURLOPT_PUT']        = 1;
3153         $options['CURLOPT_INFILESIZE'] = $size;
3154         $options['CURLOPT_INFILE']     = $fp;
3155         if (!isset($this->options['CURLOPT_USERPWD'])){
3156             $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3157         }
3158         $ret = $this->request($url, $options);
3159         fclose($fp);
3160         return $ret;
3161     }
3163     /**
3164      * HTTP DELETE method
3165      *
3166      * @param string $url
3167      * @param array $param
3168      * @param array $options
3169      * @return bool
3170      */
3171     public function delete($url, $param = array(), $options = array()){
3172         $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3173         if (!isset($options['CURLOPT_USERPWD'])) {
3174             $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3175         }
3176         $ret = $this->request($url, $options);
3177         return $ret;
3178     }
3180     /**
3181      * HTTP TRACE method
3182      *
3183      * @param string $url
3184      * @param array $options
3185      * @return bool
3186      */
3187     public function trace($url, $options = array()){
3188         $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3189         $ret = $this->request($url, $options);
3190         return $ret;
3191     }
3193     /**
3194      * HTTP OPTIONS method
3195      *
3196      * @param string $url
3197      * @param array $options
3198      * @return bool
3199      */
3200     public function options($url, $options = array()){
3201         $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3202         $ret = $this->request($url, $options);
3203         return $ret;
3204     }
3206     /**
3207      * Get curl information
3208      *
3209      * @return string
3210      */
3211     public function get_info() {
3212         return $this->info;
3213     }
3216 /**
3217  * This class is used by cURL class, use case:
3218  *
3219  * <code>
3220  * $CFG->repositorycacheexpire = 120;
3221  * $CFG->curlcache = 120;
3222  *
3223  * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3224  * $ret = $c->get('http://www.google.com');
3225  * </code>
3226  *
3227  * @package   core_files
3228  * @copyright Dongsheng Cai <dongsheng@moodle.com>
3229  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3230  */
3231 class curl_cache {
3232     /** @var string Path to cache directory */
3233     public $dir = '';
3235     /**
3236      * Constructor
3237      *
3238      * @global stdClass $CFG
3239      * @param string $module which module is using curl_cache
3240      */
3241     public function __construct($module = 'repository') {
3242         global $CFG;
3243         if (!empty($module)) {
3244             $this->dir = $CFG->cachedir.'/'.$module.'/';
3245         } else {
3246             $this->dir = $CFG->cachedir.'/misc/';
3247         }
3248         if (!file_exists($this->dir)) {
3249             mkdir($this->dir, $CFG->directorypermissions, true);
3250         }
3251         if ($module == 'repository') {
3252             if (empty($CFG->repositorycacheexpire)) {
3253                 $CFG->repositorycacheexpire = 120;
3254             }
3255             $this->ttl = $CFG->repositorycacheexpire;
3256         } else {
3257             if (empty($CFG->curlcache)) {
3258                 $CFG->curlcache = 120;
3259             }
3260             $this->ttl = $CFG->curlcache;
3261         }
3262     }
3264     /**
3265      * Get cached value
3266      *
3267      * @global stdClass $CFG
3268      * @global stdClass $USER
3269      * @param mixed $param
3270      * @return bool|string
3271      */
3272     public function get($param) {
3273         global $CFG, $USER;
3274         $this->cleanup($this->ttl);
3275         $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3276         if(file_exists($this->dir.$filename)) {
3277             $lasttime = filemtime($this->dir.$filename);
3278             if (time()-$lasttime > $this->ttl) {
3279                 return false;
3280             } else {
3281                 $fp = fopen($this->dir.$filename, 'r');
3282                 $size = filesize($this->dir.$filename);
3283                 $content = fread($fp, $size);
3284                 return unserialize($content);
3285             }
3286         }
3287         return false;
3288     }
3290     /**
3291      * Set cache value
3292      *
3293      * @global object $CFG
3294      * @global object $USER
3295      * @param mixed $param
3296      * @param mixed $val
3297      */
3298     public function set($param, $val) {
3299         global $CFG, $USER;
3300         $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3301         $fp = fopen($this->dir.$filename, 'w');
3302         fwrite($fp, serialize($val));
3303         fclose($fp);
3304     }
3306     /**
3307      * Remove cache files
3308      *
3309      * @param int $expire The number of seconds before expiry
3310      */
3311     public function cleanup($expire) {
3312         if ($dir = opendir($this->dir)) {
3313             while (false !== ($file = readdir($dir))) {
3314                 if(!is_dir($file) && $file != '.' && $file != '..') {
3315                     $lasttime = @filemtime($this->dir.$file);
3316                     if (time() - $lasttime > $expire) {
3317                         @unlink($this->dir.$file);
3318                     }
3319                 }
3320             }
3321             closedir($dir);
3322         }
3323     }
3324     /**
3325      * delete current user's cache file
3326      *
3327      * @global object $CFG
3328      * @global object $USER
3329      */
3330     public function refresh() {
3331         global $CFG, $USER;
3332         if ($dir = opendir($this->dir)) {
3333             while (false !== ($file = readdir($dir))) {
3334                 if (!is_dir($file) && $file != '.' && $file != '..') {
3335                     if (strpos($file, 'u'.$USER->id.'_') !== false) {
3336                         @unlink($this->dir.$file);
3337                     }
3338                 }
3339             }
3340         }
3341     }
3344 /**
3345  * This function delegates file serving to individual plugins
3346  *
3347  * @param string $relativepath
3348  * @param bool $forcedownload
3349  * @param null|string $preview the preview mode, defaults to serving the original file
3350  * @todo MDL-31088 file serving improments
3351  */
3352 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3353     global $DB, $CFG, $USER;
3354     // relative path must start with '/'
3355     if (!$relativepath) {
3356         print_error('invalidargorconf');
3357     } else if ($relativepath[0] != '/') {
3358         print_error('pathdoesnotstartslash');
3359     }
3361     // extract relative path components
3362     $args = explode('/', ltrim($relativepath, '/'));
3364     if (count($args) < 3) { // always at least context, component and filearea
3365         print_error('invalidarguments');
3366     }
3368     $contextid = (int)array_shift($args);
3369     $component = clean_param(array_shift($args), PARAM_COMPONENT);
3370     $filearea  = clean_param(array_shift($args), PARAM_AREA);
3372     list($context, $course, $cm) = get_context_info_array($contextid);
3374     $fs = get_file_storage();
3376     // ========================================================================================================================
3377     if ($component === 'blog') {
3378         // Blog file serving
3379         if ($context->contextlevel != CONTEXT_SYSTEM) {
3380             send_file_not_found();
3381         }
3382         if ($filearea !== 'attachment' and $filearea !== 'post') {
3383             send_file_not_found();
3384         }
3386         if (empty($CFG->bloglevel)) {
3387             print_error('siteblogdisable', 'blog');
3388         }
3390         $entryid = (int)array_shift($args);
3391         if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3392             send_file_not_found();
3393         }
3394         if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3395             require_login();
3396             if (isguestuser()) {
3397                 print_error('noguest');
3398             }
3399             if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3400                 if ($USER->id != $entry->userid) {
3401                     send_file_not_found();
3402                 }
3403             }
3404         }
3406         if ('publishstate' === 'public') {
3407             if ($CFG->forcelogin) {
3408                 require_login();
3409             }
3411         } else if ('publishstate' === 'site') {
3412             require_login();
3413             //ok
3414         } else if ('publishstate' === 'draft') {
3415             require_login();
3416             if ($USER->id != $entry->userid) {
3417                 send_file_not_found();
3418             }
3419         }
3421         $filename = array_pop($args);
3422         $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3424         if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3425             send_file_not_found();
3426         }
3428         send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3430     // ========================================================================================================================
3431     } else if ($component === 'grade') {
3432         if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3433             // Global gradebook files
3434             if ($CFG->forcelogin) {
3435                 require_login();
3436             }
3438             $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3440             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3441                 send_file_not_found();
3442             }
3444             session_get_instance()->write_close(); // unlock session during fileserving
3445             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3447         } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3448             //TODO: nobody implemented this yet in grade edit form!!
3449             send_file_not_found();
3451             if ($CFG->forcelogin || $course->id != SITEID) {
3452                 require_login($course);
3453             }
3455             $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3457             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3458                 send_file_not_found();
3459             }
3461             session_get_instance()->write_close(); // unlock session during fileserving
3462             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3463         } else {
3464             send_file_not_found();
3465         }
3467     // ========================================================================================================================
3468     } else if ($component === 'tag') {
3469         if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3471             // All tag descriptions are going to be public but we still need to respect forcelogin
3472             if ($CFG->forcelogin) {
3473                 require_login();
3474             }
3476             $fullpath = "/$context->id/tag/description/".implode('/', $args);
3478             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3479                 send_file_not_found();
3480             }
3482             session_get_instance()->write_close(); // unlock session during fileserving
3483             send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3485         } else {
3486             send_file_not_found();
3487         }
3489     // ========================================================================================================================
3490     } else if ($component === 'calendar') {
3491         if ($filearea === 'event_description'  and $context->contextlevel == CONTEXT_SYSTEM) {
3493             // All events here are public the one requirement is that we respect forcelogin
3494             if ($CFG->forcelogin) {
3495                 require_login();
3496             }
3498             // Get the event if from the args array
3499             $eventid = array_shift($args);
3501             // Load the event from the database
3502             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3503                 send_file_not_found();
3504             }
3505             // Check that we got an event and that it's userid is that of the user
3507             // Get the file and serve if successful
3508             $filename = array_pop($args);
3509             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3510             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3511                 send_file_not_found();
3512             }
3514             session_get_instance()->write_close(); // unlock session during fileserving
3515             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3517         } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3519             // Must be logged in, if they are not then they obviously can't be this user
3520             require_login();
3522             // Don't want guests here, potentially saves a DB call
3523             if (isguestuser()) {
3524                 send_file_not_found();
3525             }
3527             // Get the event if from the args array
3528             $eventid = array_shift($args);
3530             // Load the event from the database - user id must match
3531             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3532                 send_file_not_found();
3533             }
3535             // Get the file and serve if successful
3536             $filename = array_pop($args);
3537             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3538             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3539                 send_file_not_found();
3540             }
3542             session_get_instance()->write_close(); // unlock session during fileserving
3543             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3545         } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3547             // Respect forcelogin and require login unless this is the site.... it probably
3548             // should NEVER be the site
3549             if ($CFG->forcelogin || $course->id != SITEID) {
3550                 require_login($course);
3551             }
3553             // Must be able to at least view the course
3554             if (!is_enrolled($context) and !is_viewing($context)) {
3555                 //TODO: hmm, do we really want to block guests here?
3556                 send_file_not_found();
3557             }
3559             // Get the event id
3560             $eventid = array_shift($args);
3562             // Load the event from the database we need to check whether it is
3563             // a) valid course event
3564             // b) a group event
3565             // Group events use the course context (there is no group context)
3566             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3567                 send_file_not_found();
3568             }
3570             // If its a group event require either membership of view all groups capability
3571             if ($event->eventtype === 'group') {
3572                 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3573                     send_file_not_found();
3574                 }
3575             } else if ($event->eventtype === 'course') {
3576                 //ok
3577             } else {
3578                 // some other type
3579                 send_file_not_found();
3580             }
3582             // If we get this far we can serve the file
3583             $filename = array_pop($args);
3584             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3585             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3586                 send_file_not_found();
3587             }
3589             session_get_instance()->write_close(); // unlock session during fileserving
3590             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3592         } else {
3593             send_file_not_found();
3594         }
3596     // ========================================================================================================================
3597     } else if ($component === 'user') {
3598         if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3599             if (count($args) == 1) {
3600                 $themename = theme_config::DEFAULT_THEME;
3601                 $filename = array_shift($args);
3602             } else {
3603                 $themename = array_shift($args);
3604                 $filename = array_shift($args);
3605             }
3607             // fix file name automatically
3608             if ($filename !== 'f1' and $filename !== 'f2') {
3609                 $filename = 'f1';
3610             }
3612             if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3613                     (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3614                 // protect images if login required and not logged in;
3615                 // also if login is required for profile images and is not logged in or guest
3616                 // do not use require_login() because it is expensive and not suitable here anyway
3617                 $theme = theme_config::load($themename);
3618                 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3619             }
3621             if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'/.png')) {
3622                 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg')) {
3623                     // bad reference - try to prevent future retries as hard as possible!
3624                     if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3625                         if ($user->picture == 1 or $user->picture > 10) {
3626                             $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3627                         }
3628                     }
3629                     // no redirect here because it is not cached
3630                     $theme = theme_config::load($themename);
3631                     $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle');
3632                     send_file($imagefile, basename($imagefile), 60*60*24*14);
3633                 }
3634             }
3636             send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3638         } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3639             require_login();
3641             if (isguestuser()) {
3642                 send_file_not_found();
3643             }
3645             if ($USER->id !== $context->instanceid) {
3646                 send_file_not_found();
3647             }
3649             $filename = array_pop($args);
3650             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3651             if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3652                 send_file_not_found();
3653             }
3655             session_get_instance()->write_close(); // unlock session during fileserving
3656             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3658         } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3660             if ($CFG->forcelogin) {
3661                 require_login();
3662             }
3664             $userid = $context->instanceid;
3666             if ($USER->id == $userid) {
3667                 // always can access own
3669             } else if (!empty($CFG->forceloginforprofiles)) {
3670                 require_login();
3672                 if (isguestuser()) {
3673                     send_file_not_found();
3674                 }
3676                 // we allow access to site profile of all course contacts (usually teachers)
3677                 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3678                     send_file_not_found();
3679                 }
3681                 $canview = false;
3682                 if (has_capability('moodle/user:viewdetails', $context)) {
3683                     $canview = true;
3684                 } else {
3685                     $courses = enrol_get_my_courses();
3686                 }
3688                 while (!$canview && count($courses) > 0) {
3689                     $course = array_shift($courses);
3690                     if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) {
3691                         $canview = true;
3692                     }
3693                 }
3694             }
3696             $filename = array_pop($args);
3697             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3698             if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3699                 send_file_not_found();
3700             }
3702             session_get_instance()->write_close(); // unlock session during fileserving
3703             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3705         } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3706             $userid = (int)array_shift($args);
3707             $usercontext = get_context_instance(CONTEXT_USER, $userid);
3709             if ($CFG->forcelogin) {
3710                 require_login();
3711             }
3713             if (!empty($CFG->forceloginforprofiles)) {
3714                 require_login();
3715                 if (isguestuser()) {
3716                     print_error('noguest');
3717                 }
3719                 //TODO: review this logic of user profile access prevention
3720                 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3721                     print_error('usernotavailable');
3722                 }
3723                 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3724                     print_error('cannotviewprofile');
3725                 }
3726                 if (!is_enrolled($context, $userid)) {
3727                     print_error('notenrolledprofile');
3728                 }
3729                 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3730                     print_error('groupnotamember');
3731                 }
3732             }
3734             $filename = array_pop($args);
3735             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3736             if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3737                 send_file_not_found();
3738             }
3740             session_get_instance()->write_close(); // unlock session during fileserving
3741             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3743         } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3744             require_login();
3746             if (isguestuser()) {
3747                 send_file_not_found();
3748             }
3749             $userid = $context->instanceid;
3751             if ($USER->id != $userid) {
3752                 send_file_not_found();
3753             }
3755             $filename = array_pop($args);
3756             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3757             if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3758                 send_file_not_found();
3759             }
3761             session_get_instance()->write_close(); // unlock session during fileserving
3762             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3764         } else {
3765             send_file_not_found();
3766         }
3768     // ========================================================================================================================
3769     } else if ($component === 'coursecat') {
3770         if ($context->contextlevel != CONTEXT_COURSECAT) {
3771             send_file_not_found();
3772         }
3774         if ($filearea === 'description') {
3775             if ($CFG->forcelogin) {
3776                 // no login necessary - unless login forced everywhere
3777                 require_login();
3778             }
3780             $filename = array_pop($args);
3781             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3782             if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3783                 send_file_not_found();
3784             }
3786             session_get_instance()->write_close(); // unlock session during fileserving
3787             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3788         } else {
3789             send_file_not_found();
3790         }
3792     // ========================================================================================================================
3793     } else if ($component === 'course') {
3794         if ($context->contextlevel != CONTEXT_COURSE) {
3795             send_file_not_found();
3796         }
3798         if ($filearea === 'summary') {
3799             if ($CFG->forcelogin) {
3800                 require_login();
3801             }
3803             $filename = array_pop($args);
3804             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3805             if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
3806                 send_file_not_found();
3807             }
3809             session_get_instance()->write_close(); // unlock session during fileserving
3810             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3812         } else if ($filearea === 'section') {
3813             if ($CFG->forcelogin) {
3814                 require_login($course);
3815             } else if ($course->id != SITEID) {
3816                 require_login($course);
3817             }
3819             $sectionid = (int)array_shift($args);
3821             if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
3822                 send_file_not_found();
3823             }
3825             if ($course->numsections < $section->section) {
3826                 if (!has_capability('moodle/course:update', $context)) {
3827                     // block access to unavailable sections if can not edit course
3828                     send_file_not_found();
3829                 }
3830             }
3832             $filename = array_pop($args);
3833             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3834             if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3835                 send_file_not_found();
3836             }
3838             session_get_instance()->write_close(); // unlock session during fileserving
3839             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3841         } else {
3842             send_file_not_found();
3843         }
3845     } else if ($component === 'group') {
3846         if ($context->contextlevel != CONTEXT_COURSE) {
3847             send_file_not_found();
3848         }
3850         require_course_login($course, true, null, false);
3852         $groupid = (int)array_shift($args);
3854         $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
3855         if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
3856             // do not allow access to separate group info if not member or teacher
3857             send_file_not_found();
3858         }
3860         if ($filearea === 'description') {
3862             require_login($course);
3864             $filename = array_pop($args);
3865             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3866             if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
3867                 send_file_not_found();
3868             }
3870             session_get_instance()->write_close(); // unlock session during fileserving
3871             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3873         } else if ($filearea === 'icon') {
3874             $filename = array_pop($args);
3876             if ($filename !== 'f1' and $filename !== 'f2') {
3877                 send_file_not_found();
3878             }
3879             if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
3880                 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
3881                     send_file_not_found();
3882                 }
3883             }
3885             session_get_instance()->write_close(); // unlock session during fileserving
3886             send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
3888         } else {
3889             send_file_not_found();
3890         }
3892     } else if ($component === 'grouping') {
3893         if ($context->contextlevel != CONTEXT_COURSE) {
3894             send_file_not_found();
3895         }
3897         require_login($course);
3899         $groupingid = (int)array_shift($args);
3901         // note: everybody has access to grouping desc images for now
3902         if ($filearea === 'description') {
3904             $filename = array_pop($args);
3905             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3906             if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
3907                 send_file_not_found();
3908             }
3910             session_get_instance()->write_close(); // unlock session during fileserving
3911             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3913         } else {
3914             send_file_not_found();
3915         }
3917     // ========================================================================================================================
3918     } else if ($component === 'backup') {
3919         if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
3920             require_login($course);
3921             require_capability('moodle/backup:downloadfile', $context);
3923             $filename = array_pop($args);
3924             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3925             if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
3926                 send_file_not_found();
3927             }
3929             session_get_instance()->write_close(); // unlock session during fileserving
3930             send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
3932         } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
3933             require_login($course);
3934             require_capability('moodle/backup:downloadfile', $context);
3936             $sectionid = (int)array_shift($args);
3938             $filename = array_pop($args);
3939             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3940             if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3941                 send_file_not_found();
3942             }
3944             session_get_instance()->write_close();
3945             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3947         } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
3948             require_login($course, false, $cm);
3949             require_capability('moodle/backup:downloadfile', $context);
3951             $filename = array_pop($args);
3952             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3953             if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
3954                 send_file_not_found();
3955             }
3957             session_get_instance()->write_close();
3958             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3960         } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
3961             // Backup files that were generated by the automated backup systems.
3963             require_login($course);
3964             require_capability('moodle/site:config', $context);
3966             $filename = array_pop($args);
3967             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3968             if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
3969                 send_file_not_found();
3970             }
3972             session_get_instance()->write_close(); // unlock session during fileserving
3973             send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
3975         } else {
3976             send_file_not_found();
3977         }
3979     // ========================================================================================================================
3980     } else if ($component === 'question') {
3981         require_once($CFG->libdir . '/questionlib.php');
3982         question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
3983         send_file_not_found();
3985     // ========================================================================================================================
3986     } else if ($component === 'grading') {
3987         if ($filearea === 'description') {
3988             // files embedded into the form definition description
3990             if ($context->contextlevel == CONTEXT_SYSTEM) {
3991                 require_login();
3993             } else if ($context->contextlevel >= CONTEXT_COURSE) {
3994                 require_login($course, false, $cm);
3996             } else {
3997                 send_file_not_found();
3998             }
4000             $formid = (int)array_shift($args);
4002             $sql = "SELECT ga.id
4003                 FROM {grading_areas} ga
4004                 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4005                 WHERE gd.id = ? AND ga.contextid = ?";
4006             $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4008             if (!$areaid) {
4009                 send_file_not_found();
4010             }
4012             $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4014             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4015                 send_file_not_found();
4016             }
4018             session_get_instance()->write_close(); // unlock session during fileserving
4019             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4020         }
4022         // ========================================================================================================================
4023     } else if (strpos($component, 'mod_') === 0) {
4024         $modname = substr($component, 4);
4025         if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4026             send_file_not_found();
4027         }
4028         require_once("$CFG->dirroot/mod/$modname/lib.php");
4030         if ($context->contextlevel == CONTEXT_MODULE) {
4031             if ($cm->modname !== $modname) {
4032                 // somebody tries to gain illegal access, cm type must match the component!
4033                 send_file_not_found();
4034             }
4035         }
4037         if ($filearea === 'intro') {
4038             if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4039                 send_file_not_found();
4040             }
4041             require_course_login($course, true, $cm);
4043             // all users may access it
4044             $filename = array_pop($args);
4045             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4046             if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4047                 send_file_not_found();
4048             }
4050             $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4052             // finally send the file
4053             send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4054         }
4056         $filefunction = $component.'_pluginfile';
4057         $filefunctionold = $modname.'_pluginfile';
4058         if (function_exists($filefunction)) {
4059             // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4060             $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4061         } else if (function_exists($filefunctionold)) {
4062             // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4063             $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4064         }
4066         send_file_not_found();
4068     // ========================================================================================================================
4069     } else if (strpos($component, 'block_') === 0) {
4070         $blockname = substr($component, 6);
4071         // note: no more class methods in blocks please, that is ....
4072         if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4073             send_file_not_found();
4074         }
4075         require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4077         if ($context->contextlevel == CONTEXT_BLOCK) {
4078             $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4079             if ($birecord->blockname !== $blockname) {
4080                 // somebody tries to gain illegal access, cm type must match the component!
4081                 send_file_not_found();
4082             }
4083         } else {
4084             $birecord = null;
4085         }
4087         $filefunction = $component.'_pluginfile';
4088         if (function_exists($filefunction)) {
4089             // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4090             $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4091         }
4093         send_file_not_found();
4095     // ========================================================================================================================
4096     } else if (strpos($component, '_') === false) {
4097         // all core subsystems have to be specified above, no more guessing here!
4098         send_file_not_found();
4100     } else {
4101         // try to serve general plugin file in arbitrary context
4102         $dir = get_component_directory($component);
4103         if (!file_exists("$dir/lib.php")) {
4104             send_file_not_found();
4105         }
4106         include_once("$dir/lib.php");
4108         $filefunction = $component.'_pluginfile';
4109         if (function_exists($filefunction)) {
4110             // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4111             $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4112         }
4114         send_file_not_found();
4115     }
4119 /**
4120  * Universe file cacheing class
4121  *
4122  * @package    core_files
4123  * @category   files
4124  * @copyright  2012 Dongsheng Cai {@link http://dongsheng.org}
4125  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4126  */
4127 class cache_file {
4128     /** @var string */
4129     public $cachedir = '';
4131     /**
4132      * static method to create cache_file class instance
4133      *
4134      * @param array $options caching ooptions
4135      */
4136     public static function get_instance($options = array()) {
4137         return new cache_file($options);
4138     }