Merge branch 'MDL-48202-M30' of git://github.com/lazydaisy/moodle
[moodle.git] / lib / filelib.php
blob6375faf4ee89bd5419cc495821f81cbf5a9c2c60
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 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
92 * @return bool
94 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
95 global $DB;
97 if (!isset($itemid)) {
98 // Not initialised yet.
99 return false;
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
114 * displayed.
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
118 * @category files
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id != $context->id) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
161 $contextid = null;
162 $itemid = null;
163 if (!isset($data)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
176 } else {
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
183 } else {
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
195 } else {
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
199 return $data;
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
213 * @category files
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
241 if ($options['trusttext']) {
242 $data->{$field.'trust'} = trusttext_trusted($context);
243 } else {
244 $data->{$field.'trust'} = 0;
247 $editor = $data->{$field.'_editor'};
249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
250 $data->{$field} = $editor['text'];
251 } else {
252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
254 $data->{$field.'format'} = $editor['format'];
256 return $data;
260 * Saves text and files modified by Editor formslib element
262 * @category files
263 * @param stdClass $data $database entry field
264 * @param string $field name of data field
265 * @param array $options various options
266 * @param stdClass $context context - must already exist
267 * @param string $component
268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
270 * @return stdClass modified data obejct
272 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
277 if (is_null($itemid) or is_null($context)) {
278 $itemid = null;
279 $contextid = null;
280 } else {
281 $contextid = $context->id;
284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
286 $data->{$field.'_filemanager'} = $draftid_editor;
288 return $data;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
295 * @category files
296 * @param stdClass $data $database entry field
297 * @param string $field name of data field
298 * @param array $options various options
299 * @param stdClass $context context - must already exist
300 * @param string $component
301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
303 * @return stdClass modified data obejct
305 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
317 if (empty($data->{$field.'_filemanager'})) {
318 $data->$field = '';
320 } else {
321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
322 $fs = get_file_storage();
324 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
326 } else {
327 $data->$field = '';
331 return $data;
335 * Generate a draft itemid
337 * @category files
338 * @global moodle_database $DB
339 * @global stdClass $USER
340 * @return int a random but available draft itemid that can be used to create a new draft
341 * file area.
343 function file_get_unused_draft_itemid() {
344 global $DB, $USER;
346 if (isguestuser() or !isloggedin()) {
347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
348 print_error('noguest');
351 $contextid = context_user::instance($USER->id)->id;
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
356 $draftitemid = rand(1, 999999999);
359 return $draftitemid;
363 * Initialise a draft file area from a real one by copying the files. A draft
364 * area will be created if one does not already exist. Normally you should
365 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
367 * @category files
368 * @global stdClass $CFG
369 * @global stdClass $USER
370 * @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.
371 * @param int $contextid This parameter and the next two identify the file area to copy files from.
372 * @param string $component
373 * @param string $filearea helps indentify the file area.
374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
379 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
380 global $CFG, $USER, $CFG;
382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
386 if (!isset($options['forcehttps'])) {
387 $options['forcehttps'] = false;
390 $usercontext = context_user::instance($USER->id);
391 $fs = get_file_storage();
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
395 $draftitemid = file_get_unused_draft_itemid();
396 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
397 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
398 foreach ($files as $file) {
399 if ($file->is_directory() and $file->get_filepath() === '/') {
400 // we need a way to mark the age of each draft area,
401 // by not copying the root dir we force it to be created automatically with current timestamp
402 continue;
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
405 continue;
407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
408 // XXX: This is a hack for file manager (MDL-28666)
409 // File manager needs to know the original file information before copying
410 // to draft area, so we append these information in mdl_files.source field
411 // {@link file_storage::search_references()}
412 // {@link file_storage::search_references_count()}
413 $sourcefield = $file->get_source();
414 $newsourcefield = new stdClass;
415 $newsourcefield->source = $sourcefield;
416 $original = new stdClass;
417 $original->contextid = $contextid;
418 $original->component = $component;
419 $original->filearea = $filearea;
420 $original->itemid = $itemid;
421 $original->filename = $file->get_filename();
422 $original->filepath = $file->get_filepath();
423 $newsourcefield->original = file_storage::pack_reference($original);
424 $draftfile->set_source(serialize($newsourcefield));
425 // End of file manager hack
428 if (!is_null($text)) {
429 // at this point there should not be any draftfile links yet,
430 // because this is a new text from database that should still contain the @@pluginfile@@ links
431 // this happens when developers forget to post process the text
432 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
434 } else {
435 // nothing to do
438 if (is_null($text)) {
439 return null;
442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
449 * @category files
450 * @global stdClass $CFG
451 * @param string $text The content that may contain ULRs in need of rewriting.
452 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
453 * @param int $contextid This parameter and the next two identify the file area to use.
454 * @param string $component
455 * @param string $filearea helps identify the file area.
456 * @param int $itemid helps identify the file area.
457 * @param array $options text and file options ('forcehttps'=>false)
458 * @return string the processed text.
460 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
461 global $CFG;
463 $options = (array)$options;
464 if (!isset($options['forcehttps'])) {
465 $options['forcehttps'] = false;
468 if (!$CFG->slasharguments) {
469 $file = $file . '?file=';
472 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
474 if ($itemid !== null) {
475 $baseurl .= "$itemid/";
478 if ($options['forcehttps']) {
479 $baseurl = str_replace('http://', 'https://', $baseurl);
482 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
486 * Returns information about files in a draft area.
488 * @global stdClass $CFG
489 * @global stdClass $USER
490 * @param int $draftitemid the draft area item id.
491 * @param string $filepath path to the directory from which the information have to be retrieved.
492 * @return array with the following entries:
493 * 'filecount' => number of files in the draft area.
494 * 'filesize' => total size of the files in the draft area.
495 * 'foldercount' => number of folders in the draft area.
496 * 'filesize_without_references' => total size of the area excluding file references.
497 * (more information will be added as needed).
499 function file_get_draft_area_info($draftitemid, $filepath = '/') {
500 global $CFG, $USER;
502 $usercontext = context_user::instance($USER->id);
503 $fs = get_file_storage();
505 $results = array(
506 'filecount' => 0,
507 'foldercount' => 0,
508 'filesize' => 0,
509 'filesize_without_references' => 0
512 if ($filepath != '/') {
513 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
514 } else {
515 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
517 foreach ($draftfiles as $file) {
518 if ($file->is_directory()) {
519 $results['foldercount'] += 1;
520 } else {
521 $results['filecount'] += 1;
524 $filesize = $file->get_filesize();
525 $results['filesize'] += $filesize;
526 if (!$file->is_external_file()) {
527 $results['filesize_without_references'] += $filesize;
531 return $results;
535 * Returns whether a draft area has exceeded/will exceed its size limit.
537 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
539 * @param int $draftitemid the draft area item id.
540 * @param int $areamaxbytes the maximum size allowed in this draft area.
541 * @param int $newfilesize the size that would be added to the current area.
542 * @param bool $includereferences true to include the size of the references in the area size.
543 * @return bool true if the area will/has exceeded its limit.
544 * @since Moodle 2.4
546 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
547 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
548 $draftinfo = file_get_draft_area_info($draftitemid);
549 $areasize = $draftinfo['filesize_without_references'];
550 if ($includereferences) {
551 $areasize = $draftinfo['filesize'];
553 if ($areasize + $newfilesize > $areamaxbytes) {
554 return true;
557 return false;
561 * Get used space of files
562 * @global moodle_database $DB
563 * @global stdClass $USER
564 * @return int total bytes
566 function file_get_user_used_space() {
567 global $DB, $USER;
569 $usercontext = context_user::instance($USER->id);
570 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
571 JOIN (SELECT contenthash, filename, MAX(id) AS id
572 FROM {files}
573 WHERE contextid = ? AND component = ? AND filearea != ?
574 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
575 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
576 $record = $DB->get_record_sql($sql, $params);
577 return (int)$record->totalbytes;
581 * Convert any string to a valid filepath
582 * @todo review this function
583 * @param string $str
584 * @return string path
586 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
587 if ($str == '/' or empty($str)) {
588 return '/';
589 } else {
590 return '/'.trim($str, '/').'/';
595 * Generate a folder tree of draft area of current USER recursively
597 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
598 * @param int $draftitemid
599 * @param string $filepath
600 * @param mixed $data
602 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
603 global $USER, $OUTPUT, $CFG;
604 $data->children = array();
605 $context = context_user::instance($USER->id);
606 $fs = get_file_storage();
607 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
608 foreach ($files as $file) {
609 if ($file->is_directory()) {
610 $item = new stdClass();
611 $item->sortorder = $file->get_sortorder();
612 $item->filepath = $file->get_filepath();
614 $foldername = explode('/', trim($item->filepath, '/'));
615 $item->fullname = trim(array_pop($foldername), '/');
617 $item->id = uniqid();
618 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
619 $data->children[] = $item;
620 } else {
621 continue;
628 * Listing all files (including folders) in current path (draft area)
629 * used by file manager
630 * @param int $draftitemid
631 * @param string $filepath
632 * @return stdClass
634 function file_get_drafarea_files($draftitemid, $filepath = '/') {
635 global $USER, $OUTPUT, $CFG;
637 $context = context_user::instance($USER->id);
638 $fs = get_file_storage();
640 $data = new stdClass();
641 $data->path = array();
642 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
644 // will be used to build breadcrumb
645 $trail = '/';
646 if ($filepath !== '/') {
647 $filepath = file_correct_filepath($filepath);
648 $parts = explode('/', $filepath);
649 foreach ($parts as $part) {
650 if ($part != '' && $part != null) {
651 $trail .= ($part.'/');
652 $data->path[] = array('name'=>$part, 'path'=>$trail);
657 $list = array();
658 $maxlength = 12;
659 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
660 foreach ($files as $file) {
661 $item = new stdClass();
662 $item->filename = $file->get_filename();
663 $item->filepath = $file->get_filepath();
664 $item->fullname = trim($item->filename, '/');
665 $filesize = $file->get_filesize();
666 $item->size = $filesize ? $filesize : null;
667 $item->filesize = $filesize ? display_size($filesize) : '';
669 $item->sortorder = $file->get_sortorder();
670 $item->author = $file->get_author();
671 $item->license = $file->get_license();
672 $item->datemodified = $file->get_timemodified();
673 $item->datecreated = $file->get_timecreated();
674 $item->isref = $file->is_external_file();
675 if ($item->isref && $file->get_status() == 666) {
676 $item->originalmissing = true;
678 // find the file this draft file was created from and count all references in local
679 // system pointing to that file
680 $source = @unserialize($file->get_source());
681 if (isset($source->original)) {
682 $item->refcount = $fs->search_references_count($source->original);
685 if ($file->is_directory()) {
686 $item->filesize = 0;
687 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
688 $item->type = 'folder';
689 $foldername = explode('/', trim($item->filepath, '/'));
690 $item->fullname = trim(array_pop($foldername), '/');
691 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
692 } else {
693 // do NOT use file browser here!
694 $item->mimetype = get_mimetype_description($file);
695 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
696 $item->type = 'zip';
697 } else {
698 $item->type = 'file';
700 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
701 $item->url = $itemurl->out();
702 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
703 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
704 if ($imageinfo = $file->get_imageinfo()) {
705 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
706 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
707 $item->image_width = $imageinfo['width'];
708 $item->image_height = $imageinfo['height'];
711 $list[] = $item;
714 $data->itemid = $draftitemid;
715 $data->list = $list;
716 return $data;
720 * Returns draft area itemid for a given element.
722 * @category files
723 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
724 * @return int the itemid, or 0 if there is not one yet.
726 function file_get_submitted_draft_itemid($elname) {
727 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
728 if (!isset($_REQUEST[$elname])) {
729 return 0;
731 if (is_array($_REQUEST[$elname])) {
732 $param = optional_param_array($elname, 0, PARAM_INT);
733 if (!empty($param['itemid'])) {
734 $param = $param['itemid'];
735 } else {
736 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
737 return false;
740 } else {
741 $param = optional_param($elname, 0, PARAM_INT);
744 if ($param) {
745 require_sesskey();
748 return $param;
752 * Restore the original source field from draft files
754 * Do not use this function because it makes field files.source inconsistent
755 * for draft area files. This function will be deprecated in 2.6
757 * @param stored_file $storedfile This only works with draft files
758 * @return stored_file
760 function file_restore_source_field_from_draft_file($storedfile) {
761 $source = @unserialize($storedfile->get_source());
762 if (!empty($source)) {
763 if (is_object($source)) {
764 $restoredsource = $source->source;
765 $storedfile->set_source($restoredsource);
766 } else {
767 throw new moodle_exception('invalidsourcefield', 'error');
770 return $storedfile;
773 * Saves files from a draft file area to a real one (merging the list of files).
774 * Can rewrite URLs in some content at the same time if desired.
776 * @category files
777 * @global stdClass $USER
778 * @param int $draftitemid the id of the draft area to use. Normally obtained
779 * from file_get_submitted_draft_itemid('elementname') or similar.
780 * @param int $contextid This parameter and the next two identify the file area to save to.
781 * @param string $component
782 * @param string $filearea indentifies the file area.
783 * @param int $itemid helps identifies the file area.
784 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
785 * @param string $text some html content that needs to have embedded links rewritten
786 * to the @@PLUGINFILE@@ form for saving in the database.
787 * @param bool $forcehttps force https urls.
788 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
790 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
791 global $USER;
793 $usercontext = context_user::instance($USER->id);
794 $fs = get_file_storage();
796 $options = (array)$options;
797 if (!isset($options['subdirs'])) {
798 $options['subdirs'] = false;
800 if (!isset($options['maxfiles'])) {
801 $options['maxfiles'] = -1; // unlimited
803 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
804 $options['maxbytes'] = 0; // unlimited
806 if (!isset($options['areamaxbytes'])) {
807 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
809 $allowreferences = true;
810 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
811 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
812 // this is not exactly right. BUT there are many places in code where filemanager options
813 // are not passed to file_save_draft_area_files()
814 $allowreferences = false;
817 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
818 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
819 // anything at all in the next area.
820 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
821 return null;
824 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
825 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
827 // One file in filearea means it is empty (it has only top-level directory '.').
828 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
829 // we have to merge old and new files - we want to keep file ids for files that were not changed
830 // we change time modified for all new and changed files, we keep time created as is
832 $newhashes = array();
833 $filecount = 0;
834 foreach ($draftfiles as $file) {
835 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
836 continue;
838 if (!$allowreferences && $file->is_external_file()) {
839 continue;
841 if (!$file->is_directory()) {
842 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
843 // oversized file - should not get here at all
844 continue;
846 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
847 // more files - should not get here at all
848 continue;
850 $filecount++;
852 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
853 $newhashes[$newhash] = $file;
856 // Loop through oldfiles and decide which we need to delete and which to update.
857 // After this cycle the array $newhashes will only contain the files that need to be added.
858 foreach ($oldfiles as $oldfile) {
859 $oldhash = $oldfile->get_pathnamehash();
860 if (!isset($newhashes[$oldhash])) {
861 // delete files not needed any more - deleted by user
862 $oldfile->delete();
863 continue;
866 $newfile = $newhashes[$oldhash];
867 // Now we know that we have $oldfile and $newfile for the same path.
868 // Let's check if we can update this file or we need to delete and create.
869 if ($newfile->is_directory()) {
870 // Directories are always ok to just update.
871 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
872 // File has the 'original' - we need to update the file (it may even have not been changed at all).
873 $original = file_storage::unpack_reference($source->original);
874 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
875 // Very odd, original points to another file. Delete and create file.
876 $oldfile->delete();
877 continue;
879 } else {
880 // The same file name but absence of 'original' means that file was deteled and uploaded again.
881 // By deleting and creating new file we properly manage all existing references.
882 $oldfile->delete();
883 continue;
886 // status changed, we delete old file, and create a new one
887 if ($oldfile->get_status() != $newfile->get_status()) {
888 // file was changed, use updated with new timemodified data
889 $oldfile->delete();
890 // This file will be added later
891 continue;
894 // Updated author
895 if ($oldfile->get_author() != $newfile->get_author()) {
896 $oldfile->set_author($newfile->get_author());
898 // Updated license
899 if ($oldfile->get_license() != $newfile->get_license()) {
900 $oldfile->set_license($newfile->get_license());
903 // Updated file source
904 // Field files.source for draftarea files contains serialised object with source and original information.
905 // We only store the source part of it for non-draft file area.
906 $newsource = $newfile->get_source();
907 if ($source = @unserialize($newfile->get_source())) {
908 $newsource = $source->source;
910 if ($oldfile->get_source() !== $newsource) {
911 $oldfile->set_source($newsource);
914 // Updated sort order
915 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
916 $oldfile->set_sortorder($newfile->get_sortorder());
919 // Update file timemodified
920 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
921 $oldfile->set_timemodified($newfile->get_timemodified());
924 // Replaced file content
925 if (!$oldfile->is_directory() &&
926 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
927 $oldfile->get_filesize() != $newfile->get_filesize() ||
928 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
929 $oldfile->get_userid() != $newfile->get_userid())) {
930 $oldfile->replace_file_with($newfile);
933 // unchanged file or directory - we keep it as is
934 unset($newhashes[$oldhash]);
937 // Add fresh file or the file which has changed status
938 // the size and subdirectory tests are extra safety only, the UI should prevent it
939 foreach ($newhashes as $file) {
940 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
941 if ($source = @unserialize($file->get_source())) {
942 // Field files.source for draftarea files contains serialised object with source and original information.
943 // We only store the source part of it for non-draft file area.
944 $file_record['source'] = $source->source;
947 if ($file->is_external_file()) {
948 $repoid = $file->get_repository_id();
949 if (!empty($repoid)) {
950 $file_record['repositoryid'] = $repoid;
951 $file_record['reference'] = $file->get_reference();
955 $fs->create_file_from_storedfile($file_record, $file);
959 // note: do not purge the draft area - we clean up areas later in cron,
960 // the reason is that user might press submit twice and they would loose the files,
961 // also sometimes we might want to use hacks that save files into two different areas
963 if (is_null($text)) {
964 return null;
965 } else {
966 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
971 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
972 * ready to be saved in the database. Normally, this is done automatically by
973 * {@link file_save_draft_area_files()}.
975 * @category files
976 * @param string $text the content to process.
977 * @param int $draftitemid the draft file area the content was using.
978 * @param bool $forcehttps whether the content contains https URLs. Default false.
979 * @return string the processed content.
981 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
982 global $CFG, $USER;
984 $usercontext = context_user::instance($USER->id);
986 $wwwroot = $CFG->wwwroot;
987 if ($forcehttps) {
988 $wwwroot = str_replace('http://', 'https://', $wwwroot);
991 // relink embedded files if text submitted - no absolute links allowed in database!
992 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
994 if (strpos($text, 'draftfile.php?file=') !== false) {
995 $matches = array();
996 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
997 if ($matches) {
998 foreach ($matches[0] as $match) {
999 $replace = str_ireplace('%2F', '/', $match);
1000 $text = str_replace($match, $replace, $text);
1003 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1006 return $text;
1010 * Set file sort order
1012 * @global moodle_database $DB
1013 * @param int $contextid the context id
1014 * @param string $component file component
1015 * @param string $filearea file area.
1016 * @param int $itemid itemid.
1017 * @param string $filepath file path.
1018 * @param string $filename file name.
1019 * @param int $sortorder the sort order of file.
1020 * @return bool
1022 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1023 global $DB;
1024 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1025 if ($file_record = $DB->get_record('files', $conditions)) {
1026 $sortorder = (int)$sortorder;
1027 $file_record->sortorder = $sortorder;
1028 $DB->update_record('files', $file_record);
1029 return true;
1031 return false;
1035 * reset file sort order number to 0
1036 * @global moodle_database $DB
1037 * @param int $contextid the context id
1038 * @param string $component
1039 * @param string $filearea file area.
1040 * @param int|bool $itemid itemid.
1041 * @return bool
1043 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1044 global $DB;
1046 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1047 if ($itemid !== false) {
1048 $conditions['itemid'] = $itemid;
1051 $file_records = $DB->get_records('files', $conditions);
1052 foreach ($file_records as $file_record) {
1053 $file_record->sortorder = 0;
1054 $DB->update_record('files', $file_record);
1056 return true;
1060 * Returns description of upload error
1062 * @param int $errorcode found in $_FILES['filename.ext']['error']
1063 * @return string error description string, '' if ok
1065 function file_get_upload_error($errorcode) {
1067 switch ($errorcode) {
1068 case 0: // UPLOAD_ERR_OK - no error
1069 $errmessage = '';
1070 break;
1072 case 1: // UPLOAD_ERR_INI_SIZE
1073 $errmessage = get_string('uploadserverlimit');
1074 break;
1076 case 2: // UPLOAD_ERR_FORM_SIZE
1077 $errmessage = get_string('uploadformlimit');
1078 break;
1080 case 3: // UPLOAD_ERR_PARTIAL
1081 $errmessage = get_string('uploadpartialfile');
1082 break;
1084 case 4: // UPLOAD_ERR_NO_FILE
1085 $errmessage = get_string('uploadnofilefound');
1086 break;
1088 // Note: there is no error with a value of 5
1090 case 6: // UPLOAD_ERR_NO_TMP_DIR
1091 $errmessage = get_string('uploadnotempdir');
1092 break;
1094 case 7: // UPLOAD_ERR_CANT_WRITE
1095 $errmessage = get_string('uploadcantwrite');
1096 break;
1098 case 8: // UPLOAD_ERR_EXTENSION
1099 $errmessage = get_string('uploadextension');
1100 break;
1102 default:
1103 $errmessage = get_string('uploadproblem');
1106 return $errmessage;
1110 * Recursive function formating an array in POST parameter
1111 * @param array $arraydata - the array that we are going to format and add into &$data array
1112 * @param string $currentdata - a row of the final postdata array at instant T
1113 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1114 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1116 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1117 foreach ($arraydata as $k=>$v) {
1118 $newcurrentdata = $currentdata;
1119 if (is_array($v)) { //the value is an array, call the function recursively
1120 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1121 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1122 } else { //add the POST parameter to the $data array
1123 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1129 * Transform a PHP array into POST parameter
1130 * (see the recursive function format_array_postdata_for_curlcall)
1131 * @param array $postdata
1132 * @return array containing all POST parameters (1 row = 1 POST parameter)
1134 function format_postdata_for_curlcall($postdata) {
1135 $data = array();
1136 foreach ($postdata as $k=>$v) {
1137 if (is_array($v)) {
1138 $currentdata = urlencode($k);
1139 format_array_postdata_for_curlcall($v, $currentdata, $data);
1140 } else {
1141 $data[] = urlencode($k).'='.urlencode($v);
1144 $convertedpostdata = implode('&', $data);
1145 return $convertedpostdata;
1149 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1150 * Due to security concerns only downloads from http(s) sources are supported.
1152 * @category files
1153 * @param string $url file url starting with http(s)://
1154 * @param array $headers http headers, null if none. If set, should be an
1155 * associative array of header name => value pairs.
1156 * @param array $postdata array means use POST request with given parameters
1157 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1158 * (if false, just returns content)
1159 * @param int $timeout timeout for complete download process including all file transfer
1160 * (default 5 minutes)
1161 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1162 * usually happens if the remote server is completely down (default 20 seconds);
1163 * may not work when using proxy
1164 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1165 * Only use this when already in a trusted location.
1166 * @param string $tofile store the downloaded content to file instead of returning it.
1167 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1168 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1169 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1170 * if file downloaded into $tofile successfully or the file content as a string.
1172 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1173 global $CFG;
1175 // Only http and https links supported.
1176 if (!preg_match('|^https?://|i', $url)) {
1177 if ($fullresponse) {
1178 $response = new stdClass();
1179 $response->status = 0;
1180 $response->headers = array();
1181 $response->response_code = 'Invalid protocol specified in url';
1182 $response->results = '';
1183 $response->error = 'Invalid protocol specified in url';
1184 return $response;
1185 } else {
1186 return false;
1190 $options = array();
1192 $headers2 = array();
1193 if (is_array($headers)) {
1194 foreach ($headers as $key => $value) {
1195 if (is_numeric($key)) {
1196 $headers2[] = $value;
1197 } else {
1198 $headers2[] = "$key: $value";
1203 if ($skipcertverify) {
1204 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1205 } else {
1206 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1209 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1211 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1212 $options['CURLOPT_MAXREDIRS'] = 5;
1214 // Use POST if requested.
1215 if (is_array($postdata)) {
1216 $postdata = format_postdata_for_curlcall($postdata);
1217 } else if (empty($postdata)) {
1218 $postdata = null;
1221 // Optionally attempt to get more correct timeout by fetching the file size.
1222 if (!isset($CFG->curltimeoutkbitrate)) {
1223 // Use very slow rate of 56kbps as a timeout speed when not set.
1224 $bitrate = 56;
1225 } else {
1226 $bitrate = $CFG->curltimeoutkbitrate;
1228 if ($calctimeout and !isset($postdata)) {
1229 $curl = new curl();
1230 $curl->setHeader($headers2);
1232 $curl->head($url, $postdata, $options);
1234 $info = $curl->get_info();
1235 $error_no = $curl->get_errno();
1236 if (!$error_no && $info['download_content_length'] > 0) {
1237 // No curl errors - adjust for large files only - take max timeout.
1238 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1242 $curl = new curl();
1243 $curl->setHeader($headers2);
1245 $options['CURLOPT_RETURNTRANSFER'] = true;
1246 $options['CURLOPT_NOBODY'] = false;
1247 $options['CURLOPT_TIMEOUT'] = $timeout;
1249 if ($tofile) {
1250 $fh = fopen($tofile, 'w');
1251 if (!$fh) {
1252 if ($fullresponse) {
1253 $response = new stdClass();
1254 $response->status = 0;
1255 $response->headers = array();
1256 $response->response_code = 'Can not write to file';
1257 $response->results = false;
1258 $response->error = 'Can not write to file';
1259 return $response;
1260 } else {
1261 return false;
1264 $options['CURLOPT_FILE'] = $fh;
1267 if (isset($postdata)) {
1268 $content = $curl->post($url, $postdata, $options);
1269 } else {
1270 $content = $curl->get($url, null, $options);
1273 if ($tofile) {
1274 fclose($fh);
1275 @chmod($tofile, $CFG->filepermissions);
1279 // Try to detect encoding problems.
1280 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1281 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1282 $result = curl_exec($ch);
1286 $info = $curl->get_info();
1287 $error_no = $curl->get_errno();
1288 $rawheaders = $curl->get_raw_response();
1290 if ($error_no) {
1291 $error = $content;
1292 if (!$fullresponse) {
1293 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1294 return false;
1297 $response = new stdClass();
1298 if ($error_no == 28) {
1299 $response->status = '-100'; // Mimic snoopy.
1300 } else {
1301 $response->status = '0';
1303 $response->headers = array();
1304 $response->response_code = $error;
1305 $response->results = false;
1306 $response->error = $error;
1307 return $response;
1310 if ($tofile) {
1311 $content = true;
1314 if (empty($info['http_code'])) {
1315 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1316 $response = new stdClass();
1317 $response->status = '0';
1318 $response->headers = array();
1319 $response->response_code = 'Unknown cURL error';
1320 $response->results = false; // do NOT change this, we really want to ignore the result!
1321 $response->error = 'Unknown cURL error';
1323 } else {
1324 $response = new stdClass();
1325 $response->status = (string)$info['http_code'];
1326 $response->headers = $rawheaders;
1327 $response->results = $content;
1328 $response->error = '';
1330 // There might be multiple headers on redirect, find the status of the last one.
1331 $firstline = true;
1332 foreach ($rawheaders as $line) {
1333 if ($firstline) {
1334 $response->response_code = $line;
1335 $firstline = false;
1337 if (trim($line, "\r\n") === '') {
1338 $firstline = true;
1343 if ($fullresponse) {
1344 return $response;
1347 if ($info['http_code'] != 200) {
1348 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1349 return false;
1351 return $response->results;
1355 * Returns a list of information about file types based on extensions.
1357 * The following elements expected in value array for each extension:
1358 * 'type' - mimetype
1359 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1360 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1361 * also files with bigger sizes under names
1362 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1363 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1364 * commonly used in moodle the following groups:
1365 * - web_image - image that can be included as <img> in HTML
1366 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1367 * - video - file that can be imported as video in text editor
1368 * - audio - file that can be imported as audio in text editor
1369 * - archive - we can extract files from this archive
1370 * - spreadsheet - used for portfolio format
1371 * - document - used for portfolio format
1372 * - presentation - used for portfolio format
1373 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1374 * human-readable description for this filetype;
1375 * Function {@link get_mimetype_description()} first looks at the presence of string for
1376 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1377 * attribute, if not found returns the value of 'type';
1378 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1379 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1380 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1382 * @category files
1383 * @return array List of information about file types based on extensions.
1384 * Associative array of extension (lower-case) to associative array
1385 * from 'element name' to data. Current element names are 'type' and 'icon'.
1386 * Unknown types should use the 'xxx' entry which includes defaults.
1388 function &get_mimetypes_array() {
1389 // Get types from the core_filetypes function, which includes caching.
1390 return core_filetypes::get_types();
1394 * Obtains information about a filetype based on its extension. Will
1395 * use a default if no information is present about that particular
1396 * extension.
1398 * @category files
1399 * @param string $element Desired information (usually 'icon'
1400 * for icon filename or 'type' for MIME type. Can also be
1401 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1402 * @param string $filename Filename we're looking up
1403 * @return string Requested piece of information from array
1405 function mimeinfo($element, $filename) {
1406 global $CFG;
1407 $mimeinfo = & get_mimetypes_array();
1408 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1410 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1411 if (empty($filetype)) {
1412 $filetype = 'xxx'; // file without extension
1414 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1415 $iconsize = max(array(16, (int)$iconsizematch[1]));
1416 $filenames = array($mimeinfo['xxx']['icon']);
1417 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1418 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1420 // find the file with the closest size, first search for specific icon then for default icon
1421 foreach ($filenames as $filename) {
1422 foreach ($iconpostfixes as $size => $postfix) {
1423 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1424 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1425 return $filename.$postfix;
1429 } else if (isset($mimeinfo[$filetype][$element])) {
1430 return $mimeinfo[$filetype][$element];
1431 } else if (isset($mimeinfo['xxx'][$element])) {
1432 return $mimeinfo['xxx'][$element]; // By default
1433 } else {
1434 return null;
1439 * Obtains information about a filetype based on the MIME type rather than
1440 * the other way around.
1442 * @category files
1443 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1444 * @param string $mimetype MIME type we're looking up
1445 * @return string Requested piece of information from array
1447 function mimeinfo_from_type($element, $mimetype) {
1448 /* array of cached mimetype->extension associations */
1449 static $cached = array();
1450 $mimeinfo = & get_mimetypes_array();
1452 if (!array_key_exists($mimetype, $cached)) {
1453 $cached[$mimetype] = null;
1454 foreach($mimeinfo as $filetype => $values) {
1455 if ($values['type'] == $mimetype) {
1456 if ($cached[$mimetype] === null) {
1457 $cached[$mimetype] = '.'.$filetype;
1459 if (!empty($values['defaulticon'])) {
1460 $cached[$mimetype] = '.'.$filetype;
1461 break;
1465 if (empty($cached[$mimetype])) {
1466 $cached[$mimetype] = '.xxx';
1469 if ($element === 'extension') {
1470 return $cached[$mimetype];
1471 } else {
1472 return mimeinfo($element, $cached[$mimetype]);
1477 * Return the relative icon path for a given file
1479 * Usage:
1480 * <code>
1481 * // $file - instance of stored_file or file_info
1482 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1483 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1484 * </code>
1485 * or
1486 * <code>
1487 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1488 * </code>
1490 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1491 * and $file->mimetype are expected)
1492 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1493 * @return string
1495 function file_file_icon($file, $size = null) {
1496 if (!is_object($file)) {
1497 $file = (object)$file;
1499 if (isset($file->filename)) {
1500 $filename = $file->filename;
1501 } else if (method_exists($file, 'get_filename')) {
1502 $filename = $file->get_filename();
1503 } else if (method_exists($file, 'get_visible_name')) {
1504 $filename = $file->get_visible_name();
1505 } else {
1506 $filename = '';
1508 if (isset($file->mimetype)) {
1509 $mimetype = $file->mimetype;
1510 } else if (method_exists($file, 'get_mimetype')) {
1511 $mimetype = $file->get_mimetype();
1512 } else {
1513 $mimetype = '';
1515 $mimetypes = &get_mimetypes_array();
1516 if ($filename) {
1517 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1518 if ($extension && !empty($mimetypes[$extension])) {
1519 // if file name has known extension, return icon for this extension
1520 return file_extension_icon($filename, $size);
1523 return file_mimetype_icon($mimetype, $size);
1527 * Return the relative icon path for a folder image
1529 * Usage:
1530 * <code>
1531 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1532 * echo html_writer::empty_tag('img', array('src' => $icon));
1533 * </code>
1534 * or
1535 * <code>
1536 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1537 * </code>
1539 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1540 * @return string
1542 function file_folder_icon($iconsize = null) {
1543 global $CFG;
1544 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1545 static $cached = array();
1546 $iconsize = max(array(16, (int)$iconsize));
1547 if (!array_key_exists($iconsize, $cached)) {
1548 foreach ($iconpostfixes as $size => $postfix) {
1549 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1550 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1551 $cached[$iconsize] = 'f/folder'.$postfix;
1552 break;
1556 return $cached[$iconsize];
1560 * Returns the relative icon path for a given mime type
1562 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1563 * a return the full path to an icon.
1565 * <code>
1566 * $mimetype = 'image/jpg';
1567 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1568 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1569 * </code>
1571 * @category files
1572 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1573 * to conform with that.
1574 * @param string $mimetype The mimetype to fetch an icon for
1575 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1576 * @return string The relative path to the icon
1578 function file_mimetype_icon($mimetype, $size = NULL) {
1579 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1583 * Returns the relative icon path for a given file name
1585 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1586 * a return the full path to an icon.
1588 * <code>
1589 * $filename = '.jpg';
1590 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1591 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1592 * </code>
1594 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1595 * to conform with that.
1596 * @todo MDL-31074 Implement $size
1597 * @category files
1598 * @param string $filename The filename to get the icon for
1599 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1600 * @return string
1602 function file_extension_icon($filename, $size = NULL) {
1603 return 'f/'.mimeinfo('icon'.$size, $filename);
1607 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1608 * mimetypes.php language file.
1610 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1611 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1612 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1613 * @param bool $capitalise If true, capitalises first character of result
1614 * @return string Text description
1616 function get_mimetype_description($obj, $capitalise=false) {
1617 $filename = $mimetype = '';
1618 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1619 // this is an instance of stored_file
1620 $mimetype = $obj->get_mimetype();
1621 $filename = $obj->get_filename();
1622 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1623 // this is an instance of file_info
1624 $mimetype = $obj->get_mimetype();
1625 $filename = $obj->get_visible_name();
1626 } else if (is_array($obj) || is_object ($obj)) {
1627 $obj = (array)$obj;
1628 if (!empty($obj['filename'])) {
1629 $filename = $obj['filename'];
1631 if (!empty($obj['mimetype'])) {
1632 $mimetype = $obj['mimetype'];
1634 } else {
1635 $mimetype = $obj;
1637 $mimetypefromext = mimeinfo('type', $filename);
1638 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1639 // if file has a known extension, overwrite the specified mimetype
1640 $mimetype = $mimetypefromext;
1642 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1643 if (empty($extension)) {
1644 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1645 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1646 } else {
1647 $mimetypestr = mimeinfo('string', $filename);
1649 $chunks = explode('/', $mimetype, 2);
1650 $chunks[] = '';
1651 $attr = array(
1652 'mimetype' => $mimetype,
1653 'ext' => $extension,
1654 'mimetype1' => $chunks[0],
1655 'mimetype2' => $chunks[1],
1657 $a = array();
1658 foreach ($attr as $key => $value) {
1659 $a[$key] = $value;
1660 $a[strtoupper($key)] = strtoupper($value);
1661 $a[ucfirst($key)] = ucfirst($value);
1664 // MIME types may include + symbol but this is not permitted in string ids.
1665 $safemimetype = str_replace('+', '_', $mimetype);
1666 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1667 $customdescription = mimeinfo('customdescription', $filename);
1668 if ($customdescription) {
1669 // Call format_string on the custom description so that multilang
1670 // filter can be used (if enabled on system context). We use system
1671 // context because it is possible that the page context might not have
1672 // been defined yet.
1673 $result = format_string($customdescription, true,
1674 array('context' => context_system::instance()));
1675 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1676 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1677 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1678 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1679 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1680 $result = get_string('default', 'mimetypes', (object)$a);
1681 } else {
1682 $result = $mimetype;
1684 if ($capitalise) {
1685 $result=ucfirst($result);
1687 return $result;
1691 * Returns array of elements of type $element in type group(s)
1693 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1694 * @param string|array $groups one group or array of groups/extensions/mimetypes
1695 * @return array
1697 function file_get_typegroup($element, $groups) {
1698 static $cached = array();
1699 if (!is_array($groups)) {
1700 $groups = array($groups);
1702 if (!array_key_exists($element, $cached)) {
1703 $cached[$element] = array();
1705 $result = array();
1706 foreach ($groups as $group) {
1707 if (!array_key_exists($group, $cached[$element])) {
1708 // retrieive and cache all elements of type $element for group $group
1709 $mimeinfo = & get_mimetypes_array();
1710 $cached[$element][$group] = array();
1711 foreach ($mimeinfo as $extension => $value) {
1712 $value['extension'] = '.'.$extension;
1713 if (empty($value[$element])) {
1714 continue;
1716 if (($group === '.'.$extension || $group === $value['type'] ||
1717 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1718 !in_array($value[$element], $cached[$element][$group])) {
1719 $cached[$element][$group][] = $value[$element];
1723 $result = array_merge($result, $cached[$element][$group]);
1725 return array_values(array_unique($result));
1729 * Checks if file with name $filename has one of the extensions in groups $groups
1731 * @see get_mimetypes_array()
1732 * @param string $filename name of the file to check
1733 * @param string|array $groups one group or array of groups to check
1734 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1735 * file mimetype is in mimetypes in groups $groups
1736 * @return bool
1738 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1739 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1740 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1741 return true;
1743 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1747 * Checks if mimetype $mimetype belongs to one of the groups $groups
1749 * @see get_mimetypes_array()
1750 * @param string $mimetype
1751 * @param string|array $groups one group or array of groups to check
1752 * @return bool
1754 function file_mimetype_in_typegroup($mimetype, $groups) {
1755 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1759 * Requested file is not found or not accessible, does not return, terminates script
1761 * @global stdClass $CFG
1762 * @global stdClass $COURSE
1764 function send_file_not_found() {
1765 global $CFG, $COURSE;
1767 // Allow cross-origin requests only for Web Services.
1768 // This allow to receive requests done by Web Workers or webapps in different domains.
1769 if (WS_SERVER) {
1770 header('Access-Control-Allow-Origin: *');
1773 send_header_404();
1774 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1777 * Helper function to send correct 404 for server.
1779 function send_header_404() {
1780 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1781 header("Status: 404 Not Found");
1782 } else {
1783 header('HTTP/1.0 404 not found');
1788 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1789 * platforms). This wrapper uses readfile for small files and custom code for
1790 * large ones.
1792 * @param string $path Path to file
1793 * @param int $filesize Size of file (if left out, will get it automatically)
1794 * @return int|bool Size read (will always be $filesize) or false if failed
1796 function readfile_allow_large($path, $filesize = -1) {
1797 // Automatically get size if not specified.
1798 if ($filesize === -1) {
1799 $filesize = filesize($path);
1801 if ($filesize <= 2147483647) {
1802 // If the file is up to 2^31 - 1, send it normally using readfile.
1803 return readfile($path);
1804 } else {
1805 // For large files, read and output in 64KB chunks.
1806 $handle = fopen($path, 'r');
1807 if ($handle === false) {
1808 return false;
1810 $left = $filesize;
1811 while ($left > 0) {
1812 $size = min($left, 65536);
1813 $buffer = fread($handle, $size);
1814 if ($buffer === false) {
1815 return false;
1817 echo $buffer;
1818 $left -= $size;
1820 return $filesize;
1825 * Enhanced readfile() with optional acceleration.
1826 * @param string|stored_file $file
1827 * @param string $mimetype
1828 * @param bool $accelerate
1829 * @return void
1831 function readfile_accel($file, $mimetype, $accelerate) {
1832 global $CFG;
1834 if ($mimetype === 'text/plain') {
1835 // there is no encoding specified in text files, we need something consistent
1836 header('Content-Type: text/plain; charset=utf-8');
1837 } else {
1838 header('Content-Type: '.$mimetype);
1841 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1842 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1844 if (is_object($file)) {
1845 header('Etag: "' . $file->get_contenthash() . '"');
1846 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
1847 header('HTTP/1.1 304 Not Modified');
1848 return;
1852 // if etag present for stored file rely on it exclusively
1853 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1854 // get unixtime of request header; clip extra junk off first
1855 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1856 if ($since && $since >= $lastmodified) {
1857 header('HTTP/1.1 304 Not Modified');
1858 return;
1862 if ($accelerate and !empty($CFG->xsendfile)) {
1863 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1864 header('Accept-Ranges: bytes');
1865 } else {
1866 header('Accept-Ranges: none');
1869 if (is_object($file)) {
1870 $fs = get_file_storage();
1871 if ($fs->xsendfile($file->get_contenthash())) {
1872 return;
1875 } else {
1876 require_once("$CFG->libdir/xsendfilelib.php");
1877 if (xsendfile($file)) {
1878 return;
1883 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1885 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1887 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1888 header('Accept-Ranges: bytes');
1890 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1891 // byteserving stuff - for acrobat reader and download accelerators
1892 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1893 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1894 $ranges = false;
1895 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1896 foreach ($ranges as $key=>$value) {
1897 if ($ranges[$key][1] == '') {
1898 //suffix case
1899 $ranges[$key][1] = $filesize - $ranges[$key][2];
1900 $ranges[$key][2] = $filesize - 1;
1901 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1902 //fix range length
1903 $ranges[$key][2] = $filesize - 1;
1905 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1906 //invalid byte-range ==> ignore header
1907 $ranges = false;
1908 break;
1910 //prepare multipart header
1911 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1912 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1914 } else {
1915 $ranges = false;
1917 if ($ranges) {
1918 if (is_object($file)) {
1919 $handle = $file->get_content_file_handle();
1920 } else {
1921 $handle = fopen($file, 'rb');
1923 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1926 } else {
1927 // Do not byteserve
1928 header('Accept-Ranges: none');
1931 header('Content-Length: '.$filesize);
1933 if ($filesize > 10000000) {
1934 // for large files try to flush and close all buffers to conserve memory
1935 while(@ob_get_level()) {
1936 if (!@ob_end_flush()) {
1937 break;
1942 // send the whole file content
1943 if (is_object($file)) {
1944 $file->readfile();
1945 } else {
1946 readfile_allow_large($file, $filesize);
1951 * Similar to readfile_accel() but designed for strings.
1952 * @param string $string
1953 * @param string $mimetype
1954 * @param bool $accelerate
1955 * @return void
1957 function readstring_accel($string, $mimetype, $accelerate) {
1958 global $CFG;
1960 if ($mimetype === 'text/plain') {
1961 // there is no encoding specified in text files, we need something consistent
1962 header('Content-Type: text/plain; charset=utf-8');
1963 } else {
1964 header('Content-Type: '.$mimetype);
1966 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
1967 header('Accept-Ranges: none');
1969 if ($accelerate and !empty($CFG->xsendfile)) {
1970 $fs = get_file_storage();
1971 if ($fs->xsendfile(sha1($string))) {
1972 return;
1976 header('Content-Length: '.strlen($string));
1977 echo $string;
1981 * Handles the sending of temporary file to user, download is forced.
1982 * File is deleted after abort or successful sending, does not return, script terminated
1984 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1985 * @param string $filename proposed file name when saving file
1986 * @param bool $pathisstring If the path is string
1988 function send_temp_file($path, $filename, $pathisstring=false) {
1989 global $CFG;
1991 if (core_useragent::is_firefox()) {
1992 // only FF is known to correctly save to disk before opening...
1993 $mimetype = mimeinfo('type', $filename);
1994 } else {
1995 $mimetype = 'application/x-forcedownload';
1998 // close session - not needed anymore
1999 \core\session\manager::write_close();
2001 if (!$pathisstring) {
2002 if (!file_exists($path)) {
2003 send_header_404();
2004 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2006 // executed after normal finish or abort
2007 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2010 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2011 if (core_useragent::is_ie()) {
2012 $filename = urlencode($filename);
2015 header('Content-Disposition: attachment; filename="'.$filename.'"');
2016 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2017 header('Cache-Control: private, max-age=10, no-transform');
2018 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2019 header('Pragma: ');
2020 } else { //normal http - prevent caching at all cost
2021 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2022 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2023 header('Pragma: no-cache');
2026 // send the contents - we can not accelerate this because the file will be deleted asap
2027 if ($pathisstring) {
2028 readstring_accel($path, $mimetype, false);
2029 } else {
2030 readfile_accel($path, $mimetype, false);
2031 @unlink($path);
2034 die; //no more chars to output
2038 * Internal callback function used by send_temp_file()
2040 * @param string $path
2042 function send_temp_file_finished($path) {
2043 if (file_exists($path)) {
2044 @unlink($path);
2049 * Handles the sending of file data to the user's browser, including support for
2050 * byteranges etc.
2052 * @category files
2053 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2054 * @param string $filename Filename to send
2055 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2056 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2057 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2058 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2059 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2060 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2061 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2062 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2063 * and should not be reopened.
2064 * @return null script execution stopped unless $dontdie is true
2066 function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2067 global $CFG, $COURSE;
2069 if ($dontdie) {
2070 ignore_user_abort(true);
2073 if ($lifetime === 'default' or is_null($lifetime)) {
2074 $lifetime = $CFG->filelifetime;
2077 \core\session\manager::write_close(); // Unlock session during file serving.
2079 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2080 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2081 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2082 $isFF = core_useragent::is_firefox(); // only FF properly tested
2083 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2084 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2086 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2087 if (core_useragent::is_ie()) {
2088 $filename = rawurlencode($filename);
2091 if ($forcedownload) {
2092 header('Content-Disposition: attachment; filename="'.$filename.'"');
2093 } else if ($mimetype !== 'application/x-shockwave-flash') {
2094 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2095 // as an upload and enforces security that may prevent the file from being loaded.
2097 header('Content-Disposition: inline; filename="'.$filename.'"');
2100 if ($lifetime > 0) {
2101 $cacheability = ' public,';
2102 if (isloggedin() and !isguestuser()) {
2103 // By default, under the conditions above, this file must be cache-able only by browsers.
2104 $cacheability = ' private,';
2106 $nobyteserving = false;
2107 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2108 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2109 header('Pragma: ');
2111 } else { // Do not cache files in proxies and browsers
2112 $nobyteserving = true;
2113 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2114 header('Cache-Control: private, max-age=10, no-transform');
2115 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2116 header('Pragma: ');
2117 } else { //normal http - prevent caching at all cost
2118 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2119 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2120 header('Pragma: no-cache');
2124 if (empty($filter)) {
2125 // send the contents
2126 if ($pathisstring) {
2127 readstring_accel($path, $mimetype, !$dontdie);
2128 } else {
2129 readfile_accel($path, $mimetype, !$dontdie);
2132 } else {
2133 // Try to put the file through filters
2134 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2135 $options = new stdClass();
2136 $options->noclean = true;
2137 $options->nocache = true; // temporary workaround for MDL-5136
2138 $text = $pathisstring ? $path : implode('', file($path));
2140 $text = file_modify_html_header($text);
2141 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2143 readstring_accel($output, $mimetype, false);
2145 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2146 // only filter text if filter all files is selected
2147 $options = new stdClass();
2148 $options->newlines = false;
2149 $options->noclean = true;
2150 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2151 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2153 readstring_accel($output, $mimetype, false);
2155 } else {
2156 // send the contents
2157 if ($pathisstring) {
2158 readstring_accel($path, $mimetype, !$dontdie);
2159 } else {
2160 readfile_accel($path, $mimetype, !$dontdie);
2164 if ($dontdie) {
2165 return;
2167 die; //no more chars to output!!!
2171 * Handles the sending of file data to the user's browser, including support for
2172 * byteranges etc.
2174 * The $options parameter supports the following keys:
2175 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2176 * (string|null) filename - overrides the implicit filename
2177 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2178 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2179 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2180 * and should not be reopened
2181 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2182 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2183 * defaults to "public".
2185 * @category files
2186 * @param stored_file $stored_file local file object
2187 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2188 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2189 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2190 * @param array $options additional options affecting the file serving
2191 * @return null script execution stopped unless $options['dontdie'] is true
2193 function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2194 global $CFG, $COURSE;
2196 if (empty($options['filename'])) {
2197 $filename = null;
2198 } else {
2199 $filename = $options['filename'];
2202 if (empty($options['dontdie'])) {
2203 $dontdie = false;
2204 } else {
2205 $dontdie = true;
2208 if ($lifetime === 'default' or is_null($lifetime)) {
2209 $lifetime = $CFG->filelifetime;
2212 if (!empty($options['preview'])) {
2213 // replace the file with its preview
2214 $fs = get_file_storage();
2215 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2216 if (!$preview_file) {
2217 // unable to create a preview of the file, send its default mime icon instead
2218 if ($options['preview'] === 'tinyicon') {
2219 $size = 24;
2220 } else if ($options['preview'] === 'thumb') {
2221 $size = 90;
2222 } else {
2223 $size = 256;
2225 $fileicon = file_file_icon($stored_file, $size);
2226 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2227 } else {
2228 // preview images have fixed cache lifetime and they ignore forced download
2229 // (they are generated by GD and therefore they are considered reasonably safe).
2230 $stored_file = $preview_file;
2231 $lifetime = DAYSECS;
2232 $filter = 0;
2233 $forcedownload = false;
2237 // handle external resource
2238 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2239 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2240 die;
2243 if (!$stored_file or $stored_file->is_directory()) {
2244 // nothing to serve
2245 if ($dontdie) {
2246 return;
2248 die;
2251 if ($dontdie) {
2252 ignore_user_abort(true);
2255 \core\session\manager::write_close(); // Unlock session during file serving.
2257 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2258 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2259 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2260 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2261 $isFF = core_useragent::is_firefox(); // only FF properly tested
2262 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2263 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2265 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2266 if (core_useragent::is_ie()) {
2267 $filename = rawurlencode($filename);
2270 if ($forcedownload) {
2271 header('Content-Disposition: attachment; filename="'.$filename.'"');
2272 } else if ($mimetype !== 'application/x-shockwave-flash') {
2273 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2274 // as an upload and enforces security that may prevent the file from being loaded.
2276 header('Content-Disposition: inline; filename="'.$filename.'"');
2279 if ($lifetime > 0) {
2280 $cacheability = ' public,';
2281 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2282 // This file must be cache-able by both browsers and proxies.
2283 $cacheability = ' public,';
2284 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2285 // This file must be cache-able only by browsers.
2286 $cacheability = ' private,';
2287 } else if (isloggedin() and !isguestuser()) {
2288 $cacheability = ' private,';
2290 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
2291 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2292 header('Pragma: ');
2294 } else { // Do not cache files in proxies and browsers
2295 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2296 header('Cache-Control: private, max-age=10, no-transform');
2297 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2298 header('Pragma: ');
2299 } else { //normal http - prevent caching at all cost
2300 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2301 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2302 header('Pragma: no-cache');
2306 // Allow cross-origin requests only for Web Services.
2307 // This allow to receive requests done by Web Workers or webapps in different domains.
2308 if (WS_SERVER) {
2309 header('Access-Control-Allow-Origin: *');
2312 if (empty($filter)) {
2313 // send the contents
2314 readfile_accel($stored_file, $mimetype, !$dontdie);
2316 } else { // Try to put the file through filters
2317 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2318 $options = new stdClass();
2319 $options->noclean = true;
2320 $options->nocache = true; // temporary workaround for MDL-5136
2321 $text = $stored_file->get_content();
2322 $text = file_modify_html_header($text);
2323 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2325 readstring_accel($output, $mimetype, false);
2327 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2328 // only filter text if filter all files is selected
2329 $options = new stdClass();
2330 $options->newlines = false;
2331 $options->noclean = true;
2332 $text = $stored_file->get_content();
2333 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2335 readstring_accel($output, $mimetype, false);
2337 } else { // Just send it out raw
2338 readfile_accel($stored_file, $mimetype, !$dontdie);
2341 if ($dontdie) {
2342 return;
2344 die; //no more chars to output!!!
2348 * Retrieves an array of records from a CSV file and places
2349 * them into a given table structure
2351 * @global stdClass $CFG
2352 * @global moodle_database $DB
2353 * @param string $file The path to a CSV file
2354 * @param string $table The table to retrieve columns from
2355 * @return bool|array Returns an array of CSV records or false
2357 function get_records_csv($file, $table) {
2358 global $CFG, $DB;
2360 if (!$metacolumns = $DB->get_columns($table)) {
2361 return false;
2364 if(!($handle = @fopen($file, 'r'))) {
2365 print_error('get_records_csv failed to open '.$file);
2368 $fieldnames = fgetcsv($handle, 4096);
2369 if(empty($fieldnames)) {
2370 fclose($handle);
2371 return false;
2374 $columns = array();
2376 foreach($metacolumns as $metacolumn) {
2377 $ord = array_search($metacolumn->name, $fieldnames);
2378 if(is_int($ord)) {
2379 $columns[$metacolumn->name] = $ord;
2383 $rows = array();
2385 while (($data = fgetcsv($handle, 4096)) !== false) {
2386 $item = new stdClass;
2387 foreach($columns as $name => $ord) {
2388 $item->$name = $data[$ord];
2390 $rows[] = $item;
2393 fclose($handle);
2394 return $rows;
2398 * Create a file with CSV contents
2400 * @global stdClass $CFG
2401 * @global moodle_database $DB
2402 * @param string $file The file to put the CSV content into
2403 * @param array $records An array of records to write to a CSV file
2404 * @param string $table The table to get columns from
2405 * @return bool success
2407 function put_records_csv($file, $records, $table = NULL) {
2408 global $CFG, $DB;
2410 if (empty($records)) {
2411 return true;
2414 $metacolumns = NULL;
2415 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2416 return false;
2419 echo "x";
2421 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2422 print_error('put_records_csv failed to open '.$file);
2425 $proto = reset($records);
2426 if(is_object($proto)) {
2427 $fields_records = array_keys(get_object_vars($proto));
2429 else if(is_array($proto)) {
2430 $fields_records = array_keys($proto);
2432 else {
2433 return false;
2435 echo "x";
2437 if(!empty($metacolumns)) {
2438 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2439 $fields = array_intersect($fields_records, $fields_table);
2441 else {
2442 $fields = $fields_records;
2445 fwrite($fp, implode(',', $fields));
2446 fwrite($fp, "\r\n");
2448 foreach($records as $record) {
2449 $array = (array)$record;
2450 $values = array();
2451 foreach($fields as $field) {
2452 if(strpos($array[$field], ',')) {
2453 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2455 else {
2456 $values[] = $array[$field];
2459 fwrite($fp, implode(',', $values)."\r\n");
2462 fclose($fp);
2463 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
2464 return true;
2469 * Recursively delete the file or folder with path $location. That is,
2470 * if it is a file delete it. If it is a folder, delete all its content
2471 * then delete it. If $location does not exist to start, that is not
2472 * considered an error.
2474 * @param string $location the path to remove.
2475 * @return bool
2477 function fulldelete($location) {
2478 if (empty($location)) {
2479 // extra safety against wrong param
2480 return false;
2482 if (is_dir($location)) {
2483 if (!$currdir = opendir($location)) {
2484 return false;
2486 while (false !== ($file = readdir($currdir))) {
2487 if ($file <> ".." && $file <> ".") {
2488 $fullfile = $location."/".$file;
2489 if (is_dir($fullfile)) {
2490 if (!fulldelete($fullfile)) {
2491 return false;
2493 } else {
2494 if (!unlink($fullfile)) {
2495 return false;
2500 closedir($currdir);
2501 if (! rmdir($location)) {
2502 return false;
2505 } else if (file_exists($location)) {
2506 if (!unlink($location)) {
2507 return false;
2510 return true;
2514 * Send requested byterange of file.
2516 * @param resource $handle A file handle
2517 * @param string $mimetype The mimetype for the output
2518 * @param array $ranges An array of ranges to send
2519 * @param string $filesize The size of the content if only one range is used
2521 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2522 // better turn off any kind of compression and buffering
2523 ini_set('zlib.output_compression', 'Off');
2525 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2526 if ($handle === false) {
2527 die;
2529 if (count($ranges) == 1) { //only one range requested
2530 $length = $ranges[0][2] - $ranges[0][1] + 1;
2531 header('HTTP/1.1 206 Partial content');
2532 header('Content-Length: '.$length);
2533 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2534 header('Content-Type: '.$mimetype);
2536 while(@ob_get_level()) {
2537 if (!@ob_end_flush()) {
2538 break;
2542 fseek($handle, $ranges[0][1]);
2543 while (!feof($handle) && $length > 0) {
2544 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2545 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2546 echo $buffer;
2547 flush();
2548 $length -= strlen($buffer);
2550 fclose($handle);
2551 die;
2552 } else { // multiple ranges requested - not tested much
2553 $totallength = 0;
2554 foreach($ranges as $range) {
2555 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2557 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2558 header('HTTP/1.1 206 Partial content');
2559 header('Content-Length: '.$totallength);
2560 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2562 while(@ob_get_level()) {
2563 if (!@ob_end_flush()) {
2564 break;
2568 foreach($ranges as $range) {
2569 $length = $range[2] - $range[1] + 1;
2570 echo $range[0];
2571 fseek($handle, $range[1]);
2572 while (!feof($handle) && $length > 0) {
2573 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2574 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2575 echo $buffer;
2576 flush();
2577 $length -= strlen($buffer);
2580 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2581 fclose($handle);
2582 die;
2587 * add includes (js and css) into uploaded files
2588 * before returning them, useful for themes and utf.js includes
2590 * @global stdClass $CFG
2591 * @param string $text text to search and replace
2592 * @return string text with added head includes
2593 * @todo MDL-21120
2595 function file_modify_html_header($text) {
2596 // first look for <head> tag
2597 global $CFG;
2599 $stylesheetshtml = '';
2601 foreach ($CFG->stylesheets as $stylesheet) {
2602 //TODO: MDL-21120
2603 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2606 // TODO The code below is actually a waste of CPU. When MDL-29738 will be implemented it should be re-evaluated too.
2608 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2609 if ($matches) {
2610 $replacement = '<head>'.$stylesheetshtml;
2611 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2612 return $text;
2615 // if not, look for <html> tag, and stick <head> right after
2616 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2617 if ($matches) {
2618 // replace <html> tag with <html><head>includes</head>
2619 $replacement = '<html>'."\n".'<head>'.$stylesheetshtml.'</head>';
2620 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2621 return $text;
2624 // if not, look for <body> tag, and stick <head> before body
2625 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2626 if ($matches) {
2627 $replacement = '<head>'.$stylesheetshtml.'</head>'."\n".'<body>';
2628 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2629 return $text;
2632 // if not, just stick a <head> tag at the beginning
2633 $text = '<head>'.$stylesheetshtml.'</head>'."\n".$text;
2634 return $text;
2638 * RESTful cURL class
2640 * This is a wrapper class for curl, it is quite easy to use:
2641 * <code>
2642 * $c = new curl;
2643 * // enable cache
2644 * $c = new curl(array('cache'=>true));
2645 * // enable cookie
2646 * $c = new curl(array('cookie'=>true));
2647 * // enable proxy
2648 * $c = new curl(array('proxy'=>true));
2650 * // HTTP GET Method
2651 * $html = $c->get('http://example.com');
2652 * // HTTP POST Method
2653 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2654 * // HTTP PUT Method
2655 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2656 * </code>
2658 * @package core_files
2659 * @category files
2660 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2661 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2663 class curl {
2664 /** @var bool Caches http request contents */
2665 public $cache = false;
2666 /** @var bool Uses proxy, null means automatic based on URL */
2667 public $proxy = null;
2668 /** @var string library version */
2669 public $version = '0.4 dev';
2670 /** @var array http's response */
2671 public $response = array();
2672 /** @var array Raw response headers, needed for BC in download_file_content(). */
2673 public $rawresponse = array();
2674 /** @var array http header */
2675 public $header = array();
2676 /** @var string cURL information */
2677 public $info;
2678 /** @var string error */
2679 public $error;
2680 /** @var int error code */
2681 public $errno;
2682 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2683 public $emulateredirects = null;
2685 /** @var array cURL options */
2686 private $options;
2688 /** @var string Proxy host */
2689 private $proxy_host = '';
2690 /** @var string Proxy auth */
2691 private $proxy_auth = '';
2692 /** @var string Proxy type */
2693 private $proxy_type = '';
2694 /** @var bool Debug mode on */
2695 private $debug = false;
2696 /** @var bool|string Path to cookie file */
2697 private $cookie = false;
2698 /** @var bool tracks multiple headers in response - redirect detection */
2699 private $responsefinished = false;
2702 * Curl constructor.
2704 * Allowed settings are:
2705 * proxy: (bool) use proxy server, null means autodetect non-local from url
2706 * debug: (bool) use debug output
2707 * cookie: (string) path to cookie file, false if none
2708 * cache: (bool) use cache
2709 * module_cache: (string) type of cache
2711 * @param array $settings
2713 public function __construct($settings = array()) {
2714 global $CFG;
2715 if (!function_exists('curl_init')) {
2716 $this->error = 'cURL module must be enabled!';
2717 trigger_error($this->error, E_USER_ERROR);
2718 return false;
2721 // All settings of this class should be init here.
2722 $this->resetopt();
2723 if (!empty($settings['debug'])) {
2724 $this->debug = true;
2726 if (!empty($settings['cookie'])) {
2727 if($settings['cookie'] === true) {
2728 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2729 } else {
2730 $this->cookie = $settings['cookie'];
2733 if (!empty($settings['cache'])) {
2734 if (class_exists('curl_cache')) {
2735 if (!empty($settings['module_cache'])) {
2736 $this->cache = new curl_cache($settings['module_cache']);
2737 } else {
2738 $this->cache = new curl_cache('misc');
2742 if (!empty($CFG->proxyhost)) {
2743 if (empty($CFG->proxyport)) {
2744 $this->proxy_host = $CFG->proxyhost;
2745 } else {
2746 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2748 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2749 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2750 $this->setopt(array(
2751 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2752 'proxyuserpwd'=>$this->proxy_auth));
2754 if (!empty($CFG->proxytype)) {
2755 if ($CFG->proxytype == 'SOCKS5') {
2756 $this->proxy_type = CURLPROXY_SOCKS5;
2757 } else {
2758 $this->proxy_type = CURLPROXY_HTTP;
2759 $this->setopt(array('httpproxytunnel'=>false));
2761 $this->setopt(array('proxytype'=>$this->proxy_type));
2764 if (isset($settings['proxy'])) {
2765 $this->proxy = $settings['proxy'];
2767 } else {
2768 $this->proxy = false;
2771 if (!isset($this->emulateredirects)) {
2772 $this->emulateredirects = ini_get('open_basedir');
2777 * Resets the CURL options that have already been set
2779 public function resetopt() {
2780 $this->options = array();
2781 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2782 // True to include the header in the output
2783 $this->options['CURLOPT_HEADER'] = 0;
2784 // True to Exclude the body from the output
2785 $this->options['CURLOPT_NOBODY'] = 0;
2786 // Redirect ny default.
2787 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2788 $this->options['CURLOPT_MAXREDIRS'] = 10;
2789 $this->options['CURLOPT_ENCODING'] = '';
2790 // TRUE to return the transfer as a string of the return
2791 // value of curl_exec() instead of outputting it out directly.
2792 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2793 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2794 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2795 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2797 if ($cacert = self::get_cacert()) {
2798 $this->options['CURLOPT_CAINFO'] = $cacert;
2803 * Get the location of ca certificates.
2804 * @return string absolute file path or empty if default used
2806 public static function get_cacert() {
2807 global $CFG;
2809 // Bundle in dataroot always wins.
2810 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2811 return realpath("$CFG->dataroot/moodleorgca.crt");
2814 // Next comes the default from php.ini
2815 $cacert = ini_get('curl.cainfo');
2816 if (!empty($cacert) and is_readable($cacert)) {
2817 return realpath($cacert);
2820 // Windows PHP does not have any certs, we need to use something.
2821 if ($CFG->ostype === 'WINDOWS') {
2822 if (is_readable("$CFG->libdir/cacert.pem")) {
2823 return realpath("$CFG->libdir/cacert.pem");
2827 // Use default, this should work fine on all properly configured *nix systems.
2828 return null;
2832 * Reset Cookie
2834 public function resetcookie() {
2835 if (!empty($this->cookie)) {
2836 if (is_file($this->cookie)) {
2837 $fp = fopen($this->cookie, 'w');
2838 if (!empty($fp)) {
2839 fwrite($fp, '');
2840 fclose($fp);
2847 * Set curl options.
2849 * Do not use the curl constants to define the options, pass a string
2850 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2851 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2853 * @param array $options If array is null, this function will reset the options to default value.
2854 * @return void
2855 * @throws coding_exception If an option uses constant value instead of option name.
2857 public function setopt($options = array()) {
2858 if (is_array($options)) {
2859 foreach ($options as $name => $val) {
2860 if (!is_string($name)) {
2861 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2863 if (stripos($name, 'CURLOPT_') === false) {
2864 $name = strtoupper('CURLOPT_'.$name);
2865 } else {
2866 $name = strtoupper($name);
2868 $this->options[$name] = $val;
2874 * Reset http method
2876 public function cleanopt() {
2877 unset($this->options['CURLOPT_HTTPGET']);
2878 unset($this->options['CURLOPT_POST']);
2879 unset($this->options['CURLOPT_POSTFIELDS']);
2880 unset($this->options['CURLOPT_PUT']);
2881 unset($this->options['CURLOPT_INFILE']);
2882 unset($this->options['CURLOPT_INFILESIZE']);
2883 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2884 unset($this->options['CURLOPT_FILE']);
2888 * Resets the HTTP Request headers (to prepare for the new request)
2890 public function resetHeader() {
2891 $this->header = array();
2895 * Set HTTP Request Header
2897 * @param array $header
2899 public function setHeader($header) {
2900 if (is_array($header)) {
2901 foreach ($header as $v) {
2902 $this->setHeader($v);
2904 } else {
2905 // Remove newlines, they are not allowed in headers.
2906 $this->header[] = preg_replace('/[\r\n]/', '', $header);
2911 * Get HTTP Response Headers
2912 * @return array of arrays
2914 public function getResponse() {
2915 return $this->response;
2919 * Get raw HTTP Response Headers
2920 * @return array of strings
2922 public function get_raw_response() {
2923 return $this->rawresponse;
2927 * private callback function
2928 * Formatting HTTP Response Header
2930 * We only keep the last headers returned. For example during a redirect the
2931 * redirect headers will not appear in {@link self::getResponse()}, if you need
2932 * to use those headers, refer to {@link self::get_raw_response()}.
2934 * @param resource $ch Apparently not used
2935 * @param string $header
2936 * @return int The strlen of the header
2938 private function formatHeader($ch, $header) {
2939 $this->rawresponse[] = $header;
2941 if (trim($header, "\r\n") === '') {
2942 // This must be the last header.
2943 $this->responsefinished = true;
2946 if (strlen($header) > 2) {
2947 if ($this->responsefinished) {
2948 // We still have headers after the supposedly last header, we must be
2949 // in a redirect so let's empty the response to keep the last headers.
2950 $this->responsefinished = false;
2951 $this->response = array();
2953 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2954 $key = rtrim($key, ':');
2955 if (!empty($this->response[$key])) {
2956 if (is_array($this->response[$key])) {
2957 $this->response[$key][] = $value;
2958 } else {
2959 $tmp = $this->response[$key];
2960 $this->response[$key] = array();
2961 $this->response[$key][] = $tmp;
2962 $this->response[$key][] = $value;
2965 } else {
2966 $this->response[$key] = $value;
2969 return strlen($header);
2973 * Set options for individual curl instance
2975 * @param resource $curl A curl handle
2976 * @param array $options
2977 * @return resource The curl handle
2979 private function apply_opt($curl, $options) {
2980 // Clean up
2981 $this->cleanopt();
2982 // set cookie
2983 if (!empty($this->cookie) || !empty($options['cookie'])) {
2984 $this->setopt(array('cookiejar'=>$this->cookie,
2985 'cookiefile'=>$this->cookie
2989 // Bypass proxy if required.
2990 if ($this->proxy === null) {
2991 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
2992 $proxy = false;
2993 } else {
2994 $proxy = true;
2996 } else {
2997 $proxy = (bool)$this->proxy;
3000 // Set proxy.
3001 if ($proxy) {
3002 $options['CURLOPT_PROXY'] = $this->proxy_host;
3003 } else {
3004 unset($this->options['CURLOPT_PROXY']);
3007 $this->setopt($options);
3009 // Reset before set options.
3010 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3012 // Setting the User-Agent based on options provided.
3013 $useragent = '';
3015 if (!empty($options['CURLOPT_USERAGENT'])) {
3016 $useragent = $options['CURLOPT_USERAGENT'];
3017 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3018 $useragent = $this->options['CURLOPT_USERAGENT'];
3019 } else {
3020 $useragent = 'MoodleBot/1.0';
3023 // Set headers.
3024 if (empty($this->header)) {
3025 $this->setHeader(array(
3026 'User-Agent: ' . $useragent,
3027 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3028 'Connection: keep-alive'
3030 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3031 // Remove old User-Agent if one existed.
3032 // We have to partial search since we don't know what the original User-Agent is.
3033 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3034 $key = array_keys($match)[0];
3035 unset($this->header[$key]);
3037 $this->setHeader(array('User-Agent: ' . $useragent));
3039 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3041 if ($this->debug) {
3042 echo '<h1>Options</h1>';
3043 var_dump($this->options);
3044 echo '<h1>Header</h1>';
3045 var_dump($this->header);
3048 // Do not allow infinite redirects.
3049 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3050 $this->options['CURLOPT_MAXREDIRS'] = 0;
3051 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3052 $this->options['CURLOPT_MAXREDIRS'] = 100;
3053 } else {
3054 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3057 // Make sure we always know if redirects expected.
3058 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3059 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3062 // Limit the protocols to HTTP and HTTPS.
3063 if (defined('CURLOPT_PROTOCOLS')) {
3064 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3065 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3068 // Set options.
3069 foreach($this->options as $name => $val) {
3070 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3071 // The redirects are emulated elsewhere.
3072 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3073 continue;
3075 $name = constant($name);
3076 curl_setopt($curl, $name, $val);
3079 return $curl;
3083 * Download multiple files in parallel
3085 * Calls {@link multi()} with specific download headers
3087 * <code>
3088 * $c = new curl();
3089 * $file1 = fopen('a', 'wb');
3090 * $file2 = fopen('b', 'wb');
3091 * $c->download(array(
3092 * array('url'=>'http://localhost/', 'file'=>$file1),
3093 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3094 * ));
3095 * fclose($file1);
3096 * fclose($file2);
3097 * </code>
3099 * or
3101 * <code>
3102 * $c = new curl();
3103 * $c->download(array(
3104 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3105 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3106 * ));
3107 * </code>
3109 * @param array $requests An array of files to request {
3110 * url => url to download the file [required]
3111 * file => file handler, or
3112 * filepath => file path
3114 * If 'file' and 'filepath' parameters are both specified in one request, the
3115 * open file handle in the 'file' parameter will take precedence and 'filepath'
3116 * will be ignored.
3118 * @param array $options An array of options to set
3119 * @return array An array of results
3121 public function download($requests, $options = array()) {
3122 $options['RETURNTRANSFER'] = false;
3123 return $this->multi($requests, $options);
3127 * Multi HTTP Requests
3128 * This function could run multi-requests in parallel.
3130 * @param array $requests An array of files to request
3131 * @param array $options An array of options to set
3132 * @return array An array of results
3134 protected function multi($requests, $options = array()) {
3135 $count = count($requests);
3136 $handles = array();
3137 $results = array();
3138 $main = curl_multi_init();
3139 for ($i = 0; $i < $count; $i++) {
3140 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3141 // open file
3142 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3143 $requests[$i]['auto-handle'] = true;
3145 foreach($requests[$i] as $n=>$v) {
3146 $options[$n] = $v;
3148 $handles[$i] = curl_init($requests[$i]['url']);
3149 $this->apply_opt($handles[$i], $options);
3150 curl_multi_add_handle($main, $handles[$i]);
3152 $running = 0;
3153 do {
3154 curl_multi_exec($main, $running);
3155 } while($running > 0);
3156 for ($i = 0; $i < $count; $i++) {
3157 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3158 $results[] = true;
3159 } else {
3160 $results[] = curl_multi_getcontent($handles[$i]);
3162 curl_multi_remove_handle($main, $handles[$i]);
3164 curl_multi_close($main);
3166 for ($i = 0; $i < $count; $i++) {
3167 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3168 // close file handler if file is opened in this function
3169 fclose($requests[$i]['file']);
3172 return $results;
3176 * Single HTTP Request
3178 * @param string $url The URL to request
3179 * @param array $options
3180 * @return bool
3182 protected function request($url, $options = array()) {
3183 // Set the URL as a curl option.
3184 $this->setopt(array('CURLOPT_URL' => $url));
3186 // Create curl instance.
3187 $curl = curl_init();
3189 // Reset here so that the data is valid when result returned from cache.
3190 $this->info = array();
3191 $this->error = '';
3192 $this->errno = 0;
3193 $this->response = array();
3194 $this->rawresponse = array();
3195 $this->responsefinished = false;
3197 $this->apply_opt($curl, $options);
3198 if ($this->cache && $ret = $this->cache->get($this->options)) {
3199 return $ret;
3202 $ret = curl_exec($curl);
3203 $this->info = curl_getinfo($curl);
3204 $this->error = curl_error($curl);
3205 $this->errno = curl_errno($curl);
3206 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3208 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3209 $redirects = 0;
3211 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3213 if ($this->info['http_code'] == 301) {
3214 // Moved Permanently - repeat the same request on new URL.
3216 } else if ($this->info['http_code'] == 302) {
3217 // Found - the standard redirect - repeat the same request on new URL.
3219 } else if ($this->info['http_code'] == 303) {
3220 // 303 See Other - repeat only if GET, do not bother with POSTs.
3221 if (empty($this->options['CURLOPT_HTTPGET'])) {
3222 break;
3225 } else if ($this->info['http_code'] == 307) {
3226 // Temporary Redirect - must repeat using the same request type.
3228 } else if ($this->info['http_code'] == 308) {
3229 // Permanent Redirect - must repeat using the same request type.
3231 } else {
3232 // Some other http code means do not retry!
3233 break;
3236 $redirects++;
3238 $redirecturl = null;
3239 if (isset($this->info['redirect_url'])) {
3240 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3241 $redirecturl = $this->info['redirect_url'];
3244 if (!$redirecturl) {
3245 foreach ($this->response as $k => $v) {
3246 if (strtolower($k) === 'location') {
3247 $redirecturl = $v;
3248 break;
3251 if (preg_match('|^https?://|i', $redirecturl)) {
3252 // Great, this is the correct location format!
3254 } else if ($redirecturl) {
3255 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3256 if (strpos($redirecturl, '/') === 0) {
3257 // Relative to server root - just guess.
3258 $pos = strpos('/', $current, 8);
3259 if ($pos === false) {
3260 $redirecturl = $current.$redirecturl;
3261 } else {
3262 $redirecturl = substr($current, 0, $pos).$redirecturl;
3264 } else {
3265 // Relative to current script.
3266 $redirecturl = dirname($current).'/'.$redirecturl;
3271 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3272 $ret = curl_exec($curl);
3274 $this->info = curl_getinfo($curl);
3275 $this->error = curl_error($curl);
3276 $this->errno = curl_errno($curl);
3278 $this->info['redirect_count'] = $redirects;
3280 if ($this->info['http_code'] === 200) {
3281 // Finally this is what we wanted.
3282 break;
3284 if ($this->errno != CURLE_OK) {
3285 // Something wrong is going on.
3286 break;
3289 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3290 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3291 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3295 if ($this->cache) {
3296 $this->cache->set($this->options, $ret);
3299 if ($this->debug) {
3300 echo '<h1>Return Data</h1>';
3301 var_dump($ret);
3302 echo '<h1>Info</h1>';
3303 var_dump($this->info);
3304 echo '<h1>Error</h1>';
3305 var_dump($this->error);
3308 curl_close($curl);
3310 if (empty($this->error)) {
3311 return $ret;
3312 } else {
3313 return $this->error;
3314 // exception is not ajax friendly
3315 //throw new moodle_exception($this->error, 'curl');
3320 * HTTP HEAD method
3322 * @see request()
3324 * @param string $url
3325 * @param array $options
3326 * @return bool
3328 public function head($url, $options = array()) {
3329 $options['CURLOPT_HTTPGET'] = 0;
3330 $options['CURLOPT_HEADER'] = 1;
3331 $options['CURLOPT_NOBODY'] = 1;
3332 return $this->request($url, $options);
3336 * HTTP POST method
3338 * @param string $url
3339 * @param array|string $params
3340 * @param array $options
3341 * @return bool
3343 public function post($url, $params = '', $options = array()) {
3344 $options['CURLOPT_POST'] = 1;
3345 if (is_array($params)) {
3346 $this->_tmp_file_post_params = array();
3347 foreach ($params as $key => $value) {
3348 if ($value instanceof stored_file) {
3349 $value->add_to_curl_request($this, $key);
3350 } else {
3351 $this->_tmp_file_post_params[$key] = $value;
3354 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3355 unset($this->_tmp_file_post_params);
3356 } else {
3357 // $params is the raw post data
3358 $options['CURLOPT_POSTFIELDS'] = $params;
3360 return $this->request($url, $options);
3364 * HTTP GET method
3366 * @param string $url
3367 * @param array $params
3368 * @param array $options
3369 * @return bool
3371 public function get($url, $params = array(), $options = array()) {
3372 $options['CURLOPT_HTTPGET'] = 1;
3374 if (!empty($params)) {
3375 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3376 $url .= http_build_query($params, '', '&');
3378 return $this->request($url, $options);
3382 * Downloads one file and writes it to the specified file handler
3384 * <code>
3385 * $c = new curl();
3386 * $file = fopen('savepath', 'w');
3387 * $result = $c->download_one('http://localhost/', null,
3388 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3389 * fclose($file);
3390 * $download_info = $c->get_info();
3391 * if ($result === true) {
3392 * // file downloaded successfully
3393 * } else {
3394 * $error_text = $result;
3395 * $error_code = $c->get_errno();
3397 * </code>
3399 * <code>
3400 * $c = new curl();
3401 * $result = $c->download_one('http://localhost/', null,
3402 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3403 * // ... see above, no need to close handle and remove file if unsuccessful
3404 * </code>
3406 * @param string $url
3407 * @param array|null $params key-value pairs to be added to $url as query string
3408 * @param array $options request options. Must include either 'file' or 'filepath'
3409 * @return bool|string true on success or error string on failure
3411 public function download_one($url, $params, $options = array()) {
3412 $options['CURLOPT_HTTPGET'] = 1;
3413 if (!empty($params)) {
3414 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3415 $url .= http_build_query($params, '', '&');
3417 if (!empty($options['filepath']) && empty($options['file'])) {
3418 // open file
3419 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3420 $this->errno = 100;
3421 return get_string('cannotwritefile', 'error', $options['filepath']);
3423 $filepath = $options['filepath'];
3425 unset($options['filepath']);
3426 $result = $this->request($url, $options);
3427 if (isset($filepath)) {
3428 fclose($options['file']);
3429 if ($result !== true) {
3430 unlink($filepath);
3433 return $result;
3437 * HTTP PUT method
3439 * @param string $url
3440 * @param array $params
3441 * @param array $options
3442 * @return bool
3444 public function put($url, $params = array(), $options = array()) {
3445 $file = $params['file'];
3446 if (!is_file($file)) {
3447 return null;
3449 $fp = fopen($file, 'r');
3450 $size = filesize($file);
3451 $options['CURLOPT_PUT'] = 1;
3452 $options['CURLOPT_INFILESIZE'] = $size;
3453 $options['CURLOPT_INFILE'] = $fp;
3454 if (!isset($this->options['CURLOPT_USERPWD'])) {
3455 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
3457 $ret = $this->request($url, $options);
3458 fclose($fp);
3459 return $ret;
3463 * HTTP DELETE method
3465 * @param string $url
3466 * @param array $param
3467 * @param array $options
3468 * @return bool
3470 public function delete($url, $param = array(), $options = array()) {
3471 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
3472 if (!isset($options['CURLOPT_USERPWD'])) {
3473 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
3475 $ret = $this->request($url, $options);
3476 return $ret;
3480 * HTTP TRACE method
3482 * @param string $url
3483 * @param array $options
3484 * @return bool
3486 public function trace($url, $options = array()) {
3487 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
3488 $ret = $this->request($url, $options);
3489 return $ret;
3493 * HTTP OPTIONS method
3495 * @param string $url
3496 * @param array $options
3497 * @return bool
3499 public function options($url, $options = array()) {
3500 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
3501 $ret = $this->request($url, $options);
3502 return $ret;
3506 * Get curl information
3508 * @return string
3510 public function get_info() {
3511 return $this->info;
3515 * Get curl error code
3517 * @return int
3519 public function get_errno() {
3520 return $this->errno;
3524 * When using a proxy, an additional HTTP response code may appear at
3525 * the start of the header. For example, when using https over a proxy
3526 * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
3527 * also possible and some may come with their own headers.
3529 * If using the return value containing all headers, this function can be
3530 * called to remove unwanted doubles.
3532 * Note that it is not possible to distinguish this situation from valid
3533 * data unless you know the actual response part (below the headers)
3534 * will not be included in this string, or else will not 'look like' HTTP
3535 * headers. As a result it is not safe to call this function for general
3536 * data.
3538 * @param string $input Input HTTP response
3539 * @return string HTTP response with additional headers stripped if any
3541 public static function strip_double_headers($input) {
3542 // I have tried to make this regular expression as specific as possible
3543 // to avoid any case where it does weird stuff if you happen to put
3544 // HTTP/1.1 200 at the start of any line in your RSS file. This should
3545 // also make it faster because it can abandon regex processing as soon
3546 // as it hits something that doesn't look like an http header. The
3547 // header definition is taken from RFC 822, except I didn't support
3548 // folding which is never used in practice.
3549 $crlf = "\r\n";
3550 return preg_replace(
3551 // HTTP version and status code (ignore value of code).
3552 '~^HTTP/1\..*' . $crlf .
3553 // Header name: character between 33 and 126 decimal, except colon.
3554 // Colon. Header value: any character except \r and \n. CRLF.
3555 '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
3556 // Headers are terminated by another CRLF (blank line).
3557 $crlf .
3558 // Second HTTP status code, this time must be 200.
3559 '(HTTP/1.[01] 200 )~', '$1', $input);
3564 * This class is used by cURL class, use case:
3566 * <code>
3567 * $CFG->repositorycacheexpire = 120;
3568 * $CFG->curlcache = 120;
3570 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
3571 * $ret = $c->get('http://www.google.com');
3572 * </code>
3574 * @package core_files
3575 * @copyright Dongsheng Cai <dongsheng@moodle.com>
3576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3578 class curl_cache {
3579 /** @var string Path to cache directory */
3580 public $dir = '';
3583 * Constructor
3585 * @global stdClass $CFG
3586 * @param string $module which module is using curl_cache
3588 public function __construct($module = 'repository') {
3589 global $CFG;
3590 if (!empty($module)) {
3591 $this->dir = $CFG->cachedir.'/'.$module.'/';
3592 } else {
3593 $this->dir = $CFG->cachedir.'/misc/';
3595 if (!file_exists($this->dir)) {
3596 mkdir($this->dir, $CFG->directorypermissions, true);
3598 if ($module == 'repository') {
3599 if (empty($CFG->repositorycacheexpire)) {
3600 $CFG->repositorycacheexpire = 120;
3602 $this->ttl = $CFG->repositorycacheexpire;
3603 } else {
3604 if (empty($CFG->curlcache)) {
3605 $CFG->curlcache = 120;
3607 $this->ttl = $CFG->curlcache;
3612 * Get cached value
3614 * @global stdClass $CFG
3615 * @global stdClass $USER
3616 * @param mixed $param
3617 * @return bool|string
3619 public function get($param) {
3620 global $CFG, $USER;
3621 $this->cleanup($this->ttl);
3622 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3623 if(file_exists($this->dir.$filename)) {
3624 $lasttime = filemtime($this->dir.$filename);
3625 if (time()-$lasttime > $this->ttl) {
3626 return false;
3627 } else {
3628 $fp = fopen($this->dir.$filename, 'r');
3629 $size = filesize($this->dir.$filename);
3630 $content = fread($fp, $size);
3631 return unserialize($content);
3634 return false;
3638 * Set cache value
3640 * @global object $CFG
3641 * @global object $USER
3642 * @param mixed $param
3643 * @param mixed $val
3645 public function set($param, $val) {
3646 global $CFG, $USER;
3647 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3648 $fp = fopen($this->dir.$filename, 'w');
3649 fwrite($fp, serialize($val));
3650 fclose($fp);
3651 @chmod($this->dir.$filename, $CFG->filepermissions);
3655 * Remove cache files
3657 * @param int $expire The number of seconds before expiry
3659 public function cleanup($expire) {
3660 if ($dir = opendir($this->dir)) {
3661 while (false !== ($file = readdir($dir))) {
3662 if(!is_dir($file) && $file != '.' && $file != '..') {
3663 $lasttime = @filemtime($this->dir.$file);
3664 if (time() - $lasttime > $expire) {
3665 @unlink($this->dir.$file);
3669 closedir($dir);
3673 * delete current user's cache file
3675 * @global object $CFG
3676 * @global object $USER
3678 public function refresh() {
3679 global $CFG, $USER;
3680 if ($dir = opendir($this->dir)) {
3681 while (false !== ($file = readdir($dir))) {
3682 if (!is_dir($file) && $file != '.' && $file != '..') {
3683 if (strpos($file, 'u'.$USER->id.'_') !== false) {
3684 @unlink($this->dir.$file);
3693 * This function delegates file serving to individual plugins
3695 * @param string $relativepath
3696 * @param bool $forcedownload
3697 * @param null|string $preview the preview mode, defaults to serving the original file
3698 * @todo MDL-31088 file serving improments
3700 function file_pluginfile($relativepath, $forcedownload, $preview = null) {
3701 global $DB, $CFG, $USER;
3702 // relative path must start with '/'
3703 if (!$relativepath) {
3704 print_error('invalidargorconf');
3705 } else if ($relativepath[0] != '/') {
3706 print_error('pathdoesnotstartslash');
3709 // extract relative path components
3710 $args = explode('/', ltrim($relativepath, '/'));
3712 if (count($args) < 3) { // always at least context, component and filearea
3713 print_error('invalidarguments');
3716 $contextid = (int)array_shift($args);
3717 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3718 $filearea = clean_param(array_shift($args), PARAM_AREA);
3720 list($context, $course, $cm) = get_context_info_array($contextid);
3722 $fs = get_file_storage();
3724 // ========================================================================================================================
3725 if ($component === 'blog') {
3726 // Blog file serving
3727 if ($context->contextlevel != CONTEXT_SYSTEM) {
3728 send_file_not_found();
3730 if ($filearea !== 'attachment' and $filearea !== 'post') {
3731 send_file_not_found();
3734 if (empty($CFG->enableblogs)) {
3735 print_error('siteblogdisable', 'blog');
3738 $entryid = (int)array_shift($args);
3739 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3740 send_file_not_found();
3742 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3743 require_login();
3744 if (isguestuser()) {
3745 print_error('noguest');
3747 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3748 if ($USER->id != $entry->userid) {
3749 send_file_not_found();
3754 if ($entry->publishstate === 'public') {
3755 if ($CFG->forcelogin) {
3756 require_login();
3759 } else if ($entry->publishstate === 'site') {
3760 require_login();
3761 //ok
3762 } else if ($entry->publishstate === 'draft') {
3763 require_login();
3764 if ($USER->id != $entry->userid) {
3765 send_file_not_found();
3769 $filename = array_pop($args);
3770 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3772 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3773 send_file_not_found();
3776 send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
3778 // ========================================================================================================================
3779 } else if ($component === 'grade') {
3780 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3781 // Global gradebook files
3782 if ($CFG->forcelogin) {
3783 require_login();
3786 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3788 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3789 send_file_not_found();
3792 \core\session\manager::write_close(); // Unlock session during file serving.
3793 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3795 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3796 //TODO: nobody implemented this yet in grade edit form!!
3797 send_file_not_found();
3799 if ($CFG->forcelogin || $course->id != SITEID) {
3800 require_login($course);
3803 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3805 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3806 send_file_not_found();
3809 \core\session\manager::write_close(); // Unlock session during file serving.
3810 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3811 } else {
3812 send_file_not_found();
3815 // ========================================================================================================================
3816 } else if ($component === 'tag') {
3817 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3819 // All tag descriptions are going to be public but we still need to respect forcelogin
3820 if ($CFG->forcelogin) {
3821 require_login();
3824 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3826 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3827 send_file_not_found();
3830 \core\session\manager::write_close(); // Unlock session during file serving.
3831 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3833 } else {
3834 send_file_not_found();
3836 // ========================================================================================================================
3837 } else if ($component === 'badges') {
3838 require_once($CFG->libdir . '/badgeslib.php');
3840 $badgeid = (int)array_shift($args);
3841 $badge = new badge($badgeid);
3842 $filename = array_pop($args);
3844 if ($filearea === 'badgeimage') {
3845 if ($filename !== 'f1' && $filename !== 'f2') {
3846 send_file_not_found();
3848 if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
3849 send_file_not_found();
3852 \core\session\manager::write_close();
3853 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3854 } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
3855 if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
3856 send_file_not_found();
3859 \core\session\manager::write_close();
3860 send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
3862 // ========================================================================================================================
3863 } else if ($component === 'calendar') {
3864 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3866 // All events here are public the one requirement is that we respect forcelogin
3867 if ($CFG->forcelogin) {
3868 require_login();
3871 // Get the event if from the args array
3872 $eventid = array_shift($args);
3874 // Load the event from the database
3875 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3876 send_file_not_found();
3879 // Get the file and serve if successful
3880 $filename = array_pop($args);
3881 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3882 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3883 send_file_not_found();
3886 \core\session\manager::write_close(); // Unlock session during file serving.
3887 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3889 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3891 // Must be logged in, if they are not then they obviously can't be this user
3892 require_login();
3894 // Don't want guests here, potentially saves a DB call
3895 if (isguestuser()) {
3896 send_file_not_found();
3899 // Get the event if from the args array
3900 $eventid = array_shift($args);
3902 // Load the event from the database - user id must match
3903 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3904 send_file_not_found();
3907 // Get the file and serve if successful
3908 $filename = array_pop($args);
3909 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3910 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3911 send_file_not_found();
3914 \core\session\manager::write_close(); // Unlock session during file serving.
3915 send_stored_file($file, 0, 0, true, array('preview' => $preview));
3917 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3919 // Respect forcelogin and require login unless this is the site.... it probably
3920 // should NEVER be the site
3921 if ($CFG->forcelogin || $course->id != SITEID) {
3922 require_login($course);
3925 // Must be able to at least view the course. This does not apply to the front page.
3926 if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
3927 //TODO: hmm, do we really want to block guests here?
3928 send_file_not_found();
3931 // Get the event id
3932 $eventid = array_shift($args);
3934 // Load the event from the database we need to check whether it is
3935 // a) valid course event
3936 // b) a group event
3937 // Group events use the course context (there is no group context)
3938 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3939 send_file_not_found();
3942 // If its a group event require either membership of view all groups capability
3943 if ($event->eventtype === 'group') {
3944 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3945 send_file_not_found();
3947 } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
3948 // Ok. Please note that the event type 'site' still uses a course context.
3949 } else {
3950 // Some other type.
3951 send_file_not_found();
3954 // If we get this far we can serve the file
3955 $filename = array_pop($args);
3956 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3957 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3958 send_file_not_found();
3961 \core\session\manager::write_close(); // Unlock session during file serving.
3962 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
3964 } else {
3965 send_file_not_found();
3968 // ========================================================================================================================
3969 } else if ($component === 'user') {
3970 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3971 if (count($args) == 1) {
3972 $themename = theme_config::DEFAULT_THEME;
3973 $filename = array_shift($args);
3974 } else {
3975 $themename = array_shift($args);
3976 $filename = array_shift($args);
3979 // fix file name automatically
3980 if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
3981 $filename = 'f1';
3984 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3985 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3986 // protect images if login required and not logged in;
3987 // also if login is required for profile images and is not logged in or guest
3988 // do not use require_login() because it is expensive and not suitable here anyway
3989 $theme = theme_config::load($themename);
3990 redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
3993 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
3994 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
3995 if ($filename === 'f3') {
3996 // f3 512x512px was introduced in 2.3, there might be only the smaller version.
3997 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
3998 $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4003 if (!$file) {
4004 // bad reference - try to prevent future retries as hard as possible!
4005 if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4006 if ($user->picture > 0) {
4007 $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4010 // no redirect here because it is not cached
4011 $theme = theme_config::load($themename);
4012 $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4013 send_file($imagefile, basename($imagefile), 60*60*24*14);
4016 $options = array('preview' => $preview);
4017 if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4018 // Profile images should be cache-able by both browsers and proxies according
4019 // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4020 $options['cacheability'] = 'public';
4022 send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4024 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4025 require_login();
4027 if (isguestuser()) {
4028 send_file_not_found();
4031 if ($USER->id !== $context->instanceid) {
4032 send_file_not_found();
4035 $filename = array_pop($args);
4036 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4037 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4038 send_file_not_found();
4041 \core\session\manager::write_close(); // Unlock session during file serving.
4042 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4044 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4046 if ($CFG->forcelogin) {
4047 require_login();
4050 $userid = $context->instanceid;
4052 if ($USER->id == $userid) {
4053 // always can access own
4055 } else if (!empty($CFG->forceloginforprofiles)) {
4056 require_login();
4058 if (isguestuser()) {
4059 send_file_not_found();
4062 // we allow access to site profile of all course contacts (usually teachers)
4063 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4064 send_file_not_found();
4067 $canview = false;
4068 if (has_capability('moodle/user:viewdetails', $context)) {
4069 $canview = true;
4070 } else {
4071 $courses = enrol_get_my_courses();
4074 while (!$canview && count($courses) > 0) {
4075 $course = array_shift($courses);
4076 if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4077 $canview = true;
4082 $filename = array_pop($args);
4083 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4084 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4085 send_file_not_found();
4088 \core\session\manager::write_close(); // Unlock session during file serving.
4089 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4091 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4092 $userid = (int)array_shift($args);
4093 $usercontext = context_user::instance($userid);
4095 if ($CFG->forcelogin) {
4096 require_login();
4099 if (!empty($CFG->forceloginforprofiles)) {
4100 require_login();
4101 if (isguestuser()) {
4102 print_error('noguest');
4105 //TODO: review this logic of user profile access prevention
4106 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4107 print_error('usernotavailable');
4109 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4110 print_error('cannotviewprofile');
4112 if (!is_enrolled($context, $userid)) {
4113 print_error('notenrolledprofile');
4115 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4116 print_error('groupnotamember');
4120 $filename = array_pop($args);
4121 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4122 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4123 send_file_not_found();
4126 \core\session\manager::write_close(); // Unlock session during file serving.
4127 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4129 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4130 require_login();
4132 if (isguestuser()) {
4133 send_file_not_found();
4135 $userid = $context->instanceid;
4137 if ($USER->id != $userid) {
4138 send_file_not_found();
4141 $filename = array_pop($args);
4142 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4143 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4144 send_file_not_found();
4147 \core\session\manager::write_close(); // Unlock session during file serving.
4148 send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
4150 } else {
4151 send_file_not_found();
4154 // ========================================================================================================================
4155 } else if ($component === 'coursecat') {
4156 if ($context->contextlevel != CONTEXT_COURSECAT) {
4157 send_file_not_found();
4160 if ($filearea === 'description') {
4161 if ($CFG->forcelogin) {
4162 // no login necessary - unless login forced everywhere
4163 require_login();
4166 $filename = array_pop($args);
4167 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4168 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4169 send_file_not_found();
4172 \core\session\manager::write_close(); // Unlock session during file serving.
4173 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4174 } else {
4175 send_file_not_found();
4178 // ========================================================================================================================
4179 } else if ($component === 'course') {
4180 if ($context->contextlevel != CONTEXT_COURSE) {
4181 send_file_not_found();
4184 if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4185 if ($CFG->forcelogin) {
4186 require_login();
4189 $filename = array_pop($args);
4190 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4191 if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4192 send_file_not_found();
4195 \core\session\manager::write_close(); // Unlock session during file serving.
4196 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4198 } else if ($filearea === 'section') {
4199 if ($CFG->forcelogin) {
4200 require_login($course);
4201 } else if ($course->id != SITEID) {
4202 require_login($course);
4205 $sectionid = (int)array_shift($args);
4207 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4208 send_file_not_found();
4211 $filename = array_pop($args);
4212 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4213 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4214 send_file_not_found();
4217 \core\session\manager::write_close(); // Unlock session during file serving.
4218 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4220 } else {
4221 send_file_not_found();
4224 } else if ($component === 'cohort') {
4226 $cohortid = (int)array_shift($args);
4227 $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4228 $cohortcontext = context::instance_by_id($cohort->contextid);
4230 // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4231 if ($context->id != $cohort->contextid &&
4232 ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4233 send_file_not_found();
4236 // User is able to access cohort if they have view cap on cohort level or
4237 // the cohort is visible and they have view cap on course level.
4238 $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4239 ($cohort->visible && has_capability('moodle/cohort:view', $context));
4241 if ($filearea === 'description' && $canview) {
4242 $filename = array_pop($args);
4243 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4244 if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4245 && !$file->is_directory()) {
4246 \core\session\manager::write_close(); // Unlock session during file serving.
4247 send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
4251 send_file_not_found();
4253 } else if ($component === 'group') {
4254 if ($context->contextlevel != CONTEXT_COURSE) {
4255 send_file_not_found();
4258 require_course_login($course, true, null, false);
4260 $groupid = (int)array_shift($args);
4262 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4263 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4264 // do not allow access to separate group info if not member or teacher
4265 send_file_not_found();
4268 if ($filearea === 'description') {
4270 require_login($course);
4272 $filename = array_pop($args);
4273 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4274 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4275 send_file_not_found();
4278 \core\session\manager::write_close(); // Unlock session during file serving.
4279 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4281 } else if ($filearea === 'icon') {
4282 $filename = array_pop($args);
4284 if ($filename !== 'f1' and $filename !== 'f2') {
4285 send_file_not_found();
4287 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4288 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4289 send_file_not_found();
4293 \core\session\manager::write_close(); // Unlock session during file serving.
4294 send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
4296 } else {
4297 send_file_not_found();
4300 } else if ($component === 'grouping') {
4301 if ($context->contextlevel != CONTEXT_COURSE) {
4302 send_file_not_found();
4305 require_login($course);
4307 $groupingid = (int)array_shift($args);
4309 // note: everybody has access to grouping desc images for now
4310 if ($filearea === 'description') {
4312 $filename = array_pop($args);
4313 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4314 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4315 send_file_not_found();
4318 \core\session\manager::write_close(); // Unlock session during file serving.
4319 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4321 } else {
4322 send_file_not_found();
4325 // ========================================================================================================================
4326 } else if ($component === 'backup') {
4327 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4328 require_login($course);
4329 require_capability('moodle/backup:downloadfile', $context);
4331 $filename = array_pop($args);
4332 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4333 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4334 send_file_not_found();
4337 \core\session\manager::write_close(); // Unlock session during file serving.
4338 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4340 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4341 require_login($course);
4342 require_capability('moodle/backup:downloadfile', $context);
4344 $sectionid = (int)array_shift($args);
4346 $filename = array_pop($args);
4347 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4348 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4349 send_file_not_found();
4352 \core\session\manager::write_close();
4353 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4355 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4356 require_login($course, false, $cm);
4357 require_capability('moodle/backup:downloadfile', $context);
4359 $filename = array_pop($args);
4360 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4361 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4362 send_file_not_found();
4365 \core\session\manager::write_close();
4366 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4368 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4369 // Backup files that were generated by the automated backup systems.
4371 require_login($course);
4372 require_capability('moodle/site:config', $context);
4374 $filename = array_pop($args);
4375 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4376 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4377 send_file_not_found();
4380 \core\session\manager::write_close(); // Unlock session during file serving.
4381 send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
4383 } else {
4384 send_file_not_found();
4387 // ========================================================================================================================
4388 } else if ($component === 'question') {
4389 require_once($CFG->libdir . '/questionlib.php');
4390 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
4391 send_file_not_found();
4393 // ========================================================================================================================
4394 } else if ($component === 'grading') {
4395 if ($filearea === 'description') {
4396 // files embedded into the form definition description
4398 if ($context->contextlevel == CONTEXT_SYSTEM) {
4399 require_login();
4401 } else if ($context->contextlevel >= CONTEXT_COURSE) {
4402 require_login($course, false, $cm);
4404 } else {
4405 send_file_not_found();
4408 $formid = (int)array_shift($args);
4410 $sql = "SELECT ga.id
4411 FROM {grading_areas} ga
4412 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4413 WHERE gd.id = ? AND ga.contextid = ?";
4414 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4416 if (!$areaid) {
4417 send_file_not_found();
4420 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4422 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4423 send_file_not_found();
4426 \core\session\manager::write_close(); // Unlock session during file serving.
4427 send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
4430 // ========================================================================================================================
4431 } else if (strpos($component, 'mod_') === 0) {
4432 $modname = substr($component, 4);
4433 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
4434 send_file_not_found();
4436 require_once("$CFG->dirroot/mod/$modname/lib.php");
4438 if ($context->contextlevel == CONTEXT_MODULE) {
4439 if ($cm->modname !== $modname) {
4440 // somebody tries to gain illegal access, cm type must match the component!
4441 send_file_not_found();
4445 if ($filearea === 'intro') {
4446 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
4447 send_file_not_found();
4449 require_course_login($course, true, $cm);
4451 // all users may access it
4452 $filename = array_pop($args);
4453 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4454 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
4455 send_file_not_found();
4458 // finally send the file
4459 send_stored_file($file, null, 0, false, array('preview' => $preview));
4462 $filefunction = $component.'_pluginfile';
4463 $filefunctionold = $modname.'_pluginfile';
4464 if (function_exists($filefunction)) {
4465 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4466 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4467 } else if (function_exists($filefunctionold)) {
4468 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4469 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4472 send_file_not_found();
4474 // ========================================================================================================================
4475 } else if (strpos($component, 'block_') === 0) {
4476 $blockname = substr($component, 6);
4477 // note: no more class methods in blocks please, that is ....
4478 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
4479 send_file_not_found();
4481 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
4483 if ($context->contextlevel == CONTEXT_BLOCK) {
4484 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
4485 if ($birecord->blockname !== $blockname) {
4486 // somebody tries to gain illegal access, cm type must match the component!
4487 send_file_not_found();
4490 $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
4491 // User can't access file, if block is hidden or doesn't have block:view capability
4492 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
4493 send_file_not_found();
4495 } else {
4496 $birecord = null;
4499 $filefunction = $component.'_pluginfile';
4500 if (function_exists($filefunction)) {
4501 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4502 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4505 send_file_not_found();
4507 // ========================================================================================================================
4508 } else if (strpos($component, '_') === false) {
4509 // all core subsystems have to be specified above, no more guessing here!
4510 send_file_not_found();
4512 } else {
4513 // try to serve general plugin file in arbitrary context
4514 $dir = core_component::get_component_directory($component);
4515 if (!file_exists("$dir/lib.php")) {
4516 send_file_not_found();
4518 include_once("$dir/lib.php");
4520 $filefunction = $component.'_pluginfile';
4521 if (function_exists($filefunction)) {
4522 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
4523 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
4526 send_file_not_found();