Merge branch 'm22_MDL-33053_AICC_flattened_TOC' of git://github.com/scara/moodle...
[moodle.git] / lib / filelib.php
blob92565f988ea1b5937b8f1d1b75a9042ac633b588
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions for file handling.
21 * @package core
22 * @subpackage file
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** @var string unique string constant. */
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @global object
43 * @param string $urlbase
44 * @param string $path /filearea/itemid/dir/dir/file.exe
45 * @param bool $forcedownload
46 * @param bool $https https url required
47 * @return string encoded file url
49 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
50 global $CFG;
52 //TODO: deprecate this
54 if ($CFG->slasharguments) {
55 $parts = explode('/', $path);
56 $parts = array_map('rawurlencode', $parts);
57 $path = implode('/', $parts);
58 $return = $urlbase.$path;
59 if ($forcedownload) {
60 $return .= '?forcedownload=1';
62 } else {
63 $path = rawurlencode($path);
64 $return = $urlbase.'?file='.$path;
65 if ($forcedownload) {
66 $return .= '&amp;forcedownload=1';
70 if ($https) {
71 $return = str_replace('http://', 'https://', $return);
74 return $return;
77 /**
78 * Prepares 'editor' formslib element from data in database
80 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
81 * function then copies the embedded files into draft area (assigning itemids automatically),
82 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
83 * displayed.
84 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
85 * your mform's set_data() supplying the object returned by this function.
87 * @param object $data database field that holds the html text with embedded media
88 * @param string $field the name of the database field that holds the html text with embedded media
89 * @param array $options editor options (like maxifiles, maxbytes etc.)
90 * @param object $context context of the editor
91 * @param string $component
92 * @param string $filearea file area name
93 * @param int $itemid item id, required if item exists
94 * @return object modified data object
96 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
97 $options = (array)$options;
98 if (!isset($options['trusttext'])) {
99 $options['trusttext'] = false;
101 if (!isset($options['forcehttps'])) {
102 $options['forcehttps'] = false;
104 if (!isset($options['subdirs'])) {
105 $options['subdirs'] = false;
107 if (!isset($options['maxfiles'])) {
108 $options['maxfiles'] = 0; // no files by default
110 if (!isset($options['noclean'])) {
111 $options['noclean'] = false;
114 //sanity check for passed context. This function doesn't expect $option['context'] to be set
115 //But this function is called before creating editor hence, this is one of the best places to check
116 //if context is used properly. This check notify developer that they missed passing context to editor.
117 if (isset($context) && !isset($options['context'])) {
118 //if $context is not null then make sure $option['context'] is also set.
119 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
120 } else if (isset($options['context']) && isset($context)) {
121 //If both are passed then they should be equal.
122 if ($options['context']->id != $context->id) {
123 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
124 throw new coding_exception($exceptionmsg);
128 if (is_null($itemid) or is_null($context)) {
129 $contextid = null;
130 $itemid = null;
131 if (!isset($data)) {
132 $data = new stdClass();
134 if (!isset($data->{$field})) {
135 $data->{$field} = '';
137 if (!isset($data->{$field.'format'})) {
138 $data->{$field.'format'} = editors_get_preferred_format();
140 if (!$options['noclean']) {
141 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
144 } else {
145 if ($options['trusttext']) {
146 // noclean ignored if trusttext enabled
147 if (!isset($data->{$field.'trust'})) {
148 $data->{$field.'trust'} = 0;
150 $data = trusttext_pre_edit($data, $field, $context);
151 } else {
152 if (!$options['noclean']) {
153 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
156 $contextid = $context->id;
159 if ($options['maxfiles'] != 0) {
160 $draftid_editor = file_get_submitted_draft_itemid($field);
161 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
162 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
163 } else {
164 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
167 return $data;
171 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
173 * This function moves files from draft area to the destination area and
174 * encodes URLs to the draft files so they can be safely saved into DB. The
175 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
176 * is the name of the database field to hold the wysiwyg editor content. The
177 * editor data comes as an array with text, format and itemid properties. This
178 * function automatically adds $data properties foobar, foobarformat and
179 * foobartrust, where foobar has URL to embedded files encoded.
181 * @param object $data raw data submitted by the form
182 * @param string $field name of the database field containing the html with embedded media files
183 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
184 * @param object $context context, required for existing data
185 * @param string component
186 * @param string $filearea file area name
187 * @param int $itemid item id, required if item exists
188 * @return object modified data object
190 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
191 $options = (array)$options;
192 if (!isset($options['trusttext'])) {
193 $options['trusttext'] = false;
195 if (!isset($options['forcehttps'])) {
196 $options['forcehttps'] = false;
198 if (!isset($options['subdirs'])) {
199 $options['subdirs'] = false;
201 if (!isset($options['maxfiles'])) {
202 $options['maxfiles'] = 0; // no files by default
204 if (!isset($options['maxbytes'])) {
205 $options['maxbytes'] = 0; // unlimited
208 if ($options['trusttext']) {
209 $data->{$field.'trust'} = trusttext_trusted($context);
210 } else {
211 $data->{$field.'trust'} = 0;
214 $editor = $data->{$field.'_editor'};
216 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
217 $data->{$field} = $editor['text'];
218 } else {
219 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
221 $data->{$field.'format'} = $editor['format'];
223 return $data;
227 * Saves text and files modified by Editor formslib element
229 * @param object $data $database entry field
230 * @param string $field name of data field
231 * @param array $options various options
232 * @param object $context context - must already exist
233 * @param string $component
234 * @param string $filearea file area name
235 * @param int $itemid must already exist, usually means data is in db
236 * @return object modified data obejct
238 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
239 $options = (array)$options;
240 if (!isset($options['subdirs'])) {
241 $options['subdirs'] = false;
243 if (is_null($itemid) or is_null($context)) {
244 $itemid = null;
245 $contextid = null;
246 } else {
247 $contextid = $context->id;
250 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
251 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
252 $data->{$field.'_filemanager'} = $draftid_editor;
254 return $data;
258 * Saves files modified by File manager formslib element
260 * @param object $data $database entry field
261 * @param string $field name of data field
262 * @param array $options various options
263 * @param object $context context - must already exist
264 * @param string $component
265 * @param string $filearea file area name
266 * @param int $itemid must already exist, usually means data is in db
267 * @return object modified data obejct
269 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
270 $options = (array)$options;
271 if (!isset($options['subdirs'])) {
272 $options['subdirs'] = false;
274 if (!isset($options['maxfiles'])) {
275 $options['maxfiles'] = -1; // unlimited
277 if (!isset($options['maxbytes'])) {
278 $options['maxbytes'] = 0; // unlimited
281 if (empty($data->{$field.'_filemanager'})) {
282 $data->$field = '';
284 } else {
285 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
286 $fs = get_file_storage();
288 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
289 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
290 } else {
291 $data->$field = '';
295 return $data;
300 * @global object
301 * @global object
302 * @return int a random but available draft itemid that can be used to create a new draft
303 * file area.
305 function file_get_unused_draft_itemid() {
306 global $DB, $USER;
308 if (isguestuser() or !isloggedin()) {
309 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
310 print_error('noguest');
313 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
315 $fs = get_file_storage();
316 $draftitemid = rand(1, 999999999);
317 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
318 $draftitemid = rand(1, 999999999);
321 return $draftitemid;
325 * Initialise a draft file area from a real one by copying the files. A draft
326 * area will be created if one does not already exist. Normally you should
327 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
329 * @global object
330 * @global object
331 * @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.
332 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
333 * @param string $component
334 * @param string $filearea helps indentify the file area.
335 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
336 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
337 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
338 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
340 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
341 global $CFG, $USER, $CFG;
343 $options = (array)$options;
344 if (!isset($options['subdirs'])) {
345 $options['subdirs'] = false;
347 if (!isset($options['forcehttps'])) {
348 $options['forcehttps'] = false;
351 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
352 $fs = get_file_storage();
354 if (empty($draftitemid)) {
355 // create a new area and copy existing files into
356 $draftitemid = file_get_unused_draft_itemid();
357 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
358 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
359 foreach ($files as $file) {
360 if ($file->is_directory() and $file->get_filepath() === '/') {
361 // we need a way to mark the age of each draft area,
362 // by not copying the root dir we force it to be created automatically with current timestamp
363 continue;
365 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
366 continue;
368 $fs->create_file_from_storedfile($file_record, $file);
371 if (!is_null($text)) {
372 // at this point there should not be any draftfile links yet,
373 // because this is a new text from database that should still contain the @@pluginfile@@ links
374 // this happens when developers forget to post process the text
375 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
377 } else {
378 // nothing to do
381 if (is_null($text)) {
382 return null;
385 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
386 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
390 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
392 * @global object
393 * @param string $text The content that may contain ULRs in need of rewriting.
394 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
395 * @param integer $contextid This parameter and the next two identify the file area to use.
396 * @param string $component
397 * @param string $filearea helps identify the file area.
398 * @param integer $itemid helps identify the file area.
399 * @param array $options text and file options ('forcehttps'=>false)
400 * @return string the processed text.
402 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
403 global $CFG;
405 $options = (array)$options;
406 if (!isset($options['forcehttps'])) {
407 $options['forcehttps'] = false;
410 if (!$CFG->slasharguments) {
411 $file = $file . '?file=';
414 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
416 if ($itemid !== null) {
417 $baseurl .= "$itemid/";
420 if ($options['forcehttps']) {
421 $baseurl = str_replace('http://', 'https://', $baseurl);
424 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
428 * Returns information about files in a draft area.
430 * @global object
431 * @global object
432 * @param integer $draftitemid the draft area item id.
433 * @return array with the following entries:
434 * 'filecount' => number of files in the draft area.
435 * (more information will be added as needed).
437 function file_get_draft_area_info($draftitemid) {
438 global $CFG, $USER;
440 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
441 $fs = get_file_storage();
443 $results = array();
445 // The number of files
446 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
447 $results['filecount'] = count($draftfiles);
448 $results['filesize'] = 0;
449 foreach ($draftfiles as $file) {
450 $results['filesize'] += $file->get_filesize();
453 return $results;
457 * Get used space of files
458 * @return int total bytes
460 function file_get_user_used_space() {
461 global $DB, $USER;
463 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
464 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
465 JOIN (SELECT contenthash, filename, MAX(id) AS id
466 FROM {files}
467 WHERE contextid = ? AND component = ? AND filearea != ?
468 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
469 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
470 $record = $DB->get_record_sql($sql, $params);
471 return (int)$record->totalbytes;
475 * Convert any string to a valid filepath
476 * @param string $str
477 * @return string path
479 function file_correct_filepath($str) { //TODO: what is this? (skodak)
480 if ($str == '/' or empty($str)) {
481 return '/';
482 } else {
483 return '/'.trim($str, './@#$ ').'/';
488 * Generate a folder tree of draft area of current USER recursively
489 * @param int $itemid
490 * @param string $filepath
491 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
493 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
494 global $USER, $OUTPUT, $CFG;
495 $data->children = array();
496 $context = get_context_instance(CONTEXT_USER, $USER->id);
497 $fs = get_file_storage();
498 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
499 foreach ($files as $file) {
500 if ($file->is_directory()) {
501 $item = new stdClass();
502 $item->sortorder = $file->get_sortorder();
503 $item->filepath = $file->get_filepath();
505 $foldername = explode('/', trim($item->filepath, '/'));
506 $item->fullname = trim(array_pop($foldername), '/');
508 $item->id = uniqid();
509 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
510 $data->children[] = $item;
511 } else {
512 continue;
519 * Listing all files (including folders) in current path (draft area)
520 * used by file manager
521 * @param int $draftitemid
522 * @param string $filepath
523 * @return mixed
525 function file_get_drafarea_files($draftitemid, $filepath = '/') {
526 global $USER, $OUTPUT, $CFG;
528 $context = get_context_instance(CONTEXT_USER, $USER->id);
529 $fs = get_file_storage();
531 $data = new stdClass();
532 $data->path = array();
533 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
535 // will be used to build breadcrumb
536 $trail = '';
537 if ($filepath !== '/') {
538 $filepath = file_correct_filepath($filepath);
539 $parts = explode('/', $filepath);
540 foreach ($parts as $part) {
541 if ($part != '' && $part != null) {
542 $trail .= ('/'.$part.'/');
543 $data->path[] = array('name'=>$part, 'path'=>$trail);
548 $list = array();
549 $maxlength = 12;
550 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
551 foreach ($files as $file) {
552 $item = new stdClass();
553 $item->filename = $file->get_filename();
554 $item->filepath = $file->get_filepath();
555 $item->fullname = trim($item->filename, '/');
556 $filesize = $file->get_filesize();
557 $item->filesize = $filesize ? display_size($filesize) : '';
559 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
560 $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
561 $item->sortorder = $file->get_sortorder();
563 if ($icon == 'zip') {
564 $item->type = 'zip';
565 } else {
566 $item->type = 'file';
569 if ($file->is_directory()) {
570 $item->filesize = 0;
571 $item->icon = $OUTPUT->pix_url('f/folder')->out();
572 $item->type = 'folder';
573 $foldername = explode('/', trim($item->filepath, '/'));
574 $item->fullname = trim(array_pop($foldername), '/');
575 } else {
576 // do NOT use file browser here!
577 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
579 $list[] = $item;
582 $data->itemid = $draftitemid;
583 $data->list = $list;
584 return $data;
588 * Returns draft area itemid for a given element.
590 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
591 * @return integer the itemid, or 0 if there is not one yet.
593 function file_get_submitted_draft_itemid($elname) {
594 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
595 if (!isset($_REQUEST[$elname])) {
596 return 0;
598 if (is_array($_REQUEST[$elname])) {
599 $param = optional_param_array($elname, 0, PARAM_INT);
600 if (!empty($param['itemid'])) {
601 $param = $param['itemid'];
602 } else {
603 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
604 return false;
607 } else {
608 $param = optional_param($elname, 0, PARAM_INT);
611 if ($param) {
612 require_sesskey();
615 return $param;
619 * Saves files from a draft file area to a real one (merging the list of files).
620 * Can rewrite URLs in some content at the same time if desired.
622 * @global object
623 * @global object
624 * @param integer $draftitemid the id of the draft area to use. Normally obtained
625 * from file_get_submitted_draft_itemid('elementname') or similar.
626 * @param integer $contextid This parameter and the next two identify the file area to save to.
627 * @param string $component
628 * @param string $filearea indentifies the file area.
629 * @param integer $itemid helps identifies the file area.
630 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
631 * @param string $text some html content that needs to have embedded links rewritten
632 * to the @@PLUGINFILE@@ form for saving in the database.
633 * @param boolean $forcehttps force https urls.
634 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
636 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
637 global $USER;
639 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
640 $fs = get_file_storage();
642 $options = (array)$options;
643 if (!isset($options['subdirs'])) {
644 $options['subdirs'] = false;
646 if (!isset($options['maxfiles'])) {
647 $options['maxfiles'] = -1; // unlimited
649 if (!isset($options['maxbytes'])) {
650 $options['maxbytes'] = 0; // unlimited
653 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
654 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
656 if (count($draftfiles) < 2) {
657 // means there are no files - one file means root dir only ;-)
658 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
660 } else if (count($oldfiles) < 2) {
661 $filecount = 0;
662 // there were no files before - one file means root dir only ;-)
663 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
664 foreach ($draftfiles as $file) {
665 if (!$options['subdirs']) {
666 if ($file->get_filepath() !== '/' or $file->is_directory()) {
667 continue;
670 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
671 // oversized file - should not get here at all
672 continue;
674 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
675 // more files - should not get here at all
676 break;
678 if (!$file->is_directory()) {
679 $filecount++;
681 $fs->create_file_from_storedfile($file_record, $file);
684 } else {
685 // we have to merge old and new files - we want to keep file ids for files that were not changed
686 // we change time modified for all new and changed files, we keep time created as is
687 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
689 $newhashes = array();
690 foreach ($draftfiles as $file) {
691 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
692 $newhashes[$newhash] = $file;
694 $filecount = 0;
695 foreach ($oldfiles as $oldfile) {
696 $oldhash = $oldfile->get_pathnamehash();
697 if (!isset($newhashes[$oldhash])) {
698 // delete files not needed any more - deleted by user
699 $oldfile->delete();
700 continue;
702 $newfile = $newhashes[$oldhash];
703 if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
704 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
705 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
706 // file was changed, use updated with new timemodified data
707 $oldfile->delete();
708 continue;
710 // unchanged file or directory - we keep it as is
711 unset($newhashes[$oldhash]);
712 if (!$oldfile->is_directory()) {
713 $filecount++;
717 // now add new/changed files
718 // the size and subdirectory tests are extra safety only, the UI should prevent it
719 foreach ($newhashes as $file) {
720 if (!$options['subdirs']) {
721 if ($file->get_filepath() !== '/' or $file->is_directory()) {
722 continue;
725 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
726 // oversized file - should not get here at all
727 continue;
729 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
730 // more files - should not get here at all
731 break;
733 if (!$file->is_directory()) {
734 $filecount++;
736 $fs->create_file_from_storedfile($file_record, $file);
740 // note: do not purge the draft area - we clean up areas later in cron,
741 // the reason is that user might press submit twice and they would loose the files,
742 // also sometimes we might want to use hacks that save files into two different areas
744 if (is_null($text)) {
745 return null;
746 } else {
747 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
752 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
753 * ready to be saved in the database. Normally, this is done automatically by
754 * {@link file_save_draft_area_files()}.
755 * @param string $text the content to process.
756 * @param int $draftitemid the draft file area the content was using.
757 * @param bool $forcehttps whether the content contains https URLs. Default false.
758 * @return string the processed content.
760 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
761 global $CFG, $USER;
763 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
765 $wwwroot = $CFG->wwwroot;
766 if ($forcehttps) {
767 $wwwroot = str_replace('http://', 'https://', $wwwroot);
770 // relink embedded files if text submitted - no absolute links allowed in database!
771 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
773 if (strpos($text, 'draftfile.php?file=') !== false) {
774 $matches = array();
775 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
776 if ($matches) {
777 foreach ($matches[0] as $match) {
778 $replace = str_ireplace('%2F', '/', $match);
779 $text = str_replace($match, $replace, $text);
782 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
785 return $text;
789 * Set file sort order
790 * @global object $DB
791 * @param integer $contextid the context id
792 * @param string $component
793 * @param string $filearea file area.
794 * @param integer $itemid itemid.
795 * @param string $filepath file path.
796 * @param string $filename file name.
797 * @param integer $sortorer the sort order of file.
798 * @return boolean
800 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
801 global $DB;
802 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
803 if ($file_record = $DB->get_record('files', $conditions)) {
804 $sortorder = (int)$sortorder;
805 $file_record->sortorder = $sortorder;
806 $DB->update_record('files', $file_record);
807 return true;
809 return false;
813 * reset file sort order number to 0
814 * @global object $DB
815 * @param integer $contextid the context id
816 * @param string $component
817 * @param string $filearea file area.
818 * @param integer $itemid itemid.
819 * @return boolean
821 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
822 global $DB;
824 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
825 if ($itemid !== false) {
826 $conditions['itemid'] = $itemid;
829 $file_records = $DB->get_records('files', $conditions);
830 foreach ($file_records as $file_record) {
831 $file_record->sortorder = 0;
832 $DB->update_record('files', $file_record);
834 return true;
838 * Returns description of upload error
840 * @param int $errorcode found in $_FILES['filename.ext']['error']
841 * @return string error description string, '' if ok
843 function file_get_upload_error($errorcode) {
845 switch ($errorcode) {
846 case 0: // UPLOAD_ERR_OK - no error
847 $errmessage = '';
848 break;
850 case 1: // UPLOAD_ERR_INI_SIZE
851 $errmessage = get_string('uploadserverlimit');
852 break;
854 case 2: // UPLOAD_ERR_FORM_SIZE
855 $errmessage = get_string('uploadformlimit');
856 break;
858 case 3: // UPLOAD_ERR_PARTIAL
859 $errmessage = get_string('uploadpartialfile');
860 break;
862 case 4: // UPLOAD_ERR_NO_FILE
863 $errmessage = get_string('uploadnofilefound');
864 break;
866 // Note: there is no error with a value of 5
868 case 6: // UPLOAD_ERR_NO_TMP_DIR
869 $errmessage = get_string('uploadnotempdir');
870 break;
872 case 7: // UPLOAD_ERR_CANT_WRITE
873 $errmessage = get_string('uploadcantwrite');
874 break;
876 case 8: // UPLOAD_ERR_EXTENSION
877 $errmessage = get_string('uploadextension');
878 break;
880 default:
881 $errmessage = get_string('uploadproblem');
884 return $errmessage;
888 * Recursive function formating an array in POST parameter
889 * @param array $arraydata - the array that we are going to format and add into &$data array
890 * @param string $currentdata - a row of the final postdata array at instant T
891 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
892 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
894 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
895 foreach ($arraydata as $k=>$v) {
896 $newcurrentdata = $currentdata;
897 if (is_array($v)) { //the value is an array, call the function recursively
898 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
899 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
900 } else { //add the POST parameter to the $data array
901 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
907 * Transform a PHP array into POST parameter
908 * (see the recursive function format_array_postdata_for_curlcall)
909 * @param array $postdata
910 * @return array containing all POST parameters (1 row = 1 POST parameter)
912 function format_postdata_for_curlcall($postdata) {
913 $data = array();
914 foreach ($postdata as $k=>$v) {
915 if (is_array($v)) {
916 $currentdata = urlencode($k);
917 format_array_postdata_for_curlcall($v, $currentdata, $data);
918 } else {
919 $data[] = urlencode($k).'='.urlencode($v);
922 $convertedpostdata = implode('&', $data);
923 return $convertedpostdata;
930 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
931 * Due to security concerns only downloads from http(s) sources are supported.
933 * @param string $url file url starting with http(s)://
934 * @param array $headers http headers, null if none. If set, should be an
935 * associative array of header name => value pairs.
936 * @param array $postdata array means use POST request with given parameters
937 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
938 * (if false, just returns content)
939 * @param int $timeout timeout for complete download process including all file transfer
940 * (default 5 minutes)
941 * @param int $connecttimeout timeout for connection to server; this is the timeout that
942 * usually happens if the remote server is completely down (default 20 seconds);
943 * may not work when using proxy
944 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
945 * Only use this when already in a trusted location.
946 * @param string $tofile store the downloaded content to file instead of returning it.
947 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
948 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
949 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
951 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
952 global $CFG;
954 // some extra security
955 $newlines = array("\r", "\n");
956 if (is_array($headers) ) {
957 foreach ($headers as $key => $value) {
958 $headers[$key] = str_replace($newlines, '', $value);
961 $url = str_replace($newlines, '', $url);
962 if (!preg_match('|^https?://|i', $url)) {
963 if ($fullresponse) {
964 $response = new stdClass();
965 $response->status = 0;
966 $response->headers = array();
967 $response->response_code = 'Invalid protocol specified in url';
968 $response->results = '';
969 $response->error = 'Invalid protocol specified in url';
970 return $response;
971 } else {
972 return false;
976 // check if proxy (if used) should be bypassed for this url
977 $proxybypass = is_proxybypass($url);
979 if (!$ch = curl_init($url)) {
980 debugging('Can not init curl.');
981 return false;
984 // set extra headers
985 if (is_array($headers) ) {
986 $headers2 = array();
987 foreach ($headers as $key => $value) {
988 $headers2[] = "$key: $value";
990 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
993 if ($skipcertverify) {
994 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
997 // use POST if requested
998 if (is_array($postdata)) {
999 $postdata = format_postdata_for_curlcall($postdata);
1000 curl_setopt($ch, CURLOPT_POST, true);
1001 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
1004 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1005 curl_setopt($ch, CURLOPT_HEADER, false);
1006 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
1008 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
1009 // TODO: add version test for '7.10.5'
1010 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1011 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1014 if (!empty($CFG->proxyhost) and !$proxybypass) {
1015 // SOCKS supported in PHP5 only
1016 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1017 if (defined('CURLPROXY_SOCKS5')) {
1018 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1019 } else {
1020 curl_close($ch);
1021 if ($fullresponse) {
1022 $response = new stdClass();
1023 $response->status = '0';
1024 $response->headers = array();
1025 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1026 $response->results = '';
1027 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1028 return $response;
1029 } else {
1030 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1031 return false;
1036 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1038 if (empty($CFG->proxyport)) {
1039 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1040 } else {
1041 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1044 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1045 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1046 if (defined('CURLOPT_PROXYAUTH')) {
1047 // any proxy authentication if PHP 5.1
1048 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1053 // set up header and content handlers
1054 $received = new stdClass();
1055 $received->headers = array(); // received headers array
1056 $received->tofile = $tofile;
1057 $received->fh = null;
1058 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1059 if ($tofile) {
1060 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1063 if (!isset($CFG->curltimeoutkbitrate)) {
1064 //use very slow rate of 56kbps as a timeout speed when not set
1065 $bitrate = 56;
1066 } else {
1067 $bitrate = $CFG->curltimeoutkbitrate;
1070 // try to calculate the proper amount for timeout from remote file size.
1071 // if disabled or zero, we won't do any checks nor head requests.
1072 if ($calctimeout && $bitrate > 0) {
1073 //setup header request only options
1074 curl_setopt_array ($ch, array(
1075 CURLOPT_RETURNTRANSFER => false,
1076 CURLOPT_NOBODY => true)
1079 curl_exec($ch);
1080 $info = curl_getinfo($ch);
1081 $err = curl_error($ch);
1083 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1084 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1086 //reinstate affected curl options
1087 curl_setopt_array ($ch, array(
1088 CURLOPT_RETURNTRANSFER => true,
1089 CURLOPT_NOBODY => false)
1093 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1094 $result = curl_exec($ch);
1096 // try to detect encoding problems
1097 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1098 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1099 $result = curl_exec($ch);
1102 if ($received->fh) {
1103 fclose($received->fh);
1106 if (curl_errno($ch)) {
1107 $error = curl_error($ch);
1108 $error_no = curl_errno($ch);
1109 curl_close($ch);
1111 if ($fullresponse) {
1112 $response = new stdClass();
1113 if ($error_no == 28) {
1114 $response->status = '-100'; // mimic snoopy
1115 } else {
1116 $response->status = '0';
1118 $response->headers = array();
1119 $response->response_code = $error;
1120 $response->results = false;
1121 $response->error = $error;
1122 return $response;
1123 } else {
1124 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1125 return false;
1128 } else {
1129 $info = curl_getinfo($ch);
1130 curl_close($ch);
1132 if (empty($info['http_code'])) {
1133 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1134 $response = new stdClass();
1135 $response->status = '0';
1136 $response->headers = array();
1137 $response->response_code = 'Unknown cURL error';
1138 $response->results = false; // do NOT change this, we really want to ignore the result!
1139 $response->error = 'Unknown cURL error';
1141 } else {
1142 $response = new stdClass();;
1143 $response->status = (string)$info['http_code'];
1144 $response->headers = $received->headers;
1145 $response->response_code = $received->headers[0];
1146 $response->results = $result;
1147 $response->error = '';
1150 if ($fullresponse) {
1151 return $response;
1152 } else if ($info['http_code'] != 200) {
1153 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1154 return false;
1155 } else {
1156 return $response->results;
1162 * internal implementation
1164 function download_file_content_header_handler($received, $ch, $header) {
1165 $received->headers[] = $header;
1166 return strlen($header);
1170 * internal implementation
1172 function download_file_content_write_handler($received, $ch, $data) {
1173 if (!$received->fh) {
1174 $received->fh = fopen($received->tofile, 'w');
1175 if ($received->fh === false) {
1176 // bad luck, file creation or overriding failed
1177 return 0;
1180 if (fwrite($received->fh, $data) === false) {
1181 // bad luck, write failed, let's abort completely
1182 return 0;
1184 return strlen($data);
1188 * @return array List of information about file types based on extensions.
1189 * Associative array of extension (lower-case) to associative array
1190 * from 'element name' to data. Current element names are 'type' and 'icon'.
1191 * Unknown types should use the 'xxx' entry which includes defaults.
1193 function get_mimetypes_array() {
1194 static $mimearray = array (
1195 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1196 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1197 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
1198 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1199 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1200 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1201 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1202 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1203 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1204 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1205 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1206 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1207 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1208 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1209 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1210 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1211 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1212 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1213 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1214 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1215 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1217 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1218 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1219 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1220 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1221 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1223 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1224 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1225 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1226 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1227 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1228 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1229 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1230 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1231 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1232 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1233 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1234 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1235 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1236 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1237 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1238 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1239 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1240 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1241 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1242 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1243 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1244 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1245 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1246 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1247 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1248 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1249 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1250 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1251 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1252 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1253 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1254 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1255 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1256 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1257 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1258 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1259 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1260 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1261 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1262 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1263 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1264 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1265 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1266 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1267 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1268 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1269 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1270 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1272 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1273 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1274 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1275 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1276 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1277 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1278 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1279 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1280 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1281 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1282 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1283 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1284 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1285 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1286 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1287 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1288 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
1290 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1291 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1292 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1293 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1294 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1295 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1297 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1298 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1299 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1300 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1301 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1302 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1303 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1304 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1305 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1307 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1308 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1309 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1310 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1311 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1312 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1313 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
1314 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1315 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1316 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
1317 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1318 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1319 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1320 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1321 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1322 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1323 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1324 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1325 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1326 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1328 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1329 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1330 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1331 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1332 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1333 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1334 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1335 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1336 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1337 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1339 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1340 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1341 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1342 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1343 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1344 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1345 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1346 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1347 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1348 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
1349 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1350 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1351 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1352 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1353 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1355 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1356 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1357 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1358 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1359 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1360 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1361 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1363 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1364 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1365 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1367 return $mimearray;
1371 * Obtains information about a filetype based on its extension. Will
1372 * use a default if no information is present about that particular
1373 * extension.
1375 * @param string $element Desired information (usually 'icon'
1376 * for icon filename or 'type' for MIME type)
1377 * @param string $filename Filename we're looking up
1378 * @return string Requested piece of information from array
1380 function mimeinfo($element, $filename) {
1381 global $CFG;
1382 $mimeinfo = get_mimetypes_array();
1384 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1385 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1386 return $mimeinfo[strtolower($match[1])][$element];
1387 } else {
1388 if ($element == 'icon32') {
1389 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1390 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1391 } else {
1392 $filename = 'unknown';
1394 $filename .= '-32';
1395 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1396 return $filename;
1397 } else {
1398 return 'unknown-32';
1400 } else {
1401 return $mimeinfo['xxx'][$element]; // By default
1404 } else {
1405 if ($element == 'icon32') {
1406 return 'unknown-32';
1408 return $mimeinfo['xxx'][$element]; // By default
1413 * Obtains information about a filetype based on the MIME type rather than
1414 * the other way around.
1416 * @param string $element Desired information (usually 'icon')
1417 * @param string $mimetype MIME type we're looking up
1418 * @return string Requested piece of information from array
1420 function mimeinfo_from_type($element, $mimetype) {
1421 $mimeinfo = get_mimetypes_array();
1423 foreach($mimeinfo as $values) {
1424 if ($values['type']==$mimetype) {
1425 if (isset($values[$element])) {
1426 return $values[$element];
1428 break;
1431 return $mimeinfo['xxx'][$element]; // Default
1435 * Get information about a filetype based on the icon file.
1437 * @param string $element Desired information (usually 'icon')
1438 * @param string $icon Icon file name without extension
1439 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1440 * @return string Requested piece of information from array
1442 function mimeinfo_from_icon($element, $icon, $all=false) {
1443 $mimeinfo = get_mimetypes_array();
1445 if (preg_match("/\/(.*)/", $icon, $matches)) {
1446 $icon = $matches[1];
1448 // Try to get the extension
1449 $extension = '';
1450 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1451 $extension = substr($icon, $cutat + 1);
1453 $info = array($mimeinfo['xxx'][$element]); // Default
1454 foreach($mimeinfo as $key => $values) {
1455 if ($values['icon']==$icon) {
1456 if (isset($values[$element])) {
1457 $info[$key] = $values[$element];
1459 //No break, for example for 'excel' we don't want 'csv'!
1462 if ($all) {
1463 if (count($info) > 1) {
1464 array_shift($info); // take off document/unknown if we have better options
1466 return array_values($info); // Keep keys out when requesting all
1469 // Requested only one, try to get the best by extension coincidence, else return the last
1470 if ($extension && isset($info[$extension])) {
1471 return $info[$extension];
1474 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1478 * Returns the relative icon path for a given mime type
1480 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1481 * a return the full path to an icon.
1483 * <code>
1484 * $mimetype = 'image/jpg';
1485 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1486 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1487 * </code>
1489 * @todo When an $OUTPUT->icon method is available this function should be altered
1490 * to conform with that.
1492 * @param string $mimetype The mimetype to fetch an icon for
1493 * @param int $size The size of the icon. Not yet implemented
1494 * @return string The relative path to the icon
1496 function file_mimetype_icon($mimetype, $size = NULL) {
1497 global $CFG;
1499 $icon = mimeinfo_from_type('icon', $mimetype);
1500 if ($size) {
1501 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1502 $icon = "$icon-$size";
1505 return 'f/'.$icon;
1509 * Returns the relative icon path for a given file name
1511 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1512 * a return the full path to an icon.
1514 * <code>
1515 * $filename = 'jpg';
1516 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1517 * echo '<img src="'.$icon.'" alt="blah" />';
1518 * </code>
1520 * @todo When an $OUTPUT->icon method is available this function should be altered
1521 * to conform with that.
1522 * @todo Implement $size
1524 * @param string filename The filename to get the icon for
1525 * @param int $size The size of the icon. Defaults to null can also be 32
1526 * @return string
1528 function file_extension_icon($filename, $size = NULL) {
1529 global $CFG;
1531 $icon = mimeinfo('icon', $filename);
1532 if ($size) {
1533 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1534 $icon = "$icon-$size";
1537 return 'f/'.$icon;
1541 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1542 * mimetypes.php language file.
1544 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1545 * @param bool $capitalise If true, capitalises first character of result
1546 * @return string Text description
1548 function get_mimetype_description($mimetype, $capitalise=false) {
1549 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1550 $result = get_string($mimetype, 'mimetypes');
1551 } else {
1552 $result = get_string('document/unknown','mimetypes');
1554 if ($capitalise) {
1555 $result=ucfirst($result);
1557 return $result;
1561 * Requested file is not found or not accessible
1563 * @return does not return, terminates script
1565 function send_file_not_found() {
1566 global $CFG, $COURSE;
1567 send_header_404();
1568 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1571 * Helper function to send correct 404 for server.
1573 function send_header_404() {
1574 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1575 header("Status: 404 Not Found");
1576 } else {
1577 header('HTTP/1.0 404 not found');
1582 * Check output buffering settings before sending file.
1583 * Please note you should not send any other headers after calling this function.
1585 * @private to be called only from lib/filelib.php !
1586 * @return void
1588 function prepare_file_content_sending() {
1589 // We needed to be able to send headers up until now
1590 if (headers_sent()) {
1591 throw new file_serving_exception('Headers already sent, can not serve file.');
1594 $olddebug = error_reporting(0);
1596 // IE compatibility HACK - it does not like zlib compression much
1597 // there is also a problem with the length header in older PHP versions
1598 if (ini_get_bool('zlib.output_compression')) {
1599 ini_set('zlib.output_compression', 'Off');
1602 // flush and close all buffers if possible
1603 while(ob_get_level()) {
1604 if (!ob_end_flush()) {
1605 // prevent infinite loop when buffer can not be closed
1606 break;
1610 error_reporting($olddebug);
1612 //NOTE: we can not reliable test headers_sent() here because
1613 // the headers might be sent which trying to close the buffers,
1614 // this happens especially if browser does not support gzip or deflate
1618 * Handles the sending of temporary file to user, download is forced.
1619 * File is deleted after abort or successful sending.
1621 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1622 * @param string $filename proposed file name when saving file
1623 * @param bool $path is content of file
1624 * @return does not return, script terminated
1626 function send_temp_file($path, $filename, $pathisstring=false) {
1627 global $CFG;
1629 if (check_browser_version('Firefox', '1.5')) {
1630 // only FF is known to correctly save to disk before opening...
1631 $mimetype = mimeinfo('type', $filename);
1632 } else {
1633 $mimetype = 'application/x-forcedownload';
1636 // close session - not needed anymore
1637 @session_get_instance()->write_close();
1639 if (!$pathisstring) {
1640 if (!file_exists($path)) {
1641 send_header_404();
1642 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1644 // executed after normal finish or abort
1645 @register_shutdown_function('send_temp_file_finished', $path);
1648 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1649 if (check_browser_version('MSIE')) {
1650 $filename = urlencode($filename);
1653 $filesize = $pathisstring ? strlen($path) : filesize($path);
1655 header('Content-Disposition: attachment; filename='.$filename);
1656 header('Content-Length: '.$filesize);
1657 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1658 header('Cache-Control: max-age=10');
1659 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1660 header('Pragma: ');
1661 } else { //normal http - prevent caching at all cost
1662 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1663 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1664 header('Pragma: no-cache');
1666 header('Accept-Ranges: none'); // Do not allow byteserving
1668 if ($mimetype === 'text/plain') {
1669 // there is no encoding specified in text files, we need something consistent
1670 header('Content-Type: text/plain; charset=utf-8');
1671 } else {
1672 header('Content-Type: '.$mimetype);
1675 //flush the buffers - save memory and disable sid rewrite
1676 // this also disables zlib compression
1677 prepare_file_content_sending();
1679 // send the contents
1680 if ($pathisstring) {
1681 echo $path;
1682 } else {
1683 @readfile($path);
1686 die; //no more chars to output
1690 * Internal callback function used by send_temp_file()
1692 function send_temp_file_finished($path) {
1693 if (file_exists($path)) {
1694 @unlink($path);
1699 * Handles the sending of file data to the user's browser, including support for
1700 * byteranges etc.
1702 * @global object
1703 * @global object
1704 * @global object
1705 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1706 * @param string $filename Filename to send
1707 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1708 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1709 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1710 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1711 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1712 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1713 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1714 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1715 * and should not be reopened.
1716 * @return no return or void, script execution stopped unless $dontdie is true
1718 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1719 global $CFG, $COURSE, $SESSION;
1721 if ($dontdie) {
1722 ignore_user_abort(true);
1725 // MDL-11789, apply $CFG->filelifetime here
1726 if ($lifetime === 'default') {
1727 if (!empty($CFG->filelifetime)) {
1728 $lifetime = $CFG->filelifetime;
1729 } else {
1730 $lifetime = 86400;
1734 session_get_instance()->write_close(); // unlock session during fileserving
1736 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1737 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1738 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1739 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1740 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1741 ($mimetype ? $mimetype : mimeinfo('type', $filename));
1743 $lastmodified = $pathisstring ? time() : filemtime($path);
1744 $filesize = $pathisstring ? strlen($path) : filesize($path);
1746 /* - MDL-13949
1747 //Adobe Acrobat Reader XSS prevention
1748 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1749 //please note that it prevents opening of pdfs in browser when http referer disabled
1750 //or file linked from another site; browser caching of pdfs is now disabled too
1751 if (!empty($_SERVER['HTTP_RANGE'])) {
1752 //already byteserving
1753 $lifetime = 1; // >0 needed for byteserving
1754 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1755 $mimetype = 'application/x-forcedownload';
1756 $forcedownload = true;
1757 $lifetime = 0;
1758 } else {
1759 $lifetime = 1; // >0 needed for byteserving
1764 if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1765 // get unixtime of request header; clip extra junk off first
1766 $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1767 if ($since && $since >= $lastmodified) {
1768 header('HTTP/1.1 304 Not Modified');
1769 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1770 header('Cache-Control: max-age='.$lifetime);
1771 header('Content-Type: '.$mimetype);
1772 if ($dontdie) {
1773 return;
1775 die;
1779 //do not put '@' before the next header to detect incorrect moodle configurations,
1780 //error should be better than "weird" empty lines for admins/users
1781 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1783 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1784 if (check_browser_version('MSIE')) {
1785 $filename = rawurlencode($filename);
1788 if ($forcedownload) {
1789 header('Content-Disposition: attachment; filename="'.$filename.'"');
1790 } else {
1791 header('Content-Disposition: inline; filename="'.$filename.'"');
1794 if ($lifetime > 0) {
1795 header('Cache-Control: max-age='.$lifetime);
1796 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1797 header('Pragma: ');
1799 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1801 header('Accept-Ranges: bytes');
1803 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1804 // byteserving stuff - for acrobat reader and download accelerators
1805 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1806 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1807 $ranges = false;
1808 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1809 foreach ($ranges as $key=>$value) {
1810 if ($ranges[$key][1] == '') {
1811 //suffix case
1812 $ranges[$key][1] = $filesize - $ranges[$key][2];
1813 $ranges[$key][2] = $filesize - 1;
1814 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1815 //fix range length
1816 $ranges[$key][2] = $filesize - 1;
1818 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1819 //invalid byte-range ==> ignore header
1820 $ranges = false;
1821 break;
1823 //prepare multipart header
1824 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1825 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1827 } else {
1828 $ranges = false;
1830 if ($ranges) {
1831 $handle = fopen($path, 'rb');
1832 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1835 } else {
1836 /// Do not byteserve (disabled, strings, text and html files).
1837 header('Accept-Ranges: none');
1839 } else { // Do not cache files in proxies and browsers
1840 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1841 header('Cache-Control: max-age=10');
1842 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1843 header('Pragma: ');
1844 } else { //normal http - prevent caching at all cost
1845 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1846 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1847 header('Pragma: no-cache');
1849 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1852 if (empty($filter)) {
1853 if ($mimetype == 'text/plain') {
1854 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1855 } else {
1856 header('Content-Type: '.$mimetype);
1858 header('Content-Length: '.$filesize);
1860 //flush the buffers - save memory and disable sid rewrite
1861 //this also disables zlib compression
1862 prepare_file_content_sending();
1864 // send the contents
1865 if ($pathisstring) {
1866 echo $path;
1867 } else {
1868 @readfile($path);
1871 } else { // Try to put the file through filters
1872 if ($mimetype == 'text/html') {
1873 $options = new stdClass();
1874 $options->noclean = true;
1875 $options->nocache = true; // temporary workaround for MDL-5136
1876 $text = $pathisstring ? $path : implode('', file($path));
1878 $text = file_modify_html_header($text);
1879 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1881 header('Content-Length: '.strlen($output));
1882 header('Content-Type: text/html');
1884 //flush the buffers - save memory and disable sid rewrite
1885 //this also disables zlib compression
1886 prepare_file_content_sending();
1888 // send the contents
1889 echo $output;
1890 // only filter text if filter all files is selected
1891 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1892 $options = new stdClass();
1893 $options->newlines = false;
1894 $options->noclean = true;
1895 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1896 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1898 header('Content-Length: '.strlen($output));
1899 header('Content-Type: text/html; charset=utf-8'); //add encoding
1901 //flush the buffers - save memory and disable sid rewrite
1902 //this also disables zlib compression
1903 prepare_file_content_sending();
1905 // send the contents
1906 echo $output;
1908 } else { // Just send it out raw
1909 header('Content-Length: '.$filesize);
1910 header('Content-Type: '.$mimetype);
1912 //flush the buffers - save memory and disable sid rewrite
1913 //this also disables zlib compression
1914 prepare_file_content_sending();
1916 // send the contents
1917 if ($pathisstring) {
1918 echo $path;
1919 }else {
1920 @readfile($path);
1924 if ($dontdie) {
1925 return;
1927 die; //no more chars to output!!!
1931 * Handles the sending of file data to the user's browser, including support for
1932 * byteranges etc.
1934 * @global object
1935 * @global object
1936 * @global object
1937 * @param object $stored_file local file object
1938 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1939 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1940 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1941 * @param string $filename Override filename
1942 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1943 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1944 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1945 * and should not be reopened.
1946 * @return void no return or void, script execution stopped unless $dontdie is true
1948 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1949 global $CFG, $COURSE, $SESSION;
1951 if (!$stored_file or $stored_file->is_directory()) {
1952 // nothing to serve
1953 if ($dontdie) {
1954 return;
1956 die;
1959 if ($dontdie) {
1960 ignore_user_abort(true);
1963 session_get_instance()->write_close(); // unlock session during fileserving
1965 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1966 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1967 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1968 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1969 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1970 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1971 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1973 $lastmodified = $stored_file->get_timemodified();
1974 $filesize = $stored_file->get_filesize();
1976 if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1977 // get unixtime of request header; clip extra junk off first
1978 $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1979 if ($since && $since >= $lastmodified) {
1980 header('HTTP/1.1 304 Not Modified');
1981 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1982 header('Cache-Control: max-age='.$lifetime);
1983 header('Content-Type: '.$mimetype);
1984 if ($dontdie) {
1985 return;
1987 die;
1991 //do not put '@' before the next header to detect incorrect moodle configurations,
1992 //error should be better than "weird" empty lines for admins/users
1993 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1995 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1996 if (check_browser_version('MSIE')) {
1997 $filename = rawurlencode($filename);
2000 if ($forcedownload) {
2001 header('Content-Disposition: attachment; filename="'.$filename.'"');
2002 } else {
2003 header('Content-Disposition: inline; filename="'.$filename.'"');
2006 if ($lifetime > 0) {
2007 header('Cache-Control: max-age='.$lifetime);
2008 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2009 header('Pragma: ');
2011 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
2013 header('Accept-Ranges: bytes');
2015 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2016 // byteserving stuff - for acrobat reader and download accelerators
2017 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2018 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2019 $ranges = false;
2020 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2021 foreach ($ranges as $key=>$value) {
2022 if ($ranges[$key][1] == '') {
2023 //suffix case
2024 $ranges[$key][1] = $filesize - $ranges[$key][2];
2025 $ranges[$key][2] = $filesize - 1;
2026 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2027 //fix range length
2028 $ranges[$key][2] = $filesize - 1;
2030 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2031 //invalid byte-range ==> ignore header
2032 $ranges = false;
2033 break;
2035 //prepare multipart header
2036 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2037 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2039 } else {
2040 $ranges = false;
2042 if ($ranges) {
2043 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
2046 } else {
2047 /// Do not byteserve (disabled, strings, text and html files).
2048 header('Accept-Ranges: none');
2050 } else { // Do not cache files in proxies and browsers
2051 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2052 header('Cache-Control: max-age=10');
2053 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2054 header('Pragma: ');
2055 } else { //normal http - prevent caching at all cost
2056 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2057 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2058 header('Pragma: no-cache');
2060 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
2063 if (empty($filter)) {
2064 if ($mimetype == 'text/plain') {
2065 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
2066 } else {
2067 header('Content-Type: '.$mimetype);
2069 header('Content-Length: '.$filesize);
2071 //flush the buffers - save memory and disable sid rewrite
2072 //this also disables zlib compression
2073 prepare_file_content_sending();
2075 // send the contents
2076 $stored_file->readfile();
2078 } else { // Try to put the file through filters
2079 if ($mimetype == 'text/html') {
2080 $options = new stdClass();
2081 $options->noclean = true;
2082 $options->nocache = true; // temporary workaround for MDL-5136
2083 $text = $stored_file->get_content();
2084 $text = file_modify_html_header($text);
2085 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2087 header('Content-Length: '.strlen($output));
2088 header('Content-Type: text/html');
2090 //flush the buffers - save memory and disable sid rewrite
2091 //this also disables zlib compression
2092 prepare_file_content_sending();
2094 // send the contents
2095 echo $output;
2097 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2098 // only filter text if filter all files is selected
2099 $options = new stdClass();
2100 $options->newlines = false;
2101 $options->noclean = true;
2102 $text = $stored_file->get_content();
2103 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2105 header('Content-Length: '.strlen($output));
2106 header('Content-Type: text/html; charset=utf-8'); //add encoding
2108 //flush the buffers - save memory and disable sid rewrite
2109 //this also disables zlib compression
2110 prepare_file_content_sending();
2112 // send the contents
2113 echo $output;
2115 } else { // Just send it out raw
2116 header('Content-Length: '.$filesize);
2117 header('Content-Type: '.$mimetype);
2119 //flush the buffers - save memory and disable sid rewrite
2120 //this also disables zlib compression
2121 prepare_file_content_sending();
2123 // send the contents
2124 $stored_file->readfile();
2127 if ($dontdie) {
2128 return;
2130 die; //no more chars to output!!!
2134 * Retrieves an array of records from a CSV file and places
2135 * them into a given table structure
2137 * @global object
2138 * @global object
2139 * @param string $file The path to a CSV file
2140 * @param string $table The table to retrieve columns from
2141 * @return bool|array Returns an array of CSV records or false
2143 function get_records_csv($file, $table) {
2144 global $CFG, $DB;
2146 if (!$metacolumns = $DB->get_columns($table)) {
2147 return false;
2150 if(!($handle = @fopen($file, 'r'))) {
2151 print_error('get_records_csv failed to open '.$file);
2154 $fieldnames = fgetcsv($handle, 4096);
2155 if(empty($fieldnames)) {
2156 fclose($handle);
2157 return false;
2160 $columns = array();
2162 foreach($metacolumns as $metacolumn) {
2163 $ord = array_search($metacolumn->name, $fieldnames);
2164 if(is_int($ord)) {
2165 $columns[$metacolumn->name] = $ord;
2169 $rows = array();
2171 while (($data = fgetcsv($handle, 4096)) !== false) {
2172 $item = new stdClass;
2173 foreach($columns as $name => $ord) {
2174 $item->$name = $data[$ord];
2176 $rows[] = $item;
2179 fclose($handle);
2180 return $rows;
2185 * @global object
2186 * @global object
2187 * @param string $file The file to put the CSV content into
2188 * @param array $records An array of records to write to a CSV file
2189 * @param string $table The table to get columns from
2190 * @return bool success
2192 function put_records_csv($file, $records, $table = NULL) {
2193 global $CFG, $DB;
2195 if (empty($records)) {
2196 return true;
2199 $metacolumns = NULL;
2200 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2201 return false;
2204 echo "x";
2206 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2207 print_error('put_records_csv failed to open '.$file);
2210 $proto = reset($records);
2211 if(is_object($proto)) {
2212 $fields_records = array_keys(get_object_vars($proto));
2214 else if(is_array($proto)) {
2215 $fields_records = array_keys($proto);
2217 else {
2218 return false;
2220 echo "x";
2222 if(!empty($metacolumns)) {
2223 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2224 $fields = array_intersect($fields_records, $fields_table);
2226 else {
2227 $fields = $fields_records;
2230 fwrite($fp, implode(',', $fields));
2231 fwrite($fp, "\r\n");
2233 foreach($records as $record) {
2234 $array = (array)$record;
2235 $values = array();
2236 foreach($fields as $field) {
2237 if(strpos($array[$field], ',')) {
2238 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2240 else {
2241 $values[] = $array[$field];
2244 fwrite($fp, implode(',', $values)."\r\n");
2247 fclose($fp);
2248 return true;
2253 * Recursively delete the file or folder with path $location. That is,
2254 * if it is a file delete it. If it is a folder, delete all its content
2255 * then delete it. If $location does not exist to start, that is not
2256 * considered an error.
2258 * @param string $location the path to remove.
2259 * @return bool
2261 function fulldelete($location) {
2262 if (empty($location)) {
2263 // extra safety against wrong param
2264 return false;
2266 if (is_dir($location)) {
2267 $currdir = opendir($location);
2268 while (false !== ($file = readdir($currdir))) {
2269 if ($file <> ".." && $file <> ".") {
2270 $fullfile = $location."/".$file;
2271 if (is_dir($fullfile)) {
2272 if (!fulldelete($fullfile)) {
2273 return false;
2275 } else {
2276 if (!unlink($fullfile)) {
2277 return false;
2282 closedir($currdir);
2283 if (! rmdir($location)) {
2284 return false;
2287 } else if (file_exists($location)) {
2288 if (!unlink($location)) {
2289 return false;
2292 return true;
2296 * Send requested byterange of file.
2298 * @param object $handle A file handle
2299 * @param string $mimetype The mimetype for the output
2300 * @param array $ranges An array of ranges to send
2301 * @param string $filesize The size of the content if only one range is used
2303 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2304 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2305 if ($handle === false) {
2306 die;
2308 if (count($ranges) == 1) { //only one range requested
2309 $length = $ranges[0][2] - $ranges[0][1] + 1;
2310 header('HTTP/1.1 206 Partial content');
2311 header('Content-Length: '.$length);
2312 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2313 header('Content-Type: '.$mimetype);
2315 //flush the buffers - save memory and disable sid rewrite
2316 //this also disables zlib compression
2317 prepare_file_content_sending();
2319 $buffer = '';
2320 fseek($handle, $ranges[0][1]);
2321 while (!feof($handle) && $length > 0) {
2322 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2323 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2324 echo $buffer;
2325 flush();
2326 $length -= strlen($buffer);
2328 fclose($handle);
2329 die;
2330 } else { // multiple ranges requested - not tested much
2331 $totallength = 0;
2332 foreach($ranges as $range) {
2333 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2335 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2336 header('HTTP/1.1 206 Partial content');
2337 header('Content-Length: '.$totallength);
2338 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2339 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2341 //flush the buffers - save memory and disable sid rewrite
2342 //this also disables zlib compression
2343 prepare_file_content_sending();
2345 foreach($ranges as $range) {
2346 $length = $range[2] - $range[1] + 1;
2347 echo $range[0];
2348 $buffer = '';
2349 fseek($handle, $range[1]);
2350 while (!feof($handle) && $length > 0) {
2351 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2352 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2353 echo $buffer;
2354 flush();
2355 $length -= strlen($buffer);
2358 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2359 fclose($handle);
2360 die;
2365 * add includes (js and css) into uploaded files
2366 * before returning them, useful for themes and utf.js includes
2368 * @global object
2369 * @param string $text text to search and replace
2370 * @return string text with added head includes
2372 function file_modify_html_header($text) {
2373 // first look for <head> tag
2374 global $CFG;
2376 $stylesheetshtml = '';
2377 /* foreach ($CFG->stylesheets as $stylesheet) {
2378 //TODO: MDL-21120
2379 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2382 $ufo = '';
2383 if (filter_is_enabled('filter/mediaplugin')) {
2384 // this script is needed by most media filter plugins.
2385 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2386 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2389 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2390 if ($matches) {
2391 $replacement = '<head>'.$ufo.$stylesheetshtml;
2392 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2393 return $text;
2396 // if not, look for <html> tag, and stick <head> right after
2397 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2398 if ($matches) {
2399 // replace <html> tag with <html><head>includes</head>
2400 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2401 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2402 return $text;
2405 // if not, look for <body> tag, and stick <head> before body
2406 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2407 if ($matches) {
2408 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2409 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2410 return $text;
2413 // if not, just stick a <head> tag at the beginning
2414 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2415 return $text;
2419 * RESTful cURL class
2421 * This is a wrapper class for curl, it is quite easy to use:
2422 * <code>
2423 * $c = new curl;
2424 * // enable cache
2425 * $c = new curl(array('cache'=>true));
2426 * // enable cookie
2427 * $c = new curl(array('cookie'=>true));
2428 * // enable proxy
2429 * $c = new curl(array('proxy'=>true));
2431 * // HTTP GET Method
2432 * $html = $c->get('http://example.com');
2433 * // HTTP POST Method
2434 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2435 * // HTTP PUT Method
2436 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2437 * </code>
2439 * @package core
2440 * @subpackage file
2441 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2442 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2445 class curl {
2446 /** @var bool */
2447 public $cache = false;
2448 public $proxy = false;
2449 /** @var string */
2450 public $version = '0.4 dev';
2451 /** @var array */
2452 public $response = array();
2453 public $header = array();
2454 /** @var string */
2455 public $info;
2456 public $error;
2458 /** @var array */
2459 private $options;
2460 /** @var string */
2461 private $proxy_host = '';
2462 private $proxy_auth = '';
2463 private $proxy_type = '';
2464 /** @var bool */
2465 private $debug = false;
2466 private $cookie = false;
2469 * @global object
2470 * @param array $options
2472 public function __construct($options = array()){
2473 global $CFG;
2474 if (!function_exists('curl_init')) {
2475 $this->error = 'cURL module must be enabled!';
2476 trigger_error($this->error, E_USER_ERROR);
2477 return false;
2479 // the options of curl should be init here.
2480 $this->resetopt();
2481 if (!empty($options['debug'])) {
2482 $this->debug = true;
2484 if(!empty($options['cookie'])) {
2485 if($options['cookie'] === true) {
2486 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2487 } else {
2488 $this->cookie = $options['cookie'];
2491 if (!empty($options['cache'])) {
2492 if (class_exists('curl_cache')) {
2493 if (!empty($options['module_cache'])) {
2494 $this->cache = new curl_cache($options['module_cache']);
2495 } else {
2496 $this->cache = new curl_cache('misc');
2500 if (!empty($CFG->proxyhost)) {
2501 if (empty($CFG->proxyport)) {
2502 $this->proxy_host = $CFG->proxyhost;
2503 } else {
2504 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2506 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2507 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2508 $this->setopt(array(
2509 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2510 'proxyuserpwd'=>$this->proxy_auth));
2512 if (!empty($CFG->proxytype)) {
2513 if ($CFG->proxytype == 'SOCKS5') {
2514 $this->proxy_type = CURLPROXY_SOCKS5;
2515 } else {
2516 $this->proxy_type = CURLPROXY_HTTP;
2517 $this->setopt(array('httpproxytunnel'=>false));
2519 $this->setopt(array('proxytype'=>$this->proxy_type));
2522 if (!empty($this->proxy_host)) {
2523 $this->proxy = array('proxy'=>$this->proxy_host);
2527 * Resets the CURL options that have already been set
2529 public function resetopt(){
2530 $this->options = array();
2531 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2532 // True to include the header in the output
2533 $this->options['CURLOPT_HEADER'] = 0;
2534 // True to Exclude the body from the output
2535 $this->options['CURLOPT_NOBODY'] = 0;
2536 // TRUE to follow any "Location: " header that the server
2537 // sends as part of the HTTP header (note this is recursive,
2538 // PHP will follow as many "Location: " headers that it is sent,
2539 // unless CURLOPT_MAXREDIRS is set).
2540 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2541 $this->options['CURLOPT_MAXREDIRS'] = 10;
2542 $this->options['CURLOPT_ENCODING'] = '';
2543 // TRUE to return the transfer as a string of the return
2544 // value of curl_exec() instead of outputting it out directly.
2545 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2546 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2547 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2548 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2549 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2553 * Reset Cookie
2555 public function resetcookie() {
2556 if (!empty($this->cookie)) {
2557 if (is_file($this->cookie)) {
2558 $fp = fopen($this->cookie, 'w');
2559 if (!empty($fp)) {
2560 fwrite($fp, '');
2561 fclose($fp);
2568 * Set curl options
2570 * @param array $options If array is null, this function will
2571 * reset the options to default value.
2574 public function setopt($options = array()) {
2575 if (is_array($options)) {
2576 foreach($options as $name => $val){
2577 if (stripos($name, 'CURLOPT_') === false) {
2578 $name = strtoupper('CURLOPT_'.$name);
2580 $this->options[$name] = $val;
2585 * Reset http method
2588 public function cleanopt(){
2589 unset($this->options['CURLOPT_HTTPGET']);
2590 unset($this->options['CURLOPT_POST']);
2591 unset($this->options['CURLOPT_POSTFIELDS']);
2592 unset($this->options['CURLOPT_PUT']);
2593 unset($this->options['CURLOPT_INFILE']);
2594 unset($this->options['CURLOPT_INFILESIZE']);
2595 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2599 * Set HTTP Request Header
2601 * @param array $headers
2604 public function setHeader($header) {
2605 if (is_array($header)){
2606 foreach ($header as $v) {
2607 $this->setHeader($v);
2609 } else {
2610 $this->header[] = $header;
2614 * Set HTTP Response Header
2617 public function getResponse(){
2618 return $this->response;
2621 * private callback function
2622 * Formatting HTTP Response Header
2624 * @param mixed $ch Apparently not used
2625 * @param string $header
2626 * @return int The strlen of the header
2628 private function formatHeader($ch, $header)
2630 $this->count++;
2631 if (strlen($header) > 2) {
2632 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2633 $key = rtrim($key, ':');
2634 if (!empty($this->response[$key])) {
2635 if (is_array($this->response[$key])){
2636 $this->response[$key][] = $value;
2637 } else {
2638 $tmp = $this->response[$key];
2639 $this->response[$key] = array();
2640 $this->response[$key][] = $tmp;
2641 $this->response[$key][] = $value;
2644 } else {
2645 $this->response[$key] = $value;
2648 return strlen($header);
2652 * Set options for individual curl instance
2654 * @param object $curl A curl handle
2655 * @param array $options
2656 * @return object The curl handle
2658 private function apply_opt($curl, $options) {
2659 // Clean up
2660 $this->cleanopt();
2661 // set cookie
2662 if (!empty($this->cookie) || !empty($options['cookie'])) {
2663 $this->setopt(array('cookiejar'=>$this->cookie,
2664 'cookiefile'=>$this->cookie
2668 // set proxy
2669 if (!empty($this->proxy) || !empty($options['proxy'])) {
2670 $this->setopt($this->proxy);
2672 $this->setopt($options);
2673 // reset before set options
2674 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2675 // set headers
2676 if (empty($this->header)){
2677 $this->setHeader(array(
2678 'User-Agent: MoodleBot/1.0',
2679 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2680 'Connection: keep-alive'
2683 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2685 if ($this->debug){
2686 echo '<h1>Options</h1>';
2687 var_dump($this->options);
2688 echo '<h1>Header</h1>';
2689 var_dump($this->header);
2692 // set options
2693 foreach($this->options as $name => $val) {
2694 if (is_string($name)) {
2695 $name = constant(strtoupper($name));
2697 curl_setopt($curl, $name, $val);
2699 return $curl;
2702 * Download multiple files in parallel
2704 * Calls {@link multi()} with specific download headers
2706 * <code>
2707 * $c = new curl;
2708 * $c->download(array(
2709 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2710 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2711 * ));
2712 * </code>
2714 * @param array $requests An array of files to request
2715 * @param array $options An array of options to set
2716 * @return array An array of results
2718 public function download($requests, $options = array()) {
2719 $options['CURLOPT_BINARYTRANSFER'] = 1;
2720 $options['RETURNTRANSFER'] = false;
2721 return $this->multi($requests, $options);
2724 * Mulit HTTP Requests
2725 * This function could run multi-requests in parallel.
2727 * @param array $requests An array of files to request
2728 * @param array $options An array of options to set
2729 * @return array An array of results
2731 protected function multi($requests, $options = array()) {
2732 $count = count($requests);
2733 $handles = array();
2734 $results = array();
2735 $main = curl_multi_init();
2736 for ($i = 0; $i < $count; $i++) {
2737 $url = $requests[$i];
2738 foreach($url as $n=>$v){
2739 $options[$n] = $url[$n];
2741 $handles[$i] = curl_init($url['url']);
2742 $this->apply_opt($handles[$i], $options);
2743 curl_multi_add_handle($main, $handles[$i]);
2745 $running = 0;
2746 do {
2747 curl_multi_exec($main, $running);
2748 } while($running > 0);
2749 for ($i = 0; $i < $count; $i++) {
2750 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
2751 $results[] = true;
2752 } else {
2753 $results[] = curl_multi_getcontent($handles[$i]);
2755 curl_multi_remove_handle($main, $handles[$i]);
2757 curl_multi_close($main);
2758 return $results;
2761 * Single HTTP Request
2763 * @param string $url The URL to request
2764 * @param array $options
2765 * @return bool
2767 protected function request($url, $options = array()){
2768 // create curl instance
2769 $curl = curl_init($url);
2770 $options['url'] = $url;
2771 $this->apply_opt($curl, $options);
2772 if ($this->cache && $ret = $this->cache->get($this->options)) {
2773 return $ret;
2774 } else {
2775 $ret = curl_exec($curl);
2776 if ($this->cache) {
2777 $this->cache->set($this->options, $ret);
2781 $this->info = curl_getinfo($curl);
2782 $this->error = curl_error($curl);
2784 if ($this->debug){
2785 echo '<h1>Return Data</h1>';
2786 var_dump($ret);
2787 echo '<h1>Info</h1>';
2788 var_dump($this->info);
2789 echo '<h1>Error</h1>';
2790 var_dump($this->error);
2793 curl_close($curl);
2795 if (empty($this->error)){
2796 return $ret;
2797 } else {
2798 return $this->error;
2799 // exception is not ajax friendly
2800 //throw new moodle_exception($this->error, 'curl');
2805 * HTTP HEAD method
2807 * @see request()
2809 * @param string $url
2810 * @param array $options
2811 * @return bool
2813 public function head($url, $options = array()){
2814 $options['CURLOPT_HTTPGET'] = 0;
2815 $options['CURLOPT_HEADER'] = 1;
2816 $options['CURLOPT_NOBODY'] = 1;
2817 return $this->request($url, $options);
2821 * HTTP POST method
2823 * @param string $url
2824 * @param array|string $params
2825 * @param array $options
2826 * @return bool
2828 public function post($url, $params = '', $options = array()){
2829 $options['CURLOPT_POST'] = 1;
2830 if (is_array($params)) {
2831 $this->_tmp_file_post_params = array();
2832 foreach ($params as $key => $value) {
2833 if ($value instanceof stored_file) {
2834 $value->add_to_curl_request($this, $key);
2835 } else {
2836 $this->_tmp_file_post_params[$key] = $value;
2839 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2840 unset($this->_tmp_file_post_params);
2841 } else {
2842 // $params is the raw post data
2843 $options['CURLOPT_POSTFIELDS'] = $params;
2845 return $this->request($url, $options);
2849 * HTTP GET method
2851 * @param string $url
2852 * @param array $params
2853 * @param array $options
2854 * @return bool
2856 public function get($url, $params = array(), $options = array()){
2857 $options['CURLOPT_HTTPGET'] = 1;
2859 if (!empty($params)){
2860 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2861 $url .= http_build_query($params, '', '&');
2863 return $this->request($url, $options);
2867 * HTTP PUT method
2869 * @param string $url
2870 * @param array $params
2871 * @param array $options
2872 * @return bool
2874 public function put($url, $params = array(), $options = array()){
2875 $file = $params['file'];
2876 if (!is_file($file)){
2877 return null;
2879 $fp = fopen($file, 'r');
2880 $size = filesize($file);
2881 $options['CURLOPT_PUT'] = 1;
2882 $options['CURLOPT_INFILESIZE'] = $size;
2883 $options['CURLOPT_INFILE'] = $fp;
2884 if (!isset($this->options['CURLOPT_USERPWD'])){
2885 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2887 $ret = $this->request($url, $options);
2888 fclose($fp);
2889 return $ret;
2893 * HTTP DELETE method
2895 * @param string $url
2896 * @param array $params
2897 * @param array $options
2898 * @return bool
2900 public function delete($url, $param = array(), $options = array()){
2901 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2902 if (!isset($options['CURLOPT_USERPWD'])) {
2903 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2905 $ret = $this->request($url, $options);
2906 return $ret;
2909 * HTTP TRACE method
2911 * @param string $url
2912 * @param array $options
2913 * @return bool
2915 public function trace($url, $options = array()){
2916 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2917 $ret = $this->request($url, $options);
2918 return $ret;
2921 * HTTP OPTIONS method
2923 * @param string $url
2924 * @param array $options
2925 * @return bool
2927 public function options($url, $options = array()){
2928 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2929 $ret = $this->request($url, $options);
2930 return $ret;
2932 public function get_info() {
2933 return $this->info;
2938 * This class is used by cURL class, use case:
2940 * <code>
2941 * $CFG->repositorycacheexpire = 120;
2942 * $CFG->curlcache = 120;
2944 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2945 * $ret = $c->get('http://www.google.com');
2946 * </code>
2948 * @package core
2949 * @subpackage file
2950 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2951 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2953 class curl_cache {
2954 /** @var string */
2955 public $dir = '';
2958 * @global object
2959 * @param string @module which module is using curl_cache
2962 function __construct($module = 'repository'){
2963 global $CFG;
2964 if (!empty($module)) {
2965 $this->dir = $CFG->cachedir.'/'.$module.'/';
2966 } else {
2967 $this->dir = $CFG->cachedir.'/misc/';
2969 if (!file_exists($this->dir)) {
2970 mkdir($this->dir, $CFG->directorypermissions, true);
2972 if ($module == 'repository') {
2973 if (empty($CFG->repositorycacheexpire)) {
2974 $CFG->repositorycacheexpire = 120;
2976 $this->ttl = $CFG->repositorycacheexpire;
2977 } else {
2978 if (empty($CFG->curlcache)) {
2979 $CFG->curlcache = 120;
2981 $this->ttl = $CFG->curlcache;
2986 * Get cached value
2988 * @global object
2989 * @global object
2990 * @param mixed $param
2991 * @return bool|string
2993 public function get($param){
2994 global $CFG, $USER;
2995 $this->cleanup($this->ttl);
2996 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2997 if(file_exists($this->dir.$filename)) {
2998 $lasttime = filemtime($this->dir.$filename);
2999 if(time()-$lasttime > $this->ttl)
3001 return false;
3002 } else {
3003 $fp = fopen($this->dir.$filename, 'r');
3004 $size = filesize($this->dir.$filename);
3005 $content = fread($fp, $size);
3006 return unserialize($content);
3009 return false;
3013 * Set cache value
3015 * @global object $CFG
3016 * @global object $USER
3017 * @param mixed $param
3018 * @param mixed $val
3020 public function set($param, $val){
3021 global $CFG, $USER;
3022 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3023 $fp = fopen($this->dir.$filename, 'w');
3024 fwrite($fp, serialize($val));
3025 fclose($fp);
3029 * Remove cache files
3031 * @param int $expire The number os seconds before expiry
3033 public function cleanup($expire){
3034 if($dir = opendir($this->dir)){
3035 while (false !== ($file = readdir($dir))) {
3036 if(!is_dir($file) && $file != '.' && $file != '..') {
3037 $lasttime = @filemtime($this->dir.$file);
3038 if(time() - $lasttime > $expire){
3039 @unlink($this->dir.$file);
3046 * delete current user's cache file
3048 * @global object $CFG
3049 * @global object $USER
3051 public function refresh(){
3052 global $CFG, $USER;
3053 if($dir = opendir($this->dir)){
3054 while (false !== ($file = readdir($dir))) {
3055 if(!is_dir($file) && $file != '.' && $file != '..') {
3056 if(strpos($file, 'u'.$USER->id.'_')!==false){
3057 @unlink($this->dir.$file);
3066 * This class is used to parse lib/file/file_types.mm which help get file
3067 * extensions by file types.
3068 * The file_types.mm file can be edited by freemind in graphic environment.
3070 * @package core
3071 * @subpackage file
3072 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
3073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3075 class filetype_parser {
3077 * Check file_types.mm file, setup variables
3079 * @global object $CFG
3080 * @param string $file
3082 public function __construct($file = '') {
3083 global $CFG;
3084 if (empty($file)) {
3085 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
3086 } else {
3087 $this->file = $file;
3089 $this->tree = array();
3090 $this->result = array();
3094 * A private function to browse xml nodes
3096 * @param array $parent
3097 * @param array $types
3099 private function _browse_nodes($parent, $types) {
3100 $key = (string)$parent['TEXT'];
3101 if(isset($parent->node)) {
3102 $this->tree[$key] = array();
3103 if (in_array((string)$parent['TEXT'], $types)) {
3104 $this->_select_nodes($parent, $this->result);
3105 } else {
3106 foreach($parent->node as $v){
3107 $this->_browse_nodes($v, $types);
3110 } else {
3111 $this->tree[] = $key;
3116 * A private function to select text nodes
3118 * @param array $parent
3120 private function _select_nodes($parent){
3121 if(isset($parent->node)) {
3122 foreach($parent->node as $v){
3123 $this->_select_nodes($v, $this->result);
3125 } else {
3126 $this->result[] = (string)$parent['TEXT'];
3132 * Get file extensions by file types names.
3134 * @param array $types
3135 * @return mixed
3137 public function get_extensions($types) {
3138 if (!is_array($types)) {
3139 $types = array($types);
3141 $this->result = array();
3142 if ((is_array($types) && in_array('*', $types)) ||
3143 $types == '*' || empty($types)) {
3144 return array('*');
3146 foreach ($types as $key=>$value){
3147 if (strpos($value, '.') !== false) {
3148 $this->result[] = $value;
3149 unset($types[$key]);
3152 if (file_exists($this->file)) {
3153 $xml = simplexml_load_file($this->file);
3154 foreach($xml->node->node as $v){
3155 if (in_array((string)$v['TEXT'], $types)) {
3156 $this->_select_nodes($v);
3157 } else {
3158 $this->_browse_nodes($v, $types);
3161 } else {
3162 exit('Failed to open file lib/filestorage/file_types.mm');
3164 return $this->result;
3169 * This function delegates file serving to individual plugins
3171 * @param string $relativepath
3172 * @param bool $forcedownload
3174 * @package core
3175 * @subpackage file
3176 * @copyright 2008 Petr Skoda (http://skodak.org)
3177 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3179 function file_pluginfile($relativepath, $forcedownload) {
3180 global $DB, $CFG, $USER;
3181 // relative path must start with '/'
3182 if (!$relativepath) {
3183 print_error('invalidargorconf');
3184 } else if ($relativepath[0] != '/') {
3185 print_error('pathdoesnotstartslash');
3188 // extract relative path components
3189 $args = explode('/', ltrim($relativepath, '/'));
3191 if (count($args) < 3) { // always at least context, component and filearea
3192 print_error('invalidarguments');
3195 $contextid = (int)array_shift($args);
3196 $component = clean_param(array_shift($args), PARAM_COMPONENT);
3197 $filearea = clean_param(array_shift($args), PARAM_AREA);
3199 list($context, $course, $cm) = get_context_info_array($contextid);
3201 $fs = get_file_storage();
3203 // ========================================================================================================================
3204 if ($component === 'blog') {
3205 // Blog file serving
3206 if ($context->contextlevel != CONTEXT_SYSTEM) {
3207 send_file_not_found();
3209 if ($filearea !== 'attachment' and $filearea !== 'post') {
3210 send_file_not_found();
3213 if (empty($CFG->bloglevel)) {
3214 print_error('siteblogdisable', 'blog');
3217 $entryid = (int)array_shift($args);
3218 if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
3219 send_file_not_found();
3221 if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
3222 require_login();
3223 if (isguestuser()) {
3224 print_error('noguest');
3226 if ($CFG->bloglevel == BLOG_USER_LEVEL) {
3227 if ($USER->id != $entry->userid) {
3228 send_file_not_found();
3233 if ('publishstate' === 'public') {
3234 if ($CFG->forcelogin) {
3235 require_login();
3238 } else if ('publishstate' === 'site') {
3239 require_login();
3240 //ok
3241 } else if ('publishstate' === 'draft') {
3242 require_login();
3243 if ($USER->id != $entry->userid) {
3244 send_file_not_found();
3248 $filename = array_pop($args);
3249 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3251 if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
3252 send_file_not_found();
3255 send_stored_file($file, 10*60, 0, true); // download MUST be forced - security!
3257 // ========================================================================================================================
3258 } else if ($component === 'grade') {
3259 if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
3260 // Global gradebook files
3261 if ($CFG->forcelogin) {
3262 require_login();
3265 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3267 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3268 send_file_not_found();
3271 session_get_instance()->write_close(); // unlock session during fileserving
3272 send_stored_file($file, 60*60, 0, $forcedownload);
3274 } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
3275 //TODO: nobody implemented this yet in grade edit form!!
3276 send_file_not_found();
3278 if ($CFG->forcelogin || $course->id != SITEID) {
3279 require_login($course);
3282 $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
3284 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3285 send_file_not_found();
3288 session_get_instance()->write_close(); // unlock session during fileserving
3289 send_stored_file($file, 60*60, 0, $forcedownload);
3290 } else {
3291 send_file_not_found();
3294 // ========================================================================================================================
3295 } else if ($component === 'tag') {
3296 if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
3298 // All tag descriptions are going to be public but we still need to respect forcelogin
3299 if ($CFG->forcelogin) {
3300 require_login();
3303 $fullpath = "/$context->id/tag/description/".implode('/', $args);
3305 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3306 send_file_not_found();
3309 session_get_instance()->write_close(); // unlock session during fileserving
3310 send_stored_file($file, 60*60, 0, true);
3312 } else {
3313 send_file_not_found();
3316 // ========================================================================================================================
3317 } else if ($component === 'calendar') {
3318 if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
3320 // All events here are public the one requirement is that we respect forcelogin
3321 if ($CFG->forcelogin) {
3322 require_login();
3325 // Get the event if from the args array
3326 $eventid = array_shift($args);
3328 // Load the event from the database
3329 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
3330 send_file_not_found();
3332 // Check that we got an event and that it's userid is that of the user
3334 // Get the file and serve if successful
3335 $filename = array_pop($args);
3336 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3337 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3338 send_file_not_found();
3341 session_get_instance()->write_close(); // unlock session during fileserving
3342 send_stored_file($file, 60*60, 0, $forcedownload);
3344 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
3346 // Must be logged in, if they are not then they obviously can't be this user
3347 require_login();
3349 // Don't want guests here, potentially saves a DB call
3350 if (isguestuser()) {
3351 send_file_not_found();
3354 // Get the event if from the args array
3355 $eventid = array_shift($args);
3357 // Load the event from the database - user id must match
3358 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
3359 send_file_not_found();
3362 // Get the file and serve if successful
3363 $filename = array_pop($args);
3364 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3365 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3366 send_file_not_found();
3369 session_get_instance()->write_close(); // unlock session during fileserving
3370 send_stored_file($file, 60*60, 0, $forcedownload);
3372 } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
3374 // Respect forcelogin and require login unless this is the site.... it probably
3375 // should NEVER be the site
3376 if ($CFG->forcelogin || $course->id != SITEID) {
3377 require_login($course);
3380 // Must be able to at least view the course
3381 if (!is_enrolled($context) and !is_viewing($context)) {
3382 //TODO: hmm, do we really want to block guests here?
3383 send_file_not_found();
3386 // Get the event id
3387 $eventid = array_shift($args);
3389 // Load the event from the database we need to check whether it is
3390 // a) valid course event
3391 // b) a group event
3392 // Group events use the course context (there is no group context)
3393 if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
3394 send_file_not_found();
3397 // If its a group event require either membership of view all groups capability
3398 if ($event->eventtype === 'group') {
3399 if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
3400 send_file_not_found();
3402 } else if ($event->eventtype === 'course') {
3403 //ok
3404 } else {
3405 // some other type
3406 send_file_not_found();
3409 // If we get this far we can serve the file
3410 $filename = array_pop($args);
3411 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3412 if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
3413 send_file_not_found();
3416 session_get_instance()->write_close(); // unlock session during fileserving
3417 send_stored_file($file, 60*60, 0, $forcedownload);
3419 } else {
3420 send_file_not_found();
3423 // ========================================================================================================================
3424 } else if ($component === 'user') {
3425 if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
3426 $redirect = false;
3427 if (count($args) == 1) {
3428 $themename = theme_config::DEFAULT_THEME;
3429 $filename = array_shift($args);
3430 } else {
3431 $themename = array_shift($args);
3432 $filename = array_shift($args);
3434 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
3435 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
3436 // protect images if login required and not logged in;
3437 // also if login is required for profile images and is not logged in or guest
3438 // do not use require_login() because it is expensive and not suitable here anyway
3439 $redirect = true;
3441 if (!$redirect and ($filename !== 'f1' and $filename !== 'f2')) {
3442 $filename = 'f1';
3443 $redirect = true;
3445 if (!$redirect && !$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'/.png')) {
3446 if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg')) {
3447 $redirect = true;
3450 if ($redirect) {
3451 $theme = theme_config::load($themename);
3452 redirect($theme->pix_url('u/'.$filename, 'moodle'));
3454 send_stored_file($file, 60*60*24); // enable long caching, there are many images on each page
3456 } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
3457 require_login();
3459 if (isguestuser()) {
3460 send_file_not_found();
3463 if ($USER->id !== $context->instanceid) {
3464 send_file_not_found();
3467 $filename = array_pop($args);
3468 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3469 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3470 send_file_not_found();
3473 session_get_instance()->write_close(); // unlock session during fileserving
3474 send_stored_file($file, 0, 0, true); // must force download - security!
3476 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
3478 if ($CFG->forcelogin) {
3479 require_login();
3482 $userid = $context->instanceid;
3484 if ($USER->id == $userid) {
3485 // always can access own
3487 } else if (!empty($CFG->forceloginforprofiles)) {
3488 require_login();
3490 if (isguestuser()) {
3491 send_file_not_found();
3494 // we allow access to site profile of all course contacts (usually teachers)
3495 if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
3496 send_file_not_found();
3499 $canview = false;
3500 if (has_capability('moodle/user:viewdetails', $context)) {
3501 $canview = true;
3502 } else {
3503 $courses = enrol_get_my_courses();
3506 while (!$canview && count($courses) > 0) {
3507 $course = array_shift($courses);
3508 if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) {
3509 $canview = true;
3514 $filename = array_pop($args);
3515 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3516 if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
3517 send_file_not_found();
3520 session_get_instance()->write_close(); // unlock session during fileserving
3521 send_stored_file($file, 0, 0, true); // must force download - security!
3523 } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
3524 $userid = (int)array_shift($args);
3525 $usercontext = get_context_instance(CONTEXT_USER, $userid);
3527 if ($CFG->forcelogin) {
3528 require_login();
3531 if (!empty($CFG->forceloginforprofiles)) {
3532 require_login();
3533 if (isguestuser()) {
3534 print_error('noguest');
3537 //TODO: review this logic of user profile access prevention
3538 if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
3539 print_error('usernotavailable');
3541 if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
3542 print_error('cannotviewprofile');
3544 if (!is_enrolled($context, $userid)) {
3545 print_error('notenrolledprofile');
3547 if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3548 print_error('groupnotamember');
3552 $filename = array_pop($args);
3553 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3554 if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
3555 send_file_not_found();
3558 session_get_instance()->write_close(); // unlock session during fileserving
3559 send_stored_file($file, 0, 0, true); // must force download - security!
3561 } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
3562 require_login();
3564 if (isguestuser()) {
3565 send_file_not_found();
3567 $userid = $context->instanceid;
3569 if ($USER->id != $userid) {
3570 send_file_not_found();
3573 $filename = array_pop($args);
3574 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3575 if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
3576 send_file_not_found();
3579 session_get_instance()->write_close(); // unlock session during fileserving
3580 send_stored_file($file, 0, 0, true); // must force download - security!
3582 } else {
3583 send_file_not_found();
3586 // ========================================================================================================================
3587 } else if ($component === 'coursecat') {
3588 if ($context->contextlevel != CONTEXT_COURSECAT) {
3589 send_file_not_found();
3592 if ($filearea === 'description') {
3593 if ($CFG->forcelogin) {
3594 // no login necessary - unless login forced everywhere
3595 require_login();
3598 $filename = array_pop($args);
3599 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3600 if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
3601 send_file_not_found();
3604 session_get_instance()->write_close(); // unlock session during fileserving
3605 send_stored_file($file, 60*60, 0, $forcedownload);
3606 } else {
3607 send_file_not_found();
3610 // ========================================================================================================================
3611 } else if ($component === 'course') {
3612 if ($context->contextlevel != CONTEXT_COURSE) {
3613 send_file_not_found();
3616 if ($filearea === 'summary') {
3617 if ($CFG->forcelogin) {
3618 require_login();
3621 $filename = array_pop($args);
3622 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3623 if (!$file = $fs->get_file($context->id, 'course', 'summary', 0, $filepath, $filename) or $file->is_directory()) {
3624 send_file_not_found();
3627 session_get_instance()->write_close(); // unlock session during fileserving
3628 send_stored_file($file, 60*60, 0, $forcedownload);
3630 } else if ($filearea === 'section') {
3631 if ($CFG->forcelogin) {
3632 require_login($course);
3633 } else if ($course->id != SITEID) {
3634 require_login($course);
3637 $sectionid = (int)array_shift($args);
3639 if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
3640 send_file_not_found();
3643 if ($course->numsections < $section->section) {
3644 if (!has_capability('moodle/course:update', $context)) {
3645 // block access to unavailable sections if can not edit course
3646 send_file_not_found();
3650 $filename = array_pop($args);
3651 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3652 if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3653 send_file_not_found();
3656 session_get_instance()->write_close(); // unlock session during fileserving
3657 send_stored_file($file, 60*60, 0, $forcedownload);
3659 } else {
3660 send_file_not_found();
3663 } else if ($component === 'group') {
3664 if ($context->contextlevel != CONTEXT_COURSE) {
3665 send_file_not_found();
3668 require_course_login($course, true, null, false);
3670 $groupid = (int)array_shift($args);
3672 $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
3673 if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
3674 // do not allow access to separate group info if not member or teacher
3675 send_file_not_found();
3678 if ($filearea === 'description') {
3680 require_login($course);
3682 $filename = array_pop($args);
3683 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3684 if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
3685 send_file_not_found();
3688 session_get_instance()->write_close(); // unlock session during fileserving
3689 send_stored_file($file, 60*60, 0, $forcedownload);
3691 } else if ($filearea === 'icon') {
3692 $filename = array_pop($args);
3694 if ($filename !== 'f1' and $filename !== 'f2') {
3695 send_file_not_found();
3697 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
3698 if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
3699 send_file_not_found();
3703 session_get_instance()->write_close(); // unlock session during fileserving
3704 send_stored_file($file, 60*60);
3706 } else {
3707 send_file_not_found();
3710 } else if ($component === 'grouping') {
3711 if ($context->contextlevel != CONTEXT_COURSE) {
3712 send_file_not_found();
3715 require_login($course);
3717 $groupingid = (int)array_shift($args);
3719 // note: everybody has access to grouping desc images for now
3720 if ($filearea === 'description') {
3722 $filename = array_pop($args);
3723 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3724 if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
3725 send_file_not_found();
3728 session_get_instance()->write_close(); // unlock session during fileserving
3729 send_stored_file($file, 60*60, 0, $forcedownload);
3731 } else {
3732 send_file_not_found();
3735 // ========================================================================================================================
3736 } else if ($component === 'backup') {
3737 if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
3738 require_login($course);
3739 require_capability('moodle/backup:downloadfile', $context);
3741 $filename = array_pop($args);
3742 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3743 if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
3744 send_file_not_found();
3747 session_get_instance()->write_close(); // unlock session during fileserving
3748 send_stored_file($file, 0, 0, $forcedownload);
3750 } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
3751 require_login($course);
3752 require_capability('moodle/backup:downloadfile', $context);
3754 $sectionid = (int)array_shift($args);
3756 $filename = array_pop($args);
3757 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3758 if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
3759 send_file_not_found();
3762 session_get_instance()->write_close();
3763 send_stored_file($file, 60*60, 0, $forcedownload);
3765 } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
3766 require_login($course, false, $cm);
3767 require_capability('moodle/backup:downloadfile', $context);
3769 $filename = array_pop($args);
3770 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3771 if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
3772 send_file_not_found();
3775 session_get_instance()->write_close();
3776 send_stored_file($file, 60*60, 0, $forcedownload);
3778 } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
3779 // Backup files that were generated by the automated backup systems.
3781 require_login($course);
3782 require_capability('moodle/site:config', $context);
3784 $filename = array_pop($args);
3785 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3786 if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
3787 send_file_not_found();
3790 session_get_instance()->write_close(); // unlock session during fileserving
3791 send_stored_file($file, 0, 0, $forcedownload);
3793 } else {
3794 send_file_not_found();
3797 // ========================================================================================================================
3798 } else if ($component === 'question') {
3799 require_once($CFG->libdir . '/questionlib.php');
3800 question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
3801 send_file_not_found();
3803 // ========================================================================================================================
3804 } else if ($component === 'grading') {
3805 if ($filearea === 'description') {
3806 // files embedded into the form definition description
3808 if ($context->contextlevel == CONTEXT_SYSTEM) {
3809 require_login();
3811 } else if ($context->contextlevel >= CONTEXT_COURSE) {
3812 require_login($course, false, $cm);
3814 } else {
3815 send_file_not_found();
3818 $formid = (int)array_shift($args);
3820 $sql = "SELECT ga.id
3821 FROM {grading_areas} ga
3822 JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
3823 WHERE gd.id = ? AND ga.contextid = ?";
3824 $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
3826 if (!$areaid) {
3827 send_file_not_found();
3830 $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
3832 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3833 send_file_not_found();
3836 session_get_instance()->write_close(); // unlock session during fileserving
3837 send_stored_file($file, 60*60, 0, $forcedownload);
3840 // ========================================================================================================================
3841 } else if (strpos($component, 'mod_') === 0) {
3842 $modname = substr($component, 4);
3843 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
3844 send_file_not_found();
3846 require_once("$CFG->dirroot/mod/$modname/lib.php");
3848 if ($context->contextlevel == CONTEXT_MODULE) {
3849 if ($cm->modname !== $modname) {
3850 // somebody tries to gain illegal access, cm type must match the component!
3851 send_file_not_found();
3855 if ($filearea === 'intro') {
3856 if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
3857 send_file_not_found();
3859 require_course_login($course, true, $cm);
3861 // all users may access it
3862 $filename = array_pop($args);
3863 $filepath = $args ? '/'.implode('/', $args).'/' : '/';
3864 if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
3865 send_file_not_found();
3868 $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
3870 // finally send the file
3871 send_stored_file($file, $lifetime, 0);
3874 $filefunction = $component.'_pluginfile';
3875 $filefunctionold = $modname.'_pluginfile';
3876 if (function_exists($filefunction)) {
3877 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
3878 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload);
3879 } else if (function_exists($filefunctionold)) {
3880 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
3881 $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload);
3884 send_file_not_found();
3886 // ========================================================================================================================
3887 } else if (strpos($component, 'block_') === 0) {
3888 $blockname = substr($component, 6);
3889 // note: no more class methods in blocks please, that is ....
3890 if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
3891 send_file_not_found();
3893 require_once("$CFG->dirroot/blocks/$blockname/lib.php");
3895 if ($context->contextlevel == CONTEXT_BLOCK) {
3896 $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
3897 if ($birecord->blockname !== $blockname) {
3898 // somebody tries to gain illegal access, cm type must match the component!
3899 send_file_not_found();
3902 $bprecord = $DB->get_record('block_positions', array('blockinstanceid' => $context->instanceid), 'visible');
3903 // User can't access file, if block is hidden or doesn't have block:view capability
3904 if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
3905 send_file_not_found();
3907 } else {
3908 $birecord = null;
3911 $filefunction = $component.'_pluginfile';
3912 if (function_exists($filefunction)) {
3913 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
3914 $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload);
3917 send_file_not_found();
3919 } else if (strpos($component, '_') === false) {
3920 // all core subsystems have to be specified above, no more guessing here!
3921 send_file_not_found();
3923 } else {
3924 // try to serve general plugin file in arbitrary context
3925 $dir = get_component_directory($component);
3926 if (!file_exists("$dir/lib.php")) {
3927 send_file_not_found();
3929 include_once("$dir/lib.php");
3931 $filefunction = $component.'_pluginfile';
3932 if (function_exists($filefunction)) {
3933 // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
3934 $filefunction($course, $cm, $context, $filearea, $args, $forcedownload);
3937 send_file_not_found();