Merge branch 'wip-mdl-41843-m25' of git://github.com/rajeshtaneja/moodle into MOODLE_...
[moodle.git] / lib / filelib.php
blob6d07c7bac25bcde05ee77cd4c11275cdb7e9b0a3
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.
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.
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
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 /**
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
42 /**
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56 global $CFG;
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
65 if ($forcedownload) {
66 $return .= '?forcedownload=1';
68 } else {
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
71 if ($forcedownload) {
72 $return .= '&amp;forcedownload=1';
76 if ($https) {
77 $return = str_replace('http://', 'https://', $return);
80 return $return;
83 /**
84 * Prepares 'editor' formslib element from data in database
86 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
87 * function then copies the embedded files into draft area (assigning itemids automatically),
88 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
89 * displayed.
90 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
91 * your mform's set_data() supplying the object returned by this function.
93 * @category files
94 * @param stdClass $data database field that holds the html text with embedded media
95 * @param string $field the name of the database field that holds the html text with embedded media
96 * @param array $options editor options (like maxifiles, maxbytes etc.)
97 * @param stdClass $context context of the editor
98 * @param string $component
99 * @param string $filearea file area name
100 * @param int $itemid item id, required if item exists
101 * @return stdClass modified data object
103 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
104 $options = (array)$options;
105 if (!isset($options['trusttext'])) {
106 $options['trusttext'] = false;
108 if (!isset($options['forcehttps'])) {
109 $options['forcehttps'] = false;
111 if (!isset($options['subdirs'])) {
112 $options['subdirs'] = false;
114 if (!isset($options['maxfiles'])) {
115 $options['maxfiles'] = 0; // no files by default
117 if (!isset($options['noclean'])) {
118 $options['noclean'] = false;
121 //sanity check for passed context. This function doesn't expect $option['context'] to be set
122 //But this function is called before creating editor hence, this is one of the best places to check
123 //if context is used properly. This check notify developer that they missed passing context to editor.
124 if (isset($context) && !isset($options['context'])) {
125 //if $context is not null then make sure $option['context'] is also set.
126 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
127 } else if (isset($options['context']) && isset($context)) {
128 //If both are passed then they should be equal.
129 if ($options['context']->id != $context->id) {
130 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
131 throw new coding_exception($exceptionmsg);
135 if (is_null($itemid) or is_null($context)) {
136 $contextid = null;
137 $itemid = null;
138 if (!isset($data)) {
139 $data = new stdClass();
141 if (!isset($data->{$field})) {
142 $data->{$field} = '';
144 if (!isset($data->{$field.'format'})) {
145 $data->{$field.'format'} = editors_get_preferred_format();
147 if (!$options['noclean']) {
148 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
151 } else {
152 if ($options['trusttext']) {
153 // noclean ignored if trusttext enabled
154 if (!isset($data->{$field.'trust'})) {
155 $data->{$field.'trust'} = 0;
157 $data = trusttext_pre_edit($data, $field, $context);
158 } else {
159 if (!$options['noclean']) {
160 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
163 $contextid = $context->id;
166 if ($options['maxfiles'] != 0) {
167 $draftid_editor = file_get_submitted_draft_itemid($field);
168 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
169 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
170 } else {
171 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
174 return $data;
178 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
180 * This function moves files from draft area to the destination area and
181 * encodes URLs to the draft files so they can be safely saved into DB. The
182 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
183 * is the name of the database field to hold the wysiwyg editor content. The
184 * editor data comes as an array with text, format and itemid properties. This
185 * function automatically adds $data properties foobar, foobarformat and
186 * foobartrust, where foobar has URL to embedded files encoded.
188 * @category files
189 * @param stdClass $data raw data submitted by the form
190 * @param string $field name of the database field containing the html with embedded media files
191 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
192 * @param stdClass $context context, required for existing data
193 * @param string $component file component
194 * @param string $filearea file area name
195 * @param int $itemid item id, required if item exists
196 * @return stdClass modified data object
198 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
199 $options = (array)$options;
200 if (!isset($options['trusttext'])) {
201 $options['trusttext'] = false;
203 if (!isset($options['forcehttps'])) {
204 $options['forcehttps'] = false;
206 if (!isset($options['subdirs'])) {
207 $options['subdirs'] = false;
209 if (!isset($options['maxfiles'])) {
210 $options['maxfiles'] = 0; // no files by default
212 if (!isset($options['maxbytes'])) {
213 $options['maxbytes'] = 0; // unlimited
216 if ($options['trusttext']) {
217 $data->{$field.'trust'} = trusttext_trusted($context);
218 } else {
219 $data->{$field.'trust'} = 0;
222 $editor = $data->{$field.'_editor'};
224 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
225 $data->{$field} = $editor['text'];
226 } else {
227 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
229 $data->{$field.'format'} = $editor['format'];
231 return $data;
235 * Saves text and files modified by Editor formslib element
237 * @category files
238 * @param stdClass $data $database entry field
239 * @param string $field name of data field
240 * @param array $options various options
241 * @param stdClass $context context - must already exist
242 * @param string $component
243 * @param string $filearea file area name
244 * @param int $itemid must already exist, usually means data is in db
245 * @return stdClass modified data obejct
247 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
248 $options = (array)$options;
249 if (!isset($options['subdirs'])) {
250 $options['subdirs'] = false;
252 if (is_null($itemid) or is_null($context)) {
253 $itemid = null;
254 $contextid = null;
255 } else {
256 $contextid = $context->id;
259 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
260 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
261 $data->{$field.'_filemanager'} = $draftid_editor;
263 return $data;
267 * Saves files modified by File manager formslib element
269 * @todo MDL-31073 review this function
270 * @category files
271 * @param stdClass $data $database entry field
272 * @param string $field name of data field
273 * @param array $options various options
274 * @param stdClass $context context - must already exist
275 * @param string $component
276 * @param string $filearea file area name
277 * @param int $itemid must already exist, usually means data is in db
278 * @return stdClass modified data obejct
280 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
281 $options = (array)$options;
282 if (!isset($options['subdirs'])) {
283 $options['subdirs'] = false;
285 if (!isset($options['maxfiles'])) {
286 $options['maxfiles'] = -1; // unlimited
288 if (!isset($options['maxbytes'])) {
289 $options['maxbytes'] = 0; // unlimited
292 if (empty($data->{$field.'_filemanager'})) {
293 $data->$field = '';
295 } else {
296 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
297 $fs = get_file_storage();
299 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
300 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
301 } else {
302 $data->$field = '';
306 return $data;
310 * Generate a draft itemid
312 * @category files
313 * @global moodle_database $DB
314 * @global stdClass $USER
315 * @return int a random but available draft itemid that can be used to create a new draft
316 * file area.
318 function file_get_unused_draft_itemid() {
319 global $DB, $USER;
321 if (isguestuser() or !isloggedin()) {
322 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
323 print_error('noguest');
326 $contextid = context_user::instance($USER->id)->id;
328 $fs = get_file_storage();
329 $draftitemid = rand(1, 999999999);
330 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
331 $draftitemid = rand(1, 999999999);
334 return $draftitemid;
338 * Initialise a draft file area from a real one by copying the files. A draft
339 * area will be created if one does not already exist. Normally you should
340 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
342 * @category files
343 * @global stdClass $CFG
344 * @global stdClass $USER
345 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
346 * @param int $contextid This parameter and the next two identify the file area to copy files from.
347 * @param string $component
348 * @param string $filearea helps indentify the file area.
349 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
350 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
351 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
352 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
354 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
355 global $CFG, $USER, $CFG;
357 $options = (array)$options;
358 if (!isset($options['subdirs'])) {
359 $options['subdirs'] = false;
361 if (!isset($options['forcehttps'])) {
362 $options['forcehttps'] = false;
365 $usercontext = context_user::instance($USER->id);
366 $fs = get_file_storage();
368 if (empty($draftitemid)) {
369 // create a new area and copy existing files into
370 $draftitemid = file_get_unused_draft_itemid();
371 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
372 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
373 foreach ($files as $file) {
374 if ($file->is_directory() and $file->get_filepath() === '/') {
375 // we need a way to mark the age of each draft area,
376 // by not copying the root dir we force it to be created automatically with current timestamp
377 continue;
379 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
380 continue;
382 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
383 // XXX: This is a hack for file manager (MDL-28666)
384 // File manager needs to know the original file information before copying
385 // to draft area, so we append these information in mdl_files.source field
386 // {@link file_storage::search_references()}
387 // {@link file_storage::search_references_count()}
388 $sourcefield = $file->get_source();
389 $newsourcefield = new stdClass;
390 $newsourcefield->source = $sourcefield;
391 $original = new stdClass;
392 $original->contextid = $contextid;
393 $original->component = $component;
394 $original->filearea = $filearea;
395 $original->itemid = $itemid;
396 $original->filename = $file->get_filename();
397 $original->filepath = $file->get_filepath();
398 $newsourcefield->original = file_storage::pack_reference($original);
399 $draftfile->set_source(serialize($newsourcefield));
400 // End of file manager hack
403 if (!is_null($text)) {
404 // at this point there should not be any draftfile links yet,
405 // because this is a new text from database that should still contain the @@pluginfile@@ links
406 // this happens when developers forget to post process the text
407 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
409 } else {
410 // nothing to do
413 if (is_null($text)) {
414 return null;
417 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
418 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
422 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
424 * @category files
425 * @global stdClass $CFG
426 * @param string $text The content that may contain ULRs in need of rewriting.
427 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
428 * @param int $contextid This parameter and the next two identify the file area to use.
429 * @param string $component
430 * @param string $filearea helps identify the file area.
431 * @param int $itemid helps identify the file area.
432 * @param array $options text and file options ('forcehttps'=>false)
433 * @return string the processed text.
435 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
436 global $CFG;
438 $options = (array)$options;
439 if (!isset($options['forcehttps'])) {
440 $options['forcehttps'] = false;
443 if (!$CFG->slasharguments) {
444 $file = $file . '?file=';
447 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
449 if ($itemid !== null) {
450 $baseurl .= "$itemid/";
453 if ($options['forcehttps']) {
454 $baseurl = str_replace('http://', 'https://', $baseurl);
457 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
461 * Returns information about files in a draft area.
463 * @global stdClass $CFG
464 * @global stdClass $USER
465 * @param int $draftitemid the draft area item id.
466 * @param string $filepath path to the directory from which the information have to be retrieved.
467 * @return array with the following entries:
468 * 'filecount' => number of files in the draft area.
469 * 'filesize' => total size of the files in the draft area.
470 * 'foldercount' => number of folders in the draft area.
471 * 'filesize_without_references' => total size of the area excluding file references.
472 * (more information will be added as needed).
474 function file_get_draft_area_info($draftitemid, $filepath = '/') {
475 global $CFG, $USER;
477 $usercontext = context_user::instance($USER->id);
478 $fs = get_file_storage();
480 $results = array(
481 'filecount' => 0,
482 'foldercount' => 0,
483 'filesize' => 0,
484 'filesize_without_references' => 0
487 if ($filepath != '/') {
488 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
489 } else {
490 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
492 foreach ($draftfiles as $file) {
493 if ($file->is_directory()) {
494 $results['foldercount'] += 1;
495 } else {
496 $results['filecount'] += 1;
499 $filesize = $file->get_filesize();
500 $results['filesize'] += $filesize;
501 if (!$file->is_external_file()) {
502 $results['filesize_without_references'] += $filesize;
506 return $results;
510 * Returns whether a draft area has exceeded/will exceed its size limit.
512 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
514 * @param int $draftitemid the draft area item id.
515 * @param int $areamaxbytes the maximum size allowed in this draft area.
516 * @param int $newfilesize the size that would be added to the current area.
517 * @param bool $includereferences true to include the size of the references in the area size.
518 * @return bool true if the area will/has exceeded its limit.
519 * @since 2.4
521 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
522 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
523 $draftinfo = file_get_draft_area_info($draftitemid);
524 $areasize = $draftinfo['filesize_without_references'];
525 if ($includereferences) {
526 $areasize = $draftinfo['filesize'];
528 if ($areasize + $newfilesize > $areamaxbytes) {
529 return true;
532 return false;
536 * Get used space of files
537 * @global moodle_database $DB
538 * @global stdClass $USER
539 * @return int total bytes
541 function file_get_user_used_space() {
542 global $DB, $USER;
544 $usercontext = context_user::instance($USER->id);
545 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
546 JOIN (SELECT contenthash, filename, MAX(id) AS id
547 FROM {files}
548 WHERE contextid = ? AND component = ? AND filearea != ?
549 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
550 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
551 $record = $DB->get_record_sql($sql, $params);
552 return (int)$record->totalbytes;
556 * Convert any string to a valid filepath
557 * @todo review this function
558 * @param string $str
559 * @return string path
561 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
562 if ($str == '/' or empty($str)) {
563 return '/';
564 } else {
565 return '/'.trim($str, '/').'/';
570 * Generate a folder tree of draft area of current USER recursively
572 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
573 * @param int $draftitemid
574 * @param string $filepath
575 * @param mixed $data
577 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
578 global $USER, $OUTPUT, $CFG;
579 $data->children = array();
580 $context = context_user::instance($USER->id);
581 $fs = get_file_storage();
582 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
583 foreach ($files as $file) {
584 if ($file->is_directory()) {
585 $item = new stdClass();
586 $item->sortorder = $file->get_sortorder();
587 $item->filepath = $file->get_filepath();
589 $foldername = explode('/', trim($item->filepath, '/'));
590 $item->fullname = trim(array_pop($foldername), '/');
592 $item->id = uniqid();
593 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
594 $data->children[] = $item;
595 } else {
596 continue;
603 * Listing all files (including folders) in current path (draft area)
604 * used by file manager
605 * @param int $draftitemid
606 * @param string $filepath
607 * @return stdClass
609 function file_get_drafarea_files($draftitemid, $filepath = '/') {
610 global $USER, $OUTPUT, $CFG;
612 $context = context_user::instance($USER->id);
613 $fs = get_file_storage();
615 $data = new stdClass();
616 $data->path = array();
617 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
619 // will be used to build breadcrumb
620 $trail = '/';
621 if ($filepath !== '/') {
622 $filepath = file_correct_filepath($filepath);
623 $parts = explode('/', $filepath);
624 foreach ($parts as $part) {
625 if ($part != '' && $part != null) {
626 $trail .= ($part.'/');
627 $data->path[] = array('name'=>$part, 'path'=>$trail);
632 $list = array();
633 $maxlength = 12;
634 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
635 foreach ($files as $file) {
636 $item = new stdClass();
637 $item->filename = $file->get_filename();
638 $item->filepath = $file->get_filepath();
639 $item->fullname = trim($item->filename, '/');
640 $filesize = $file->get_filesize();
641 $item->size = $filesize ? $filesize : null;
642 $item->filesize = $filesize ? display_size($filesize) : '';
644 $item->sortorder = $file->get_sortorder();
645 $item->author = $file->get_author();
646 $item->license = $file->get_license();
647 $item->datemodified = $file->get_timemodified();
648 $item->datecreated = $file->get_timecreated();
649 $item->isref = $file->is_external_file();
650 if ($item->isref && $file->get_status() == 666) {
651 $item->originalmissing = true;
653 // find the file this draft file was created from and count all references in local
654 // system pointing to that file
655 $source = @unserialize($file->get_source());
656 if (isset($source->original)) {
657 $item->refcount = $fs->search_references_count($source->original);
660 if ($file->is_directory()) {
661 $item->filesize = 0;
662 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
663 $item->type = 'folder';
664 $foldername = explode('/', trim($item->filepath, '/'));
665 $item->fullname = trim(array_pop($foldername), '/');
666 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
667 } else {
668 // do NOT use file browser here!
669 $item->mimetype = get_mimetype_description($file);
670 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
671 $item->type = 'zip';
672 } else {
673 $item->type = 'file';
675 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
676 $item->url = $itemurl->out();
677 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
678 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
679 if ($imageinfo = $file->get_imageinfo()) {
680 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
681 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
682 $item->image_width = $imageinfo['width'];
683 $item->image_height = $imageinfo['height'];
686 $list[] = $item;
689 $data->itemid = $draftitemid;
690 $data->list = $list;
691 return $data;
695 * Returns draft area itemid for a given element.
697 * @category files
698 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
699 * @return int the itemid, or 0 if there is not one yet.
701 function file_get_submitted_draft_itemid($elname) {
702 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
703 if (!isset($_REQUEST[$elname])) {
704 return 0;
706 if (is_array($_REQUEST[$elname])) {
707 $param = optional_param_array($elname, 0, PARAM_INT);
708 if (!empty($param['itemid'])) {
709 $param = $param['itemid'];
710 } else {
711 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
712 return false;
715 } else {
716 $param = optional_param($elname, 0, PARAM_INT);
719 if ($param) {
720 require_sesskey();
723 return $param;
727 * Restore the original source field from draft files
729 * Do not use this function because it makes field files.source inconsistent
730 * for draft area files. This function will be deprecated in 2.6
732 * @param stored_file $storedfile This only works with draft files
733 * @return stored_file
735 function file_restore_source_field_from_draft_file($storedfile) {
736 $source = @unserialize($storedfile->get_source());
737 if (!empty($source)) {
738 if (is_object($source)) {
739 $restoredsource = $source->source;
740 $storedfile->set_source($restoredsource);
741 } else {
742 throw new moodle_exception('invalidsourcefield', 'error');
745 return $storedfile;
748 * Saves files from a draft file area to a real one (merging the list of files).
749 * Can rewrite URLs in some content at the same time if desired.
751 * @category files
752 * @global stdClass $USER
753 * @param int $draftitemid the id of the draft area to use. Normally obtained
754 * from file_get_submitted_draft_itemid('elementname') or similar.
755 * @param int $contextid This parameter and the next two identify the file area to save to.
756 * @param string $component
757 * @param string $filearea indentifies the file area.
758 * @param int $itemid helps identifies the file area.
759 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
760 * @param string $text some html content that needs to have embedded links rewritten
761 * to the @@PLUGINFILE@@ form for saving in the database.
762 * @param bool $forcehttps force https urls.
763 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
765 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
766 global $USER;
768 $usercontext = context_user::instance($USER->id);
769 $fs = get_file_storage();
771 $options = (array)$options;
772 if (!isset($options['subdirs'])) {
773 $options['subdirs'] = false;
775 if (!isset($options['maxfiles'])) {
776 $options['maxfiles'] = -1; // unlimited
778 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
779 $options['maxbytes'] = 0; // unlimited
781 if (!isset($options['areamaxbytes'])) {
782 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
784 $allowreferences = true;
785 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
786 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
787 // this is not exactly right. BUT there are many places in code where filemanager options
788 // are not passed to file_save_draft_area_files()
789 $allowreferences = false;
792 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
793 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
794 // anything at all in the next area.
795 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
796 return null;
799 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
800 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
802 // One file in filearea means it is empty (it has only top-level directory '.').
803 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
804 // we have to merge old and new files - we want to keep file ids for files that were not changed
805 // we change time modified for all new and changed files, we keep time created as is
807 $newhashes = array();
808 $filecount = 0;
809 foreach ($draftfiles as $file) {
810 if (!$options['subdirs'] && ($file->get_filepath() !== '/' or $file->is_directory())) {
811 continue;
813 if (!$allowreferences && $file->is_external_file()) {
814 continue;
816 if (!$file->is_directory()) {
817 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
818 // oversized file - should not get here at all
819 continue;
821 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
822 // more files - should not get here at all
823 continue;
825 $filecount++;
827 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
828 $newhashes[$newhash] = $file;
831 // Loop through oldfiles and decide which we need to delete and which to update.
832 // After this cycle the array $newhashes will only contain the files that need to be added.
833 foreach ($oldfiles as $oldfile) {
834 $oldhash = $oldfile->get_pathnamehash();
835 if (!isset($newhashes[$oldhash])) {
836 // delete files not needed any more - deleted by user
837 $oldfile->delete();
838 continue;
841 $newfile = $newhashes[$oldhash];
842 // Now we know that we have $oldfile and $newfile for the same path.
843 // Let's check if we can update this file or we need to delete and create.
844 if ($newfile->is_directory()) {
845 // Directories are always ok to just update.
846 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
847 // File has the 'original' - we need to update the file (it may even have not been changed at all).
848 $original = file_storage::unpack_reference($source->original);
849 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
850 // Very odd, original points to another file. Delete and create file.
851 $oldfile->delete();
852 continue;
854 } else {
855 // The same file name but absence of 'original' means that file was deteled and uploaded again.
856 // By deleting and creating new file we properly manage all existing references.
857 $oldfile->delete();
858 continue;
861 // status changed, we delete old file, and create a new one
862 if ($oldfile->get_status() != $newfile->get_status()) {
863 // file was changed, use updated with new timemodified data
864 $oldfile->delete();
865 // This file will be added later
866 continue;
869 // Updated author
870 if ($oldfile->get_author() != $newfile->get_author()) {
871 $oldfile->set_author($newfile->get_author());
873 // Updated license
874 if ($oldfile->get_license() != $newfile->get_license()) {
875 $oldfile->set_license($newfile->get_license());
878 // Updated file source
879 // Field files.source for draftarea files contains serialised object with source and original information.
880 // We only store the source part of it for non-draft file area.
881 $newsource = $newfile->get_source();
882 if ($source = @unserialize($newfile->get_source())) {
883 $newsource = $source->source;
885 if ($oldfile->get_source() !== $newsource) {
886 $oldfile->set_source($newsource);
889 // Updated sort order
890 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
891 $oldfile->set_sortorder($newfile->get_sortorder());
894 // Update file timemodified
895 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
896 $oldfile->set_timemodified($newfile->get_timemodified());
899 // Replaced file content
900 if (!$oldfile->is_directory() &&
901 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
902 $oldfile->get_filesize() != $newfile->get_filesize() ||
903 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
904 $oldfile->get_userid() != $newfile->get_userid())) {
905 $oldfile->replace_file_with($newfile);
906 // push changes to all local files that are referencing this file
907 $fs->update_references_to_storedfile($oldfile);
910 // unchanged file or directory - we keep it as is
911 unset($newhashes[$oldhash]);
914 // Add fresh file or the file which has changed status
915 // the size and subdirectory tests are extra safety only, the UI should prevent it
916 foreach ($newhashes as $file) {
917 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
918 if ($source = @unserialize($file->get_source())) {
919 // Field files.source for draftarea files contains serialised object with source and original information.
920 // We only store the source part of it for non-draft file area.
921 $file_record['source'] = $source->source;
924 if ($file->is_external_file()) {
925 $repoid = $file->get_repository_id();
926 if (!empty($repoid)) {
927 $file_record['repositoryid'] = $repoid;
928 $file_record['reference'] = $file->get_reference();
932 $fs->create_file_from_storedfile($file_record, $file);
936 // note: do not purge the draft area - we clean up areas later in cron,
937 // the reason is that user might press submit twice and they would loose the files,
938 // also sometimes we might want to use hacks that save files into two different areas
940 if (is_null($text)) {
941 return null;
942 } else {
943 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
948 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
949 * ready to be saved in the database. Normally, this is done automatically by
950 * {@link file_save_draft_area_files()}.
952 * @category files
953 * @param string $text the content to process.
954 * @param int $draftitemid the draft file area the content was using.
955 * @param bool $forcehttps whether the content contains https URLs. Default false.
956 * @return string the processed content.
958 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
959 global $CFG, $USER;
961 $usercontext = context_user::instance($USER->id);
963 $wwwroot = $CFG->wwwroot;
964 if ($forcehttps) {
965 $wwwroot = str_replace('http://', 'https://', $wwwroot);
968 // relink embedded files if text submitted - no absolute links allowed in database!
969 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
971 if (strpos($text, 'draftfile.php?file=') !== false) {
972 $matches = array();
973 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
974 if ($matches) {
975 foreach ($matches[0] as $match) {
976 $replace = str_ireplace('%2F', '/', $match);
977 $text = str_replace($match, $replace, $text);
980 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
983 return $text;
987 * Set file sort order
989 * @global moodle_database $DB
990 * @param int $contextid the context id
991 * @param string $component file component
992 * @param string $filearea file area.
993 * @param int $itemid itemid.
994 * @param string $filepath file path.
995 * @param string $filename file name.
996 * @param int $sortorder the sort order of file.
997 * @return bool
999 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1000 global $DB;
1001 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1002 if ($file_record = $DB->get_record('files', $conditions)) {
1003 $sortorder = (int)$sortorder;
1004 $file_record->sortorder = $sortorder;
1005 $DB->update_record('files', $file_record);
1006 return true;
1008 return false;
1012 * reset file sort order number to 0
1013 * @global moodle_database $DB
1014 * @param int $contextid the context id
1015 * @param string $component
1016 * @param string $filearea file area.
1017 * @param int|bool $itemid itemid.
1018 * @return bool
1020 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1021 global $DB;
1023 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1024 if ($itemid !== false) {
1025 $conditions['itemid'] = $itemid;
1028 $file_records = $DB->get_records('files', $conditions);
1029 foreach ($file_records as $file_record) {
1030 $file_record->sortorder = 0;
1031 $DB->update_record('files', $file_record);
1033 return true;
1037 * Returns description of upload error
1039 * @param int $errorcode found in $_FILES['filename.ext']['error']
1040 * @return string error description string, '' if ok
1042 function file_get_upload_error($errorcode) {
1044 switch ($errorcode) {
1045 case 0: // UPLOAD_ERR_OK - no error
1046 $errmessage = '';
1047 break;
1049 case 1: // UPLOAD_ERR_INI_SIZE
1050 $errmessage = get_string('uploadserverlimit');
1051 break;
1053 case 2: // UPLOAD_ERR_FORM_SIZE
1054 $errmessage = get_string('uploadformlimit');
1055 break;
1057 case 3: // UPLOAD_ERR_PARTIAL
1058 $errmessage = get_string('uploadpartialfile');
1059 break;
1061 case 4: // UPLOAD_ERR_NO_FILE
1062 $errmessage = get_string('uploadnofilefound');
1063 break;
1065 // Note: there is no error with a value of 5
1067 case 6: // UPLOAD_ERR_NO_TMP_DIR
1068 $errmessage = get_string('uploadnotempdir');
1069 break;
1071 case 7: // UPLOAD_ERR_CANT_WRITE
1072 $errmessage = get_string('uploadcantwrite');
1073 break;
1075 case 8: // UPLOAD_ERR_EXTENSION
1076 $errmessage = get_string('uploadextension');
1077 break;
1079 default:
1080 $errmessage = get_string('uploadproblem');
1083 return $errmessage;
1087 * Recursive function formating an array in POST parameter
1088 * @param array $arraydata - the array that we are going to format and add into &$data array
1089 * @param string $currentdata - a row of the final postdata array at instant T
1090 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1091 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1093 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1094 foreach ($arraydata as $k=>$v) {
1095 $newcurrentdata = $currentdata;
1096 if (is_array($v)) { //the value is an array, call the function recursively
1097 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1098 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1099 } else { //add the POST parameter to the $data array
1100 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1106 * Transform a PHP array into POST parameter
1107 * (see the recursive function format_array_postdata_for_curlcall)
1108 * @param array $postdata
1109 * @return array containing all POST parameters (1 row = 1 POST parameter)
1111 function format_postdata_for_curlcall($postdata) {
1112 $data = array();
1113 foreach ($postdata as $k=>$v) {
1114 if (is_array($v)) {
1115 $currentdata = urlencode($k);
1116 format_array_postdata_for_curlcall($v, $currentdata, $data);
1117 } else {
1118 $data[] = urlencode($k).'='.urlencode($v);
1121 $convertedpostdata = implode('&', $data);
1122 return $convertedpostdata;
1126 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1127 * Due to security concerns only downloads from http(s) sources are supported.
1129 * @todo MDL-31073 add version test for '7.10.5'
1130 * @category files
1131 * @param string $url file url starting with http(s)://
1132 * @param array $headers http headers, null if none. If set, should be an
1133 * associative array of header name => value pairs.
1134 * @param array $postdata array means use POST request with given parameters
1135 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1136 * (if false, just returns content)
1137 * @param int $timeout timeout for complete download process including all file transfer
1138 * (default 5 minutes)
1139 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1140 * usually happens if the remote server is completely down (default 20 seconds);
1141 * may not work when using proxy
1142 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1143 * Only use this when already in a trusted location.
1144 * @param string $tofile store the downloaded content to file instead of returning it.
1145 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1146 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1147 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1149 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1150 global $CFG;
1152 // some extra security
1153 $newlines = array("\r", "\n");
1154 if (is_array($headers) ) {
1155 foreach ($headers as $key => $value) {
1156 $headers[$key] = str_replace($newlines, '', $value);
1159 $url = str_replace($newlines, '', $url);
1160 if (!preg_match('|^https?://|i', $url)) {
1161 if ($fullresponse) {
1162 $response = new stdClass();
1163 $response->status = 0;
1164 $response->headers = array();
1165 $response->response_code = 'Invalid protocol specified in url';
1166 $response->results = '';
1167 $response->error = 'Invalid protocol specified in url';
1168 return $response;
1169 } else {
1170 return false;
1174 // check if proxy (if used) should be bypassed for this url
1175 $proxybypass = is_proxybypass($url);
1177 if (!$ch = curl_init($url)) {
1178 debugging('Can not init curl.');
1179 return false;
1182 // set extra headers
1183 if (is_array($headers) ) {
1184 $headers2 = array();
1185 foreach ($headers as $key => $value) {
1186 $headers2[] = "$key: $value";
1188 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
1191 if ($skipcertverify) {
1192 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1195 // use POST if requested
1196 if (is_array($postdata)) {
1197 $postdata = format_postdata_for_curlcall($postdata);
1198 curl_setopt($ch, CURLOPT_POST, true);
1199 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1202 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1203 curl_setopt($ch, CURLOPT_HEADER, false);
1204 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1206 if ($cacert = curl::get_cacert()) {
1207 curl_setopt($ch, CURLOPT_CAINFO, $cacert);
1210 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1211 // TODO: add version test for '7.10.5'
1212 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1213 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1216 if (!empty($CFG->proxyhost) and !$proxybypass) {
1217 // SOCKS supported in PHP5 only
1218 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1219 if (defined('CURLPROXY_SOCKS5')) {
1220 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1221 } else {
1222 curl_close($ch);
1223 if ($fullresponse) {
1224 $response = new stdClass();
1225 $response->status = '0';
1226 $response->headers = array();
1227 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1228 $response->results = '';
1229 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1230 return $response;
1231 } else {
1232 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1233 return false;
1238 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1240 if (empty($CFG->proxyport)) {
1241 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1242 } else {
1243 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1246 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1247 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1248 if (defined('CURLOPT_PROXYAUTH')) {
1249 // any proxy authentication if PHP 5.1
1250 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1255 // set up header and content handlers
1256 $received = new stdClass();
1257 $received->headers = array(); // received headers array
1258 $received->tofile = $tofile;
1259 $received->fh = null;
1260 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1261 if ($tofile) {
1262 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1265 if (!isset($CFG->curltimeoutkbitrate)) {
1266 //use very slow rate of 56kbps as a timeout speed when not set
1267 $bitrate = 56;
1268 } else {
1269 $bitrate = $CFG->curltimeoutkbitrate;
1272 // try to calculate the proper amount for timeout from remote file size.
1273 // if disabled or zero, we won't do any checks nor head requests.
1274 if ($calctimeout && $bitrate > 0) {
1275 //setup header request only options
1276 curl_setopt_array ($ch, array(
1277 CURLOPT_RETURNTRANSFER => false,
1278 CURLOPT_NOBODY => true)
1281 curl_exec($ch);
1282 $info = curl_getinfo($ch);
1283 $err = curl_error($ch);
1285 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1286 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1288 //reinstate affected curl options
1289 curl_setopt_array ($ch, array(
1290 CURLOPT_RETURNTRANSFER => true,
1291 CURLOPT_NOBODY => false,
1292 CURLOPT_HTTPGET => true)
1296 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1297 $result = curl_exec($ch);
1299 // try to detect encoding problems
1300 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1301 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1302 $result = curl_exec($ch);
1305 if ($received->fh) {
1306 fclose($received->fh);
1309 if (curl_errno($ch)) {
1310 $error = curl_error($ch);
1311 $error_no = curl_errno($ch);
1312 curl_close($ch);
1314 if ($fullresponse) {
1315 $response = new stdClass();
1316 if ($error_no == 28) {
1317 $response->status = '-100'; // mimic snoopy
1318 } else {
1319 $response->status = '0';
1321 $response->headers = array();
1322 $response->response_code = $error;
1323 $response->results = false;
1324 $response->error = $error;
1325 return $response;
1326 } else {
1327 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1328 return false;
1331 } else {
1332 $info = curl_getinfo($ch);
1333 curl_close($ch);
1335 if (empty($info['http_code'])) {
1336 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1337 $response = new stdClass();
1338 $response->status = '0';
1339 $response->headers = array();
1340 $response->response_code = 'Unknown cURL error';
1341 $response->results = false; // do NOT change this, we really want to ignore the result!
1342 $response->error = 'Unknown cURL error';
1344 } else {
1345 $response = new stdClass();
1346 $response->status = (string)$info['http_code'];
1347 $response->headers = $received->headers;
1348 $response->response_code = $received->headers[0];
1349 $response->results = $result;
1350 $response->error = '';
1353 if ($fullresponse) {
1354 return $response;
1355 } else if ($info['http_code'] != 200) {
1356 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1357 return false;
1358 } else {
1359 return $response->results;
1365 * internal implementation
1366 * @param stdClass $received
1367 * @param resource $ch
1368 * @param mixed $header
1369 * @return int header length
1371 function download_file_content_header_handler($received, $ch, $header) {
1372 $received->headers[] = $header;
1373 return strlen($header);
1377 * internal implementation
1378 * @param stdClass $received
1379 * @param resource $ch
1380 * @param mixed $data
1382 function download_file_content_write_handler($received, $ch, $data) {
1383 if (!$received->fh) {
1384 $received->fh = fopen($received->tofile, 'w');
1385 if ($received->fh === false) {
1386 // bad luck, file creation or overriding failed
1387 return 0;
1390 if (fwrite($received->fh, $data) === false) {
1391 // bad luck, write failed, let's abort completely
1392 return 0;
1394 return strlen($data);
1398 * Returns a list of information about file types based on extensions.
1400 * The following elements expected in value array for each extension:
1401 * 'type' - mimetype
1402 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1403 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1404 * also files with bigger sizes under names
1405 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1406 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1407 * commonly used in moodle the following groups:
1408 * - web_image - image that can be included as <img> in HTML
1409 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1410 * - video - file that can be imported as video in text editor
1411 * - audio - file that can be imported as audio in text editor
1412 * - archive - we can extract files from this archive
1413 * - spreadsheet - used for portfolio format
1414 * - document - used for portfolio format
1415 * - presentation - used for portfolio format
1416 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1417 * human-readable description for this filetype;
1418 * Function {@link get_mimetype_description()} first looks at the presence of string for
1419 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1420 * attribute, if not found returns the value of 'type';
1421 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1422 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1423 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1425 * @category files
1426 * @return array List of information about file types based on extensions.
1427 * Associative array of extension (lower-case) to associative array
1428 * from 'element name' to data. Current element names are 'type' and 'icon'.
1429 * Unknown types should use the 'xxx' entry which includes defaults.
1431 function &get_mimetypes_array() {
1432 static $mimearray = array (
1433 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1434 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1435 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1436 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1437 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1438 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1439 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1440 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1441 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1442 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1443 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1444 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1445 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1446 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1447 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1448 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1449 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1450 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1451 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1452 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1453 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1454 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1456 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1457 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1458 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1459 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1460 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1462 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1463 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1464 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1465 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1466 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1467 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1468 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1469 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1470 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1472 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1473 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1474 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1475 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1476 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1477 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1478 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1479 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1480 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1481 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1482 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1483 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1484 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1485 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1486 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1487 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1488 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1489 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1490 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1491 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1492 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1493 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1494 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1495 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1496 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1497 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1498 'jnlp' => array ('type'=>'application/x-java-jnlp-file', 'icon'=>'markup'),
1499 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1500 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1501 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1502 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1503 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1504 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1505 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1506 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1507 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1508 'mht' => array ('type'=>'message/rfc822', 'icon'=>'archive'),
1509 'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
1510 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1511 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1512 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1513 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1514 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1515 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1516 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1517 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1518 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1519 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1520 'mpr' => array ('type'=>'application/vnd.moodle.profiling', 'icon'=>'moodle'),
1522 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1523 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1525 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1526 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1527 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1528 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1529 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1530 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1531 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1532 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1533 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1534 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1535 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1536 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1537 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1538 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1539 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1540 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1541 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1543 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1544 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1545 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1546 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1547 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1548 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1550 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1551 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1552 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1553 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1554 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1555 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1556 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1557 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1558 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1560 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1561 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1562 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1563 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1564 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1565 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1566 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1567 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1568 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1569 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1570 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1571 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1572 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1573 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1574 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1575 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1576 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1577 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1578 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1579 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1581 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1582 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1583 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1584 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1585 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1586 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1587 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1588 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1589 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1590 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1592 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1593 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1594 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1595 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1596 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1597 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1598 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1599 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1600 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1601 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1602 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1603 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1605 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1606 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1607 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1608 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1610 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1611 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1612 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1613 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1614 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1615 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1616 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1618 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1619 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1621 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1623 return $mimearray;
1627 * Obtains information about a filetype based on its extension. Will
1628 * use a default if no information is present about that particular
1629 * extension.
1631 * @category files
1632 * @param string $element Desired information (usually 'icon'
1633 * for icon filename or 'type' for MIME type. Can also be
1634 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1635 * @param string $filename Filename we're looking up
1636 * @return string Requested piece of information from array
1638 function mimeinfo($element, $filename) {
1639 global $CFG;
1640 $mimeinfo = & get_mimetypes_array();
1641 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1643 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1644 if (empty($filetype)) {
1645 $filetype = 'xxx'; // file without extension
1647 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1648 $iconsize = max(array(16, (int)$iconsizematch[1]));
1649 $filenames = array($mimeinfo['xxx']['icon']);
1650 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1651 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1653 // find the file with the closest size, first search for specific icon then for default icon
1654 foreach ($filenames as $filename) {
1655 foreach ($iconpostfixes as $size => $postfix) {
1656 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1657 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1658 return $filename.$postfix;
1662 } else if (isset($mimeinfo[$filetype][$element])) {
1663 return $mimeinfo[$filetype][$element];
1664 } else if (isset($mimeinfo['xxx'][$element])) {
1665 return $mimeinfo['xxx'][$element]; // By default
1666 } else {
1667 return null;
1672 * Obtains information about a filetype based on the MIME type rather than
1673 * the other way around.
1675 * @category files
1676 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1677 * @param string $mimetype MIME type we're looking up
1678 * @return string Requested piece of information from array
1680 function mimeinfo_from_type($element, $mimetype) {
1681 /* array of cached mimetype->extension associations */
1682 static $cached = array();
1683 $mimeinfo = & get_mimetypes_array();
1685 if (!array_key_exists($mimetype, $cached)) {
1686 $cached[$mimetype] = null;
1687 foreach($mimeinfo as $filetype => $values) {
1688 if ($values['type'] == $mimetype) {
1689 if ($cached[$mimetype] === null) {
1690 $cached[$mimetype] = '.'.$filetype;
1692 if (!empty($values['defaulticon'])) {
1693 $cached[$mimetype] = '.'.$filetype;
1694 break;
1698 if (empty($cached[$mimetype])) {
1699 $cached[$mimetype] = '.xxx';
1702 if ($element === 'extension') {
1703 return $cached[$mimetype];
1704 } else {
1705 return mimeinfo($element, $cached[$mimetype]);
1710 * Return the relative icon path for a given file
1712 * Usage:
1713 * <code>
1714 * // $file - instance of stored_file or file_info
1715 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1716 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1717 * </code>
1718 * or
1719 * <code>
1720 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1721 * </code>
1723 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1724 * and $file->mimetype are expected)
1725 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1726 * @return string
1728 function file_file_icon($file, $size = null) {
1729 if (!is_object($file)) {
1730 $file = (object)$file;
1732 if (isset($file->filename)) {
1733 $filename = $file->filename;
1734 } else if (method_exists($file, 'get_filename')) {
1735 $filename = $file->get_filename();
1736 } else if (method_exists($file, 'get_visible_name')) {
1737 $filename = $file->get_visible_name();
1738 } else {
1739 $filename = '';
1741 if (isset($file->mimetype)) {
1742 $mimetype = $file->mimetype;
1743 } else if (method_exists($file, 'get_mimetype')) {
1744 $mimetype = $file->get_mimetype();
1745 } else {
1746 $mimetype = '';
1748 $mimetypes = &get_mimetypes_array();
1749 if ($filename) {
1750 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1751 if ($extension && !empty($mimetypes[$extension])) {
1752 // if file name has known extension, return icon for this extension
1753 return file_extension_icon($filename, $size);
1756 return file_mimetype_icon($mimetype, $size);
1760 * Return the relative icon path for a folder image
1762 * Usage:
1763 * <code>
1764 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1765 * echo html_writer::empty_tag('img', array('src' => $icon));
1766 * </code>
1767 * or
1768 * <code>
1769 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1770 * </code>
1772 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1773 * @return string
1775 function file_folder_icon($iconsize = null) {
1776 global $CFG;
1777 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1778 static $cached = array();
1779 $iconsize = max(array(16, (int)$iconsize));
1780 if (!array_key_exists($iconsize, $cached)) {
1781 foreach ($iconpostfixes as $size => $postfix) {
1782 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1783 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1784 $cached[$iconsize] = 'f/folder'.$postfix;
1785 break;
1789 return $cached[$iconsize];
1793 * Returns the relative icon path for a given mime type
1795 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1796 * a return the full path to an icon.
1798 * <code>
1799 * $mimetype = 'image/jpg';
1800 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1801 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1802 * </code>
1804 * @category files
1805 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1806 * to conform with that.
1807 * @param string $mimetype The mimetype to fetch an icon for
1808 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1809 * @return string The relative path to the icon
1811 function file_mimetype_icon($mimetype, $size = NULL) {
1812 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1816 * Returns the relative icon path for a given file name
1818 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1819 * a return the full path to an icon.
1821 * <code>
1822 * $filename = '.jpg';
1823 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1824 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1825 * </code>
1827 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1828 * to conform with that.
1829 * @todo MDL-31074 Implement $size
1830 * @category files
1831 * @param string $filename The filename to get the icon for
1832 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1833 * @return string
1835 function file_extension_icon($filename, $size = NULL) {
1836 return 'f/'.mimeinfo('icon'.$size, $filename);
1840 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1841 * mimetypes.php language file.
1843 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1844 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1845 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1846 * @param bool $capitalise If true, capitalises first character of result
1847 * @return string Text description
1849 function get_mimetype_description($obj, $capitalise=false) {
1850 $filename = $mimetype = '';
1851 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1852 // this is an instance of stored_file
1853 $mimetype = $obj->get_mimetype();
1854 $filename = $obj->get_filename();
1855 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1856 // this is an instance of file_info
1857 $mimetype = $obj->get_mimetype();
1858 $filename = $obj->get_visible_name();
1859 } else if (is_array($obj) || is_object ($obj)) {
1860 $obj = (array)$obj;
1861 if (!empty($obj['filename'])) {
1862 $filename = $obj['filename'];
1864 if (!empty($obj['mimetype'])) {
1865 $mimetype = $obj['mimetype'];
1867 } else {
1868 $mimetype = $obj;
1870 $mimetypefromext = mimeinfo('type', $filename);
1871 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1872 // if file has a known extension, overwrite the specified mimetype
1873 $mimetype = $mimetypefromext;
1875 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1876 if (empty($extension)) {
1877 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1878 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1879 } else {
1880 $mimetypestr = mimeinfo('string', $filename);
1882 $chunks = explode('/', $mimetype, 2);
1883 $chunks[] = '';
1884 $attr = array(
1885 'mimetype' => $mimetype,
1886 'ext' => $extension,
1887 'mimetype1' => $chunks[0],
1888 'mimetype2' => $chunks[1],
1890 $a = array();
1891 foreach ($attr as $key => $value) {
1892 $a[$key] = $value;
1893 $a[strtoupper($key)] = strtoupper($value);
1894 $a[ucfirst($key)] = ucfirst($value);
1897 // MIME types may include + symbol but this is not permitted in string ids.
1898 $safemimetype = str_replace('+', '_', $mimetype);
1899 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1900 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1901 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1902 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1903 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1904 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1905 $result = get_string('default', 'mimetypes', (object)$a);
1906 } else {
1907 $result = $mimetype;
1909 if ($capitalise) {
1910 $result=ucfirst($result);
1912 return $result;
1916 * Returns array of elements of type $element in type group(s)
1918 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1919 * @param string|array $groups one group or array of groups/extensions/mimetypes
1920 * @return array
1922 function file_get_typegroup($element, $groups) {
1923 static $cached = array();
1924 if (!is_array($groups)) {
1925 $groups = array($groups);
1927 if (!array_key_exists($element, $cached)) {
1928 $cached[$element] = array();
1930 $result = array();
1931 foreach ($groups as $group) {
1932 if (!array_key_exists($group, $cached[$element])) {
1933 // retrieive and cache all elements of type $element for group $group
1934 $mimeinfo = & get_mimetypes_array();
1935 $cached[$element][$group] = array();
1936 foreach ($mimeinfo as $extension => $value) {
1937 $value['extension'] = '.'.$extension;
1938 if (empty($value[$element])) {
1939 continue;
1941 if (($group === '.'.$extension || $group === $value['type'] ||
1942 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1943 !in_array($value[$element], $cached[$element][$group])) {
1944 $cached[$element][$group][] = $value[$element];
1948 $result = array_merge($result, $cached[$element][$group]);
1950 return array_values(array_unique($result));
1954 * Checks if file with name $filename has one of the extensions in groups $groups
1956 * @see get_mimetypes_array()
1957 * @param string $filename name of the file to check
1958 * @param string|array $groups one group or array of groups to check
1959 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1960 * file mimetype is in mimetypes in groups $groups
1961 * @return bool
1963 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1964 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1965 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1966 return true;
1968 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1972 * Checks if mimetype $mimetype belongs to one of the groups $groups
1974 * @see get_mimetypes_array()
1975 * @param string $mimetype
1976 * @param string|array $groups one group or array of groups to check
1977 * @return bool
1979 function file_mimetype_in_typegroup($mimetype, $groups) {
1980 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1984 * Requested file is not found or not accessible, does not return, terminates script
1986 * @global stdClass $CFG
1987 * @global stdClass $COURSE
1989 function send_file_not_found() {
1990 global $CFG, $COURSE;
1991 send_header_404();
1992 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1995 * Helper function to send correct 404 for server.
1997 function send_header_404() {
1998 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1999 header("Status: 404 Not Found");
2000 } else {
2001 header('HTTP/1.0 404 not found');
2006 * The readfile function can fail when files are larger than 2GB (even on 64-bit
2007 * platforms). This wrapper uses readfile for small files and custom code for
2008 * large ones.
2010 * @param string $path Path to file
2011 * @param int $filesize Size of file (if left out, will get it automatically)
2012 * @return int|bool Size read (will always be $filesize) or false if failed
2014 function readfile_allow_large($path, $filesize = -1) {
2015 // Automatically get size if not specified.
2016 if ($filesize === -1) {
2017 $filesize = filesize($path);
2019 if ($filesize <= 2147483647) {
2020 // If the file is up to 2^31 - 1, send it normally using readfile.
2021 return readfile($path);
2022 } else {
2023 // For large files, read and output in 64KB chunks.
2024 $handle = fopen($path, 'r');
2025 if ($handle === false) {
2026 return false;
2028 $left = $filesize;
2029 while ($left > 0) {
2030 $size = min($left, 65536);
2031 $buffer = fread($handle, $size);
2032 if ($buffer === false) {
2033 return false;
2035 echo $buffer;
2036 $left -= $size;
2038 return $filesize;
2043 * Enhanced readfile() with optional acceleration.
2044 * @param string|stored_file $file
2045 * @param string $mimetype
2046 * @param bool $accelerate
2047 * @return void
2049 function readfile_accel($file, $mimetype, $accelerate) {
2050 global $CFG;
2052 if ($mimetype === 'text/plain') {
2053 // there is no encoding specified in text files, we need something consistent
2054 header('Content-Type: text/plain; charset=utf-8');
2055 } else {
2056 header('Content-Type: '.$mimetype);
2059 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2060 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2062 if (is_object($file)) {
2063 header('Etag: "' . $file->get_contenthash() . '"');
2064 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
2065 header('HTTP/1.1 304 Not Modified');
2066 return;
2070 // if etag present for stored file rely on it exclusively
2071 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2072 // get unixtime of request header; clip extra junk off first
2073 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2074 if ($since && $since >= $lastmodified) {
2075 header('HTTP/1.1 304 Not Modified');
2076 return;
2080 if ($accelerate and !empty($CFG->xsendfile)) {
2081 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2082 header('Accept-Ranges: bytes');
2083 } else {
2084 header('Accept-Ranges: none');
2087 if (is_object($file)) {
2088 $fs = get_file_storage();
2089 if ($fs->xsendfile($file->get_contenthash())) {
2090 return;
2093 } else {
2094 require_once("$CFG->libdir/xsendfilelib.php");
2095 if (xsendfile($file)) {
2096 return;
2101 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2103 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2105 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2106 header('Accept-Ranges: bytes');
2108 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2109 // byteserving stuff - for acrobat reader and download accelerators
2110 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2111 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2112 $ranges = false;
2113 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2114 foreach ($ranges as $key=>$value) {
2115 if ($ranges[$key][1] == '') {
2116 //suffix case
2117 $ranges[$key][1] = $filesize - $ranges[$key][2];
2118 $ranges[$key][2] = $filesize - 1;
2119 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2120 //fix range length
2121 $ranges[$key][2] = $filesize - 1;
2123 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2124 //invalid byte-range ==> ignore header
2125 $ranges = false;
2126 break;
2128 //prepare multipart header
2129 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2130 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2132 } else {
2133 $ranges = false;
2135 if ($ranges) {
2136 if (is_object($file)) {
2137 $handle = $file->get_content_file_handle();
2138 } else {
2139 $handle = fopen($file, 'rb');
2141 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2144 } else {
2145 // Do not byteserve
2146 header('Accept-Ranges: none');
2149 header('Content-Length: '.$filesize);
2151 if ($filesize > 10000000) {
2152 // for large files try to flush and close all buffers to conserve memory
2153 while(@ob_get_level()) {
2154 if (!@ob_end_flush()) {
2155 break;
2160 // send the whole file content
2161 if (is_object($file)) {
2162 $file->readfile();
2163 } else {
2164 readfile_allow_large($file, $filesize);
2169 * Similar to readfile_accel() but designed for strings.
2170 * @param string $string
2171 * @param string $mimetype
2172 * @param bool $accelerate
2173 * @return void
2175 function readstring_accel($string, $mimetype, $accelerate) {
2176 global $CFG;
2178 if ($mimetype === 'text/plain') {
2179 // there is no encoding specified in text files, we need something consistent
2180 header('Content-Type: text/plain; charset=utf-8');
2181 } else {
2182 header('Content-Type: '.$mimetype);
2184 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2185 header('Accept-Ranges: none');
2187 if ($accelerate and !empty($CFG->xsendfile)) {
2188 $fs = get_file_storage();
2189 if ($fs->xsendfile(sha1($string))) {
2190 return;
2194 header('Content-Length: '.strlen($string));
2195 echo $string;
2199 * Handles the sending of temporary file to user, download is forced.
2200 * File is deleted after abort or successful sending, does not return, script terminated
2202 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2203 * @param string $filename proposed file name when saving file
2204 * @param bool $pathisstring If the path is string
2206 function send_temp_file($path, $filename, $pathisstring=false) {
2207 global $CFG;
2209 if (check_browser_version('Firefox', '1.5')) {
2210 // only FF is known to correctly save to disk before opening...
2211 $mimetype = mimeinfo('type', $filename);
2212 } else {
2213 $mimetype = 'application/x-forcedownload';
2216 // close session - not needed anymore
2217 session_get_instance()->write_close();
2219 if (!$pathisstring) {
2220 if (!file_exists($path)) {
2221 send_header_404();
2222 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2224 // executed after normal finish or abort
2225 @register_shutdown_function('send_temp_file_finished', $path);
2228 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2229 if (check_browser_version('MSIE')) {
2230 $filename = urlencode($filename);
2233 header('Content-Disposition: attachment; filename="'.$filename.'"');
2234 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2235 header('Cache-Control: max-age=10');
2236 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2237 header('Pragma: ');
2238 } else { //normal http - prevent caching at all cost
2239 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2240 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2241 header('Pragma: no-cache');
2244 // send the contents - we can not accelerate this because the file will be deleted asap
2245 if ($pathisstring) {
2246 readstring_accel($path, $mimetype, false);
2247 } else {
2248 readfile_accel($path, $mimetype, false);
2249 @unlink($path);
2252 die; //no more chars to output
2256 * Internal callback function used by send_temp_file()
2258 * @param string $path
2260 function send_temp_file_finished($path) {
2261 if (file_exists($path)) {
2262 @unlink($path);
2267 * Handles the sending of file data to the user's browser, including support for
2268 * byteranges etc.
2270 * @category files
2271 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2272 * @param string $filename Filename to send
2273 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2274 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2275 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2276 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2277 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2278 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2279 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2280 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2281 * and should not be reopened.
2282 * @return null script execution stopped unless $dontdie is true
2284 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2285 global $CFG, $COURSE;
2287 if ($dontdie) {
2288 ignore_user_abort(true);
2291 // MDL-11789, apply $CFG->filelifetime here
2292 if ($lifetime === 'default') {
2293 if (!empty($CFG->filelifetime)) {
2294 $lifetime = $CFG->filelifetime;
2295 } else {
2296 $lifetime = 86400;
2300 session_get_instance()->write_close(); // unlock session during fileserving
2302 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2303 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2304 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2305 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2306 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2307 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2309 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2310 if (check_browser_version('MSIE')) {
2311 $filename = rawurlencode($filename);
2314 if ($forcedownload) {
2315 header('Content-Disposition: attachment; filename="'.$filename.'"');
2316 } else {
2317 header('Content-Disposition: inline; filename="'.$filename.'"');
2320 if ($lifetime > 0) {
2321 $nobyteserving = false;
2322 header('Cache-Control: max-age='.$lifetime);
2323 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2324 header('Pragma: ');
2326 } else { // Do not cache files in proxies and browsers
2327 $nobyteserving = true;
2328 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2329 header('Cache-Control: max-age=10');
2330 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2331 header('Pragma: ');
2332 } else { //normal http - prevent caching at all cost
2333 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2334 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2335 header('Pragma: no-cache');
2339 if (empty($filter)) {
2340 // send the contents
2341 if ($pathisstring) {
2342 readstring_accel($path, $mimetype, !$dontdie);
2343 } else {
2344 readfile_accel($path, $mimetype, !$dontdie);
2347 } else {
2348 // Try to put the file through filters
2349 if ($mimetype == 'text/html') {
2350 $options = new stdClass();
2351 $options->noclean = true;
2352 $options->nocache = true; // temporary workaround for MDL-5136
2353 $text = $pathisstring ? $path : implode('', file($path));
2355 $text = file_modify_html_header($text);
2356 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2358 readstring_accel($output, $mimetype, false);
2360 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2361 // only filter text if filter all files is selected
2362 $options = new stdClass();
2363 $options->newlines = false;
2364 $options->noclean = true;
2365 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2366 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2368 readstring_accel($output, $mimetype, false);
2370 } else {
2371 // send the contents
2372 if ($pathisstring) {
2373 readstring_accel($path, $mimetype, !$dontdie);
2374 } else {
2375 readfile_accel($path, $mimetype, !$dontdie);
2379 if ($dontdie) {
2380 return;
2382 die; //no more chars to output!!!
2386 * Handles the sending of file data to the user's browser, including support for
2387 * byteranges etc.
2389 * The $options parameter supports the following keys:
2390 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2391 * (string|null) filename - overrides the implicit filename
2392 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2393 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2394 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2395 * and should not be reopened.
2397 * @category files
2398 * @param stored_file $stored_file local file object
2399 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2400 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2401 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2402 * @param array $options additional options affecting the file serving
2403 * @return null script execution stopped unless $options['dontdie'] is true
2405 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2406 global $CFG, $COURSE;
2408 if (empty($options['filename'])) {
2409 $filename = null;
2410 } else {
2411 $filename = $options['filename'];
2414 if (empty($options['dontdie'])) {
2415 $dontdie = false;
2416 } else {
2417 $dontdie = true;
2420 if (!empty($options['preview'])) {
2421 // replace the file with its preview
2422 $fs = get_file_storage();
2423 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2424 if (!$preview_file) {
2425 // unable to create a preview of the file, send its default mime icon instead
2426 if ($options['preview'] === 'tinyicon') {
2427 $size = 24;
2428 } else if ($options['preview'] === 'thumb') {
2429 $size = 90;
2430 } else {
2431 $size = 256;
2433 $fileicon = file_file_icon($stored_file, $size);
2434 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2435 } else {
2436 // preview images have fixed cache lifetime and they ignore forced download
2437 // (they are generated by GD and therefore they are considered reasonably safe).
2438 $stored_file = $preview_file;
2439 $lifetime = DAYSECS;
2440 $filter = 0;
2441 $forcedownload = false;
2445 // handle external resource
2446 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2447 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2448 die;
2451 if (!$stored_file or $stored_file->is_directory()) {
2452 // nothing to serve
2453 if ($dontdie) {
2454 return;
2456 die;
2459 if ($dontdie) {
2460 ignore_user_abort(true);
2463 session_get_instance()->write_close(); // unlock session during fileserving
2465 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2466 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2467 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2468 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2469 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
2470 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2471 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2473 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2474 if (check_browser_version('MSIE')) {
2475 $filename = rawurlencode($filename);
2478 if ($forcedownload) {
2479 header('Content-Disposition: attachment; filename="'.$filename.'"');
2480 } else {
2481 header('Content-Disposition: inline; filename="'.$filename.'"');
2484 if ($lifetime > 0) {
2485 header('Cache-Control: max-age='.$lifetime);
2486 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2487 header('Pragma: ');
2489 } else { // Do not cache files in proxies and browsers
2490 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2491 header('Cache-Control: max-age=10');
2492 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2493 header('Pragma: ');
2494 } else { //normal http - prevent caching at all cost
2495 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2496 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2497 header('Pragma: no-cache');
2501 if (empty($filter)) {
2502 // send the contents
2503 readfile_accel($stored_file, $mimetype, !$dontdie);
2505 } else { // Try to put the file through filters
2506 if ($mimetype == 'text/html') {
2507 $options = new stdClass();
2508 $options->noclean = true;
2509 $options->nocache = true; // temporary workaround for MDL-5136
2510 $text = $stored_file->get_content();
2511 $text = file_modify_html_header($text);
2512 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2514 readstring_accel($output, $mimetype, false);
2516 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2517 // only filter text if filter all files is selected
2518 $options = new stdClass();
2519 $options->newlines = false;
2520 $options->noclean = true;
2521 $text = $stored_file->get_content();
2522 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2524 readstring_accel($output, $mimetype, false);
2526 } else { // Just send it out raw
2527 readfile_accel($stored_file, $mimetype, !$dontdie);
2530 if ($dontdie) {
2531 return;
2533 die; //no more chars to output!!!
2537 * Retrieves an array of records from a CSV file and places
2538 * them into a given table structure
2540 * @global stdClass $CFG
2541 * @global moodle_database $DB
2542 * @param string $file The path to a CSV file
2543 * @param string $table The table to retrieve columns from
2544 * @return bool|array Returns an array of CSV records or false
2546 function get_records_csv($file, $table) {
2547 global $CFG, $DB;
2549 if (!$metacolumns = $DB->get_columns($table)) {
2550 return false;
2553 if(!($handle = @fopen($file, 'r'))) {
2554 print_error('get_records_csv failed to open '.$file);
2557 $fieldnames = fgetcsv($handle, 4096);
2558 if(empty($fieldnames)) {
2559 fclose($handle);
2560 return false;
2563 $columns = array();
2565 foreach($metacolumns as $metacolumn) {
2566 $ord = array_search($metacolumn->name, $fieldnames);
2567 if(is_int($ord)) {
2568 $columns[$metacolumn->name] = $ord;
2572 $rows = array();
2574 while (($data = fgetcsv($handle, 4096)) !== false) {
2575 $item = new stdClass;
2576 foreach($columns as $name => $ord) {
2577 $item->$name = $data[$ord];
2579 $rows[] = $item;
2582 fclose($handle);
2583 return $rows;
2587 * Create a file with CSV contents
2589 * @global stdClass $CFG
2590 * @global moodle_database $DB
2591 * @param string $file The file to put the CSV content into
2592 * @param array $records An array of records to write to a CSV file
2593 * @param string $table The table to get columns from
2594 * @return bool success
2596 function put_records_csv($file, $records, $table = NULL) {
2597 global $CFG, $DB;
2599 if (empty($records)) {
2600 return true;
2603 $metacolumns = NULL;
2604 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2605 return false;
2608 echo "x";
2610 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2611 print_error('put_records_csv failed to open '.$file);
2614 $proto = reset($records);
2615 if(is_object($proto)) {
2616 $fields_records = array_keys(get_object_vars($proto));
2618 else if(is_array($proto)) {
2619 $fields_records = array_keys($proto);
2621 else {
2622 return false;
2624 echo "x";
2626 if(!empty($metacolumns)) {
2627 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2628 $fields = array_intersect($fields_records, $fields_table);
2630 else {
2631 $fields = $fields_records;
2634 fwrite($fp, implode(',', $fields));
2635 fwrite($fp, "\r\n");
2637 foreach($records as $record) {
2638 $array = (array)$record;
2639 $values = array();
2640 foreach($fields as $field) {
2641 if(strpos($array[$field], ',')) {
2642 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2644 else {
2645 $values[] = $array[$field];
2648 fwrite($fp, implode(',', $values)."\r\n");
2651 fclose($fp);
2652 return true;
2657 * Recursively delete the file or folder with path $location. That is,
2658 * if it is a file delete it. If it is a folder, delete all its content
2659 * then delete it. If $location does not exist to start, that is not
2660 * considered an error.
2662 * @param string $location the path to remove.
2663 * @return bool
2665 function fulldelete($location) {
2666 if (empty($location)) {
2667 // extra safety against wrong param
2668 return false;
2670 if (is_dir($location)) {
2671 if (!$currdir = opendir($location)) {
2672 return false;
2674 while (false !== ($file = readdir($currdir))) {
2675 if ($file <> ".." && $file <> ".") {
2676 $fullfile = $location."/".$file;
2677 if (is_dir($fullfile)) {
2678 if (!fulldelete($fullfile)) {
2679 return false;
2681 } else {
2682 if (!unlink($fullfile)) {
2683 return false;
2688 closedir($currdir);
2689 if (! rmdir($location)) {
2690 return false;
2693 } else if (file_exists($location)) {
2694 if (!unlink($location)) {
2695 return false;
2698 return true;
2702 * Send requested byterange of file.
2704 * @param resource $handle A file handle
2705 * @param string $mimetype The mimetype for the output
2706 * @param array $ranges An array of ranges to send
2707 * @param string $filesize The size of the content if only one range is used
2709 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2710 // better turn off any kind of compression and buffering
2711 @ini_set('zlib.output_compression', 'Off');
2713 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2714 if ($handle === false) {
2715 die;
2717 if (count($ranges) == 1) { //only one range requested
2718 $length = $ranges[0][2] - $ranges[0][1] + 1;
2719 header('HTTP/1.1 206 Partial content');
2720 header('Content-Length: '.$length);
2721 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2722 header('Content-Type: '.$mimetype);
2724 while(@ob_get_level()) {
2725 if (!@ob_end_flush()) {
2726 break;
2730 fseek($handle, $ranges[0][1]);
2731 while (!feof($handle) && $length > 0) {
2732 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2733 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2734 echo $buffer;
2735 flush();
2736 $length -= strlen($buffer);
2738 fclose($handle);
2739 die;
2740 } else { // multiple ranges requested - not tested much
2741 $totallength = 0;
2742 foreach($ranges as $range) {
2743 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2745 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2746 header('HTTP/1.1 206 Partial content');
2747 header('Content-Length: '.$totallength);
2748 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2750 while(@ob_get_level()) {
2751 if (!@ob_end_flush()) {
2752 break;
2756 foreach($ranges as $range) {
2757 $length = $range[2] - $range[1] + 1;
2758 echo $range[0];
2759 fseek($handle, $range[1]);
2760 while (!feof($handle) && $length > 0) {
2761 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2762 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2763 echo $buffer;
2764 flush();
2765 $length -= strlen($buffer);
2768 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2769 fclose($handle);
2770 die;
2775 * add includes (js and css) into uploaded files
2776 * before returning them, useful for themes and utf.js includes
2778 * @global stdClass $CFG
2779 * @param string $text text to search and replace
2780 * @return string text with added head includes
2781 * @todo MDL-21120
2783 function file_modify_html_header($text) {
2784 // first look for <head> tag
2785 global $CFG;
2787 $stylesheetshtml = '';
2788 /* foreach ($CFG->stylesheets as $stylesheet) {
2789 //TODO: MDL-21120
2790 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2793 $ufo = '';
2794 if (filter_is_enabled('mediaplugin')) {
2795 // this script is needed by most media filter plugins.
2796 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2797 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2800 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2801 if ($matches) {
2802 $replacement = '<head>'.$ufo.$stylesheetshtml;
2803 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2804 return $text;
2807 // if not, look for <html> tag, and stick <head> right after
2808 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2809 if ($matches) {
2810 // replace <html> tag with <html><head>includes</head>
2811 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2812 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2813 return $text;
2816 // if not, look for <body> tag, and stick <head> before body
2817 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2818 if ($matches) {
2819 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2820 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2821 return $text;
2824 // if not, just stick a <head> tag at the beginning
2825 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2826 return $text;
2830 * RESTful cURL class
2832 * This is a wrapper class for curl, it is quite easy to use:
2833 * <code>
2834 * $c = new curl;
2835 * // enable cache
2836 * $c = new curl(array('cache'=>true));
2837 * // enable cookie
2838 * $c = new curl(array('cookie'=>true));
2839 * // enable proxy
2840 * $c = new curl(array('proxy'=>true));
2842 * // HTTP GET Method
2843 * $html = $c->get('http://example.com');
2844 * // HTTP POST Method
2845 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2846 * // HTTP PUT Method
2847 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2848 * </code>
2850 * @package core_files
2851 * @category files
2852 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2853 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2855 class curl {
2856 /** @var bool Caches http request contents */
2857 public $cache = false;
2858 /** @var bool Uses proxy */
2859 public $proxy = false;
2860 /** @var string library version */
2861 public $version = '0.4 dev';
2862 /** @var array http's response */
2863 public $response = array();
2864 /** @var array http header */
2865 public $header = array();
2866 /** @var string cURL information */
2867 public $info;
2868 /** @var string error */
2869 public $error;
2870 /** @var int error code */
2871 public $errno;
2873 /** @var array cURL options */
2874 private $options;
2875 /** @var string Proxy host */
2876 private $proxy_host = '';
2877 /** @var string Proxy auth */
2878 private $proxy_auth = '';
2879 /** @var string Proxy type */
2880 private $proxy_type = '';
2881 /** @var bool Debug mode on */
2882 private $debug = false;
2883 /** @var bool|string Path to cookie file */
2884 private $cookie = false;
2887 * Constructor
2889 * @global stdClass $CFG
2890 * @param array $options
2892 public function __construct($options = array()){
2893 global $CFG;
2894 if (!function_exists('curl_init')) {
2895 $this->error = 'cURL module must be enabled!';
2896 trigger_error($this->error, E_USER_ERROR);
2897 return false;
2899 // the options of curl should be init here.
2900 $this->resetopt();
2901 if (!empty($options['debug'])) {
2902 $this->debug = true;
2904 if(!empty($options['cookie'])) {
2905 if($options['cookie'] === true) {
2906 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2907 } else {
2908 $this->cookie = $options['cookie'];
2911 if (!empty($options['cache'])) {
2912 if (class_exists('curl_cache')) {
2913 if (!empty($options['module_cache'])) {
2914 $this->cache = new curl_cache($options['module_cache']);
2915 } else {
2916 $this->cache = new curl_cache('misc');
2920 if (!empty($CFG->proxyhost)) {
2921 if (empty($CFG->proxyport)) {
2922 $this->proxy_host = $CFG->proxyhost;
2923 } else {
2924 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2926 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2927 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2928 $this->setopt(array(
2929 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2930 'proxyuserpwd'=>$this->proxy_auth));
2932 if (!empty($CFG->proxytype)) {
2933 if ($CFG->proxytype == 'SOCKS5') {
2934 $this->proxy_type = CURLPROXY_SOCKS5;
2935 } else {
2936 $this->proxy_type = CURLPROXY_HTTP;
2937 $this->setopt(array('httpproxytunnel'=>false));
2939 $this->setopt(array('proxytype'=>$this->proxy_type));
2942 if (!empty($this->proxy_host)) {
2943 $this->proxy = array('proxy'=>$this->proxy_host);
2947 * Resets the CURL options that have already been set
2949 public function resetopt(){
2950 $this->options = array();
2951 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2952 // True to include the header in the output
2953 $this->options['CURLOPT_HEADER'] = 0;
2954 // True to Exclude the body from the output
2955 $this->options['CURLOPT_NOBODY'] = 0;
2956 // TRUE to follow any "Location: " header that the server
2957 // sends as part of the HTTP header (note this is recursive,
2958 // PHP will follow as many "Location: " headers that it is sent,
2959 // unless CURLOPT_MAXREDIRS is set).
2960 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2961 $this->options['CURLOPT_MAXREDIRS'] = 10;
2962 $this->options['CURLOPT_ENCODING'] = '';
2963 // TRUE to return the transfer as a string of the return
2964 // value of curl_exec() instead of outputting it out directly.
2965 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2966 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2967 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2968 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2969 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2971 if ($cacert = self::get_cacert()) {
2972 $this->options['CURLOPT_CAINFO'] = $cacert;
2977 * Get the location of ca certificates.
2978 * @return string absolute file path or empty if default used
2980 public static function get_cacert() {
2981 global $CFG;
2983 // Bundle in dataroot always wins.
2984 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2985 return realpath("$CFG->dataroot/moodleorgca.crt");
2988 // Next comes the default from php.ini
2989 $cacert = ini_get('curl.cainfo');
2990 if (!empty($cacert) and is_readable($cacert)) {
2991 return realpath($cacert);
2994 // Windows PHP does not have any certs, we need to use something.
2995 if ($CFG->ostype === 'WINDOWS') {
2996 if (is_readable("$CFG->libdir/cacert.pem")) {
2997 return realpath("$CFG->libdir/cacert.pem");
3001 // Use default, this should work fine on all properly configured *nix systems.
3002 return null;
3006 * Reset Cookie
3008 public function resetcookie() {
3009 if (!empty($this->cookie)) {
3010 if (is_file($this->cookie)) {
3011 $fp = fopen($this->cookie, 'w');
3012 if (!empty($fp)) {
3013 fwrite($fp, '');
3014 fclose($fp);
3021 * Set curl options.
3023 * Do not use the curl constants to define the options, pass a string
3024 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3025 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3027 * @param array $options If array is null, this function will reset the options to default value.
3028 * @return void
3029 * @throws coding_exception If an option uses constant value instead of option name.
3031 public function setopt($options = array()) {
3032 if (is_array($options)) {
3033 foreach ($options as $name => $val){
3034 if (!is_string($name)) {
3035 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3037 if (stripos($name, 'CURLOPT_') === false) {
3038 $name = strtoupper('CURLOPT_'.$name);
3040 $this->options[$name] = $val;
3046 * Reset http method
3048 public function cleanopt(){
3049 unset($this->options['CURLOPT_HTTPGET']);
3050 unset($this->options['CURLOPT_POST']);
3051 unset($this->options['CURLOPT_POSTFIELDS']);
3052 unset($this->options['CURLOPT_PUT']);
3053 unset($this->options['CURLOPT_INFILE']);
3054 unset($this->options['CURLOPT_INFILESIZE']);
3055 unset($this->options['CURLOPT_CUSTOMREQUEST']);
3056 unset($this->options['CURLOPT_FILE']);
3060 * Resets the HTTP Request headers (to prepare for the new request)
3062 public function resetHeader() {
3063 $this->header = array();
3067 * Set HTTP Request Header
3069 * @param array $header
3071 public function setHeader($header) {
3072 if (is_array($header)){
3073 foreach ($header as $v) {
3074 $this->setHeader($v);
3076 } else {
3077 $this->header[] = $header;
3082 * Set HTTP Response Header
3085 public function getResponse(){
3086 return $this->response;
3090 * private callback function
3091 * Formatting HTTP Response Header
3093 * @param resource $ch Apparently not used
3094 * @param string $header
3095 * @return int The strlen of the header
3097 private function formatHeader($ch, $header)
3099 if (strlen($header) > 2) {
3100 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3101 $key = rtrim($key, ':');
3102 if (!empty($this->response[$key])) {
3103 if (is_array($this->response[$key])){
3104 $this->response[$key][] = $value;
3105 } else {
3106 $tmp = $this->response[$key];
3107 $this->response[$key] = array();
3108 $this->response[$key][] = $tmp;
3109 $this->response[$key][] = $value;
3112 } else {
3113 $this->response[$key] = $value;
3116 return strlen($header);
3120 * Set options for individual curl instance
3122 * @param resource $curl A curl handle
3123 * @param array $options
3124 * @return resource The curl handle
3126 private function apply_opt($curl, $options) {
3127 // Clean up
3128 $this->cleanopt();
3129 // set cookie
3130 if (!empty($this->cookie) || !empty($options['cookie'])) {
3131 $this->setopt(array('cookiejar'=>$this->cookie,
3132 'cookiefile'=>$this->cookie
3136 // set proxy
3137 if (!empty($this->proxy) || !empty($options['proxy'])) {
3138 $this->setopt($this->proxy);
3140 $this->setopt($options);
3141 // reset before set options
3142 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3143 // set headers
3144 if (empty($this->header)){
3145 $this->setHeader(array(
3146 'User-Agent: MoodleBot/1.0',
3147 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3148 'Connection: keep-alive'
3151 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3153 // Bypass proxy (for this request only) if required.
3154 if (!empty($this->options['CURLOPT_URL']) &&
3155 is_proxybypass($this->options['CURLOPT_URL'])) {
3156 unset($this->options['CURLOPT_PROXY']);
3159 if ($this->debug){
3160 echo '<h1>Options</h1>';
3161 var_dump($this->options);
3162 echo '<h1>Header</h1>';
3163 var_dump($this->header);
3166 // Set options.
3167 foreach($this->options as $name => $val) {
3168 $name = constant(strtoupper($name));
3169 curl_setopt($curl, $name, $val);
3171 return $curl;
3175 * Download multiple files in parallel
3177 * Calls {@link multi()} with specific download headers
3179 * <code>
3180 * $c = new curl();
3181 * $file1 = fopen('a', 'wb');
3182 * $file2 = fopen('b', 'wb');
3183 * $c->download(array(
3184 * array('url'=>'http://localhost/', 'file'=>$file1),
3185 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3186 * ));
3187 * fclose($file1);
3188 * fclose($file2);
3189 * </code>
3191 * or
3193 * <code>
3194 * $c = new curl();
3195 * $c->download(array(
3196 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3197 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3198 * ));
3199 * </code>
3201 * @param array $requests An array of files to request {
3202 * url => url to download the file [required]
3203 * file => file handler, or
3204 * filepath => file path
3206 * If 'file' and 'filepath' parameters are both specified in one request, the
3207 * open file handle in the 'file' parameter will take precedence and 'filepath'
3208 * will be ignored.
3210 * @param array $options An array of options to set
3211 * @return array An array of results
3213 public function download($requests, $options = array()) {
3214 $options['CURLOPT_BINARYTRANSFER'] = 1;
3215 $options['RETURNTRANSFER'] = false;
3216 return $this->multi($requests, $options);
3220 * Mulit HTTP Requests
3221 * This function could run multi-requests in parallel.
3223 * @param array $requests An array of files to request
3224 * @param array $options An array of options to set
3225 * @return array An array of results
3227 protected function multi($requests, $options = array()) {
3228 $count = count($requests);
3229 $handles = array();
3230 $results = array();
3231 $main = curl_multi_init();
3232 for ($i = 0; $i < $count; $i++) {
3233 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3234 // open file
3235 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3236 $requests[$i]['auto-handle'] = true;
3238 foreach($requests[$i] as $n=>$v){
3239 $options[$n] = $v;
3241 $handles[$i] = curl_init($requests[$i]['url']);
3242 $this->apply_opt($handles[$i], $options);
3243 curl_multi_add_handle($main, $handles[$i]);
3245 $running = 0;
3246 do {
3247 curl_multi_exec($main, $running);
3248 } while($running > 0);
3249 for ($i = 0; $i < $count; $i++) {
3250 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3251 $results[] = true;
3252 } else {
3253 $results[] = curl_multi_getcontent($handles[$i]);
3255 curl_multi_remove_handle($main, $handles[$i]);
3257 curl_multi_close($main);
3259 for ($i = 0; $i < $count; $i++) {
3260 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3261 // close file handler if file is opened in this function
3262 fclose($requests[$i]['file']);
3265 return $results;
3269 * Single HTTP Request
3271 * @param string $url The URL to request
3272 * @param array $options
3273 * @return bool
3275 protected function request($url, $options = array()){
3276 // create curl instance
3277 $curl = curl_init($url);
3278 $options['url'] = $url;
3279 $this->apply_opt($curl, $options);
3280 if ($this->cache && $ret = $this->cache->get($this->options)) {
3281 return $ret;
3282 } else {
3283 $ret = curl_exec($curl);
3284 if ($this->cache) {
3285 $this->cache->set($this->options, $ret);
3289 $this->info = curl_getinfo($curl);
3290 $this->error = curl_error($curl);
3291 $this->errno = curl_errno($curl);
3293 if ($this->debug){
3294 echo '<h1>Return Data</h1>';
3295 var_dump($ret);
3296 echo '<h1>Info</h1>';
3297 var_dump($this->info);
3298 echo '<h1>Error</h1>';
3299 var_dump($this->error);
3302 curl_close($curl);
3304 if (empty($this->error)){
3305 return $ret;
3306 } else {
3307 return $this->error;
3308 // exception is not ajax friendly
3309 //throw new moodle_exception($this->error, 'curl');
3314 * HTTP HEAD method
3316 * @see request()
3318 * @param string $url
3319 * @param array $options
3320 * @return bool
3322 public function head($url, $options = array()){
3323 $options['CURLOPT_HTTPGET'] = 0;
3324 $options['CURLOPT_HEADER'] = 1;
3325 $options['CURLOPT_NOBODY'] = 1;
3326 return $this->request($url, $options);
3330 * HTTP POST method
3332 * @param string $url
3333 * @param array|string $params
3334 * @param array $options
3335 * @return bool
3337 public function post($url, $params = '', $options = array()){
3338 $options['CURLOPT_POST'] = 1;
3339 if (is_array($params)) {
3340 $this->_tmp_file_post_params = array();
3341 foreach ($params as $key => $value) {
3342 if ($value instanceof stored_file) {
3343 $value->add_to_curl_request($this, $key);
3344 } else {
3345 $this->_tmp_file_post_params[$key] = $value;
3348 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3349 unset($this->_tmp_file_post_params);
3350 } else {
3351 // $params is the raw post data
3352 $options['CURLOPT_POSTFIELDS'] = $params;
3354 return $this->request($url, $options);
3358 * HTTP GET method
3360 * @param string $url
3361 * @param array $params
3362 * @param array $options
3363 * @return bool
3365 public function get($url, $params = array(), $options = array()){
3366 $options['CURLOPT_HTTPGET'] = 1;
3368 if (!empty($params)){
3369 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3370 $url .= http_build_query($params, '', '&');
3372 return $this->request($url, $options);
3376 * Downloads one file and writes it to the specified file handler
3378 * <code>
3379 * $c = new curl();
3380 * $file = fopen('savepath', 'w');
3381 * $result = $c->download_one('http://localhost/', null,
3382 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3383 * fclose($file);
3384 * $download_info = $c->get_info();
3385 * if ($result === true) {
3386 * // file downloaded successfully
3387 * } else {
3388 * $error_text = $result;
3389 * $error_code = $c->get_errno();
3391 * </code>
3393 * <code>
3394 * $c = new curl();
3395 * $result = $c->download_one('http://localhost/', null,
3396 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3397 * // ... see above, no need to close handle and remove file if unsuccessful
3398 * </code>
3400 * @param string $url
3401 * @param array|null $params key-value pairs to be added to $url as query string
3402 * @param array $options request options. Must include either 'file' or 'filepath'
3403 * @return bool|string true on success or error string on failure
3405 public function download_one($url, $params, $options = array()) {
3406 $options['CURLOPT_HTTPGET'] = 1;
3407 $options['CURLOPT_BINARYTRANSFER'] = true;
3408 if (!empty($params)){
3409 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3410 $url .= http_build_query($params, '', '&');
3412 if (!empty($options['filepath']) && empty($options['file'])) {
3413 // open file
3414 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3415 $this->errno = 100;
3416 return get_string('cannotwritefile', 'error', $options['filepath']);
3418 $filepath = $options['filepath'];
3420 unset($options['filepath']);
3421 $result = $this->request($url, $options);
3422 if (isset($filepath)) {
3423 fclose($options['file']);
3424 if ($result !== true) {
3425 unlink($filepath);
3428 return $result;
3432 * HTTP PUT method
3434 * @param string $url
3435 * @param array $params
3436 * @param array $options
3437 * @return bool
3439 public function put($url, $params = array(), $options = array()){
3440 $file = $params['file'];
3441 if (!is_file($file)){
3442 return null;
3444 $fp = fopen($file, 'r');
3445 $size = filesize($file);
3446 $options['CURLOPT_PUT'] = 1;
3447 $options['CURLOPT_INFILESIZE'] = $size;
3448 $options['CURLOPT_INFILE'] = $fp;
3449 if (!isset($this->options['CURLOPT_USERPWD'])){
3450 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3452 $ret = $this->request($url, $options);
3453 fclose($fp);
3454 return $ret;
3458 * HTTP DELETE method
3460 * @param string $url
3461 * @param array $param
3462 * @param array $options
3463 * @return bool
3465 public function delete($url, $param = array(), $options = array()){
3466 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3467 if (!isset($options['CURLOPT_USERPWD'])) {
3468 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3470 $ret = $this->request($url, $options);
3471 return $ret;
3475 * HTTP TRACE method
3477 * @param string $url
3478 * @param array $options
3479 * @return bool
3481 public function trace($url, $options = array()){
3482 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3483 $ret = $this->request($url, $options);
3484 return $ret;
3488 * HTTP OPTIONS method
3490 * @param string $url
3491 * @param array $options
3492 * @return bool
3494 public function options($url, $options = array()){
3495 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3496 $ret = $this->request($url, $options);
3497 return $ret;
3501 * Get curl information
3503 * @return string
3505 public function get_info() {
3506 return $this->info;
3510 * Get curl error code
3512 * @return int
3514 public function get_errno() {
3515 return $this->errno;
3519 * When using a proxy, an additional HTTP response code may appear at
3520 * the start of the header. For example, when using https over a proxy
3521 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3522 * also possible and some may come with their own headers.
3524 * If using the return value containing all headers, this function can be
3525 * called to remove unwanted doubles.
3527 * Note that it is not possible to distinguish this situation from valid
3528 * data unless you know the actual response part (below the headers)
3529 * will not be included in this string, or else will not 'look like' HTTP
3530 * headers. As a result it is not safe to call this function for general
3531 * data.
3533 * @param string $input Input HTTP response
3534 * @return string HTTP response with additional headers stripped if any
3536 public static function strip_double_headers($input) {
3537 // I have tried to make this regular expression as specific as possible
3538 // to avoid any case where it does weird stuff if you happen to put
3539 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3540 // also make it faster because it can abandon regex processing as soon
3541 // as it hits something that doesn't look like an http header. The
3542 // header definition is taken from RFC 822, except I didn't support
3543 // folding which is never used in practice.
3544 $crlf = "\r\n";
3545 return preg_replace(
3546 // HTTP version and status code (ignore value of code).
3547 '~^HTTP/1\..*' . $crlf .
3548 // Header name: character between 33 and 126 decimal, except colon.
3549 // Colon. Header value: any character except \r and \n. CRLF.
3550 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3551 // Headers are terminated by another CRLF (blank line).
3552 $crlf .
3553 // Second HTTP status code, this time must be 200.
3554 '(HTTP/1.[01] 200 )~', '$1', $input);
3559 * This class is used by cURL class, use case:
3561 * <code>
3562 * $CFG->repositorycacheexpire = 120;
3563 * $CFG->curlcache = 120;
3565 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3566 * $ret = $c->get('http://www.google.com');
3567 * </code>
3569 * @package core_files
3570 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3573 class curl_cache {
3574 /** @var string Path to cache directory */
3575 public $dir = '';
3578 * Constructor
3580 * @global stdClass $CFG
3581 * @param string $module which module is using curl_cache
3583 public function __construct($module = 'repository') {
3584 global $CFG;
3585 if (!empty($module)) {
3586 $this->dir = $CFG->cachedir.'/'.$module.'/';
3587 } else {
3588 $this->dir = $CFG->cachedir.'/misc/';
3590 if (!file_exists($this->dir)) {
3591 mkdir($this->dir, $CFG->directorypermissions, true);
3593 if ($module == 'repository') {
3594 if (empty($CFG->repositorycacheexpire)) {
3595 $CFG->repositorycacheexpire = 120;
3597 $this->ttl = $CFG->repositorycacheexpire;
3598 } else {
3599 if (empty($CFG->curlcache)) {
3600 $CFG->curlcache = 120;
3602 $this->ttl = $CFG->curlcache;
3607 * Get cached value
3609 * @global stdClass $CFG
3610 * @global stdClass $USER
3611 * @param mixed $param
3612 * @return bool|string
3614 public function get($param) {
3615 global $CFG, $USER;
3616 $this->cleanup($this->ttl);
3617 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3618 if(file_exists($this->dir.$filename)) {
3619 $lasttime = filemtime($this->dir.$filename);
3620 if (time()-$lasttime > $this->ttl) {
3621 return false;
3622 } else {
3623 $fp = fopen($this->dir.$filename, 'r');
3624 $size = filesize($this->dir.$filename);
3625 $content = fread($fp, $size);
3626 return unserialize($content);
3629 return false;
3633 * Set cache value
3635 * @global object $CFG
3636 * @global object $USER
3637 * @param mixed $param
3638 * @param mixed $val
3640 public function set($param, $val) {
3641 global $CFG, $USER;
3642 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3643 $fp = fopen($this->dir.$filename, 'w');
3644 fwrite($fp, serialize($val));
3645 fclose($fp);
3649 * Remove cache files
3651 * @param int $expire The number of seconds before expiry
3653 public function cleanup($expire) {
3654 if ($dir = opendir($this->dir)) {
3655 while (false !== ($file = readdir($dir))) {
3656 if(!is_dir($file) && $file != '.' && $file != '..') {
3657 $lasttime = @filemtime($this->dir.$file);
3658 if (time() - $lasttime > $expire) {
3659 @unlink($this->dir.$file);
3663 closedir($dir);
3667 * delete current user's cache file
3669 * @global object $CFG
3670 * @global object $USER
3672 public function refresh() {
3673 global $CFG, $USER;
3674 if ($dir = opendir($this->dir)) {
3675 while (false !== ($file = readdir($dir))) {
3676 if (!is_dir($file) && $file != '.' && $file != '..') {
3677 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3678 @unlink($this->dir.$file);
3687 * This function delegates file serving to individual plugins
3689 * @param string $relativepath
3690 * @param bool $forcedownload
3691 * @param null|string $preview the preview mode, defaults to serving the original file
3692 * @todo MDL-31088 file serving improments
3694 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3695 global $DB, $CFG, $USER;
3696 // relative path must start with '/'
3697 if (!$relativepath) {
3698 print_error('invalidargorconf');
3699 } else if ($relativepath[0] != '/') {
3700 print_error('pathdoesnotstartslash');
3703 // extract relative path components
3704 $args = explode('/', ltrim($relativepath, '/'));
3706 if (count($args) < 3) { // always at least context, component and filearea
3707 print_error('invalidarguments');
3710 $contextid = (int)array_shift($args);
3711 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3712 $filearea = clean_param(array_shift($args), PARAM_AREA);
3714 list($context, $course, $cm) = get_context_info_array($contextid);
3716 $fs = get_file_storage();
3718 // ========================================================================================================================
3719 if ($component === 'blog') {
3720 // Blog file serving
3721 if ($context->contextlevel != CONTEXT_SYSTEM) {
3722 send_file_not_found();
3724 if ($filearea !== 'attachment' and $filearea !== 'post') {
3725 send_file_not_found();
3728 if (empty($CFG->enableblogs)) {
3729 print_error('siteblogdisable', 'blog');
3732 $entryid = (int)array_shift($args);
3733 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3734 send_file_not_found();
3736 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3737 require_login();
3738 if (isguestuser()) {
3739 print_error('noguest');
3741 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3742 if ($USER->id != $entry->userid) {
3743 send_file_not_found();
3748 if ($entry->publishstate === 'public') {
3749 if ($CFG->forcelogin) {
3750 require_login();
3753 } else if ($entry->publishstate === 'site') {
3754 require_login();
3755 //ok
3756 } else if ($entry->publishstate === 'draft') {
3757 require_login();
3758 if ($USER->id != $entry->userid) {
3759 send_file_not_found();
3763 $filename = array_pop($args);
3764 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3766 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3767 send_file_not_found();
3770 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3772 // ========================================================================================================================
3773 } else if ($component === 'grade') {
3774 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3775 // Global gradebook files
3776 if ($CFG->forcelogin) {
3777 require_login();
3780 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3782 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3783 send_file_not_found();
3786 session_get_instance()->write_close(); // unlock session during fileserving
3787 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3789 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3790 //TODO: nobody implemented this yet in grade edit form!!
3791 send_file_not_found();
3793 if ($CFG->forcelogin || $course->id != SITEID) {
3794 require_login($course);
3797 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3799 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3800 send_file_not_found();
3803 session_get_instance()->write_close(); // unlock session during fileserving
3804 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3805 } else {
3806 send_file_not_found();
3809 // ========================================================================================================================
3810 } else if ($component === 'tag') {
3811 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3813 // All tag descriptions are going to be public but we still need to respect forcelogin
3814 if ($CFG->forcelogin) {
3815 require_login();
3818 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3820 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3821 send_file_not_found();
3824 session_get_instance()->write_close(); // unlock session during fileserving
3825 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3827 } else {
3828 send_file_not_found();
3830 // ========================================================================================================================
3831 } else if ($component === 'badges') {
3832 require_once($CFG->libdir . '/badgeslib.php');
3834 $badgeid = (int)array_shift($args);
3835 $badge = new badge($badgeid);
3836 $filename = array_pop($args);
3838 if ($filearea === 'badgeimage') {
3839 if ($filename !== 'f1' && $filename !== 'f2') {
3840 send_file_not_found();
3842 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
3843 send_file_not_found();
3846 session_get_instance()->write_close();
3847 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3848 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
3849 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
3850 send_file_not_found();
3853 session_get_instance()->write_close();
3854 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3856 // ========================================================================================================================
3857 } else if ($component === 'calendar') {
3858 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3860 // All events here are public the one requirement is that we respect forcelogin
3861 if ($CFG->forcelogin) {
3862 require_login();
3865 // Get the event if from the args array
3866 $eventid = array_shift($args);
3868 // Load the event from the database
3869 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3870 send_file_not_found();
3873 // Get the file and serve if successful
3874 $filename = array_pop($args);
3875 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3876 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3877 send_file_not_found();
3880 session_get_instance()->write_close(); // unlock session during fileserving
3881 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3883 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3885 // Must be logged in, if they are not then they obviously can't be this user
3886 require_login();
3888 // Don't want guests here, potentially saves a DB call
3889 if (isguestuser()) {
3890 send_file_not_found();
3893 // Get the event if from the args array
3894 $eventid = array_shift($args);
3896 // Load the event from the database - user id must match
3897 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3898 send_file_not_found();
3901 // Get the file and serve if successful
3902 $filename = array_pop($args);
3903 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3904 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3905 send_file_not_found();
3908 session_get_instance()->write_close(); // unlock session during fileserving
3909 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3911 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3913 // Respect forcelogin and require login unless this is the site.... it probably
3914 // should NEVER be the site
3915 if ($CFG->forcelogin || $course->id != SITEID) {
3916 require_login($course);
3919 // Must be able to at least view the course. This does not apply to the front page.
3920 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
3921 //TODO: hmm, do we really want to block guests here?
3922 send_file_not_found();
3925 // Get the event id
3926 $eventid = array_shift($args);
3928 // Load the event from the database we need to check whether it is
3929 // a) valid course event
3930 // b) a group event
3931 // Group events use the course context (there is no group context)
3932 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3933 send_file_not_found();
3936 // If its a group event require either membership of view all groups capability
3937 if ($event->eventtype === 'group') {
3938 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3939 send_file_not_found();
3941 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
3942 // Ok. Please note that the event type 'site' still uses a course context.
3943 } else {
3944 // Some other type.
3945 send_file_not_found();
3948 // If we get this far we can serve the file
3949 $filename = array_pop($args);
3950 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3951 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3952 send_file_not_found();
3955 session_get_instance()->write_close(); // unlock session during fileserving
3956 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3958 } else {
3959 send_file_not_found();
3962 // ========================================================================================================================
3963 } else if ($component === 'user') {
3964 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3965 if (count($args) == 1) {
3966 $themename = theme_config::DEFAULT_THEME;
3967 $filename = array_shift($args);
3968 } else {
3969 $themename = array_shift($args);
3970 $filename = array_shift($args);
3973 // fix file name automatically
3974 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3975 $filename = 'f1';
3978 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3979 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3980 // protect images if login required and not logged in;
3981 // also if login is required for profile images and is not logged in or guest
3982 // do not use require_login() because it is expensive and not suitable here anyway
3983 $theme = theme_config::load($themename);
3984 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3987 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3988 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3989 if ($filename === 'f3') {
3990 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3991 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3992 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
3997 if (!$file) {
3998 // bad reference - try to prevent future retries as hard as possible!
3999 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4000 if ($user->picture > 0) {
4001 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4004 // no redirect here because it is not cached
4005 $theme = theme_config::load($themename);
4006 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4007 send_file($imagefile, basename($imagefile), 60*60*24*14);
4010 send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
4012 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4013 require_login();
4015 if (isguestuser()) {
4016 send_file_not_found();
4019 if ($USER->id !== $context->instanceid) {
4020 send_file_not_found();
4023 $filename = array_pop($args);
4024 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4025 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4026 send_file_not_found();
4029 session_get_instance()->write_close(); // unlock session during fileserving
4030 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4032 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4034 if ($CFG->forcelogin) {
4035 require_login();
4038 $userid = $context->instanceid;
4040 if ($USER->id == $userid) {
4041 // always can access own
4043 } else if (!empty($CFG->forceloginforprofiles)) {
4044 require_login();
4046 if (isguestuser()) {
4047 send_file_not_found();
4050 // we allow access to site profile of all course contacts (usually teachers)
4051 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4052 send_file_not_found();
4055 $canview = false;
4056 if (has_capability('moodle/user:viewdetails', $context)) {
4057 $canview = true;
4058 } else {
4059 $courses = enrol_get_my_courses();
4062 while (!$canview && count($courses) > 0) {
4063 $course = array_shift($courses);
4064 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4065 $canview = true;
4070 $filename = array_pop($args);
4071 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4072 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4073 send_file_not_found();
4076 session_get_instance()->write_close(); // unlock session during fileserving
4077 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4079 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4080 $userid = (int)array_shift($args);
4081 $usercontext = context_user::instance($userid);
4083 if ($CFG->forcelogin) {
4084 require_login();
4087 if (!empty($CFG->forceloginforprofiles)) {
4088 require_login();
4089 if (isguestuser()) {
4090 print_error('noguest');
4093 //TODO: review this logic of user profile access prevention
4094 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4095 print_error('usernotavailable');
4097 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4098 print_error('cannotviewprofile');
4100 if (!is_enrolled($context, $userid)) {
4101 print_error('notenrolledprofile');
4103 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4104 print_error('groupnotamember');
4108 $filename = array_pop($args);
4109 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4110 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4111 send_file_not_found();
4114 session_get_instance()->write_close(); // unlock session during fileserving
4115 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4117 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4118 require_login();
4120 if (isguestuser()) {
4121 send_file_not_found();
4123 $userid = $context->instanceid;
4125 if ($USER->id != $userid) {
4126 send_file_not_found();
4129 $filename = array_pop($args);
4130 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4131 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4132 send_file_not_found();
4135 session_get_instance()->write_close(); // unlock session during fileserving
4136 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4138 } else {
4139 send_file_not_found();
4142 // ========================================================================================================================
4143 } else if ($component === 'coursecat') {
4144 if ($context->contextlevel != CONTEXT_COURSECAT) {
4145 send_file_not_found();
4148 if ($filearea === 'description') {
4149 if ($CFG->forcelogin) {
4150 // no login necessary - unless login forced everywhere
4151 require_login();
4154 $filename = array_pop($args);
4155 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4156 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4157 send_file_not_found();
4160 session_get_instance()->write_close(); // unlock session during fileserving
4161 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4162 } else {
4163 send_file_not_found();
4166 // ========================================================================================================================
4167 } else if ($component === 'course') {
4168 if ($context->contextlevel != CONTEXT_COURSE) {
4169 send_file_not_found();
4172 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4173 if ($CFG->forcelogin) {
4174 require_login();
4177 $filename = array_pop($args);
4178 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4179 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4180 send_file_not_found();
4183 session_get_instance()->write_close(); // unlock session during fileserving
4184 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4186 } else if ($filearea === 'section') {
4187 if ($CFG->forcelogin) {
4188 require_login($course);
4189 } else if ($course->id != SITEID) {
4190 require_login($course);
4193 $sectionid = (int)array_shift($args);
4195 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4196 send_file_not_found();
4199 $filename = array_pop($args);
4200 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4201 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4202 send_file_not_found();
4205 session_get_instance()->write_close(); // unlock session during fileserving
4206 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4208 } else {
4209 send_file_not_found();
4212 } else if ($component === 'group') {
4213 if ($context->contextlevel != CONTEXT_COURSE) {
4214 send_file_not_found();
4217 require_course_login($course, true, null, false);
4219 $groupid = (int)array_shift($args);
4221 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4222 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4223 // do not allow access to separate group info if not member or teacher
4224 send_file_not_found();
4227 if ($filearea === 'description') {
4229 require_login($course);
4231 $filename = array_pop($args);
4232 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4233 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4234 send_file_not_found();
4237 session_get_instance()->write_close(); // unlock session during fileserving
4238 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4240 } else if ($filearea === 'icon') {
4241 $filename = array_pop($args);
4243 if ($filename !== 'f1' and $filename !== 'f2') {
4244 send_file_not_found();
4246 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4247 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4248 send_file_not_found();
4252 session_get_instance()->write_close(); // unlock session during fileserving
4253 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4255 } else {
4256 send_file_not_found();
4259 } else if ($component === 'grouping') {
4260 if ($context->contextlevel != CONTEXT_COURSE) {
4261 send_file_not_found();
4264 require_login($course);
4266 $groupingid = (int)array_shift($args);
4268 // note: everybody has access to grouping desc images for now
4269 if ($filearea === 'description') {
4271 $filename = array_pop($args);
4272 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4273 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4274 send_file_not_found();
4277 session_get_instance()->write_close(); // unlock session during fileserving
4278 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4280 } else {
4281 send_file_not_found();
4284 // ========================================================================================================================
4285 } else if ($component === 'backup') {
4286 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4287 require_login($course);
4288 require_capability('moodle/backup:downloadfile', $context);
4290 $filename = array_pop($args);
4291 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4292 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4293 send_file_not_found();
4296 session_get_instance()->write_close(); // unlock session during fileserving
4297 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4299 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4300 require_login($course);
4301 require_capability('moodle/backup:downloadfile', $context);
4303 $sectionid = (int)array_shift($args);
4305 $filename = array_pop($args);
4306 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4307 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4308 send_file_not_found();
4311 session_get_instance()->write_close();
4312 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4314 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4315 require_login($course, false, $cm);
4316 require_capability('moodle/backup:downloadfile', $context);
4318 $filename = array_pop($args);
4319 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4320 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4321 send_file_not_found();
4324 session_get_instance()->write_close();
4325 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4327 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4328 // Backup files that were generated by the automated backup systems.
4330 require_login($course);
4331 require_capability('moodle/site:config', $context);
4333 $filename = array_pop($args);
4334 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4335 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4336 send_file_not_found();
4339 session_get_instance()->write_close(); // unlock session during fileserving
4340 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4342 } else {
4343 send_file_not_found();
4346 // ========================================================================================================================
4347 } else if ($component === 'question') {
4348 require_once($CFG->libdir . '/questionlib.php');
4349 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4350 send_file_not_found();
4352 // ========================================================================================================================
4353 } else if ($component === 'grading') {
4354 if ($filearea === 'description') {
4355 // files embedded into the form definition description
4357 if ($context->contextlevel == CONTEXT_SYSTEM) {
4358 require_login();
4360 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4361 require_login($course, false, $cm);
4363 } else {
4364 send_file_not_found();
4367 $formid = (int)array_shift($args);
4369 $sql = "SELECT ga.id
4370 FROM {grading_areas} ga
4371 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4372 WHERE gd.id = ? AND ga.contextid = ?";
4373 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4375 if (!$areaid) {
4376 send_file_not_found();
4379 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4381 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4382 send_file_not_found();
4385 session_get_instance()->write_close(); // unlock session during fileserving
4386 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4389 // ========================================================================================================================
4390 } else if (strpos($component, 'mod_') === 0) {
4391 $modname = substr($component, 4);
4392 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4393 send_file_not_found();
4395 require_once("$CFG->dirroot/mod/$modname/lib.php");
4397 if ($context->contextlevel == CONTEXT_MODULE) {
4398 if ($cm->modname !== $modname) {
4399 // somebody tries to gain illegal access, cm type must match the component!
4400 send_file_not_found();
4404 if ($filearea === 'intro') {
4405 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4406 send_file_not_found();
4408 require_course_login($course, true, $cm);
4410 // all users may access it
4411 $filename = array_pop($args);
4412 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4413 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4414 send_file_not_found();
4417 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
4419 // finally send the file
4420 send_stored_file($file, $lifetime, 0, false, array('preview' => $preview));
4423 $filefunction = $component.'_pluginfile';
4424 $filefunctionold = $modname.'_pluginfile';
4425 if (function_exists($filefunction)) {
4426 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4427 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4428 } else if (function_exists($filefunctionold)) {
4429 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4430 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4433 send_file_not_found();
4435 // ========================================================================================================================
4436 } else if (strpos($component, 'block_') === 0) {
4437 $blockname = substr($component, 6);
4438 // note: no more class methods in blocks please, that is ....
4439 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4440 send_file_not_found();
4442 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4444 if ($context->contextlevel == CONTEXT_BLOCK) {
4445 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4446 if ($birecord->blockname !== $blockname) {
4447 // somebody tries to gain illegal access, cm type must match the component!
4448 send_file_not_found();
4451 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4452 // User can't access file, if block is hidden or doesn't have block:view capability
4453 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4454 send_file_not_found();
4456 } else {
4457 $birecord = null;
4460 $filefunction = $component.'_pluginfile';
4461 if (function_exists($filefunction)) {
4462 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4463 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4466 send_file_not_found();
4468 // ========================================================================================================================
4469 } else if (strpos($component, '_') === false) {
4470 // all core subsystems have to be specified above, no more guessing here!
4471 send_file_not_found();
4473 } else {
4474 // try to serve general plugin file in arbitrary context
4475 $dir = get_component_directory($component);
4476 if (!file_exists("$dir/lib.php")) {
4477 send_file_not_found();
4479 include_once("$dir/lib.php");
4481 $filefunction = $component.'_pluginfile';
4482 if (function_exists($filefunction)) {
4483 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4484 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4487 send_file_not_found();