af71f16188300bd25d9e1d6c3740f47d06fbecbb
[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 = context_user::instance($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 = context_user::instance($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 = context_user::instance($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 = context_user::instance($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 = context_user::instance($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 = context_user::instance($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             if ($item->isref && $file->get_status() == 666) {
600                 $item->originalmissing = true;
601             }
602             // find the file this draft file was created from and count all references in local
603             // system pointing to that file
604             $source = @unserialize($file->get_source());
605             if (isset($source->original)) {
606                 $item->refcount = $fs->search_references_count($source->original);
607             }
609             if ($file->is_directory()) {
610                 $item->filesize = 0;
611                 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
612                 $item->type = 'folder';
613                 $foldername = explode('/', trim($item->filepath, '/'));
614                 $item->fullname = trim(array_pop($foldername), '/');
615                 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
616             } else {
617                 // do NOT use file browser here!
618                 $item->mimetype = get_mimetype_description($file);
619                 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
620                     $item->type = 'zip';
621                 } else {
622                     $item->type = 'file';
623                 }
624                 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
625                 $item->url = $itemurl->out();
626                 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
627                 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
628                 if ($imageinfo = $file->get_imageinfo()) {
629                     $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
630                     $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
631                     $item->image_width = $imageinfo['width'];
632                     $item->image_height = $imageinfo['height'];
633                 }
634             }
635             $list[] = $item;
636         }
637     }
638     $data->itemid = $draftitemid;
639     $data->list = $list;
640     return $data;
643 /**
644  * Returns draft area itemid for a given element.
645  *
646  * @category files
647  * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
648  * @return int the itemid, or 0 if there is not one yet.
649  */
650 function file_get_submitted_draft_itemid($elname) {
651     // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
652     if (!isset($_REQUEST[$elname])) {
653         return 0;
654     }
655     if (is_array($_REQUEST[$elname])) {
656         $param = optional_param_array($elname, 0, PARAM_INT);
657         if (!empty($param['itemid'])) {
658             $param = $param['itemid'];
659         } else {
660             debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
661             return false;
662         }
664     } else {
665         $param = optional_param($elname, 0, PARAM_INT);
666     }
668     if ($param) {
669         require_sesskey();
670     }
672     return $param;
675 /**
676  * Restore the original source field from draft files
677  *
678  * @param stored_file $storedfile This only works with draft files
679  * @return stored_file
680  */
681 function file_restore_source_field_from_draft_file($storedfile) {
682     $source = @unserialize($storedfile->get_source());
683     if (!empty($source)) {
684         if (is_object($source)) {
685             $restoredsource = $source->source;
686             $storedfile->set_source($restoredsource);
687         } else {
688             throw new moodle_exception('invalidsourcefield', 'error');
689         }
690     }
691     return $storedfile;
693 /**
694  * Saves files from a draft file area to a real one (merging the list of files).
695  * Can rewrite URLs in some content at the same time if desired.
696  *
697  * @category files
698  * @global stdClass $USER
699  * @param int $draftitemid the id of the draft area to use. Normally obtained
700  *      from file_get_submitted_draft_itemid('elementname') or similar.
701  * @param int $contextid This parameter and the next two identify the file area to save to.
702  * @param string $component
703  * @param string $filearea indentifies the file area.
704  * @param int $itemid helps identifies the file area.
705  * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
706  * @param string $text some html content that needs to have embedded links rewritten
707  *      to the @@PLUGINFILE@@ form for saving in the database.
708  * @param bool $forcehttps force https urls.
709  * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
710  */
711 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
712     global $USER;
714     $usercontext = context_user::instance($USER->id);
715     $fs = get_file_storage();
717     $options = (array)$options;
718     if (!isset($options['subdirs'])) {
719         $options['subdirs'] = false;
720     }
721     if (!isset($options['maxfiles'])) {
722         $options['maxfiles'] = -1; // unlimited
723     }
724     if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
725         $options['maxbytes'] = 0; // unlimited
726     }
727     $allowreferences = true;
728     if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
729         // we assume that if $options['return_types'] is NOT specified, we DO allow references.
730         // this is not exactly right. BUT there are many places in code where filemanager options
731         // are not passed to file_save_draft_area_files()
732         $allowreferences = false;
733     }
735     $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
736     $oldfiles   = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
738     if (count($draftfiles) < 2) {
739         // means there are no files - one file means root dir only ;-)
740         $fs->delete_area_files($contextid, $component, $filearea, $itemid);
742     } else if (count($oldfiles) < 2) {
743         $filecount = 0;
744         // there were no files before - one file means root dir only ;-)
745         foreach ($draftfiles as $file) {
746             $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
747             if (!$options['subdirs']) {
748                 if ($file->get_filepath() !== '/' or $file->is_directory()) {
749                     continue;
750                 }
751             }
752             if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
753                 // oversized file - should not get here at all
754                 continue;
755             }
756             if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
757                 // more files - should not get here at all
758                 break;
759             }
760             if (!$file->is_directory()) {
761                 $filecount++;
762             }
764             if ($file->is_external_file()) {
765                 if (!$allowreferences) {
766                     continue;
767                 }
768                 $repoid = $file->get_repository_id();
769                 if (!empty($repoid)) {
770                     $file_record['repositoryid'] = $repoid;
771                     $file_record['reference'] = $file->get_reference();
772                 }
773             }
774             file_restore_source_field_from_draft_file($file);
776             $fs->create_file_from_storedfile($file_record, $file);
777         }
779     } else {
780         // we have to merge old and new files - we want to keep file ids for files that were not changed
781         // we change time modified for all new and changed files, we keep time created as is
783         $newhashes = array();
784         foreach ($draftfiles as $file) {
785             $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
786             file_restore_source_field_from_draft_file($file);
787             $newhashes[$newhash] = $file;
788         }
789         $filecount = 0;
790         foreach ($oldfiles as $oldfile) {
791             $oldhash = $oldfile->get_pathnamehash();
792             if (!isset($newhashes[$oldhash])) {
793                 // delete files not needed any more - deleted by user
794                 $oldfile->delete();
795                 continue;
796             }
798             $newfile = $newhashes[$oldhash];
799             // status changed, we delete old file, and create a new one
800             if ($oldfile->get_status() != $newfile->get_status()) {
801                 // file was changed, use updated with new timemodified data
802                 $oldfile->delete();
803                 // This file will be added later
804                 continue;
805             }
807             // Replaced file content
808             if ($oldfile->get_contenthash() != $newfile->get_contenthash()) {
809                 $oldfile->replace_content_with($newfile);
810             }
811             // Updated author
812             if ($oldfile->get_author() != $newfile->get_author()) {
813                 $oldfile->set_author($newfile->get_author());
814             }
815             // Updated license
816             if ($oldfile->get_license() != $newfile->get_license()) {
817                 $oldfile->set_license($newfile->get_license());
818             }
820             // Updated file source
821             if ($oldfile->get_source() != $newfile->get_source()) {
822                 $oldfile->set_source($newfile->get_source());
823             }
825             // Updated sort order
826             if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
827                 $oldfile->set_sortorder($newfile->get_sortorder());
828             }
830             // Update file size
831             if ($oldfile->get_filesize() != $newfile->get_filesize()) {
832                 $oldfile->set_filesize($newfile->get_filesize());
833             }
835             // Update file timemodified
836             if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
837                 $oldfile->set_timemodified($newfile->get_timemodified());
838             }
840             // unchanged file or directory - we keep it as is
841             unset($newhashes[$oldhash]);
842             if (!$oldfile->is_directory()) {
843                 $filecount++;
844             }
845         }
847         // Add fresh file or the file which has changed status
848         // the size and subdirectory tests are extra safety only, the UI should prevent it
849         foreach ($newhashes as $file) {
850             $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
851             if (!$options['subdirs']) {
852                 if ($file->get_filepath() !== '/' or $file->is_directory()) {
853                     continue;
854                 }
855             }
856             if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
857                 // oversized file - should not get here at all
858                 continue;
859             }
860             if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
861                 // more files - should not get here at all
862                 break;
863             }
864             if (!$file->is_directory()) {
865                 $filecount++;
866             }
868             if ($file->is_external_file()) {
869                 if (!$allowreferences) {
870                     continue;
871                 }
872                 $repoid = $file->get_repository_id();
873                 if (!empty($repoid)) {
874                     $file_record['repositoryid'] = $repoid;
875                     $file_record['reference'] = $file->get_reference();
876                 }
877             }
879             $fs->create_file_from_storedfile($file_record, $file);
880         }
881     }
883     // note: do not purge the draft area - we clean up areas later in cron,
884     //       the reason is that user might press submit twice and they would loose the files,
885     //       also sometimes we might want to use hacks that save files into two different areas
887     if (is_null($text)) {
888         return null;
889     } else {
890         return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
891     }
894 /**
895  * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
896  * ready to be saved in the database. Normally, this is done automatically by
897  * {@link file_save_draft_area_files()}.
898  *
899  * @category files
900  * @param string $text the content to process.
901  * @param int $draftitemid the draft file area the content was using.
902  * @param bool $forcehttps whether the content contains https URLs. Default false.
903  * @return string the processed content.
904  */
905 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
906     global $CFG, $USER;
908     $usercontext = context_user::instance($USER->id);
910     $wwwroot = $CFG->wwwroot;
911     if ($forcehttps) {
912         $wwwroot = str_replace('http://', 'https://', $wwwroot);
913     }
915     // relink embedded files if text submitted - no absolute links allowed in database!
916     $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
918     if (strpos($text, 'draftfile.php?file=') !== false) {
919         $matches = array();
920         preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
921         if ($matches) {
922             foreach ($matches[0] as $match) {
923                 $replace = str_ireplace('%2F', '/', $match);
924                 $text = str_replace($match, $replace, $text);
925             }
926         }
927         $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
928     }
930     return $text;
933 /**
934  * Set file sort order
935  *
936  * @global moodle_database $DB
937  * @param int $contextid the context id
938  * @param string $component file component
939  * @param string $filearea file area.
940  * @param int $itemid itemid.
941  * @param string $filepath file path.
942  * @param string $filename file name.
943  * @param int $sortorder the sort order of file.
944  * @return bool
945  */
946 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
947     global $DB;
948     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
949     if ($file_record = $DB->get_record('files', $conditions)) {
950         $sortorder = (int)$sortorder;
951         $file_record->sortorder = $sortorder;
952         $DB->update_record('files', $file_record);
953         return true;
954     }
955     return false;
958 /**
959  * reset file sort order number to 0
960  * @global moodle_database $DB
961  * @param int $contextid the context id
962  * @param string $component
963  * @param string $filearea file area.
964  * @param int|bool $itemid itemid.
965  * @return bool
966  */
967 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
968     global $DB;
970     $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
971     if ($itemid !== false) {
972         $conditions['itemid'] = $itemid;
973     }
975     $file_records = $DB->get_records('files', $conditions);
976     foreach ($file_records as $file_record) {
977         $file_record->sortorder = 0;
978         $DB->update_record('files', $file_record);
979     }
980     return true;
983 /**
984  * Returns description of upload error
985  *
986  * @param int $errorcode found in $_FILES['filename.ext']['error']
987  * @return string error description string, '' if ok
988  */
989 function file_get_upload_error($errorcode) {
991     switch ($errorcode) {
992     case 0: // UPLOAD_ERR_OK - no error
993         $errmessage = '';
994         break;
996     case 1: // UPLOAD_ERR_INI_SIZE
997         $errmessage = get_string('uploadserverlimit');
998         break;
1000     case 2: // UPLOAD_ERR_FORM_SIZE
1001         $errmessage = get_string('uploadformlimit');
1002         break;
1004     case 3: // UPLOAD_ERR_PARTIAL
1005         $errmessage = get_string('uploadpartialfile');
1006         break;
1008     case 4: // UPLOAD_ERR_NO_FILE
1009         $errmessage = get_string('uploadnofilefound');
1010         break;
1012     // Note: there is no error with a value of 5
1014     case 6: // UPLOAD_ERR_NO_TMP_DIR
1015         $errmessage = get_string('uploadnotempdir');
1016         break;
1018     case 7: // UPLOAD_ERR_CANT_WRITE
1019         $errmessage = get_string('uploadcantwrite');
1020         break;
1022     case 8: // UPLOAD_ERR_EXTENSION
1023         $errmessage = get_string('uploadextension');
1024         break;
1026     default:
1027         $errmessage = get_string('uploadproblem');
1028     }
1030     return $errmessage;
1033 /**
1034  * Recursive function formating an array in POST parameter
1035  * @param array $arraydata - the array that we are going to format and add into &$data array
1036  * @param string $currentdata - a row of the final postdata array at instant T
1037  *                when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1038  * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1039  */
1040 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1041         foreach ($arraydata as $k=>$v) {
1042             $newcurrentdata = $currentdata;
1043             if (is_array($v)) { //the value is an array, call the function recursively
1044                 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1045                 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1046             }  else { //add the POST parameter to the $data array
1047                 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1048             }
1049         }
1052 /**
1053  * Transform a PHP array into POST parameter
1054  * (see the recursive function format_array_postdata_for_curlcall)
1055  * @param array $postdata
1056  * @return array containing all POST parameters  (1 row = 1 POST parameter)
1057  */
1058 function format_postdata_for_curlcall($postdata) {
1059         $data = array();
1060         foreach ($postdata as $k=>$v) {
1061             if (is_array($v)) {
1062                 $currentdata = urlencode($k);
1063                 format_array_postdata_for_curlcall($v, $currentdata, $data);
1064             }  else {
1065                 $data[] = urlencode($k).'='.urlencode($v);
1066             }
1067         }
1068         $convertedpostdata = implode('&', $data);
1069         return $convertedpostdata;
1072 /**
1073  * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1074  * Due to security concerns only downloads from http(s) sources are supported.
1075  *
1076  * @todo MDL-31073 add version test for '7.10.5'
1077  * @category files
1078  * @param string $url file url starting with http(s)://
1079  * @param array $headers http headers, null if none. If set, should be an
1080  *   associative array of header name => value pairs.
1081  * @param array $postdata array means use POST request with given parameters
1082  * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1083  *   (if false, just returns content)
1084  * @param int $timeout timeout for complete download process including all file transfer
1085  *   (default 5 minutes)
1086  * @param int $connecttimeout timeout for connection to server; this is the timeout that
1087  *   usually happens if the remote server is completely down (default 20 seconds);
1088  *   may not work when using proxy
1089  * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1090  *   Only use this when already in a trusted location.
1091  * @param string $tofile store the downloaded content to file instead of returning it.
1092  * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1093  *   filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1094  * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1095  */
1096 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1097     global $CFG;
1099     // some extra security
1100     $newlines = array("\r", "\n");
1101     if (is_array($headers) ) {
1102         foreach ($headers as $key => $value) {
1103             $headers[$key] = str_replace($newlines, '', $value);
1104         }
1105     }
1106     $url = str_replace($newlines, '', $url);
1107     if (!preg_match('|^https?://|i', $url)) {
1108         if ($fullresponse) {
1109             $response = new stdClass();
1110             $response->status        = 0;
1111             $response->headers       = array();
1112             $response->response_code = 'Invalid protocol specified in url';
1113             $response->results       = '';
1114             $response->error         = 'Invalid protocol specified in url';
1115             return $response;
1116         } else {
1117             return false;
1118         }
1119     }
1121     // check if proxy (if used) should be bypassed for this url
1122     $proxybypass = is_proxybypass($url);
1124     if (!$ch = curl_init($url)) {
1125         debugging('Can not init curl.');
1126         return false;
1127     }
1129     // set extra headers
1130     if (is_array($headers) ) {
1131         $headers2 = array();
1132         foreach ($headers as $key => $value) {
1133             $headers2[] = "$key: $value";
1134         }
1135         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1136     }
1138     if ($skipcertverify) {
1139         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1140     }
1142     // use POST if requested
1143     if (is_array($postdata)) {
1144         $postdata = format_postdata_for_curlcall($postdata);
1145         curl_setopt($ch, CURLOPT_POST, true);
1146         curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1147     }
1149     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1150     curl_setopt($ch, CURLOPT_HEADER, false);
1151     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1153     if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1154         // TODO: add version test for '7.10.5'
1155         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1156         curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1157     }
1159     if (!empty($CFG->proxyhost) and !$proxybypass) {
1160         // SOCKS supported in PHP5 only
1161         if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1162             if (defined('CURLPROXY_SOCKS5')) {
1163                 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1164             } else {
1165                 curl_close($ch);
1166                 if ($fullresponse) {
1167                     $response = new stdClass();
1168                     $response->status        = '0';
1169                     $response->headers       = array();
1170                     $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1171                     $response->results       = '';
1172                     $response->error         = 'SOCKS5 proxy is not supported in PHP4';
1173                     return $response;
1174                 } else {
1175                     debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1176                     return false;
1177                 }
1178             }
1179         }
1181         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1183         if (empty($CFG->proxyport)) {
1184             curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1185         } else {
1186             curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1187         }
1189         if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1190             curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1191             if (defined('CURLOPT_PROXYAUTH')) {
1192                 // any proxy authentication if PHP 5.1
1193                 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1194             }
1195         }
1196     }
1198     // set up header and content handlers
1199     $received = new stdClass();
1200     $received->headers = array(); // received headers array
1201     $received->tofile  = $tofile;
1202     $received->fh      = null;
1203     curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1204     if ($tofile) {
1205         curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1206     }
1208     if (!isset($CFG->curltimeoutkbitrate)) {
1209         //use very slow rate of 56kbps as a timeout speed when not set
1210         $bitrate = 56;
1211     } else {
1212         $bitrate = $CFG->curltimeoutkbitrate;
1213     }
1215     // try to calculate the proper amount for timeout from remote file size.
1216     // if disabled or zero, we won't do any checks nor head requests.
1217     if ($calctimeout && $bitrate > 0) {
1218         //setup header request only options
1219         curl_setopt_array ($ch, array(
1220             CURLOPT_RETURNTRANSFER => false,
1221             CURLOPT_NOBODY         => true)
1222         );
1224         curl_exec($ch);
1225         $info = curl_getinfo($ch);
1226         $err = curl_error($ch);
1228         if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1229             $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1230         }
1231         //reinstate affected curl options
1232         curl_setopt_array ($ch, array(
1233             CURLOPT_RETURNTRANSFER => true,
1234             CURLOPT_NOBODY         => false)
1235         );
1236     }
1238     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1239     $result = curl_exec($ch);
1241     // try to detect encoding problems
1242     if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1243         curl_setopt($ch, CURLOPT_ENCODING, 'none');
1244         $result = curl_exec($ch);
1245     }
1247     if ($received->fh) {
1248         fclose($received->fh);
1249     }
1251     if (curl_errno($ch)) {
1252         $error    = curl_error($ch);
1253         $error_no = curl_errno($ch);
1254         curl_close($ch);
1256         if ($fullresponse) {
1257             $response = new stdClass();
1258             if ($error_no == 28) {
1259                 $response->status    = '-100'; // mimic snoopy
1260             } else {
1261                 $response->status    = '0';
1262             }
1263             $response->headers       = array();
1264             $response->response_code = $error;
1265             $response->results       = false;
1266             $response->error         = $error;
1267             return $response;
1268         } else {
1269             debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1270             return false;
1271         }
1273     } else {
1274         $info = curl_getinfo($ch);
1275         curl_close($ch);
1277         if (empty($info['http_code'])) {
1278             // for security reasons we support only true http connections (Location: file:// exploit prevention)
1279             $response = new stdClass();
1280             $response->status        = '0';
1281             $response->headers       = array();
1282             $response->response_code = 'Unknown cURL error';
1283             $response->results       = false; // do NOT change this, we really want to ignore the result!
1284             $response->error         = 'Unknown cURL error';
1286         } else {
1287             $response = new stdClass();;
1288             $response->status        = (string)$info['http_code'];
1289             $response->headers       = $received->headers;
1290             $response->response_code = $received->headers[0];
1291             $response->results       = $result;
1292             $response->error         = '';
1293         }
1295         if ($fullresponse) {
1296             return $response;
1297         } else if ($info['http_code'] != 200) {
1298             debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1299             return false;
1300         } else {
1301             return $response->results;
1302         }
1303     }
1306 /**
1307  * internal implementation
1308  * @param stdClass $received
1309  * @param resource $ch
1310  * @param mixed $header
1311  * @return int header length
1312  */
1313 function download_file_content_header_handler($received, $ch, $header) {
1314     $received->headers[] = $header;
1315     return strlen($header);
1318 /**
1319  * internal implementation
1320  * @param stdClass $received
1321  * @param resource $ch
1322  * @param mixed $data
1323  */
1324 function download_file_content_write_handler($received, $ch, $data) {
1325     if (!$received->fh) {
1326         $received->fh = fopen($received->tofile, 'w');
1327         if ($received->fh === false) {
1328             // bad luck, file creation or overriding failed
1329             return 0;
1330         }
1331     }
1332     if (fwrite($received->fh, $data) === false) {
1333         // bad luck, write failed, let's abort completely
1334         return 0;
1335     }
1336     return strlen($data);
1339 /**
1340  * Returns a list of information about file types based on extensions.
1341  *
1342  * The following elements expected in value array for each extension:
1343  * 'type' - mimetype
1344  * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1345  *     or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1346  *     also files with bigger sizes under names
1347  *     FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1348  * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1349  *     commonly used in moodle the following groups:
1350  *       - web_image - image that can be included as <img> in HTML
1351  *       - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1352  *       - video - file that can be imported as video in text editor
1353  *       - audio - file that can be imported as audio in text editor
1354  *       - archive - we can extract files from this archive
1355  *       - spreadsheet - used for portfolio format
1356  *       - document - used for portfolio format
1357  *       - presentation - used for portfolio format
1358  * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1359  *     human-readable description for this filetype;
1360  *     Function {@link get_mimetype_description()} first looks at the presence of string for
1361  *     particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1362  *     attribute, if not found returns the value of 'type';
1363  * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1364  *     an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1365  *     this function will return first found icon; Especially usefull for types such as 'text/plain'
1366  *
1367  * @category files
1368  * @return array List of information about file types based on extensions.
1369  *   Associative array of extension (lower-case) to associative array
1370  *   from 'element name' to data. Current element names are 'type' and 'icon'.
1371  *   Unknown types should use the 'xxx' entry which includes defaults.
1372  */
1373 function &get_mimetypes_array() {
1374     static $mimearray = array (
1375         'xxx'  => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1376         '3gp'  => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1377         'aac'  => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1378         'accdb'  => array ('type'=>'application/msaccess', 'icon'=>'base'),
1379         'ai'   => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1380         'aif'  => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1381         'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1382         'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1383         'applescript'  => array ('type'=>'text/plain', 'icon'=>'text'),
1384         'asc'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1385         'asm'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1386         'au'   => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1387         'avi'  => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1388         'bmp'  => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1389         'c'    => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1390         'cct'  => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1391         'cpp'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1392         'cs'   => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1393         'css'  => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1394         'csv'  => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1395         'dv'   => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1396         'dmg'  => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1398         'doc'  => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1399         'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1400         'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1401         'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1402         'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1404         'dcr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1405         'dif'  => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1406         'dir'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1407         'dxr'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1408         'eps'  => array ('type'=>'application/postscript', 'icon'=>'eps'),
1409         'fdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1410         'flv'  => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1411         'f4v'  => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1412         'gif'  => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1413         'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1414         'tgz'  => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1415         'gz'   => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1416         'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1417         'h'    => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1418         'hpp'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1419         'hqx'  => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1420         'htc'  => array ('type'=>'text/x-component', 'icon'=>'markup'),
1421         'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1422         'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1423         'htm'  => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1424         'ico'  => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1425         'ics'  => array ('type'=>'text/calendar', 'icon'=>'text'),
1426         'isf'  => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1427         'ist'  => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1428         'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1429         'jcb'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1430         'jcl'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1431         'jcw'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1432         'jmt'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1433         'jmx'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1434         'jpe'  => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1435         'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1436         'jpg'  => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1437         'jqz'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1438         'js'   => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1439         'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1440         'm'    => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1441         'mbz'  => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1442         'mdb'  => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1443         'mov'  => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1444         'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1445         'm3u'  => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1446         'mp3'  => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1447         'mp4'  => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1448         'm4v'  => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1449         'm4a'  => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1450         'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1451         'mpe'  => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1452         'mpg'  => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1454         'odt'  => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1455         'ott'  => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1456         'oth'  => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1457         'odm'  => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1458         'odg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1459         'otg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1460         'odp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1461         'otp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1462         'ods'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1463         'ots'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1464         'odc'  => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1465         'odf'  => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1466         'odb'  => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1467         'odi'  => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1468         'oga'  => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1469         'ogg'  => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1470         'ogv'  => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1472         'pct'  => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1473         'pdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1474         'php'  => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1475         'pic'  => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1476         'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1477         'png'  => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1479         'pps'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1480         'ppt'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1481         'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1482         'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1483         'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1484         'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1485         'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1486         'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1487         'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1489         'ps'   => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1490         'qt'   => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1491         'ra'   => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1492         'ram'  => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1493         'rhb'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1494         'rm'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1495         'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1496         'rtf'  => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1497         'rtx'  => array ('type'=>'text/richtext', 'icon'=>'text'),
1498         'rv'   => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1499         'sh'   => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1500         'sit'  => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1501         'smi'  => array ('type'=>'application/smil', 'icon'=>'text'),
1502         'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1503         'sqt'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1504         'svg'  => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1505         'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1506         'swa'  => array ('type'=>'application/x-director', 'icon'=>'flash'),
1507         'swf'  => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1508         'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1510         'sxw'  => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1511         'stw'  => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1512         'sxc'  => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1513         'stc'  => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1514         'sxd'  => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1515         'std'  => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1516         'sxi'  => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1517         'sti'  => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1518         'sxg'  => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1519         'sxm'  => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1521         'tar'  => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1522         'tif'  => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1523         'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1524         'tex'  => array ('type'=>'application/x-tex', 'icon'=>'text'),
1525         'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1526         'texinfo'  => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1527         'tsv'  => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1528         'txt'  => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1529         'wav'  => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1530         'webm'  => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1531         'wmv'  => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1532         'asf'  => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1533         'xdp'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1534         'xfd'  => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1535         'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1537         'xls'  => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1538         'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1539         'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1540         'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1541         'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1542         'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1543         'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1545         'xml'  => array ('type'=>'application/xml', 'icon'=>'markup'),
1546         'xsl'  => array ('type'=>'text/xml', 'icon'=>'markup'),
1547         'zip'  => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1548     );
1549     return $mimearray;
1552 /**
1553  * Obtains information about a filetype based on its extension. Will
1554  * use a default if no information is present about that particular
1555  * extension.
1556  *
1557  * @category files
1558  * @param string $element Desired information (usually 'icon'
1559  *   for icon filename or 'type' for MIME type. Can also be
1560  *   'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1561  * @param string $filename Filename we're looking up
1562  * @return string Requested piece of information from array
1563  */
1564 function mimeinfo($element, $filename) {
1565     global $CFG;
1566     $mimeinfo = & get_mimetypes_array();
1567     static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1569     $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1570     if (empty($filetype)) {
1571         $filetype = 'xxx'; // file without extension
1572     }
1573     if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1574         $iconsize = max(array(16, (int)$iconsizematch[1]));
1575         $filenames = array($mimeinfo['xxx']['icon']);
1576         if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1577             array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1578         }
1579         // find the file with the closest size, first search for specific icon then for default icon
1580         foreach ($filenames as $filename) {
1581             foreach ($iconpostfixes as $size => $postfix) {
1582                 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1583                 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1584                     return $filename.$postfix;
1585                 }
1586             }
1587         }
1588     } else if (isset($mimeinfo[$filetype][$element])) {
1589         return $mimeinfo[$filetype][$element];
1590     } else if (isset($mimeinfo['xxx'][$element])) {
1591         return $mimeinfo['xxx'][$element];   // By default
1592     } else {
1593         return null;
1594     }
1597 /**
1598  * Obtains information about a filetype based on the MIME type rather than
1599  * the other way around.
1600  *
1601  * @category files
1602  * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1603  * @param string $mimetype MIME type we're looking up
1604  * @return string Requested piece of information from array
1605  */
1606 function mimeinfo_from_type($element, $mimetype) {
1607     /* array of cached mimetype->extension associations */
1608     static $cached = array();
1609     $mimeinfo = & get_mimetypes_array();
1611     if (!array_key_exists($mimetype, $cached)) {
1612         $cached[$mimetype] = null;
1613         foreach($mimeinfo as $filetype => $values) {
1614             if ($values['type'] == $mimetype) {
1615                 if ($cached[$mimetype] === null) {
1616                     $cached[$mimetype] = '.'.$filetype;
1617                 }
1618                 if (!empty($values['defaulticon'])) {
1619                     $cached[$mimetype] = '.'.$filetype;
1620                     break;
1621                 }
1622             }
1623         }
1624         if (empty($cached[$mimetype])) {
1625             $cached[$mimetype] = '.xxx';
1626         }
1627     }
1628     if ($element === 'extension') {
1629         return $cached[$mimetype];
1630     } else {
1631         return mimeinfo($element, $cached[$mimetype]);
1632     }
1635 /**
1636  * Return the relative icon path for a given file
1637  *
1638  * Usage:
1639  * <code>
1640  * // $file - instance of stored_file or file_info
1641  * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1642  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1643  * </code>
1644  * or
1645  * <code>
1646  * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1647  * </code>
1648  *
1649  * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1650  *     and $file->mimetype are expected)
1651  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1652  * @return string
1653  */
1654 function file_file_icon($file, $size = null) {
1655     if (!is_object($file)) {
1656         $file = (object)$file;
1657     }
1658     if (isset($file->filename)) {
1659         $filename = $file->filename;
1660     } else if (method_exists($file, 'get_filename')) {
1661         $filename = $file->get_filename();
1662     } else if (method_exists($file, 'get_visible_name')) {
1663         $filename = $file->get_visible_name();
1664     } else {
1665         $filename = '';
1666     }
1667     if (isset($file->mimetype)) {
1668         $mimetype = $file->mimetype;
1669     } else if (method_exists($file, 'get_mimetype')) {
1670         $mimetype = $file->get_mimetype();
1671     } else {
1672         $mimetype = '';
1673     }
1674     $mimetypes = &get_mimetypes_array();
1675     if ($filename) {
1676         $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1677         if ($extension && !empty($mimetypes[$extension])) {
1678             // if file name has known extension, return icon for this extension
1679             return file_extension_icon($filename, $size);
1680         }
1681     }
1682     return file_mimetype_icon($mimetype, $size);
1685 /**
1686  * Return the relative icon path for a folder image
1687  *
1688  * Usage:
1689  * <code>
1690  * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1691  * echo html_writer::empty_tag('img', array('src' => $icon));
1692  * </code>
1693  * or
1694  * <code>
1695  * echo $OUTPUT->pix_icon(file_folder_icon(32));
1696  * </code>
1697  *
1698  * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1699  * @return string
1700  */
1701 function file_folder_icon($iconsize = null) {
1702     global $CFG;
1703     static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1704     static $cached = array();
1705     $iconsize = max(array(16, (int)$iconsize));
1706     if (!array_key_exists($iconsize, $cached)) {
1707         foreach ($iconpostfixes as $size => $postfix) {
1708             $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1709             if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1710                 $cached[$iconsize] = 'f/folder'.$postfix;
1711                 break;
1712             }
1713         }
1714     }
1715     return $cached[$iconsize];
1718 /**
1719  * Returns the relative icon path for a given mime type
1720  *
1721  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1722  * a return the full path to an icon.
1723  *
1724  * <code>
1725  * $mimetype = 'image/jpg';
1726  * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1727  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1728  * </code>
1729  *
1730  * @category files
1731  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1732  * to conform with that.
1733  * @param string $mimetype The mimetype to fetch an 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 The relative path to the icon
1736  */
1737 function file_mimetype_icon($mimetype, $size = NULL) {
1738     return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1741 /**
1742  * Returns the relative icon path for a given file name
1743  *
1744  * This function should be used in conjunction with $OUTPUT->pix_url to produce
1745  * a return the full path to an icon.
1746  *
1747  * <code>
1748  * $filename = '.jpg';
1749  * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1750  * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1751  * </code>
1752  *
1753  * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1754  * to conform with that.
1755  * @todo MDL-31074 Implement $size
1756  * @category files
1757  * @param string $filename The filename to get the icon for
1758  * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1759  * @return string
1760  */
1761 function file_extension_icon($filename, $size = NULL) {
1762     return 'f/'.mimeinfo('icon'.$size, $filename);
1765 /**
1766  * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1767  * mimetypes.php language file.
1768  *
1769  * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1770  *   'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1771  *   have filename); In case of array/stdClass the field 'mimetype' is optional.
1772  * @param bool $capitalise If true, capitalises first character of result
1773  * @return string Text description
1774  */
1775 function get_mimetype_description($obj, $capitalise=false) {
1776     $filename = $mimetype = '';
1777     if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1778         // this is an instance of stored_file
1779         $mimetype = $obj->get_mimetype();
1780         $filename = $obj->get_filename();
1781     } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1782         // this is an instance of file_info
1783         $mimetype = $obj->get_mimetype();
1784         $filename = $obj->get_visible_name();
1785     } else if (is_array($obj) || is_object ($obj)) {
1786         $obj = (array)$obj;
1787         if (!empty($obj['filename'])) {
1788             $filename = $obj['filename'];
1789         }
1790         if (!empty($obj['mimetype'])) {
1791             $mimetype = $obj['mimetype'];
1792         }
1793     } else {
1794         $mimetype = $obj;
1795     }
1796     $mimetypefromext = mimeinfo('type', $filename);
1797     if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1798         // if file has a known extension, overwrite the specified mimetype
1799         $mimetype = $mimetypefromext;
1800     }
1801     $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1802     if (empty($extension)) {
1803         $mimetypestr = mimeinfo_from_type('string', $mimetype);
1804         $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1805     } else {
1806         $mimetypestr = mimeinfo('string', $filename);
1807     }
1808     $chunks = explode('/', $mimetype, 2);
1809     $chunks[] = '';
1810     $attr = array(
1811         'mimetype' => $mimetype,
1812         'ext' => $extension,
1813         'mimetype1' => $chunks[0],
1814         'mimetype2' => $chunks[1],
1815     );
1816     $a = array();
1817     foreach ($attr as $key => $value) {
1818         $a[$key] = $value;
1819         $a[strtoupper($key)] = strtoupper($value);
1820         $a[ucfirst($key)] = ucfirst($value);
1821     }
1822     if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1823         $result = get_string($mimetype, 'mimetypes', (object)$a);
1824     } else if (get_string_manager()->string_exists($mimetypestr, 'mimetypes')) {
1825         $result = get_string($mimetypestr, 'mimetypes', (object)$a);
1826     } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1827         $result = get_string('default', 'mimetypes', (object)$a);
1828     } else {
1829         $result = $mimetype;
1830     }
1831     if ($capitalise) {
1832         $result=ucfirst($result);
1833     }
1834     return $result;
1837 /**
1838  * Returns array of elements of type $element in type group(s)
1839  *
1840  * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1841  * @param string|array $groups one group or array of groups/extensions/mimetypes
1842  * @return array
1843  */
1844 function file_get_typegroup($element, $groups) {
1845     static $cached = array();
1846     if (!is_array($groups)) {
1847         $groups = array($groups);
1848     }
1849     if (!array_key_exists($element, $cached)) {
1850         $cached[$element] = array();
1851     }
1852     $result = array();
1853     foreach ($groups as $group) {
1854         if (!array_key_exists($group, $cached[$element])) {
1855             // retrieive and cache all elements of type $element for group $group
1856             $mimeinfo = & get_mimetypes_array();
1857             $cached[$element][$group] = array();
1858             foreach ($mimeinfo as $extension => $value) {
1859                 $value['extension'] = '.'.$extension;
1860                 if (empty($value[$element])) {
1861                     continue;
1862                 }
1863                 if (($group === '.'.$extension || $group === $value['type'] ||
1864                         (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1865                         !in_array($value[$element], $cached[$element][$group])) {
1866                     $cached[$element][$group][] = $value[$element];
1867                 }
1868             }
1869         }
1870         $result = array_merge($result, $cached[$element][$group]);
1871     }
1872     return array_unique($result);
1875 /**
1876  * Checks if file with name $filename has one of the extensions in groups $groups
1877  *
1878  * @see get_mimetypes_array()
1879  * @param string $filename name of the file to check
1880  * @param string|array $groups one group or array of groups to check
1881  * @param bool $checktype if true and extension check fails, find the mimetype and check if
1882  * file mimetype is in mimetypes in groups $groups
1883  * @return bool
1884  */
1885 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1886     $extension = pathinfo($filename, PATHINFO_EXTENSION);
1887     if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1888         return true;
1889     }
1890     return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1893 /**
1894  * Checks if mimetype $mimetype belongs to one of the groups $groups
1895  *
1896  * @see get_mimetypes_array()
1897  * @param string $mimetype
1898  * @param string|array $groups one group or array of groups to check
1899  * @return bool
1900  */
1901 function file_mimetype_in_typegroup($mimetype, $groups) {
1902     return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1905 /**
1906  * Requested file is not found or not accessible, does not return, terminates script
1907  *
1908  * @global stdClass $CFG
1909  * @global stdClass $COURSE
1910  */
1911 function send_file_not_found() {
1912     global $CFG, $COURSE;
1913     send_header_404();
1914     print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1916 /**
1917  * Helper function to send correct 404 for server.
1918  */
1919 function send_header_404() {
1920     if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1921         header("Status: 404 Not Found");
1922     } else {
1923         header('HTTP/1.0 404 not found');
1924     }
1927 /**
1928  * Enhanced readfile() with optional acceleration.
1929  * @param string|stored_file $file
1930  * @param string $mimetype
1931  * @param bool $accelerate
1932  * @return void
1933  */
1934 function readfile_accel($file, $mimetype, $accelerate) {
1935     global $CFG;
1937     if ($mimetype === 'text/plain') {
1938         // there is no encoding specified in text files, we need something consistent
1939         header('Content-Type: text/plain; charset=utf-8');
1940     } else {
1941         header('Content-Type: '.$mimetype);
1942     }
1944     $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1945     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1947     if (is_object($file)) {
1948         header('ETag: ' . $file->get_contenthash());
1949         if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1950             header('HTTP/1.1 304 Not Modified');
1951             return;
1952         }
1953     }
1955     // if etag present for stored file rely on it exclusively
1956     if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1957         // get unixtime of request header; clip extra junk off first
1958         $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1959         if ($since && $since >= $lastmodified) {
1960             header('HTTP/1.1 304 Not Modified');
1961             return;
1962         }
1963     }
1965     if ($accelerate and !empty($CFG->xsendfile)) {
1966         if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1967             header('Accept-Ranges: bytes');
1968         } else {
1969             header('Accept-Ranges: none');
1970         }
1972         if (is_object($file)) {
1973             $fs = get_file_storage();
1974             if ($fs->xsendfile($file->get_contenthash())) {
1975                 return;
1976             }
1978         } else {
1979             require_once("$CFG->libdir/xsendfilelib.php");
1980             if (xsendfile($file)) {
1981                 return;
1982             }
1983         }
1984     }
1986     $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1988     header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1990     if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1991         header('Accept-Ranges: bytes');
1993         if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1994             // byteserving stuff - for acrobat reader and download accelerators
1995             // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1996             // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1997             $ranges = false;
1998             if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1999                 foreach ($ranges as $key=>$value) {
2000                     if ($ranges[$key][1] == '') {
2001                         //suffix case
2002                         $ranges[$key][1] = $filesize - $ranges[$key][2];
2003                         $ranges[$key][2] = $filesize - 1;
2004                     } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2005                         //fix range length
2006                         $ranges[$key][2] = $filesize - 1;
2007                     }
2008                     if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2009                         //invalid byte-range ==> ignore header
2010                         $ranges = false;
2011                         break;
2012                     }
2013                     //prepare multipart header
2014                     $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2015                     $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2016                 }
2017             } else {
2018                 $ranges = false;
2019             }
2020             if ($ranges) {
2021                 if (is_object($file)) {
2022                     $handle = $file->get_content_file_handle();
2023                 } else {
2024                     $handle = fopen($file, 'rb');
2025                 }
2026                 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2027             }
2028         }
2029     } else {
2030         // Do not byteserve
2031         header('Accept-Ranges: none');
2032     }
2034     header('Content-Length: '.$filesize);
2036     if ($filesize > 10000000) {
2037         // for large files try to flush and close all buffers to conserve memory
2038         while(@ob_get_level()) {
2039             if (!@ob_end_flush()) {
2040                 break;
2041             }
2042         }
2043     }
2045     // send the whole file content
2046     if (is_object($file)) {
2047         $file->readfile();
2048     } else {
2049         readfile($file);
2050     }
2053 /**
2054  * Similar to readfile_accel() but designed for strings.
2055  * @param string $string
2056  * @param string $mimetype
2057  * @param bool $accelerate
2058  * @return void
2059  */
2060 function readstring_accel($string, $mimetype, $accelerate) {
2061     global $CFG;
2063     if ($mimetype === 'text/plain') {
2064         // there is no encoding specified in text files, we need something consistent
2065         header('Content-Type: text/plain; charset=utf-8');
2066     } else {
2067         header('Content-Type: '.$mimetype);
2068     }
2069     header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2070     header('Accept-Ranges: none');
2072     if ($accelerate and !empty($CFG->xsendfile)) {
2073         $fs = get_file_storage();
2074         if ($fs->xsendfile(sha1($string))) {
2075             return;
2076         }
2077     }
2079     header('Content-Length: '.strlen($string));
2080     echo $string;
2083 /**
2084  * Handles the sending of temporary file to user, download is forced.
2085  * File is deleted after abort or successful sending, does not return, script terminated
2086  *
2087  * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2088  * @param string $filename proposed file name when saving file
2089  * @param bool $pathisstring If the path is string
2090  */
2091 function send_temp_file($path, $filename, $pathisstring=false) {
2092     global $CFG;
2094     if (check_browser_version('Firefox', '1.5')) {
2095         // only FF is known to correctly save to disk before opening...
2096         $mimetype = mimeinfo('type', $filename);
2097     } else {
2098         $mimetype = 'application/x-forcedownload';
2099     }
2101     // close session - not needed anymore
2102     session_get_instance()->write_close();
2104     if (!$pathisstring) {
2105         if (!file_exists($path)) {
2106             send_header_404();
2107             print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2108         }
2109         // executed after normal finish or abort
2110         @register_shutdown_function('send_temp_file_finished', $path);
2111     }
2113     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2114     if (check_browser_version('MSIE')) {
2115         $filename = urlencode($filename);
2116     }
2118     header('Content-Disposition: attachment; filename="'.$filename.'"');
2119     if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2120         header('Cache-Control: max-age=10');
2121         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2122         header('Pragma: ');
2123     } else { //normal http - prevent caching at all cost
2124         header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2125         header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2126         header('Pragma: no-cache');
2127     }
2129     // send the contents - we can not accelerate this because the file will be deleted asap
2130     if ($pathisstring) {
2131         readstring_accel($path, $mimetype, false);
2132     } else {
2133         readfile_accel($path, $mimetype, false);
2134         @unlink($path);
2135     }
2137     die; //no more chars to output
2140 /**
2141  * Internal callback function used by send_temp_file()
2142  *
2143  * @param string $path
2144  */
2145 function send_temp_file_finished($path) {
2146     if (file_exists($path)) {
2147         @unlink($path);
2148     }
2151 /**
2152  * Handles the sending of file data to the user's browser, including support for
2153  * byteranges etc.
2154  *
2155  * @category files
2156  * @param string $path Path of file on disk (including real filename), or actual content of file as string
2157  * @param string $filename Filename to send
2158  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2159  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2160  * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2161  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2162  * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2163  * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2164  *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2165  *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
2166  *                        and should not be reopened.
2167  * @return null script execution stopped unless $dontdie is true
2168  */
2169 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2170     global $CFG, $COURSE;
2172     if ($dontdie) {
2173         ignore_user_abort(true);
2174     }
2176     // MDL-11789, apply $CFG->filelifetime here
2177     if ($lifetime === 'default') {
2178         if (!empty($CFG->filelifetime)) {
2179             $lifetime = $CFG->filelifetime;
2180         } else {
2181             $lifetime = 86400;
2182         }
2183     }
2185     session_get_instance()->write_close(); // unlock session during fileserving
2187     // Use given MIME type if specified, otherwise guess it using mimeinfo.
2188     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2189     // only Firefox saves all files locally before opening when content-disposition: attachment stated
2190     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2191     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2192                          ($mimetype ? $mimetype : mimeinfo('type', $filename));
2194     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2195     if (check_browser_version('MSIE')) {
2196         $filename = rawurlencode($filename);
2197     }
2199     if ($forcedownload) {
2200         header('Content-Disposition: attachment; filename="'.$filename.'"');
2201     } else {
2202         header('Content-Disposition: inline; filename="'.$filename.'"');
2203     }
2205     if ($lifetime > 0) {
2206         $nobyteserving = false;
2207         header('Cache-Control: max-age='.$lifetime);
2208         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2209         header('Pragma: ');
2211     } else { // Do not cache files in proxies and browsers
2212         $nobyteserving = true;
2213         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2214             header('Cache-Control: max-age=10');
2215             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2216             header('Pragma: ');
2217         } else { //normal http - prevent caching at all cost
2218             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2219             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2220             header('Pragma: no-cache');
2221         }
2222     }
2224     if (empty($filter)) {
2225         // send the contents
2226         if ($pathisstring) {
2227             readstring_accel($path, $mimetype, !$dontdie);
2228         } else {
2229             readfile_accel($path, $mimetype, !$dontdie);
2230         }
2232     } else {
2233         // Try to put the file through filters
2234         if ($mimetype == 'text/html') {
2235             $options = new stdClass();
2236             $options->noclean = true;
2237             $options->nocache = true; // temporary workaround for MDL-5136
2238             $text = $pathisstring ? $path : implode('', file($path));
2240             $text = file_modify_html_header($text);
2241             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2243             readstring_accel($output, $mimetype, false);
2245         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2246             // only filter text if filter all files is selected
2247             $options = new stdClass();
2248             $options->newlines = false;
2249             $options->noclean = true;
2250             $text = htmlentities($pathisstring ? $path : implode('', file($path)));
2251             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2253             readstring_accel($output, $mimetype, false);
2255         } else {
2256             // send the contents
2257             if ($pathisstring) {
2258                 readstring_accel($path, $mimetype, !$dontdie);
2259             } else {
2260                 readfile_accel($path, $mimetype, !$dontdie);
2261             }
2262         }
2263     }
2264     if ($dontdie) {
2265         return;
2266     }
2267     die; //no more chars to output!!!
2270 /**
2271  * Handles the sending of file data to the user's browser, including support for
2272  * byteranges etc.
2273  *
2274  * The $options parameter supports the following keys:
2275  *  (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2276  *  (string|null) filename - overrides the implicit filename
2277  *  (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2278  *      if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2279  *      you must detect this case when control is returned using connection_aborted. Please not that session is closed
2280  *      and should not be reopened.
2281  *
2282  * @category files
2283  * @param stored_file $stored_file local file object
2284  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2285  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2286  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2287  * @param array $options additional options affecting the file serving
2288  * @return null script execution stopped unless $options['dontdie'] is true
2289  */
2290 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2291     global $CFG, $COURSE;
2293     if (empty($options['filename'])) {
2294         $filename = null;
2295     } else {
2296         $filename = $options['filename'];
2297     }
2299     if (empty($options['dontdie'])) {
2300         $dontdie = false;
2301     } else {
2302         $dontdie = true;
2303     }
2305     if (!empty($options['preview'])) {
2306         // replace the file with its preview
2307         $fs = get_file_storage();
2308         $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2309         if (!$preview_file) {
2310             // unable to create a preview of the file, send its default mime icon instead
2311             if ($options['preview'] === 'tinyicon') {
2312                 $size = 24;
2313             } else if ($options['preview'] === 'thumb') {
2314                 $size = 90;
2315             } else {
2316                 $size = 256;
2317             }
2318             $fileicon = file_file_icon($stored_file, $size);
2319             send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2320         } else {
2321             // preview images have fixed cache lifetime and they ignore forced download
2322             // (they are generated by GD and therefore they are considered reasonably safe).
2323             $stored_file = $preview_file;
2324             $lifetime = DAYSECS;
2325             $filter = 0;
2326             $forcedownload = false;
2327         }
2328     }
2330     // handle external resource
2331     if ($stored_file && $stored_file->is_external_file()) {
2332         $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2333         die;
2334     }
2336     if (!$stored_file or $stored_file->is_directory()) {
2337         // nothing to serve
2338         if ($dontdie) {
2339             return;
2340         }
2341         die;
2342     }
2344     if ($dontdie) {
2345         ignore_user_abort(true);
2346     }
2348     session_get_instance()->write_close(); // unlock session during fileserving
2350     // Use given MIME type if specified, otherwise guess it using mimeinfo.
2351     // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2352     // only Firefox saves all files locally before opening when content-disposition: attachment stated
2353     $filename     = is_null($filename) ? $stored_file->get_filename() : $filename;
2354     $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2355     $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2356                          ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2358     // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2359     if (check_browser_version('MSIE')) {
2360         $filename = rawurlencode($filename);
2361     }
2363     if ($forcedownload) {
2364         header('Content-Disposition: attachment; filename="'.$filename.'"');
2365     } else {
2366         header('Content-Disposition: inline; filename="'.$filename.'"');
2367     }
2369     if ($lifetime > 0) {
2370         header('Cache-Control: max-age='.$lifetime);
2371         header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2372         header('Pragma: ');
2374     } else { // Do not cache files in proxies and browsers
2375         if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2376             header('Cache-Control: max-age=10');
2377             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2378             header('Pragma: ');
2379         } else { //normal http - prevent caching at all cost
2380             header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2381             header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2382             header('Pragma: no-cache');
2383         }
2384     }
2386     if (empty($filter)) {
2387         // send the contents
2388         readfile_accel($stored_file, $mimetype, !$dontdie);
2390     } else {     // Try to put the file through filters
2391         if ($mimetype == 'text/html') {
2392             $options = new stdClass();
2393             $options->noclean = true;
2394             $options->nocache = true; // temporary workaround for MDL-5136
2395             $text = $stored_file->get_content();
2396             $text = file_modify_html_header($text);
2397             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2399             readstring_accel($output, $mimetype, false);
2401         } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2402             // only filter text if filter all files is selected
2403             $options = new stdClass();
2404             $options->newlines = false;
2405             $options->noclean = true;
2406             $text = $stored_file->get_content();
2407             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2409             readstring_accel($output, $mimetype, false);
2411         } else {    // Just send it out raw
2412             readfile_accel($stored_file, $mimetype, !$dontdie);
2413         }
2414     }
2415     if ($dontdie) {
2416         return;
2417     }
2418     die; //no more chars to output!!!
2421 /**
2422  * Retrieves an array of records from a CSV file and places
2423  * them into a given table structure
2424  *
2425  * @global stdClass $CFG
2426  * @global moodle_database $DB
2427  * @param string $file The path to a CSV file
2428  * @param string $table The table to retrieve columns from
2429  * @return bool|array Returns an array of CSV records or false
2430  */
2431 function get_records_csv($file, $table) {
2432     global $CFG, $DB;
2434     if (!$metacolumns = $DB->get_columns($table)) {
2435         return false;
2436     }
2438     if(!($handle = @fopen($file, 'r'))) {
2439         print_error('get_records_csv failed to open '.$file);
2440     }
2442     $fieldnames = fgetcsv($handle, 4096);
2443     if(empty($fieldnames)) {
2444         fclose($handle);
2445         return false;
2446     }
2448     $columns = array();
2450     foreach($metacolumns as $metacolumn) {
2451         $ord = array_search($metacolumn->name, $fieldnames);
2452         if(is_int($ord)) {
2453             $columns[$metacolumn->name] = $ord;
2454         }
2455     }
2457     $rows = array();
2459     while (($data = fgetcsv($handle, 4096)) !== false) {
2460         $item = new stdClass;
2461         foreach($columns as $name => $ord) {
2462             $item->$name = $data[$ord];
2463         }
2464         $rows[] = $item;
2465     }
2467     fclose($handle);
2468     return $rows;
2471 /**
2472  * Create a file with CSV contents
2473  *
2474  * @global stdClass $CFG
2475  * @global moodle_database $DB
2476  * @param string $file The file to put the CSV content into
2477  * @param array $records An array of records to write to a CSV file
2478  * @param string $table The table to get columns from
2479  * @return bool success
2480  */
2481 function put_records_csv($file, $records, $table = NULL) {
2482     global $CFG, $DB;
2484     if (empty($records)) {
2485         return true;
2486     }
2488     $metacolumns = NULL;
2489     if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2490         return false;
2491     }
2493     echo "x";
2495     if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2496         print_error('put_records_csv failed to open '.$file);
2497     }
2499     $proto = reset($records);
2500     if(is_object($proto)) {
2501         $fields_records = array_keys(get_object_vars($proto));
2502     }
2503     else if(is_array($proto)) {
2504         $fields_records = array_keys($proto);
2505     }
2506     else {
2507         return false;
2508     }
2509     echo "x";
2511     if(!empty($metacolumns)) {
2512         $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2513         $fields = array_intersect($fields_records, $fields_table);
2514     }
2515     else {
2516         $fields = $fields_records;
2517     }
2519     fwrite($fp, implode(',', $fields));
2520     fwrite($fp, "\r\n");
2522     foreach($records as $record) {
2523         $array  = (array)$record;
2524         $values = array();
2525         foreach($fields as $field) {
2526             if(strpos($array[$field], ',')) {
2527                 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2528             }
2529             else {
2530                 $values[] = $array[$field];
2531             }
2532         }
2533         fwrite($fp, implode(',', $values)."\r\n");
2534     }
2536     fclose($fp);
2537     return true;
2541 /**
2542  * Recursively delete the file or folder with path $location. That is,
2543  * if it is a file delete it. If it is a folder, delete all its content
2544  * then delete it. If $location does not exist to start, that is not
2545  * considered an error.
2546  *
2547  * @param string $location the path to remove.
2548  * @return bool
2549  */
2550 function fulldelete($location) {
2551     if (empty($location)) {
2552         // extra safety against wrong param
2553         return false;
2554     }
2555     if (is_dir($location)) {
2556         if (!$currdir = opendir($location)) {
2557             return false;
2558         }
2559         while (false !== ($file = readdir($currdir))) {
2560             if ($file <> ".." && $file <> ".") {
2561                 $fullfile = $location."/".$file;
2562                 if (is_dir($fullfile)) {
2563                     if (!fulldelete($fullfile)) {
2564                         return false;
2565                     }
2566                 } else {
2567                     if (!unlink($fullfile)) {
2568                         return false;
2569                     }
2570                 }
2571             }
2572         }
2573         closedir($currdir);
2574         if (! rmdir($location)) {
2575             return false;
2576         }
2578     } else if (file_exists($location)) {
2579         if (!unlink($location)) {
2580             return false;
2581         }
2582     }
2583     return true;
2586 /**
2587  * Send requested byterange of file.
2588  *
2589  * @param resource $handle A file handle
2590  * @param string $mimetype The mimetype for the output
2591  * @param array $ranges An array of ranges to send
2592  * @param string $filesize The size of the content if only one range is used
2593  */
2594 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2595     // better turn off any kind of compression and buffering
2596     @ini_set('zlib.output_compression', 'Off');
2598     $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2599     if ($handle === false) {
2600         die;
2601     }
2602     if (count($ranges) == 1) { //only one range requested
2603         $length = $ranges[0][2] - $ranges[0][1] + 1;
2604         header('HTTP/1.1 206 Partial content');
2605         header('Content-Length: '.$length);
2606         header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2607         header('Content-Type: '.$mimetype);
2609         while(@ob_get_level()) {
2610             if (!@ob_end_flush()) {
2611                 break;
2612             }
2613         }
2615         fseek($handle, $ranges[0][1]);
2616         while (!feof($handle) && $length > 0) {
2617             @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2618             $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2619             echo $buffer;
2620             flush();
2621             $length -= strlen($buffer);
2622         }
2623         fclose($handle);
2624         die;
2625     } else { // multiple ranges requested - not tested much
2626         $totallength = 0;
2627         foreach($ranges as $range) {
2628             $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2629         }
2630         $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2631         header('HTTP/1.1 206 Partial content');
2632         header('Content-Length: '.$totallength);
2633         header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2635         while(@ob_get_level()) {
2636             if (!@ob_end_flush()) {
2637                 break;
2638             }
2639         }
2641         foreach($ranges as $range) {
2642             $length = $range[2] - $range[1] + 1;
2643             echo $range[0];
2644             fseek($handle, $range[1]);
2645             while (!feof($handle) && $length > 0) {
2646                 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2647                 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2648                 echo $buffer;
2649                 flush();
2650                 $length -= strlen($buffer);
2651             }
2652         }
2653         echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2654         fclose($handle);
2655         die;
2656     }
2659 /**
2660  * add includes (js and css) into uploaded files
2661  * before returning them, useful for themes and utf.js includes
2662  *
2663  * @global stdClass $CFG
2664  * @param string $text text to search and replace
2665  * @return string text with added head includes
2666  * @todo MDL-21120
2667  */
2668 function file_modify_html_header($text) {
2669     // first look for <head> tag
2670     global $CFG;
2672     $stylesheetshtml = '';
2673 /*    foreach ($CFG->stylesheets as $stylesheet) {
2674         //TODO: MDL-21120
2675         $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2676     }*/
2678     $ufo = '';
2679     if (filter_is_enabled('filter/mediaplugin')) {
2680         // this script is needed by most media filter plugins.
2681         $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2682         $ufo = html_writer::tag('script', '', $attributes) . "\n";
2683     }
2685     preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2686     if ($matches) {
2687         $replacement = '<head>'.$ufo.$stylesheetshtml;
2688         $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2689         return $text;
2690     }
2692     // if not, look for <html> tag, and stick <head> right after
2693     preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2694     if ($matches) {
2695         // replace <html> tag with <html><head>includes</head>
2696         $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2697         $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2698         return $text;
2699     }
2701     // if not, look for <body> tag, and stick <head> before body
2702     preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2703     if ($matches) {
2704         $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2705         $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2706         return $text;
2707     }
2709     // if not, just stick a <head> tag at the beginning
2710     $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2711     return $text;
2714 /**
2715  * RESTful cURL class
2716  *
2717  * This is a wrapper class for curl, it is quite easy to use:
2718  * <code>
2719  * $c = new curl;
2720  * // enable cache
2721  * $c = new curl(array('cache'=>true));
2722  * // enable cookie
2723  * $c = new curl(array('cookie'=>true));
2724  * // enable proxy
2725  * $c = new curl(array('proxy'=>true));
2726  *
2727  * // HTTP GET Method
2728  * $html = $c->get('http://example.com');
2729  * // HTTP POST Method
2730  * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2731  * // HTTP PUT Method
2732  * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2733  * </code>
2734  *
2735  * @package   core_files
2736  * @category files
2737  * @copyright Dongsheng Cai <dongsheng@moodle.com>
2738  * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
2739  */
2740 class curl {
2741     /** @var bool Caches http request contents */
2742     public  $cache    = false;
2743     /** @var bool Uses proxy */
2744     public  $proxy    = false;
2745     /** @var string library version */
2746     public  $version  = '0.4 dev';
2747     /** @var array http's response */
2748     public  $response = array();
2749     /** @var array http header */
2750     public  $header   = array();
2751     /** @var string cURL information */
2752     public  $info;
2753     /** @var string error */
2754     public  $error;
2756     /** @var array cURL options */
2757     private $options;
2758     /** @var string Proxy host */
2759     private $proxy_host = '';
2760     /** @var string Proxy auth */
2761     private $proxy_auth = '';
2762     /** @var string Proxy type */
2763     private $proxy_type = '';
2764     /** @var bool Debug mode on */
2765     private $debug    = false;
2766     /** @var bool|string Path to cookie file */
2767     private $cookie   = false;
2769     /**
2770      * Constructor
2771      *
2772      * @global stdClass $CFG
2773      * @param array $options
2774      */
2775     public function __construct($options = array()){
2776         global $CFG;
2777         if (!function_exists('curl_init')) {
2778             $this->error = 'cURL module must be enabled!';
2779             trigger_error($this->error, E_USER_ERROR);
2780             return false;
2781         }
2782         // the options of curl should be init here.
2783         $this->resetopt();
2784         if (!empty($options['debug'])) {
2785             $this->debug = true;
2786         }
2787         if(!empty($options['cookie'])) {
2788             if($options['cookie'] === true) {
2789                 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2790             } else {
2791                 $this->cookie = $options['cookie'];
2792             }
2793         }
2794         if (!empty($options['cache'])) {
2795             if (class_exists('curl_cache')) {
2796                 if (!empty($options['module_cache'])) {
2797                     $this->cache = new curl_cache($options['module_cache']);
2798                 } else {
2799                     $this->cache = new curl_cache('misc');
2800                 }
2801             }
2802         }
2803         if (!empty($CFG->proxyhost)) {
2804             if (empty($CFG->proxyport)) {
2805                 $this->proxy_host = $CFG->proxyhost;
2806             } else {
2807                 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2808             }
2809             if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2810                 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2811                 $this->setopt(array(
2812                             'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2813                             'proxyuserpwd'=>$this->proxy_auth));
2814             }
2815             if (!empty($CFG->proxytype)) {
2816                 if ($CFG->proxytype == 'SOCKS5') {
2817                     $this->proxy_type = CURLPROXY_SOCKS5;
2818                 } else {
2819                     $this->proxy_type = CURLPROXY_HTTP;
2820                     $this->setopt(array('httpproxytunnel'=>false));
2821                 }
2822                 $this->setopt(array('proxytype'=>$this->proxy_type));
2823             }
2824         }
2825         if (!empty($this->proxy_host)) {
2826             $this->proxy = array('proxy'=>$this->proxy_host);
2827         }
2828     }
2829     /**
2830      * Resets the CURL options that have already been set
2831      */
2832     public function resetopt(){
2833         $this->options = array();
2834         $this->options['CURLOPT_USERAGENT']         = 'MoodleBot/1.0';
2835         // True to include the header in the output
2836         $this->options['CURLOPT_HEADER']            = 0;
2837         // True to Exclude the body from the output
2838         $this->options['CURLOPT_NOBODY']            = 0;
2839         // TRUE to follow any "Location: " header that the server
2840         // sends as part of the HTTP header (note this is recursive,
2841         // PHP will follow as many "Location: " headers that it is sent,
2842         // unless CURLOPT_MAXREDIRS is set).
2843         //$this->options['CURLOPT_FOLLOWLOCATION']    = 1;
2844         $this->options['CURLOPT_MAXREDIRS']         = 10;
2845         $this->options['CURLOPT_ENCODING']          = '';
2846         // TRUE to return the transfer as a string of the return
2847         // value of curl_exec() instead of outputting it out directly.
2848         $this->options['CURLOPT_RETURNTRANSFER']    = 1;
2849         $this->options['CURLOPT_BINARYTRANSFER']    = 0;
2850         $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
2851         $this->options['CURLOPT_SSL_VERIFYHOST']    = 2;
2852         $this->options['CURLOPT_CONNECTTIMEOUT']    = 30;
2853     }
2855     /**
2856      * Reset Cookie
2857      */
2858     public function resetcookie() {
2859         if (!empty($this->cookie)) {
2860             if (is_file($this->cookie)) {
2861                 $fp = fopen($this->cookie, 'w');
2862                 if (!empty($fp)) {
2863                     fwrite($fp, '');
2864                     fclose($fp);
2865                 }
2866             }
2867         }
2868     }
2870     /**
2871      * Set curl options
2872      *
2873      * @param array $options If array is null, this function will
2874      * reset the options to default value.
2875      */
2876     public function setopt($options = array()) {
2877         if (is_array($options)) {
2878             foreach($options as $name => $val){
2879                 if (stripos($name, 'CURLOPT_') === false) {
2880                     $name = strtoupper('CURLOPT_'.$name);
2881                 }
2882                 $this->options[$name] = $val;
2883             }
2884         }
2885     }
2887     /**
2888      * Reset http method
2889      */
2890     public function cleanopt(){
2891         unset($this->options['CURLOPT_HTTPGET']);
2892         unset($this->options['CURLOPT_POST']);
2893         unset($this->options['CURLOPT_POSTFIELDS']);
2894         unset($this->options['CURLOPT_PUT']);
2895         unset($this->options['CURLOPT_INFILE']);
2896         unset($this->options['CURLOPT_INFILESIZE']);
2897         unset($this->options['CURLOPT_CUSTOMREQUEST']);
2898     }
2900     /**
2901      * Set HTTP Request Header
2902      *
2903      * @param array $header
2904      */
2905     public function setHeader($header) {
2906         if (is_array($header)){
2907             foreach ($header as $v) {
2908                 $this->setHeader($v);
2909             }
2910         } else {
2911             $this->header[] = $header;
2912         }
2913     }
2915     /**
2916      * Set HTTP Response Header
2917      *
2918      */
2919     public function getResponse(){
2920         return $this->response;
2921     }
2923     /**
2924      * private callback function
2925      * Formatting HTTP Response Header
2926      *
2927      * @param resource $ch Apparently not used
2928      * @param string $header
2929      * @return int The strlen of the header
2930      */
2931     private function formatHeader($ch, $header)
2932     {
2933         $this->count++;
2934         if (strlen($header) > 2) {
2935             list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2936             $key = rtrim($key, ':');
2937             if (!empty($this->response[$key])) {
2938                 if (is_array($this->response[$key])){
2939                     $this->response[$key][] = $value;
2940                 } else {
2941                     $tmp = $this->response[$key];
2942                     $this->response[$key] = array();
2943                     $this->response[$key][] = $tmp;
2944                     $this->response[$key][] = $value;
2946                 }
2947             } else {
2948                 $this->response[$key] = $value;
2949             }
2950         }
2951         return strlen($header);
2952     }
2954     /**
2955      * Set options for individual curl instance
2956      *
2957      * @param resource $curl A curl handle
2958      * @param array $options
2959      * @return resource The curl handle
2960      */
2961     private function apply_opt($curl, $options) {
2962         // Clean up
2963         $this->cleanopt();
2964         // set cookie
2965         if (!empty($this->cookie) || !empty($options['cookie'])) {
2966             $this->setopt(array('cookiejar'=>$this->cookie,
2967                             'cookiefile'=>$this->cookie
2968                              ));
2969         }
2971         // set proxy
2972         if (!empty($this->proxy) || !empty($options['proxy'])) {
2973             $this->setopt($this->proxy);
2974         }
2975         $this->setopt($options);
2976         // reset before set options
2977         curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2978         // set headers
2979         if (empty($this->header)){
2980             $this->setHeader(array(
2981                 'User-Agent: MoodleBot/1.0',
2982                 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2983                 'Connection: keep-alive'
2984                 ));
2985         }
2986         curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2988         if ($this->debug){
2989             echo '<h1>Options</h1>';
2990             var_dump($this->options);
2991             echo '<h1>Header</h1>';
2992             var_dump($this->header);
2993         }
2995         // set options
2996         foreach($this->options as $name => $val) {
2997             if (is_string($name)) {
2998                 $name = constant(strtoupper($name));
2999             }
3000             curl_setopt($curl, $name, $val);
3001         }
3002         return $curl;
3003     }
3005     /**
3006      * Download multiple files in parallel
3007      *
3008      * Calls {@link multi()} with specific download headers
3009      *
3010      * <code>
3011      * $c = new curl();
3012      * $file1 = fopen('a', 'wb');
3013      * $file2 = fopen('b', 'wb');
3014      * $c->download(array(
3015      *     array('url'=>'http://localhost/', 'file'=>$file1),
3016      *     array('url'=>'http://localhost/20/', 'file'=>$file2)
3017      * ));
3018      * fclose($file1);
3019      * fclose($file2);
3020      * </code>
3021      *
3022      * or
3023      *
3024      * <code>
3025      * $c = new curl();
3026      * $c->download(array(
3027      *              array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3028      *              array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3029      *              ));
3030      * </code>
3031      *
3032      * @param array $requests An array of files to request {
3033      *                  url => url to download the file [required]
3034      *                  file => file handler, or
3035      *                  filepath => file path
3036      * }
3037      * If 'file' and 'filepath' parameters are both specified in one request, the
3038      * open file handle in the 'file' parameter will take precedence and 'filepath'
3039      * will be ignored.
3040      *
3041      * @param array $options An array of options to set
3042      * @return array An array of results
3043      */
3044     public function download($requests, $options = array()) {
3045         $options['CURLOPT_BINARYTRANSFER'] = 1;
3046         $options['RETURNTRANSFER'] = false;
3047         return $this->multi($requests, $options);
3048     }
3050     /**
3051      * Mulit HTTP Requests
3052      * This function could run multi-requests in parallel.
3053      *
3054      * @param array $requests An array of files to request
3055      * @param array $options An array of options to set
3056      * @return array An array of results
3057      */
3058     protected function multi($requests, $options = array()) {
3059         $count   = count($requests);
3060         $handles = array();
3061         $results = array();
3062         $main    = curl_multi_init();
3063         for ($i = 0; $i < $count; $i++) {
3064             if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3065                 // open file
3066                 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3067                 $requests[$i]['auto-handle'] = true;
3068             }
3069             foreach($requests[$i] as $n=>$v){
3070                 $options[$n] = $v;
3071             }
3072             $handles[$i] = curl_init($requests[$i]['url']);
3073             $this->apply_opt($handles[$i], $options);
3074             curl_multi_add_handle($main, $handles[$i]);
3075         }
3076         $running = 0;
3077         do {
3078             curl_multi_exec($main, $running);
3079         } while($running > 0);
3080         for ($i = 0; $i < $count; $i++) {
3081             if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3082                 $results[] = true;
3083             } else {
3084                 $results[] = curl_multi_getcontent($handles[$i]);
3085             }
3086             curl_multi_remove_handle($main, $handles[$i]);
3087         }
3088         curl_multi_close($main);
3090         for ($i = 0; $i < $count; $i++) {
3091             if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3092                 // close file handler if file is opened in this function
3093                 fclose($requests[$i]['file']);
3094             }
3095         }
3096         return $results;
3097     }
3099     /**
3100      * Single HTTP Request
3101      *
3102      * @param string $url The URL to request
3103      * @param array $options
3104      * @return bool
3105      */
3106     protected function request($url, $options = array()){
3107         // create curl instance
3108         $curl = curl_init($url);
3109         $options['url'] = $url;
3110         $this->apply_opt($curl, $options);
3111         if ($this->cache && $ret = $this->cache->get($this->options)) {
3112             return $ret;
3113         } else {
3114             $ret = curl_exec($curl);
3115             if ($this->cache) {
3116                 $this->cache->set($this->options, $ret);
3117             }
3118         }
3120         $this->info  = curl_getinfo($curl);
3121         $this->error = curl_error($curl);
3123         if ($this->debug){
3124             echo '<h1>Return Data</h1>';
3125             var_dump($ret);
3126             echo '<h1>Info</h1>';
3127             var_dump($this->info);
3128             echo '<h1>Error</h1>';
3129             var_dump($this->error);
3130         }
3132         curl_close($curl);
3134         if (empty($this->error)){
3135             return $ret;
3136         } else {
3137             return $this->error;
3138             // exception is not ajax friendly
3139             //throw new moodle_exception($this->error, 'curl');
3140         }
3141     }
3143     /**
3144      * HTTP HEAD method
3145      *
3146      * @see request()
3147      *
3148      * @param string $url
3149      * @param array $options
3150      * @return bool
3151      */
3152     public function head($url, $options = array()){
3153         $options['CURLOPT_HTTPGET'] = 0;
3154         $options['CURLOPT_HEADER']  = 1;
3155         $options['CURLOPT_NOBODY']  = 1;
3156         return $this->request($url, $options);
3157     }
3159     /**
3160      * HTTP POST method
3161      *
3162      * @param string $url
3163      * @param array|string $params
3164      * @param array $options
3165      * @return bool
3166      */
3167     public function post($url, $params = '', $options = array()){
3168         $options['CURLOPT_POST']       = 1;
3169         if (is_array($params)) {
3170             $this->_tmp_file_post_params = array();
3171             foreach ($params as $key => $value) {
3172                 if ($value instanceof stored_file) {
3173                     $value->add_to_curl_request($this, $key);
3174                 } else {
3175                     $this->_tmp_file_post_params[$key] = $value;
3176                 }
3177             }
3178             $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3179             unset($this->_tmp_file_post_params);
3180         } else {
3181             // $params is the raw post data
3182             $options['CURLOPT_POSTFIELDS'] = $params;
3183         }
3184         return $this->request($url, $options);
3185     }
3187     /**
3188      * HTTP GET method
3189      *
3190      * @param string $url
3191      * @param array $params
3192      * @param array $options
3193      * @return bool
3194      */
3195     public function get($url, $params = array(), $options = array()){
3196         $options['CURLOPT_HTTPGET'] = 1;
3198         if (!empty($params)){
3199             $url .= (stripos($url, '?') !== false) ? '&' : '?';
3200             $url .= http_build_query($params, '', '&');
3201         }
3202         return $this->request($url, $options);
3203     }
3205     /**
3206      * HTTP PUT method
3207      *
3208      * @param string $url
3209      * @param array $params
3210      * @param array $options
3211      * @return bool
3212      */
3213     public function put($url, $params = array(), $options = array()){
3214         $file = $params['file'];
3215         if (!is_file($file)){
3216             return null;
3217         }
3218         $fp   = fopen($file, 'r');
3219         $size = filesize($file);
3220         $options['CURLOPT_PUT']        = 1;
3221         $options['CURLOPT_INFILESIZE'] = $size;
3222         $options['CURLOPT_INFILE']     = $fp;
3223         if (!isset($this->options['CURLOPT_USERPWD'])){
3224             $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3225         }
3226         $ret = $this->request($url, $options);
3227         fclose($fp);
3228         return $ret;
3229     }
3231     /**
3232      * HTTP DELETE method
3233      *
3234      * @param string $url
3235      * @param array $param
3236      * @param array $options
3237      * @return bool
3238      */
3239     public function delete($url, $param = array(), $options = array()){
3240         $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3241         if (!isset($options['CURLOPT_USERPWD'])) {
3242             $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3243         }
3244         $ret = $this->request($url, $options);
3245         return $ret;
3246     }
3248     /**
3249      * HTTP TRACE method
3250      *
3251      * @param string $url
3252      * @param array $options
3253      * @return bool
3254      */
3255     public function trace($url, $options = array()){
3256         $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3257         $ret = $this->request($url, $options);
3258         return $ret;
3259     }
3261     /**
3262      * HTTP OPTIONS method
3263      *
3264      * @param string $url
3265      * @param array $options
3266      * @return bool
3267      */
3268     public function options($url, $options = array()){
3269         $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3270         $ret = $this->request($url, $options);
3271         return $ret;
3272     }
3274     /**
3275      * Get curl information
3276      *
3277      * @return string
3278      */
3279     public function get_info() {
3280         return $this->info;
3281     }
3284 /**
3285  * This class is used by cURL class, use case:
3286  *
3287  * <code>
3288  * $CFG->repositorycacheexpire = 120;
3289  * $CFG->curlcache = 120;
3290  *
3291  * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3292  * $ret = $c->get('http://www.google.com');
3293  * </code>
3294  *
3295  * @package   core_files
3296  * @copyright Dongsheng Cai <dongsheng@moodle.com>
3297  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3298  */
3299 class curl_cache {
3300     /** @var string Path to cache directory */
3301     public $dir = '';
3303     /**
3304      * Constructor
3305      *
3306      * @global stdClass $CFG
3307      * @param string $module which module is using curl_cache
3308      */
3309     public function __construct($module = 'repository') {
3310         global $CFG;
3311         if (!empty($module)) {
3312             $this->dir = $CFG->cachedir.'/'.$module.'/';
3313         } else {
3314             $this->dir = $CFG->cachedir.'/misc/';
3315         }
3316         if (!file_exists($this->dir)) {
3317             mkdir($this->dir, $CFG->directorypermissions, true);
3318         }
3319         if ($module == 'repository') {
3320             if (empty($CFG->repositorycacheexpire)) {
3321                 $CFG->repositorycacheexpire = 120;
3322             }
3323             $this->ttl = $CFG->repositorycacheexpire;
3324         } else {
3325             if (empty($CFG->curlcache)) {
3326                 $CFG->curlcache = 120;
3327             }
3328             $this->ttl = $CFG->curlcache;
3329         }
3330     }
3332     /**
3333      * Get cached value
3334      *
3335      * @global stdClass $CFG
3336      * @global stdClass $USER
3337      * @param mixed $param
3338      * @return bool|string
3339      */
3340     public function get($param) {
3341         global $CFG, $USER;
3342         $this->cleanup($this->ttl);
3343         $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3344         if(file_exists($this->dir.$filename)) {
3345             $lasttime = filemtime($this->dir.$filename);
3346             if (time()-$lasttime > $this->ttl) {
3347                 return false;
3348             } else {
3349                 $fp = fopen($this->dir.$filename, 'r');
3350                 $size = filesize($this->dir.$filename);
3351                 $content = fread($fp, $size);
3352                 return unserialize($content);
3353             }
3354         }
3355         return false;
3356     }
3358     /**
3359      * Set cache value
3360      *
3361      * @global object $CFG
3362      * @global object $USER
3363      * @param mixed $param
3364      * @param mixed $val
3365      */
3366     public function set($param, $val) {
3367         global $CFG, $USER;
3368         $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3369         $fp = fopen($this->dir.$filename, 'w');
3370         fwrite($fp, serialize($val));
3371         fclose($fp);
3372     }
3374     /**
3375      * Remove cache files
3376      *
3377      * @param int $expire The number of seconds before expiry
3378      */
3379     public function cleanup($expire) {
3380         if ($dir = opendir($this->dir)) {
3381             while (false !== ($file = readdir($dir))) {
3382                 if(!is_dir($file) && $file != '.' && $file != '..') {
3383                     $lasttime = @filemtime($this->dir.$file);
3384                     if (time() - $lasttime > $expire) {
3385                         @unlink($this->dir.$file);
3386                     }
3387                 }
3388             }
3389             closedir($dir);
3390         }
3391     }
3392     /**
3393      * delete current user's cache file
3394      *
3395      * @global object $CFG
3396      * @global object $USER
3397      */
3398     public function refresh() {
3399         global $CFG, $USER;
3400         if ($dir = opendir($this->dir)) {
3401             while (false !== ($file = readdir($dir))) {
3402                 if (!is_dir($file) && $file != '.' && $file != '..') {
3403                     if (strpos($file, 'u'.$USER->id.'_') !== false) {
3404                         @unlink($this->dir.$file);
3405                     }
3406                 }
3407             }
3408         }
3409     }
3412 /**
3413  * This function delegates file serving to individual plugins
3414  *
3415  * @param string $relativepath
3416  * @param bool $forcedownload
3417  * @param null|string $preview the preview mode, defaults to serving the original file
3418  * @todo MDL-31088 file serving improments
3419  */
3420 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3421     global $DB, $CFG, $USER;
3422     // relative path must start with '/'
3423     if (!$relativepath) {
3424         print_error('invalidargorconf');
3425     } else if ($relativepath[0] != '/') {
3426         print_error('pathdoesnotstartslash');
3427     }
3429     // extract relative path components
3430     $args = explode('/', ltrim($relativepath, '/'));
3432     if (count($args) < 3) { // always at least context, component and filearea
3433         print_error('invalidarguments');
3434     }
3436     $contextid = (int)array_shift($args);
3437     $component = clean_param(array_shift($args), PARAM_COMPONENT);
3438     $filearea  = clean_param(array_shift($args), PARAM_AREA);
3440     list($context, $course, $cm) = get_context_info_array($contextid);
3442     $fs = get_file_storage();
3444     // ========================================================================================================================
3445     if ($component === 'blog') {
3446         // Blog file serving
3447         if ($context->contextlevel != CONTEXT_SYSTEM) {
3448             send_file_not_found();
3449         }
3450         if ($filearea !== 'attachment' and $filearea !== 'post') {
3451             send_file_not_found();
3452         }
3454         if (empty($CFG->enableblogs)) {
3455             print_error('siteblogdisable', 'blog');
3456         }
3458         $entryid = (int)array_shift($args);
3459         if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3460             send_file_not_found();
3461         }
3462         if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3463             require_login();
3464             if (isguestuser()) {
3465                 print_error('noguest');
3466             }
3467             if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3468                 if ($USER->id != $entry->userid) {
3469                     send_file_not_found();
3470                 }
3471             }
3472         }
3474         if ($entry->publishstate === 'public') {
3475             if ($CFG->forcelogin) {
3476                 require_login();
3477             }
3479         } else if ($entry->publishstate === 'site') {
3480             require_login();
3481             //ok
3482         } else if ($entry->publishstate === 'draft') {
3483             require_login();
3484             if ($USER->id != $entry->userid) {
3485                 send_file_not_found();
3486             }
3487         }
3489         $filename = array_pop($args);
3490         $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3492         if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3493             send_file_not_found();
3494         }
3496         send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3498     // ========================================================================================================================
3499     } else if ($component === 'grade') {
3500         if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3501             // Global gradebook files
3502             if ($CFG->forcelogin) {
3503                 require_login();
3504             }
3506             $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3508             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3509                 send_file_not_found();
3510             }
3512             session_get_instance()->write_close(); // unlock session during fileserving
3513             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3515         } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3516             //TODO: nobody implemented this yet in grade edit form!!
3517             send_file_not_found();
3519             if ($CFG->forcelogin || $course->id != SITEID) {
3520                 require_login($course);
3521             }
3523             $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3525             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3526                 send_file_not_found();
3527             }
3529             session_get_instance()->write_close(); // unlock session during fileserving
3530             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3531         } else {
3532             send_file_not_found();
3533         }
3535     // ========================================================================================================================
3536     } else if ($component === 'tag') {
3537         if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3539             // All tag descriptions are going to be public but we still need to respect forcelogin
3540             if ($CFG->forcelogin) {
3541                 require_login();
3542             }
3544             $fullpath = "/$context->id/tag/description/".implode('/', $args);
3546             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3547                 send_file_not_found();
3548             }
3550             session_get_instance()->write_close(); // unlock session during fileserving
3551             send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3553         } else {
3554             send_file_not_found();
3555         }
3557     // ========================================================================================================================
3558     } else if ($component === 'calendar') {
3559         if ($filearea === 'event_description'  and $context->contextlevel == CONTEXT_SYSTEM) {
3561             // All events here are public the one requirement is that we respect forcelogin
3562             if ($CFG->forcelogin) {
3563                 require_login();
3564             }
3566             // Get the event if from the args array
3567             $eventid = array_shift($args);
3569             // Load the event from the database
3570             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3571                 send_file_not_found();
3572             }
3573             // Check that we got an event and that it's userid is that of the user
3575             // Get the file and serve if successful
3576             $filename = array_pop($args);
3577             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3578             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3579                 send_file_not_found();
3580             }
3582             session_get_instance()->write_close(); // unlock session during fileserving
3583             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3585         } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3587             // Must be logged in, if they are not then they obviously can't be this user
3588             require_login();
3590             // Don't want guests here, potentially saves a DB call
3591             if (isguestuser()) {
3592                 send_file_not_found();
3593             }
3595             // Get the event if from the args array
3596             $eventid = array_shift($args);
3598             // Load the event from the database - user id must match
3599             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3600                 send_file_not_found();
3601             }
3603             // Get the file and serve if successful
3604             $filename = array_pop($args);
3605             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3606             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3607                 send_file_not_found();
3608             }
3610             session_get_instance()->write_close(); // unlock session during fileserving
3611             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3613         } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3615             // Respect forcelogin and require login unless this is the site.... it probably
3616             // should NEVER be the site
3617             if ($CFG->forcelogin || $course->id != SITEID) {
3618                 require_login($course);
3619             }
3621             // Must be able to at least view the course
3622             if (!is_enrolled($context) and !is_viewing($context)) {
3623                 //TODO: hmm, do we really want to block guests here?
3624                 send_file_not_found();
3625             }
3627             // Get the event id
3628             $eventid = array_shift($args);
3630             // Load the event from the database we need to check whether it is
3631             // a) valid course event
3632             // b) a group event
3633             // Group events use the course context (there is no group context)
3634             if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3635                 send_file_not_found();
3636             }
3638             // If its a group event require either membership of view all groups capability
3639             if ($event->eventtype === 'group') {
3640                 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3641                     send_file_not_found();
3642                 }
3643             } else if ($event->eventtype === 'course') {
3644                 //ok
3645             } else {
3646                 // some other type
3647                 send_file_not_found();
3648             }
3650             // If we get this far we can serve the file
3651             $filename = array_pop($args);
3652             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3653             if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3654                 send_file_not_found();
3655             }
3657             session_get_instance()->write_close(); // unlock session during fileserving
3658             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3660         } else {
3661             send_file_not_found();
3662         }
3664     // ========================================================================================================================
3665     } else if ($component === 'user') {
3666         if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3667             if (count($args) == 1) {
3668                 $themename = theme_config::DEFAULT_THEME;
3669                 $filename = array_shift($args);
3670             } else {
3671                 $themename = array_shift($args);
3672                 $filename = array_shift($args);
3673             }
3675             // fix file name automatically
3676             if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3677                 $filename = 'f1';
3678             }
3680             if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3681                     (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3682                 // protect images if login required and not logged in;
3683                 // also if login is required for profile images and is not logged in or guest
3684                 // do not use require_login() because it is expensive and not suitable here anyway
3685                 $theme = theme_config::load($themename);
3686                 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3687             }
3689             if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3690                 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3691                     if ($filename === 'f3') {
3692                         // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3693                         if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3694                             $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3695                         }
3696                     }
3697                 }
3698             }
3699             if (!$file) {
3700                 // bad reference - try to prevent future retries as hard as possible!
3701                 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
3702                     if ($user->picture > 0) {
3703                         $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
3704                     }
3705                 }
3706                 // no redirect here because it is not cached
3707                 $theme = theme_config::load($themename);
3708                 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle');
3709                 send_file($imagefile, basename($imagefile), 60*60*24*14);
3710             }
3712             send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
3714         } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3715             require_login();
3717             if (isguestuser()) {
3718                 send_file_not_found();
3719             }
3721             if ($USER->id !== $context->instanceid) {
3722                 send_file_not_found();
3723             }
3725             $filename = array_pop($args);
3726             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3727             if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3728                 send_file_not_found();
3729             }
3731             session_get_instance()->write_close(); // unlock session during fileserving
3732             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3734         } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3736             if ($CFG->forcelogin) {
3737                 require_login();
3738             }
3740             $userid = $context->instanceid;
3742             if ($USER->id == $userid) {
3743                 // always can access own
3745             } else if (!empty($CFG->forceloginforprofiles)) {
3746                 require_login();
3748                 if (isguestuser()) {
3749                     send_file_not_found();
3750                 }
3752                 // we allow access to site profile of all course contacts (usually teachers)
3753                 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3754                     send_file_not_found();
3755                 }
3757                 $canview = false;
3758                 if (has_capability('moodle/user:viewdetails', $context)) {
3759                     $canview = true;
3760                 } else {
3761                     $courses = enrol_get_my_courses();
3762                 }
3764                 while (!$canview && count($courses) > 0) {
3765                     $course = array_shift($courses);
3766                     if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
3767                         $canview = true;
3768                     }
3769                 }
3770             }
3772             $filename = array_pop($args);
3773             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3774             if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3775                 send_file_not_found();
3776             }
3778             session_get_instance()->write_close(); // unlock session during fileserving
3779             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3781         } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3782             $userid = (int)array_shift($args);
3783             $usercontext = context_user::instance($userid);
3785             if ($CFG->forcelogin) {
3786                 require_login();
3787             }
3789             if (!empty($CFG->forceloginforprofiles)) {
3790                 require_login();
3791                 if (isguestuser()) {
3792                     print_error('noguest');
3793                 }
3795                 //TODO: review this logic of user profile access prevention
3796                 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3797                     print_error('usernotavailable');
3798                 }
3799                 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3800                     print_error('cannotviewprofile');
3801                 }
3802                 if (!is_enrolled($context, $userid)) {
3803                     print_error('notenrolledprofile');
3804                 }
3805                 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3806                     print_error('groupnotamember');
3807                 }
3808             }
3810             $filename = array_pop($args);
3811             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3812             if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3813                 send_file_not_found();
3814             }
3816             session_get_instance()->write_close(); // unlock session during fileserving
3817             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3819         } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3820             require_login();
3822             if (isguestuser()) {
3823                 send_file_not_found();
3824             }
3825             $userid = $context->instanceid;
3827             if ($USER->id != $userid) {
3828                 send_file_not_found();
3829             }
3831             $filename = array_pop($args);
3832             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3833             if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3834                 send_file_not_found();
3835             }
3837             session_get_instance()->write_close(); // unlock session during fileserving
3838             send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
3840         } else {
3841             send_file_not_found();
3842         }
3844     // ========================================================================================================================
3845     } else if ($component === 'coursecat') {
3846         if ($context->contextlevel != CONTEXT_COURSECAT) {
3847             send_file_not_found();
3848         }
3850         if ($filearea === 'description') {
3851             if ($CFG->forcelogin) {
3852                 // no login necessary - unless login forced everywhere
3853                 require_login();
3854             }
3856             $filename = array_pop($args);
3857             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3858             if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3859                 send_file_not_found();
3860             }
3862             session_get_instance()->write_close(); // unlock session during fileserving
3863             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3864         } else {
3865             send_file_not_found();
3866         }
3868     // ========================================================================================================================
3869     } else if ($component === 'course') {
3870         if ($context->contextlevel != CONTEXT_COURSE) {
3871             send_file_not_found();
3872         }
3874         if ($filearea === 'summary') {
3875             if ($CFG->forcelogin) {
3876                 require_login();
3877             }
3879             $filename = array_pop($args);
3880             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3881             if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
3882                 send_file_not_found();
3883             }
3885             session_get_instance()->write_close(); // unlock session during fileserving
3886             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3888         } else if ($filearea === 'section') {
3889             if ($CFG->forcelogin) {
3890                 require_login($course);
3891             } else if ($course->id != SITEID) {
3892                 require_login($course);
3893             }
3895             $sectionid = (int)array_shift($args);
3897             if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
3898                 send_file_not_found();
3899             }
3901             if ($course->numsections < $section->section) {
3902                 if (!has_capability('moodle/course:update', $context)) {
3903                     // block access to unavailable sections if can not edit course
3904                     send_file_not_found();
3905                 }
3906             }
3908             $filename = array_pop($args);
3909             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3910             if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3911                 send_file_not_found();
3912             }
3914             session_get_instance()->write_close(); // unlock session during fileserving
3915             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3917         } else {
3918             send_file_not_found();
3919         }
3921     } else if ($component === 'group') {
3922         if ($context->contextlevel != CONTEXT_COURSE) {
3923             send_file_not_found();
3924         }
3926         require_course_login($course, true, null, false);
3928         $groupid = (int)array_shift($args);
3930         $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
3931         if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
3932             // do not allow access to separate group info if not member or teacher
3933             send_file_not_found();
3934         }
3936         if ($filearea === 'description') {
3938             require_login($course);
3940             $filename = array_pop($args);
3941             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3942             if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
3943                 send_file_not_found();
3944             }
3946             session_get_instance()->write_close(); // unlock session during fileserving
3947             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3949         } else if ($filearea === 'icon') {
3950             $filename = array_pop($args);
3952             if ($filename !== 'f1' and $filename !== 'f2') {
3953                 send_file_not_found();
3954             }
3955             if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
3956                 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
3957                     send_file_not_found();
3958                 }
3959             }
3961             session_get_instance()->write_close(); // unlock session during fileserving
3962             send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
3964         } else {
3965             send_file_not_found();
3966         }
3968     } else if ($component === 'grouping') {
3969         if ($context->contextlevel != CONTEXT_COURSE) {
3970             send_file_not_found();
3971         }
3973         require_login($course);
3975         $groupingid = (int)array_shift($args);
3977         // note: everybody has access to grouping desc images for now
3978         if ($filearea === 'description') {
3980             $filename = array_pop($args);
3981             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3982             if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
3983                 send_file_not_found();
3984             }
3986             session_get_instance()->write_close(); // unlock session during fileserving
3987             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3989         } else {
3990             send_file_not_found();
3991         }
3993     // ========================================================================================================================
3994     } else if ($component === 'backup') {
3995         if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
3996             require_login($course);
3997             require_capability('moodle/backup:downloadfile', $context);
3999             $filename = array_pop($args);
4000             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4001             if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4002                 send_file_not_found();
4003             }
4005             session_get_instance()->write_close(); // unlock session during fileserving
4006             send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4008         } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4009             require_login($course);
4010             require_capability('moodle/backup:downloadfile', $context);
4012             $sectionid = (int)array_shift($args);
4014             $filename = array_pop($args);
4015             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4016             if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4017                 send_file_not_found();
4018             }
4020             session_get_instance()->write_close();
4021             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4023         } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4024             require_login($course, false, $cm);
4025             require_capability('moodle/backup:downloadfile', $context);
4027             $filename = array_pop($args);
4028             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4029             if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4030                 send_file_not_found();
4031             }
4033             session_get_instance()->write_close();
4034             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4036         } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4037             // Backup files that were generated by the automated backup systems.
4039             require_login($course);
4040             require_capability('moodle/site:config', $context);
4042             $filename = array_pop($args);
4043             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4044             if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4045                 send_file_not_found();
4046             }
4048             session_get_instance()->write_close(); // unlock session during fileserving
4049             send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4051         } else {
4052             send_file_not_found();
4053         }
4055     // ========================================================================================================================
4056     } else if ($component === 'question') {
4057         require_once($CFG->libdir . '/questionlib.php');
4058         question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4059         send_file_not_found();
4061     // ========================================================================================================================
4062     } else if ($component === 'grading') {
4063         if ($filearea === 'description') {
4064             // files embedded into the form definition description
4066             if ($context->contextlevel == CONTEXT_SYSTEM) {
4067                 require_login();
4069             } else if ($context->contextlevel >= CONTEXT_COURSE) {
4070                 require_login($course, false, $cm);
4072             } else {
4073                 send_file_not_found();
4074             }
4076             $formid = (int)array_shift($args);
4078             $sql = "SELECT ga.id
4079                 FROM {grading_areas} ga
4080                 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4081                 WHERE gd.id = ? AND ga.contextid = ?";
4082             $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4084             if (!$areaid) {
4085                 send_file_not_found();
4086             }
4088             $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4090             if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4091                 send_file_not_found();
4092             }
4094             session_get_instance()->write_close(); // unlock session during fileserving
4095             send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4096         }
4098         // ========================================================================================================================
4099     } else if (strpos($component, 'mod_') === 0) {
4100         $modname = substr($component, 4);
4101         if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4102             send_file_not_found();
4103         }
4104         require_once("$CFG->dirroot/mod/$modname/lib.php");
4106         if ($context->contextlevel == CONTEXT_MODULE) {
4107             if ($cm->modname !== $modname) {
4108                 // somebody tries to gain illegal access, cm type must match the component!
4109                 send_file_not_found();
4110             }
4111         }
4113         if ($filearea === 'intro') {
4114             if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4115                 send_file_not_found();
4116             }
4117             require_course_login($course, true, $cm);
4119             // all users may access it
4120             $filename = array_pop($args);
4121             $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4122             if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4123                 send_file_not_found();
4124             }
4126             $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;