Merge branch 'MDL-27293-customlang-timeout_20_STABLE' of git://github.com/mudrd8mz...
[moodle.git] / lib / filelib.php
blob3e86263bc1273eb2349d80a4828fda0d440eb6ad
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 if (is_null($itemid) or is_null($context)) {
115 $contextid = null;
116 $itemid = null;
117 if (!isset($data->{$field})) {
118 $data->{$field} = '';
120 if (!isset($data->{$field.'format'})) {
121 $data->{$field.'format'} = editors_get_preferred_format();
123 if (!$options['noclean']) {
124 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
127 } else {
128 if ($options['trusttext']) {
129 // noclean ignored if trusttext enabled
130 if (!isset($data->{$field.'trust'})) {
131 $data->{$field.'trust'} = 0;
133 $data = trusttext_pre_edit($data, $field, $context);
134 } else {
135 if (!$options['noclean']) {
136 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
139 $contextid = $context->id;
142 if ($options['maxfiles'] != 0) {
143 $draftid_editor = file_get_submitted_draft_itemid($field);
144 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
145 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
146 } else {
147 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
150 return $data;
154 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
156 * This function moves files from draft area to the destination area and
157 * encodes URLs to the draft files so they can be safely saved into DB. The
158 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
159 * is the name of the database field to hold the wysiwyg editor content. The
160 * editor data comes as an array with text, format and itemid properties. This
161 * function automatically adds $data properties foobar, foobarformat and
162 * foobartrust, where foobar has URL to embedded files encoded.
164 * @param object $data raw data submitted by the form
165 * @param string $field name of the database field containing the html with embedded media files
166 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
167 * @param object $context context, required for existing data
168 * @param string component
169 * @param string $filearea file area name
170 * @param int $itemid item id, required if item exists
171 * @return object modified data object
173 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
174 $options = (array)$options;
175 if (!isset($options['trusttext'])) {
176 $options['trusttext'] = false;
178 if (!isset($options['forcehttps'])) {
179 $options['forcehttps'] = false;
181 if (!isset($options['subdirs'])) {
182 $options['subdirs'] = false;
184 if (!isset($options['maxfiles'])) {
185 $options['maxfiles'] = 0; // no files by default
187 if (!isset($options['maxbytes'])) {
188 $options['maxbytes'] = 0; // unlimited
191 if ($options['trusttext']) {
192 $data->{$field.'trust'} = trusttext_trusted($context);
193 } else {
194 $data->{$field.'trust'} = 0;
197 $editor = $data->{$field.'_editor'};
199 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
200 $data->{$field} = $editor['text'];
201 } else {
202 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
204 $data->{$field.'format'} = $editor['format'];
206 return $data;
210 * Saves text and files modified by Editor formslib element
212 * @param object $data $database entry field
213 * @param string $field name of data field
214 * @param array $options various options
215 * @param object $context context - must already exist
216 * @param string $component
217 * @param string $filearea file area name
218 * @param int $itemid must already exist, usually means data is in db
219 * @return object modified data obejct
221 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
222 $options = (array)$options;
223 if (!isset($options['subdirs'])) {
224 $options['subdirs'] = false;
226 if (is_null($itemid) or is_null($context)) {
227 $itemid = null;
228 $contextid = null;
229 } else {
230 $contextid = $context->id;
233 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
234 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
235 $data->{$field.'_filemanager'} = $draftid_editor;
237 return $data;
241 * Saves files modified by File manager formslib element
243 * @param object $data $database entry field
244 * @param string $field name of data field
245 * @param array $options various options
246 * @param object $context context - must already exist
247 * @param string $component
248 * @param string $filearea file area name
249 * @param int $itemid must already exist, usually means data is in db
250 * @return object modified data obejct
252 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
253 $options = (array)$options;
254 if (!isset($options['subdirs'])) {
255 $options['subdirs'] = false;
257 if (!isset($options['maxfiles'])) {
258 $options['maxfiles'] = -1; // unlimited
260 if (!isset($options['maxbytes'])) {
261 $options['maxbytes'] = 0; // unlimited
264 if (empty($data->{$field.'_filemanager'})) {
265 $data->$field = '';
267 } else {
268 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
269 $fs = get_file_storage();
271 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
272 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
273 } else {
274 $data->$field = '';
278 return $data;
283 * @global object
284 * @global object
285 * @return int a random but available draft itemid that can be used to create a new draft
286 * file area.
288 function file_get_unused_draft_itemid() {
289 global $DB, $USER;
291 if (isguestuser() or !isloggedin()) {
292 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
293 print_error('noguest');
296 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
298 $fs = get_file_storage();
299 $draftitemid = rand(1, 999999999);
300 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
301 $draftitemid = rand(1, 999999999);
304 return $draftitemid;
308 * Initialise a draft file area from a real one by copying the files. A draft
309 * area will be created if one does not already exist. Normally you should
310 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
312 * @global object
313 * @global object
314 * @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.
315 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
316 * @param string $component
317 * @param string $filearea helps indentify the file area.
318 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
319 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
320 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
321 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
323 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
324 global $CFG, $USER, $CFG;
326 $options = (array)$options;
327 if (!isset($options['subdirs'])) {
328 $options['subdirs'] = false;
330 if (!isset($options['forcehttps'])) {
331 $options['forcehttps'] = false;
334 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
335 $fs = get_file_storage();
337 if (empty($draftitemid)) {
338 // create a new area and copy existing files into
339 $draftitemid = file_get_unused_draft_itemid();
340 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
341 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
342 foreach ($files as $file) {
343 if ($file->is_directory() and $file->get_filepath() === '/') {
344 // we need a way to mark the age of each draft area,
345 // by not copying the root dir we force it to be created automatically with current timestamp
346 continue;
348 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
349 continue;
351 $fs->create_file_from_storedfile($file_record, $file);
354 if (!is_null($text)) {
355 // at this point there should not be any draftfile links yet,
356 // because this is a new text from database that should still contain the @@pluginfile@@ links
357 // this happens when developers forget to post process the text
358 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
360 } else {
361 // nothing to do
364 if (is_null($text)) {
365 return null;
368 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
369 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
373 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
375 * @global object
376 * @param string $text The content that may contain ULRs in need of rewriting.
377 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
378 * @param integer $contextid This parameter and the next two identify the file area to use.
379 * @param string $component
380 * @param string $filearea helps identify the file area.
381 * @param integer $itemid helps identify the file area.
382 * @param array $options text and file options ('forcehttps'=>false)
383 * @return string the processed text.
385 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
386 global $CFG;
388 $options = (array)$options;
389 if (!isset($options['forcehttps'])) {
390 $options['forcehttps'] = false;
393 if (!$CFG->slasharguments) {
394 $file = $file . '?file=';
397 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
399 if ($itemid !== null) {
400 $baseurl .= "$itemid/";
403 if ($options['forcehttps']) {
404 $baseurl = str_replace('http://', 'https://', $baseurl);
407 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
411 * Returns information about files in a draft area.
413 * @global object
414 * @global object
415 * @param integer $draftitemid the draft area item id.
416 * @return array with the following entries:
417 * 'filecount' => number of files in the draft area.
418 * (more information will be added as needed).
420 function file_get_draft_area_info($draftitemid) {
421 global $CFG, $USER;
423 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
424 $fs = get_file_storage();
426 $results = array();
428 // The number of files
429 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
430 $results['filecount'] = count($draftfiles);
431 $results['filesize'] = 0;
432 foreach ($draftfiles as $file) {
433 $results['filesize'] += $file->get_filesize();
436 return $results;
440 * Get used space of files
441 * @return int total bytes
443 function file_get_user_used_space() {
444 global $DB, $USER;
446 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
447 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
448 JOIN (SELECT contenthash, filename, MAX(id) AS id
449 FROM {files}
450 WHERE contextid = ? AND component = ? AND filearea != ?
451 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
452 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
453 $record = $DB->get_record_sql($sql, $params);
454 return (int)$record->totalbytes;
458 * Convert any string to a valid filepath
459 * @param string $str
460 * @return string path
462 function file_correct_filepath($str) { //TODO: what is this? (skodak)
463 if ($str == '/' or empty($str)) {
464 return '/';
465 } else {
466 return '/'.trim($str, './@#$ ').'/';
471 * Generate a folder tree of draft area of current USER recursively
472 * @param int $itemid
473 * @param string $filepath
474 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
476 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
477 global $USER, $OUTPUT, $CFG;
478 $data->children = array();
479 $context = get_context_instance(CONTEXT_USER, $USER->id);
480 $fs = get_file_storage();
481 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
482 foreach ($files as $file) {
483 if ($file->is_directory()) {
484 $item = new stdClass();
485 $item->sortorder = $file->get_sortorder();
486 $item->filepath = $file->get_filepath();
488 $foldername = explode('/', trim($item->filepath, '/'));
489 $item->fullname = trim(array_pop($foldername), '/');
491 $item->id = uniqid();
492 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
493 $data->children[] = $item;
494 } else {
495 continue;
502 * Listing all files (including folders) in current path (draft area)
503 * used by file manager
504 * @param int $draftitemid
505 * @param string $filepath
506 * @return mixed
508 function file_get_drafarea_files($draftitemid, $filepath = '/') {
509 global $USER, $OUTPUT, $CFG;
511 $context = get_context_instance(CONTEXT_USER, $USER->id);
512 $fs = get_file_storage();
514 $data = new stdClass();
515 $data->path = array();
516 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
518 // will be used to build breadcrumb
519 $trail = '';
520 if ($filepath !== '/') {
521 $filepath = file_correct_filepath($filepath);
522 $parts = explode('/', $filepath);
523 foreach ($parts as $part) {
524 if ($part != '' && $part != null) {
525 $trail .= ('/'.$part.'/');
526 $data->path[] = array('name'=>$part, 'path'=>$trail);
531 $list = array();
532 $maxlength = 12;
533 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
534 foreach ($files as $file) {
535 $item = new stdClass();
536 $item->filename = $file->get_filename();
537 $item->filepath = $file->get_filepath();
538 $item->fullname = trim($item->filename, '/');
539 $filesize = $file->get_filesize();
540 $item->filesize = $filesize ? display_size($filesize) : '';
542 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
543 $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
544 $item->sortorder = $file->get_sortorder();
546 if ($icon == 'zip') {
547 $item->type = 'zip';
548 } else {
549 $item->type = 'file';
552 if ($file->is_directory()) {
553 $item->filesize = 0;
554 $item->icon = $OUTPUT->pix_url('f/folder')->out();
555 $item->type = 'folder';
556 $foldername = explode('/', trim($item->filepath, '/'));
557 $item->fullname = trim(array_pop($foldername), '/');
558 } else {
559 // do NOT use file browser here!
560 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
562 $list[] = $item;
565 $data->itemid = $draftitemid;
566 $data->list = $list;
567 return $data;
571 * Returns draft area itemid for a given element.
573 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
574 * @return integer the itemid, or 0 if there is not one yet.
576 function file_get_submitted_draft_itemid($elname) {
577 $param = optional_param($elname, 0, PARAM_INT);
578 if ($param) {
579 require_sesskey();
581 if (is_array($param)) {
582 if (!empty($param['itemid'])) {
583 $param = $param['itemid'];
584 } else {
585 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
586 return false;
589 return $param;
593 * Saves files from a draft file area to a real one (merging the list of files).
594 * Can rewrite URLs in some content at the same time if desired.
596 * @global object
597 * @global object
598 * @param integer $draftitemid the id of the draft area to use. Normally obtained
599 * from file_get_submitted_draft_itemid('elementname') or similar.
600 * @param integer $contextid This parameter and the next two identify the file area to save to.
601 * @param string $component
602 * @param string $filearea indentifies the file area.
603 * @param integer $itemid helps identifies the file area.
604 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
605 * @param string $text some html content that needs to have embedded links rewritten
606 * to the @@PLUGINFILE@@ form for saving in the database.
607 * @param boolean $forcehttps force https urls.
608 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
610 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
611 global $USER;
613 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
614 $fs = get_file_storage();
616 $options = (array)$options;
617 if (!isset($options['subdirs'])) {
618 $options['subdirs'] = false;
620 if (!isset($options['maxfiles'])) {
621 $options['maxfiles'] = -1; // unlimited
623 if (!isset($options['maxbytes'])) {
624 $options['maxbytes'] = 0; // unlimited
627 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
628 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
630 if (count($draftfiles) < 2) {
631 // means there are no files - one file means root dir only ;-)
632 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
634 } else if (count($oldfiles) < 2) {
635 $filecount = 0;
636 // there were no files before - one file means root dir only ;-)
637 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
638 foreach ($draftfiles as $file) {
639 if (!$options['subdirs']) {
640 if ($file->get_filepath() !== '/' or $file->is_directory()) {
641 continue;
644 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
645 // oversized file - should not get here at all
646 continue;
648 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
649 // more files - should not get here at all
650 break;
652 if (!$file->is_directory()) {
653 $filecount++;
655 $fs->create_file_from_storedfile($file_record, $file);
658 } else {
659 // we have to merge old and new files - we want to keep file ids for files that were not changed
660 // we change time modified for all new and changed files, we keep time created as is
661 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
663 $newhashes = array();
664 foreach ($draftfiles as $file) {
665 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
666 $newhashes[$newhash] = $file;
668 $filecount = 0;
669 foreach ($oldfiles as $oldfile) {
670 $oldhash = $oldfile->get_pathnamehash();
671 if (!isset($newhashes[$oldhash])) {
672 // delete files not needed any more - deleted by user
673 $oldfile->delete();
674 continue;
676 $newfile = $newhashes[$oldhash];
677 if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
678 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
679 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
680 // file was changed, use updated with new timemodified data
681 $oldfile->delete();
682 continue;
684 // unchanged file or directory - we keep it as is
685 unset($newhashes[$oldhash]);
686 if (!$oldfile->is_directory()) {
687 $filecount++;
691 // now add new/changed files
692 // the size and subdirectory tests are extra safety only, the UI should prevent it
693 foreach ($newhashes as $file) {
694 if (!$options['subdirs']) {
695 if ($file->get_filepath() !== '/' or $file->is_directory()) {
696 continue;
699 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
700 // oversized file - should not get here at all
701 continue;
703 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
704 // more files - should not get here at all
705 break;
707 if (!$file->is_directory()) {
708 $filecount++;
710 $fs->create_file_from_storedfile($file_record, $file);
714 // note: do not purge the draft area - we clean up areas later in cron,
715 // the reason is that user might press submit twice and they would loose the files,
716 // also sometimes we might want to use hacks that save files into two different areas
718 if (is_null($text)) {
719 return null;
720 } else {
721 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
726 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
727 * ready to be saved in the database. Normally, this is done automatically by
728 * {@link file_save_draft_area_files()}.
729 * @param string $text the content to process.
730 * @param int $draftitemid the draft file area the content was using.
731 * @param bool $forcehttps whether the content contains https URLs. Default false.
732 * @return string the processed content.
734 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
735 global $CFG, $USER;
737 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
739 $wwwroot = $CFG->wwwroot;
740 if ($forcehttps) {
741 $wwwroot = str_replace('http://', 'https://', $wwwroot);
744 // relink embedded files if text submitted - no absolute links allowed in database!
745 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
747 if (strpos($text, 'draftfile.php?file=') !== false) {
748 $matches = array();
749 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
750 if ($matches) {
751 foreach ($matches[0] as $match) {
752 $replace = str_ireplace('%2F', '/', $match);
753 $text = str_replace($match, $replace, $text);
756 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
759 return $text;
763 * Set file sort order
764 * @global object $DB
765 * @param integer $contextid the context id
766 * @param string $component
767 * @param string $filearea file area.
768 * @param integer $itemid itemid.
769 * @param string $filepath file path.
770 * @param string $filename file name.
771 * @param integer $sortorer the sort order of file.
772 * @return boolean
774 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
775 global $DB;
776 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
777 if ($file_record = $DB->get_record('files', $conditions)) {
778 $sortorder = (int)$sortorder;
779 $file_record->sortorder = $sortorder;
780 $DB->update_record('files', $file_record);
781 return true;
783 return false;
787 * reset file sort order number to 0
788 * @global object $DB
789 * @param integer $contextid the context id
790 * @param string $component
791 * @param string $filearea file area.
792 * @param integer $itemid itemid.
793 * @return boolean
795 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
796 global $DB;
798 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
799 if ($itemid !== false) {
800 $conditions['itemid'] = $itemid;
803 $file_records = $DB->get_records('files', $conditions);
804 foreach ($file_records as $file_record) {
805 $file_record->sortorder = 0;
806 $DB->update_record('files', $file_record);
808 return true;
812 * Returns description of upload error
814 * @param int $errorcode found in $_FILES['filename.ext']['error']
815 * @return string error description string, '' if ok
817 function file_get_upload_error($errorcode) {
819 switch ($errorcode) {
820 case 0: // UPLOAD_ERR_OK - no error
821 $errmessage = '';
822 break;
824 case 1: // UPLOAD_ERR_INI_SIZE
825 $errmessage = get_string('uploadserverlimit');
826 break;
828 case 2: // UPLOAD_ERR_FORM_SIZE
829 $errmessage = get_string('uploadformlimit');
830 break;
832 case 3: // UPLOAD_ERR_PARTIAL
833 $errmessage = get_string('uploadpartialfile');
834 break;
836 case 4: // UPLOAD_ERR_NO_FILE
837 $errmessage = get_string('uploadnofilefound');
838 break;
840 // Note: there is no error with a value of 5
842 case 6: // UPLOAD_ERR_NO_TMP_DIR
843 $errmessage = get_string('uploadnotempdir');
844 break;
846 case 7: // UPLOAD_ERR_CANT_WRITE
847 $errmessage = get_string('uploadcantwrite');
848 break;
850 case 8: // UPLOAD_ERR_EXTENSION
851 $errmessage = get_string('uploadextension');
852 break;
854 default:
855 $errmessage = get_string('uploadproblem');
858 return $errmessage;
862 * Recursive function formating an array in POST parameter
863 * @param array $arraydata - the array that we are going to format and add into &$data array
864 * @param string $currentdata - a row of the final postdata array at instant T
865 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
866 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
868 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
869 foreach ($arraydata as $k=>$v) {
870 $newcurrentdata = $currentdata;
871 if (is_array($v)) { //the value is an array, call the function recursively
872 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
873 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
874 } else { //add the POST parameter to the $data array
875 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
881 * Transform a PHP array into POST parameter
882 * (see the recursive function format_array_postdata_for_curlcall)
883 * @param array $postdata
884 * @return array containing all POST parameters (1 row = 1 POST parameter)
886 function format_postdata_for_curlcall($postdata) {
887 $data = array();
888 foreach ($postdata as $k=>$v) {
889 if (is_array($v)) {
890 $currentdata = urlencode($k);
891 format_array_postdata_for_curlcall($v, $currentdata, $data);
892 } else {
893 $data[] = urlencode($k).'='.urlencode($v);
896 $convertedpostdata = implode('&', $data);
897 return $convertedpostdata;
904 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
905 * Due to security concerns only downloads from http(s) sources are supported.
907 * @global object
908 * @param string $url file url starting with http(s)://
909 * @param array $headers http headers, null if none. If set, should be an
910 * associative array of header name => value pairs.
911 * @param array $postdata array means use POST request with given parameters
912 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
913 * (if false, just returns content)
914 * @param int $timeout timeout for complete download process including all file transfer
915 * (default 5 minutes)
916 * @param int $connecttimeout timeout for connection to server; this is the timeout that
917 * usually happens if the remote server is completely down (default 20 seconds);
918 * may not work when using proxy
919 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
920 * @param string $tofile store the downloaded content to file instead of returning it
921 * @return mixed false if request failed or content of the file as string if ok. true if file downloaded into $tofile successfully.
923 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL) {
924 global $CFG;
926 // some extra security
927 $newlines = array("\r", "\n");
928 if (is_array($headers) ) {
929 foreach ($headers as $key => $value) {
930 $headers[$key] = str_replace($newlines, '', $value);
933 $url = str_replace($newlines, '', $url);
934 if (!preg_match('|^https?://|i', $url)) {
935 if ($fullresponse) {
936 $response = new stdClass();
937 $response->status = 0;
938 $response->headers = array();
939 $response->response_code = 'Invalid protocol specified in url';
940 $response->results = '';
941 $response->error = 'Invalid protocol specified in url';
942 return $response;
943 } else {
944 return false;
948 // check if proxy (if used) should be bypassed for this url
949 $proxybypass = is_proxybypass($url);
951 if (!$ch = curl_init($url)) {
952 debugging('Can not init curl.');
953 return false;
956 // set extra headers
957 if (is_array($headers) ) {
958 $headers2 = array();
959 foreach ($headers as $key => $value) {
960 $headers2[] = "$key: $value";
962 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
966 if ($skipcertverify) {
967 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
970 // use POST if requested
971 if (is_array($postdata)) {
972 $postdata = format_postdata_for_curlcall($postdata);
973 curl_setopt($ch, CURLOPT_POST, true);
974 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
977 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
978 curl_setopt($ch, CURLOPT_HEADER, false);
979 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
980 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
981 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
982 // TODO: add version test for '7.10.5'
983 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
984 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
987 if (!empty($CFG->proxyhost) and !$proxybypass) {
988 // SOCKS supported in PHP5 only
989 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
990 if (defined('CURLPROXY_SOCKS5')) {
991 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
992 } else {
993 curl_close($ch);
994 if ($fullresponse) {
995 $response = new stdClass();
996 $response->status = '0';
997 $response->headers = array();
998 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
999 $response->results = '';
1000 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1001 return $response;
1002 } else {
1003 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1004 return false;
1009 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1011 if (empty($CFG->proxyport)) {
1012 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1013 } else {
1014 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1017 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1018 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1019 if (defined('CURLOPT_PROXYAUTH')) {
1020 // any proxy authentication if PHP 5.1
1021 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1026 // set up header and content handlers
1027 $received = new stdClass();
1028 $received->headers = array(); // received headers array
1029 $received->tofile = $tofile;
1030 $received->fh = null;
1031 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1032 if ($tofile) {
1033 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1036 $result = curl_exec($ch);
1038 // try to detect encoding problems
1039 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1040 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1041 $result = curl_exec($ch);
1044 if ($received->fh) {
1045 fclose($received->fh);
1048 if (curl_errno($ch)) {
1049 $error = curl_error($ch);
1050 $error_no = curl_errno($ch);
1051 curl_close($ch);
1053 if ($fullresponse) {
1054 $response = new stdClass();
1055 if ($error_no == 28) {
1056 $response->status = '-100'; // mimic snoopy
1057 } else {
1058 $response->status = '0';
1060 $response->headers = array();
1061 $response->response_code = $error;
1062 $response->results = false;
1063 $response->error = $error;
1064 return $response;
1065 } else {
1066 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1067 return false;
1070 } else {
1071 $info = curl_getinfo($ch);
1072 curl_close($ch);
1074 if (empty($info['http_code'])) {
1075 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1076 $response = new stdClass();
1077 $response->status = '0';
1078 $response->headers = array();
1079 $response->response_code = 'Unknown cURL error';
1080 $response->results = false; // do NOT change this, we really want to ignore the result!
1081 $response->error = 'Unknown cURL error';
1083 } else {
1084 $response = new stdClass();;
1085 $response->status = (string)$info['http_code'];
1086 $response->headers = $received->headers;
1087 $response->response_code = $received->headers[0];
1088 $response->results = $result;
1089 $response->error = '';
1092 if ($fullresponse) {
1093 return $response;
1094 } else if ($info['http_code'] != 200) {
1095 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1096 return false;
1097 } else {
1098 return $response->results;
1104 * internal implementation
1106 function download_file_content_header_handler($received, $ch, $header) {
1107 $received->headers[] = $header;
1108 return strlen($header);
1112 * internal implementation
1114 function download_file_content_write_handler($received, $ch, $data) {
1115 if (!$received->fh) {
1116 $received->fh = fopen($received->tofile, 'w');
1117 if ($received->fh === false) {
1118 // bad luck, file creation or overriding failed
1119 return 0;
1122 if (fwrite($received->fh, $data) === false) {
1123 // bad luck, write failed, let's abort completely
1124 return 0;
1126 return strlen($data);
1130 * @return array List of information about file types based on extensions.
1131 * Associative array of extension (lower-case) to associative array
1132 * from 'element name' to data. Current element names are 'type' and 'icon'.
1133 * Unknown types should use the 'xxx' entry which includes defaults.
1135 function get_mimetypes_array() {
1136 static $mimearray = array (
1137 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1138 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1139 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
1140 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1141 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1142 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1143 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1144 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1145 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1146 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1147 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1148 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1149 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1150 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1151 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1152 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1153 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1154 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1155 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1156 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1157 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1159 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1160 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1161 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1162 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1163 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1165 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1166 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1167 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1168 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1169 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1170 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1171 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1172 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1173 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1174 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1175 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1176 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1177 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1178 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1179 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1180 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1181 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1182 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1183 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1184 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1185 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1186 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1187 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1188 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1189 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1190 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1191 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1192 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1193 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1194 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1195 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1196 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1197 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1198 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1199 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1200 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1201 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1202 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1203 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1204 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1205 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1206 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1207 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1208 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1209 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1210 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1211 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1212 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1214 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1215 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1216 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1217 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1218 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1219 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1220 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1221 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1222 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1223 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1224 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1225 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1226 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1227 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1228 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1229 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1230 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
1232 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1233 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1234 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1235 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1236 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1237 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1239 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1240 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1241 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1242 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1243 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1244 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1245 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1246 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1247 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1249 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1250 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1251 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1252 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1253 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1254 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1255 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
1256 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1257 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1258 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
1259 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1260 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1261 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1262 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1263 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1264 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1265 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1266 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1267 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1268 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1270 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1271 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1272 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1273 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1274 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1275 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1276 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1277 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1278 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1279 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1281 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1282 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1283 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1284 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1285 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1286 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1287 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1288 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1289 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1290 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
1291 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1292 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1293 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1294 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1295 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1297 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1298 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1299 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1300 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1301 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1302 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1303 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1305 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1306 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1307 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1309 return $mimearray;
1313 * Obtains information about a filetype based on its extension. Will
1314 * use a default if no information is present about that particular
1315 * extension.
1317 * @param string $element Desired information (usually 'icon'
1318 * for icon filename or 'type' for MIME type)
1319 * @param string $filename Filename we're looking up
1320 * @return string Requested piece of information from array
1322 function mimeinfo($element, $filename) {
1323 global $CFG;
1324 $mimeinfo = get_mimetypes_array();
1326 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1327 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1328 return $mimeinfo[strtolower($match[1])][$element];
1329 } else {
1330 if ($element == 'icon32') {
1331 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1332 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1333 } else {
1334 $filename = 'unknown';
1336 $filename .= '-32';
1337 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1338 return $filename;
1339 } else {
1340 return 'unknown-32';
1342 } else {
1343 return $mimeinfo['xxx'][$element]; // By default
1346 } else {
1347 if ($element == 'icon32') {
1348 return 'unknown-32';
1350 return $mimeinfo['xxx'][$element]; // By default
1355 * Obtains information about a filetype based on the MIME type rather than
1356 * the other way around.
1358 * @param string $element Desired information (usually 'icon')
1359 * @param string $mimetype MIME type we're looking up
1360 * @return string Requested piece of information from array
1362 function mimeinfo_from_type($element, $mimetype) {
1363 $mimeinfo = get_mimetypes_array();
1365 foreach($mimeinfo as $values) {
1366 if ($values['type']==$mimetype) {
1367 if (isset($values[$element])) {
1368 return $values[$element];
1370 break;
1373 return $mimeinfo['xxx'][$element]; // Default
1377 * Get information about a filetype based on the icon file.
1379 * @param string $element Desired information (usually 'icon')
1380 * @param string $icon Icon file name without extension
1381 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1382 * @return string Requested piece of information from array
1384 function mimeinfo_from_icon($element, $icon, $all=false) {
1385 $mimeinfo = get_mimetypes_array();
1387 if (preg_match("/\/(.*)/", $icon, $matches)) {
1388 $icon = $matches[1];
1390 // Try to get the extension
1391 $extension = '';
1392 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1393 $extension = substr($icon, $cutat + 1);
1395 $info = array($mimeinfo['xxx'][$element]); // Default
1396 foreach($mimeinfo as $key => $values) {
1397 if ($values['icon']==$icon) {
1398 if (isset($values[$element])) {
1399 $info[$key] = $values[$element];
1401 //No break, for example for 'excel' we don't want 'csv'!
1404 if ($all) {
1405 if (count($info) > 1) {
1406 array_shift($info); // take off document/unknown if we have better options
1408 return array_values($info); // Keep keys out when requesting all
1411 // Requested only one, try to get the best by extension coincidence, else return the last
1412 if ($extension && isset($info[$extension])) {
1413 return $info[$extension];
1416 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1420 * Returns the relative icon path for a given mime type
1422 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1423 * a return the full path to an icon.
1425 * <code>
1426 * $mimetype = 'image/jpg';
1427 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1428 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1429 * </code>
1431 * @todo When an $OUTPUT->icon method is available this function should be altered
1432 * to conform with that.
1434 * @param string $mimetype The mimetype to fetch an icon for
1435 * @param int $size The size of the icon. Not yet implemented
1436 * @return string The relative path to the icon
1438 function file_mimetype_icon($mimetype, $size = NULL) {
1439 global $CFG;
1441 $icon = mimeinfo_from_type('icon', $mimetype);
1442 if ($size) {
1443 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1444 $icon = "$icon-$size";
1447 return 'f/'.$icon;
1451 * Returns the relative icon path for a given file name
1453 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1454 * a return the full path to an icon.
1456 * <code>
1457 * $filename = 'jpg';
1458 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1459 * echo '<img src="'.$icon.'" alt="blah" />';
1460 * </code>
1462 * @todo When an $OUTPUT->icon method is available this function should be altered
1463 * to conform with that.
1464 * @todo Implement $size
1466 * @param string filename The filename to get the icon for
1467 * @param int $size The size of the icon. Defaults to null can also be 32
1468 * @return string
1470 function file_extension_icon($filename, $size = NULL) {
1471 global $CFG;
1473 $icon = mimeinfo('icon', $filename);
1474 if ($size) {
1475 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1476 $icon = "$icon-$size";
1479 return 'f/'.$icon;
1483 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1484 * mimetypes.php language file.
1486 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1487 * @param bool $capitalise If true, capitalises first character of result
1488 * @return string Text description
1490 function get_mimetype_description($mimetype, $capitalise=false) {
1491 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1492 $result = get_string($mimetype, 'mimetypes');
1493 } else {
1494 $result = get_string('document/unknown','mimetypes');
1496 if ($capitalise) {
1497 $result=ucfirst($result);
1499 return $result;
1503 * Requested file is not found or not accessible
1505 * @return does not return, terminates script
1507 function send_file_not_found() {
1508 global $CFG, $COURSE;
1509 header('HTTP/1.0 404 not found');
1510 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1514 * Check output buffering settings before sending file.
1515 * Please note you should not send any other headers after calling this function.
1517 * @private to be called only from lib/filelib.php !
1518 * @return void
1520 function prepare_file_content_sending() {
1521 // We needed to be able to send headers up until now
1522 if (headers_sent()) {
1523 throw new file_serving_exception('Headers already sent, can not serve file.');
1526 $olddebug = error_reporting(0);
1528 // IE compatibility HACK - it does not like zlib compression much
1529 // there is also a problem with the length header in older PHP versions
1530 if (ini_get_bool('zlib.output_compression')) {
1531 ini_set('zlib.output_compression', 'Off');
1534 // flush and close all buffers if possible
1535 while(ob_get_level()) {
1536 if (!ob_end_flush()) {
1537 // prevent infinite loop when buffer can not be closed
1538 break;
1542 error_reporting($olddebug);
1544 //NOTE: we can not reliable test headers_sent() here because
1545 // the headers might be sent which trying to close the buffers,
1546 // this happens especially if browser does not support gzip or deflate
1550 * Handles the sending of temporary file to user, download is forced.
1551 * File is deleted after abort or successful sending.
1553 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1554 * @param string $filename proposed file name when saving file
1555 * @param bool $path is content of file
1556 * @return does not return, script terminated
1558 function send_temp_file($path, $filename, $pathisstring=false) {
1559 global $CFG;
1561 // close session - not needed anymore
1562 @session_get_instance()->write_close();
1564 if (!$pathisstring) {
1565 if (!file_exists($path)) {
1566 header('HTTP/1.0 404 not found');
1567 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1569 // executed after normal finish or abort
1570 @register_shutdown_function('send_temp_file_finished', $path);
1573 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1574 if (check_browser_version('MSIE')) {
1575 $filename = urlencode($filename);
1578 $filesize = $pathisstring ? strlen($path) : filesize($path);
1580 header('Content-Disposition: attachment; filename='.$filename);
1581 header('Content-Length: '.$filesize);
1582 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1583 header('Cache-Control: max-age=10');
1584 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1585 header('Pragma: ');
1586 } else { //normal http - prevent caching at all cost
1587 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1588 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1589 header('Pragma: no-cache');
1591 header('Accept-Ranges: none'); // Do not allow byteserving
1593 //flush the buffers - save memory and disable sid rewrite
1594 // this also disables zlib compression
1595 prepare_file_content_sending();
1597 // send the contents
1598 if ($pathisstring) {
1599 echo $path;
1600 } else {
1601 @readfile($path);
1604 die; //no more chars to output
1608 * Internal callback function used by send_temp_file()
1610 function send_temp_file_finished($path) {
1611 if (file_exists($path)) {
1612 @unlink($path);
1617 * Handles the sending of file data to the user's browser, including support for
1618 * byteranges etc.
1620 * @global object
1621 * @global object
1622 * @global object
1623 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1624 * @param string $filename Filename to send
1625 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1626 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1627 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1628 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1629 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1630 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1631 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1632 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1633 * and should not be reopened.
1634 * @return no return or void, script execution stopped unless $dontdie is true
1636 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1637 global $CFG, $COURSE, $SESSION;
1639 if ($dontdie) {
1640 ignore_user_abort(true);
1643 // MDL-11789, apply $CFG->filelifetime here
1644 if ($lifetime === 'default') {
1645 if (!empty($CFG->filelifetime)) {
1646 $lifetime = $CFG->filelifetime;
1647 } else {
1648 $lifetime = 86400;
1652 session_get_instance()->write_close(); // unlock session during fileserving
1654 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1655 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1656 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1657 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1658 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1659 ($mimetype ? $mimetype : mimeinfo('type', $filename));
1661 $lastmodified = $pathisstring ? time() : filemtime($path);
1662 $filesize = $pathisstring ? strlen($path) : filesize($path);
1664 /* - MDL-13949
1665 //Adobe Acrobat Reader XSS prevention
1666 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1667 //please note that it prevents opening of pdfs in browser when http referer disabled
1668 //or file linked from another site; browser caching of pdfs is now disabled too
1669 if (!empty($_SERVER['HTTP_RANGE'])) {
1670 //already byteserving
1671 $lifetime = 1; // >0 needed for byteserving
1672 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1673 $mimetype = 'application/x-forcedownload';
1674 $forcedownload = true;
1675 $lifetime = 0;
1676 } else {
1677 $lifetime = 1; // >0 needed for byteserving
1682 //try to disable automatic sid rewrite in cookieless mode
1683 @ini_set("session.use_trans_sid", "false");
1685 //do not put '@' before the next header to detect incorrect moodle configurations,
1686 //error should be better than "weird" empty lines for admins/users
1687 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1689 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1690 if (check_browser_version('MSIE')) {
1691 $filename = rawurlencode($filename);
1694 if ($forcedownload) {
1695 header('Content-Disposition: attachment; filename="'.$filename.'"');
1696 } else {
1697 header('Content-Disposition: inline; filename="'.$filename.'"');
1700 if ($lifetime > 0) {
1701 header('Cache-Control: max-age='.$lifetime);
1702 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1703 header('Pragma: ');
1705 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1707 header('Accept-Ranges: bytes');
1709 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1710 // byteserving stuff - for acrobat reader and download accelerators
1711 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1712 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1713 $ranges = false;
1714 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1715 foreach ($ranges as $key=>$value) {
1716 if ($ranges[$key][1] == '') {
1717 //suffix case
1718 $ranges[$key][1] = $filesize - $ranges[$key][2];
1719 $ranges[$key][2] = $filesize - 1;
1720 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1721 //fix range length
1722 $ranges[$key][2] = $filesize - 1;
1724 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1725 //invalid byte-range ==> ignore header
1726 $ranges = false;
1727 break;
1729 //prepare multipart header
1730 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1731 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1733 } else {
1734 $ranges = false;
1736 if ($ranges) {
1737 $handle = fopen($path, 'rb');
1738 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1741 } else {
1742 /// Do not byteserve (disabled, strings, text and html files).
1743 header('Accept-Ranges: none');
1745 } else { // Do not cache files in proxies and browsers
1746 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1747 header('Cache-Control: max-age=10');
1748 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1749 header('Pragma: ');
1750 } else { //normal http - prevent caching at all cost
1751 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1752 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1753 header('Pragma: no-cache');
1755 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1758 if (empty($filter)) {
1759 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
1760 //cookieless mode - rewrite links
1761 header('Content-Type: text/html');
1762 $path = $pathisstring ? $path : implode('', file($path));
1763 $path = sid_ob_rewrite($path);
1764 $filesize = strlen($path);
1765 $pathisstring = true;
1766 } else if ($mimetype == 'text/plain') {
1767 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1768 } else {
1769 header('Content-Type: '.$mimetype);
1771 header('Content-Length: '.$filesize);
1773 //flush the buffers - save memory and disable sid rewrite
1774 //this also disables zlib compression
1775 prepare_file_content_sending();
1777 // send the contents
1778 if ($pathisstring) {
1779 echo $path;
1780 } else {
1781 @readfile($path);
1784 } else { // Try to put the file through filters
1785 if ($mimetype == 'text/html') {
1786 $options = new stdClass();
1787 $options->noclean = true;
1788 $options->nocache = true; // temporary workaround for MDL-5136
1789 $text = $pathisstring ? $path : implode('', file($path));
1791 $text = file_modify_html_header($text);
1792 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1793 if (!empty($CFG->usesid)) {
1794 //cookieless mode - rewrite links
1795 $output = sid_ob_rewrite($output);
1798 header('Content-Length: '.strlen($output));
1799 header('Content-Type: text/html');
1801 //flush the buffers - save memory and disable sid rewrite
1802 //this also disables zlib compression
1803 prepare_file_content_sending();
1805 // send the contents
1806 echo $output;
1807 // only filter text if filter all files is selected
1808 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1809 $options = new stdClass();
1810 $options->newlines = false;
1811 $options->noclean = true;
1812 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1813 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1814 if (!empty($CFG->usesid)) {
1815 //cookieless mode - rewrite links
1816 $output = sid_ob_rewrite($output);
1819 header('Content-Length: '.strlen($output));
1820 header('Content-Type: text/html; charset=utf-8'); //add encoding
1822 //flush the buffers - save memory and disable sid rewrite
1823 //this also disables zlib compression
1824 prepare_file_content_sending();
1826 // send the contents
1827 echo $output;
1829 } else { // Just send it out raw
1830 header('Content-Length: '.$filesize);
1831 header('Content-Type: '.$mimetype);
1833 //flush the buffers - save memory and disable sid rewrite
1834 //this also disables zlib compression
1835 prepare_file_content_sending();
1837 // send the contents
1838 if ($pathisstring) {
1839 echo $path;
1840 }else {
1841 @readfile($path);
1845 if ($dontdie) {
1846 return;
1848 die; //no more chars to output!!!
1852 * Handles the sending of file data to the user's browser, including support for
1853 * byteranges etc.
1855 * @global object
1856 * @global object
1857 * @global object
1858 * @param object $stored_file local file object
1859 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1860 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1861 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1862 * @param string $filename Override filename
1863 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1864 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1865 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1866 * and should not be reopened.
1867 * @return void no return or void, script execution stopped unless $dontdie is true
1869 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1870 global $CFG, $COURSE, $SESSION;
1872 if (!$stored_file or $stored_file->is_directory()) {
1873 // nothing to serve
1874 if ($dontdie) {
1875 return;
1877 die;
1880 if ($dontdie) {
1881 ignore_user_abort(true);
1884 session_get_instance()->write_close(); // unlock session during fileserving
1886 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1887 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1888 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1889 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1890 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1891 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1892 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1894 $lastmodified = $stored_file->get_timemodified();
1895 $filesize = $stored_file->get_filesize();
1897 //try to disable automatic sid rewrite in cookieless mode
1898 @ini_set("session.use_trans_sid", "false");
1900 //do not put '@' before the next header to detect incorrect moodle configurations,
1901 //error should be better than "weird" empty lines for admins/users
1902 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1903 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1905 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1906 if (check_browser_version('MSIE')) {
1907 $filename = rawurlencode($filename);
1910 if ($forcedownload) {
1911 header('Content-Disposition: attachment; filename="'.$filename.'"');
1912 } else {
1913 header('Content-Disposition: inline; filename="'.$filename.'"');
1916 if ($lifetime > 0) {
1917 header('Cache-Control: max-age='.$lifetime);
1918 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1919 header('Pragma: ');
1921 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1923 header('Accept-Ranges: bytes');
1925 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1926 // byteserving stuff - for acrobat reader and download accelerators
1927 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1928 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1929 $ranges = false;
1930 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1931 foreach ($ranges as $key=>$value) {
1932 if ($ranges[$key][1] == '') {
1933 //suffix case
1934 $ranges[$key][1] = $filesize - $ranges[$key][2];
1935 $ranges[$key][2] = $filesize - 1;
1936 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1937 //fix range length
1938 $ranges[$key][2] = $filesize - 1;
1940 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1941 //invalid byte-range ==> ignore header
1942 $ranges = false;
1943 break;
1945 //prepare multipart header
1946 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1947 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1949 } else {
1950 $ranges = false;
1952 if ($ranges) {
1953 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1956 } else {
1957 /// Do not byteserve (disabled, strings, text and html files).
1958 header('Accept-Ranges: none');
1960 } else { // Do not cache files in proxies and browsers
1961 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1962 header('Cache-Control: max-age=10');
1963 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1964 header('Pragma: ');
1965 } else { //normal http - prevent caching at all cost
1966 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1967 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1968 header('Pragma: no-cache');
1970 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1973 if (empty($filter)) {
1974 $filtered = false;
1975 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
1976 //cookieless mode - rewrite links
1977 header('Content-Type: text/html');
1978 $text = $stored_file->get_content();
1979 $text = sid_ob_rewrite($text);
1980 $filesize = strlen($text);
1981 $filtered = true;
1982 } else if ($mimetype == 'text/plain') {
1983 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1984 } else {
1985 header('Content-Type: '.$mimetype);
1987 header('Content-Length: '.$filesize);
1989 //flush the buffers - save memory and disable sid rewrite
1990 //this also disables zlib compression
1991 prepare_file_content_sending();
1993 // send the contents
1994 if ($filtered) {
1995 echo $text;
1996 } else {
1997 $stored_file->readfile();
2000 } else { // Try to put the file through filters
2001 if ($mimetype == 'text/html') {
2002 $options = new stdClass();
2003 $options->noclean = true;
2004 $options->nocache = true; // temporary workaround for MDL-5136
2005 $text = $stored_file->get_content();
2006 $text = file_modify_html_header($text);
2007 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2008 if (!empty($CFG->usesid)) {
2009 //cookieless mode - rewrite links
2010 $output = sid_ob_rewrite($output);
2013 header('Content-Length: '.strlen($output));
2014 header('Content-Type: text/html');
2016 //flush the buffers - save memory and disable sid rewrite
2017 //this also disables zlib compression
2018 prepare_file_content_sending();
2020 // send the contents
2021 echo $output;
2023 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2024 // only filter text if filter all files is selected
2025 $options = new stdClass();
2026 $options->newlines = false;
2027 $options->noclean = true;
2028 $text = $stored_file->get_content();
2029 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2030 if (!empty($CFG->usesid)) {
2031 //cookieless mode - rewrite links
2032 $output = sid_ob_rewrite($output);
2035 header('Content-Length: '.strlen($output));
2036 header('Content-Type: text/html; charset=utf-8'); //add encoding
2038 //flush the buffers - save memory and disable sid rewrite
2039 //this also disables zlib compression
2040 prepare_file_content_sending();
2042 // send the contents
2043 echo $output;
2045 } else { // Just send it out raw
2046 header('Content-Length: '.$filesize);
2047 header('Content-Type: '.$mimetype);
2049 //flush the buffers - save memory and disable sid rewrite
2050 //this also disables zlib compression
2051 prepare_file_content_sending();
2053 // send the contents
2054 $stored_file->readfile();
2057 if ($dontdie) {
2058 return;
2060 die; //no more chars to output!!!
2064 * Retrieves an array of records from a CSV file and places
2065 * them into a given table structure
2067 * @global object
2068 * @global object
2069 * @param string $file The path to a CSV file
2070 * @param string $table The table to retrieve columns from
2071 * @return bool|array Returns an array of CSV records or false
2073 function get_records_csv($file, $table) {
2074 global $CFG, $DB;
2076 if (!$metacolumns = $DB->get_columns($table)) {
2077 return false;
2080 if(!($handle = @fopen($file, 'r'))) {
2081 print_error('get_records_csv failed to open '.$file);
2084 $fieldnames = fgetcsv($handle, 4096);
2085 if(empty($fieldnames)) {
2086 fclose($handle);
2087 return false;
2090 $columns = array();
2092 foreach($metacolumns as $metacolumn) {
2093 $ord = array_search($metacolumn->name, $fieldnames);
2094 if(is_int($ord)) {
2095 $columns[$metacolumn->name] = $ord;
2099 $rows = array();
2101 while (($data = fgetcsv($handle, 4096)) !== false) {
2102 $item = new stdClass;
2103 foreach($columns as $name => $ord) {
2104 $item->$name = $data[$ord];
2106 $rows[] = $item;
2109 fclose($handle);
2110 return $rows;
2115 * @global object
2116 * @global object
2117 * @param string $file The file to put the CSV content into
2118 * @param array $records An array of records to write to a CSV file
2119 * @param string $table The table to get columns from
2120 * @return bool success
2122 function put_records_csv($file, $records, $table = NULL) {
2123 global $CFG, $DB;
2125 if (empty($records)) {
2126 return true;
2129 $metacolumns = NULL;
2130 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2131 return false;
2134 echo "x";
2136 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
2137 print_error('put_records_csv failed to open '.$file);
2140 $proto = reset($records);
2141 if(is_object($proto)) {
2142 $fields_records = array_keys(get_object_vars($proto));
2144 else if(is_array($proto)) {
2145 $fields_records = array_keys($proto);
2147 else {
2148 return false;
2150 echo "x";
2152 if(!empty($metacolumns)) {
2153 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2154 $fields = array_intersect($fields_records, $fields_table);
2156 else {
2157 $fields = $fields_records;
2160 fwrite($fp, implode(',', $fields));
2161 fwrite($fp, "\r\n");
2163 foreach($records as $record) {
2164 $array = (array)$record;
2165 $values = array();
2166 foreach($fields as $field) {
2167 if(strpos($array[$field], ',')) {
2168 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2170 else {
2171 $values[] = $array[$field];
2174 fwrite($fp, implode(',', $values)."\r\n");
2177 fclose($fp);
2178 return true;
2183 * Recursively delete the file or folder with path $location. That is,
2184 * if it is a file delete it. If it is a folder, delete all its content
2185 * then delete it. If $location does not exist to start, that is not
2186 * considered an error.
2188 * @param string $location the path to remove.
2189 * @return bool
2191 function fulldelete($location) {
2192 if (empty($location)) {
2193 // extra safety against wrong param
2194 return false;
2196 if (is_dir($location)) {
2197 $currdir = opendir($location);
2198 while (false !== ($file = readdir($currdir))) {
2199 if ($file <> ".." && $file <> ".") {
2200 $fullfile = $location."/".$file;
2201 if (is_dir($fullfile)) {
2202 if (!fulldelete($fullfile)) {
2203 return false;
2205 } else {
2206 if (!unlink($fullfile)) {
2207 return false;
2212 closedir($currdir);
2213 if (! rmdir($location)) {
2214 return false;
2217 } else if (file_exists($location)) {
2218 if (!unlink($location)) {
2219 return false;
2222 return true;
2226 * Send requested byterange of file.
2228 * @param object $handle A file handle
2229 * @param string $mimetype The mimetype for the output
2230 * @param array $ranges An array of ranges to send
2231 * @param string $filesize The size of the content if only one range is used
2233 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2234 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2235 if ($handle === false) {
2236 die;
2238 if (count($ranges) == 1) { //only one range requested
2239 $length = $ranges[0][2] - $ranges[0][1] + 1;
2240 header('HTTP/1.1 206 Partial content');
2241 header('Content-Length: '.$length);
2242 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2243 header('Content-Type: '.$mimetype);
2245 //flush the buffers - save memory and disable sid rewrite
2246 //this also disables zlib compression
2247 prepare_file_content_sending();
2249 $buffer = '';
2250 fseek($handle, $ranges[0][1]);
2251 while (!feof($handle) && $length > 0) {
2252 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2253 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2254 echo $buffer;
2255 flush();
2256 $length -= strlen($buffer);
2258 fclose($handle);
2259 die;
2260 } else { // multiple ranges requested - not tested much
2261 $totallength = 0;
2262 foreach($ranges as $range) {
2263 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2265 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2266 header('HTTP/1.1 206 Partial content');
2267 header('Content-Length: '.$totallength);
2268 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2269 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2271 //flush the buffers - save memory and disable sid rewrite
2272 //this also disables zlib compression
2273 prepare_file_content_sending();
2275 foreach($ranges as $range) {
2276 $length = $range[2] - $range[1] + 1;
2277 echo $range[0];
2278 $buffer = '';
2279 fseek($handle, $range[1]);
2280 while (!feof($handle) && $length > 0) {
2281 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2282 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2283 echo $buffer;
2284 flush();
2285 $length -= strlen($buffer);
2288 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2289 fclose($handle);
2290 die;
2295 * add includes (js and css) into uploaded files
2296 * before returning them, useful for themes and utf.js includes
2298 * @global object
2299 * @param string $text text to search and replace
2300 * @return string text with added head includes
2302 function file_modify_html_header($text) {
2303 // first look for <head> tag
2304 global $CFG;
2306 $stylesheetshtml = '';
2307 /* foreach ($CFG->stylesheets as $stylesheet) {
2308 //TODO: MDL-21120
2309 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2312 $ufo = '';
2313 if (filter_is_enabled('filter/mediaplugin')) {
2314 // this script is needed by most media filter plugins.
2315 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2316 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2319 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2320 if ($matches) {
2321 $replacement = '<head>'.$ufo.$stylesheetshtml;
2322 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2323 return $text;
2326 // if not, look for <html> tag, and stick <head> right after
2327 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2328 if ($matches) {
2329 // replace <html> tag with <html><head>includes</head>
2330 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2331 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2332 return $text;
2335 // if not, look for <body> tag, and stick <head> before body
2336 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2337 if ($matches) {
2338 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2339 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2340 return $text;
2343 // if not, just stick a <head> tag at the beginning
2344 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2345 return $text;
2349 * RESTful cURL class
2351 * This is a wrapper class for curl, it is quite easy to use:
2352 * <code>
2353 * $c = new curl;
2354 * // enable cache
2355 * $c = new curl(array('cache'=>true));
2356 * // enable cookie
2357 * $c = new curl(array('cookie'=>true));
2358 * // enable proxy
2359 * $c = new curl(array('proxy'=>true));
2361 * // HTTP GET Method
2362 * $html = $c->get('http://example.com');
2363 * // HTTP POST Method
2364 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2365 * // HTTP PUT Method
2366 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2367 * </code>
2369 * @package core
2370 * @subpackage file
2371 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2372 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2375 class curl {
2376 /** @var bool */
2377 public $cache = false;
2378 public $proxy = false;
2379 /** @var string */
2380 public $version = '0.4 dev';
2381 /** @var array */
2382 public $response = array();
2383 public $header = array();
2384 /** @var string */
2385 public $info;
2386 public $error;
2388 /** @var array */
2389 private $options;
2390 /** @var string */
2391 private $proxy_host = '';
2392 private $proxy_auth = '';
2393 private $proxy_type = '';
2394 /** @var bool */
2395 private $debug = false;
2396 private $cookie = false;
2399 * @global object
2400 * @param array $options
2402 public function __construct($options = array()){
2403 global $CFG;
2404 if (!function_exists('curl_init')) {
2405 $this->error = 'cURL module must be enabled!';
2406 trigger_error($this->error, E_USER_ERROR);
2407 return false;
2409 // the options of curl should be init here.
2410 $this->resetopt();
2411 if (!empty($options['debug'])) {
2412 $this->debug = true;
2414 if(!empty($options['cookie'])) {
2415 if($options['cookie'] === true) {
2416 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2417 } else {
2418 $this->cookie = $options['cookie'];
2421 if (!empty($options['cache'])) {
2422 if (class_exists('curl_cache')) {
2423 if (!empty($options['module_cache'])) {
2424 $this->cache = new curl_cache($options['module_cache']);
2425 } else {
2426 $this->cache = new curl_cache('misc');
2430 if (!empty($CFG->proxyhost)) {
2431 if (empty($CFG->proxyport)) {
2432 $this->proxy_host = $CFG->proxyhost;
2433 } else {
2434 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2436 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2437 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2438 $this->setopt(array(
2439 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2440 'proxyuserpwd'=>$this->proxy_auth));
2442 if (!empty($CFG->proxytype)) {
2443 if ($CFG->proxytype == 'SOCKS5') {
2444 $this->proxy_type = CURLPROXY_SOCKS5;
2445 } else {
2446 $this->proxy_type = CURLPROXY_HTTP;
2447 $this->setopt(array('httpproxytunnel'=>false));
2449 $this->setopt(array('proxytype'=>$this->proxy_type));
2452 if (!empty($this->proxy_host)) {
2453 $this->proxy = array('proxy'=>$this->proxy_host);
2457 * Resets the CURL options that have already been set
2459 public function resetopt(){
2460 $this->options = array();
2461 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2462 // True to include the header in the output
2463 $this->options['CURLOPT_HEADER'] = 0;
2464 // True to Exclude the body from the output
2465 $this->options['CURLOPT_NOBODY'] = 0;
2466 // TRUE to follow any "Location: " header that the server
2467 // sends as part of the HTTP header (note this is recursive,
2468 // PHP will follow as many "Location: " headers that it is sent,
2469 // unless CURLOPT_MAXREDIRS is set).
2470 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2471 $this->options['CURLOPT_MAXREDIRS'] = 10;
2472 $this->options['CURLOPT_ENCODING'] = '';
2473 // TRUE to return the transfer as a string of the return
2474 // value of curl_exec() instead of outputting it out directly.
2475 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2476 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2477 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2478 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2479 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2483 * Reset Cookie
2485 public function resetcookie() {
2486 if (!empty($this->cookie)) {
2487 if (is_file($this->cookie)) {
2488 $fp = fopen($this->cookie, 'w');
2489 if (!empty($fp)) {
2490 fwrite($fp, '');
2491 fclose($fp);
2498 * Set curl options
2500 * @param array $options If array is null, this function will
2501 * reset the options to default value.
2504 public function setopt($options = array()) {
2505 if (is_array($options)) {
2506 foreach($options as $name => $val){
2507 if (stripos($name, 'CURLOPT_') === false) {
2508 $name = strtoupper('CURLOPT_'.$name);
2510 $this->options[$name] = $val;
2515 * Reset http method
2518 public function cleanopt(){
2519 unset($this->options['CURLOPT_HTTPGET']);
2520 unset($this->options['CURLOPT_POST']);
2521 unset($this->options['CURLOPT_POSTFIELDS']);
2522 unset($this->options['CURLOPT_PUT']);
2523 unset($this->options['CURLOPT_INFILE']);
2524 unset($this->options['CURLOPT_INFILESIZE']);
2525 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2529 * Set HTTP Request Header
2531 * @param array $headers
2534 public function setHeader($header) {
2535 if (is_array($header)){
2536 foreach ($header as $v) {
2537 $this->setHeader($v);
2539 } else {
2540 $this->header[] = $header;
2544 * Set HTTP Response Header
2547 public function getResponse(){
2548 return $this->response;
2551 * private callback function
2552 * Formatting HTTP Response Header
2554 * @param mixed $ch Apparently not used
2555 * @param string $header
2556 * @return int The strlen of the header
2558 private function formatHeader($ch, $header)
2560 $this->count++;
2561 if (strlen($header) > 2) {
2562 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2563 $key = rtrim($key, ':');
2564 if (!empty($this->response[$key])) {
2565 if (is_array($this->response[$key])){
2566 $this->response[$key][] = $value;
2567 } else {
2568 $tmp = $this->response[$key];
2569 $this->response[$key] = array();
2570 $this->response[$key][] = $tmp;
2571 $this->response[$key][] = $value;
2574 } else {
2575 $this->response[$key] = $value;
2578 return strlen($header);
2582 * Set options for individual curl instance
2584 * @param object $curl A curl handle
2585 * @param array $options
2586 * @return object The curl handle
2588 private function apply_opt($curl, $options) {
2589 // Clean up
2590 $this->cleanopt();
2591 // set cookie
2592 if (!empty($this->cookie) || !empty($options['cookie'])) {
2593 $this->setopt(array('cookiejar'=>$this->cookie,
2594 'cookiefile'=>$this->cookie
2598 // set proxy
2599 if (!empty($this->proxy) || !empty($options['proxy'])) {
2600 $this->setopt($this->proxy);
2602 $this->setopt($options);
2603 // reset before set options
2604 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2605 // set headers
2606 if (empty($this->header)){
2607 $this->setHeader(array(
2608 'User-Agent: MoodleBot/1.0',
2609 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2610 'Connection: keep-alive'
2613 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2615 if ($this->debug){
2616 echo '<h1>Options</h1>';
2617 var_dump($this->options);
2618 echo '<h1>Header</h1>';
2619 var_dump($this->header);
2622 // set options
2623 foreach($this->options as $name => $val) {
2624 if (is_string($name)) {
2625 $name = constant(strtoupper($name));
2627 curl_setopt($curl, $name, $val);
2629 return $curl;
2632 * Download multiple files in parallel
2634 * Calls {@link multi()} with specific download headers
2636 * <code>
2637 * $c = new curl;
2638 * $c->download(array(
2639 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2640 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2641 * ));
2642 * </code>
2644 * @param array $requests An array of files to request
2645 * @param array $options An array of options to set
2646 * @return array An array of results
2648 public function download($requests, $options = array()) {
2649 $options['CURLOPT_BINARYTRANSFER'] = 1;
2650 $options['RETURNTRANSFER'] = false;
2651 return $this->multi($requests, $options);
2654 * Mulit HTTP Requests
2655 * This function could run multi-requests in parallel.
2657 * @param array $requests An array of files to request
2658 * @param array $options An array of options to set
2659 * @return array An array of results
2661 protected function multi($requests, $options = array()) {
2662 $count = count($requests);
2663 $handles = array();
2664 $results = array();
2665 $main = curl_multi_init();
2666 for ($i = 0; $i < $count; $i++) {
2667 $url = $requests[$i];
2668 foreach($url as $n=>$v){
2669 $options[$n] = $url[$n];
2671 $handles[$i] = curl_init($url['url']);
2672 $this->apply_opt($handles[$i], $options);
2673 curl_multi_add_handle($main, $handles[$i]);
2675 $running = 0;
2676 do {
2677 curl_multi_exec($main, $running);
2678 } while($running > 0);
2679 for ($i = 0; $i < $count; $i++) {
2680 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
2681 $results[] = true;
2682 } else {
2683 $results[] = curl_multi_getcontent($handles[$i]);
2685 curl_multi_remove_handle($main, $handles[$i]);
2687 curl_multi_close($main);
2688 return $results;
2691 * Single HTTP Request
2693 * @param string $url The URL to request
2694 * @param array $options
2695 * @return bool
2697 protected function request($url, $options = array()){
2698 // create curl instance
2699 $curl = curl_init($url);
2700 $options['url'] = $url;
2701 $this->apply_opt($curl, $options);
2702 if ($this->cache && $ret = $this->cache->get($this->options)) {
2703 return $ret;
2704 } else {
2705 $ret = curl_exec($curl);
2706 if ($this->cache) {
2707 $this->cache->set($this->options, $ret);
2711 $this->info = curl_getinfo($curl);
2712 $this->error = curl_error($curl);
2714 if ($this->debug){
2715 echo '<h1>Return Data</h1>';
2716 var_dump($ret);
2717 echo '<h1>Info</h1>';
2718 var_dump($this->info);
2719 echo '<h1>Error</h1>';
2720 var_dump($this->error);
2723 curl_close($curl);
2725 if (empty($this->error)){
2726 return $ret;
2727 } else {
2728 return $this->error;
2729 // exception is not ajax friendly
2730 //throw new moodle_exception($this->error, 'curl');
2735 * HTTP HEAD method
2737 * @see request()
2739 * @param string $url
2740 * @param array $options
2741 * @return bool
2743 public function head($url, $options = array()){
2744 $options['CURLOPT_HTTPGET'] = 0;
2745 $options['CURLOPT_HEADER'] = 1;
2746 $options['CURLOPT_NOBODY'] = 1;
2747 return $this->request($url, $options);
2751 * HTTP POST method
2753 * @param string $url
2754 * @param array|string $params
2755 * @param array $options
2756 * @return bool
2758 public function post($url, $params = '', $options = array()){
2759 $options['CURLOPT_POST'] = 1;
2760 if (is_array($params)) {
2761 $this->_tmp_file_post_params = array();
2762 foreach ($params as $key => $value) {
2763 if ($value instanceof stored_file) {
2764 $value->add_to_curl_request($this, $key);
2765 } else {
2766 $this->_tmp_file_post_params[$key] = $value;
2769 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2770 unset($this->_tmp_file_post_params);
2771 } else {
2772 // $params is the raw post data
2773 $options['CURLOPT_POSTFIELDS'] = $params;
2775 return $this->request($url, $options);
2779 * HTTP GET method
2781 * @param string $url
2782 * @param array $params
2783 * @param array $options
2784 * @return bool
2786 public function get($url, $params = array(), $options = array()){
2787 $options['CURLOPT_HTTPGET'] = 1;
2789 if (!empty($params)){
2790 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2791 $url .= http_build_query($params, '', '&');
2793 return $this->request($url, $options);
2797 * HTTP PUT method
2799 * @param string $url
2800 * @param array $params
2801 * @param array $options
2802 * @return bool
2804 public function put($url, $params = array(), $options = array()){
2805 $file = $params['file'];
2806 if (!is_file($file)){
2807 return null;
2809 $fp = fopen($file, 'r');
2810 $size = filesize($file);
2811 $options['CURLOPT_PUT'] = 1;
2812 $options['CURLOPT_INFILESIZE'] = $size;
2813 $options['CURLOPT_INFILE'] = $fp;
2814 if (!isset($this->options['CURLOPT_USERPWD'])){
2815 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2817 $ret = $this->request($url, $options);
2818 fclose($fp);
2819 return $ret;
2823 * HTTP DELETE method
2825 * @param string $url
2826 * @param array $params
2827 * @param array $options
2828 * @return bool
2830 public function delete($url, $param = array(), $options = array()){
2831 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2832 if (!isset($options['CURLOPT_USERPWD'])) {
2833 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2835 $ret = $this->request($url, $options);
2836 return $ret;
2839 * HTTP TRACE method
2841 * @param string $url
2842 * @param array $options
2843 * @return bool
2845 public function trace($url, $options = array()){
2846 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2847 $ret = $this->request($url, $options);
2848 return $ret;
2851 * HTTP OPTIONS method
2853 * @param string $url
2854 * @param array $options
2855 * @return bool
2857 public function options($url, $options = array()){
2858 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2859 $ret = $this->request($url, $options);
2860 return $ret;
2862 public function get_info() {
2863 return $this->info;
2868 * This class is used by cURL class, use case:
2870 * <code>
2871 * $CFG->repositorycacheexpire = 120;
2872 * $CFG->curlcache = 120;
2874 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2875 * $ret = $c->get('http://www.google.com');
2876 * </code>
2878 * @package core
2879 * @subpackage file
2880 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2881 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2883 class curl_cache {
2884 /** @var string */
2885 public $dir = '';
2888 * @global object
2889 * @param string @module which module is using curl_cache
2892 function __construct($module = 'repository'){
2893 global $CFG;
2894 if (!empty($module)) {
2895 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2896 } else {
2897 $this->dir = $CFG->dataroot.'/cache/misc/';
2899 if (!file_exists($this->dir)) {
2900 mkdir($this->dir, $CFG->directorypermissions, true);
2902 if ($module == 'repository') {
2903 if (empty($CFG->repositorycacheexpire)) {
2904 $CFG->repositorycacheexpire = 120;
2906 $this->ttl = $CFG->repositorycacheexpire;
2907 } else {
2908 if (empty($CFG->curlcache)) {
2909 $CFG->curlcache = 120;
2911 $this->ttl = $CFG->curlcache;
2916 * Get cached value
2918 * @global object
2919 * @global object
2920 * @param mixed $param
2921 * @return bool|string
2923 public function get($param){
2924 global $CFG, $USER;
2925 $this->cleanup($this->ttl);
2926 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2927 if(file_exists($this->dir.$filename)) {
2928 $lasttime = filemtime($this->dir.$filename);
2929 if(time()-$lasttime > $this->ttl)
2931 return false;
2932 } else {
2933 $fp = fopen($this->dir.$filename, 'r');
2934 $size = filesize($this->dir.$filename);
2935 $content = fread($fp, $size);
2936 return unserialize($content);
2939 return false;
2943 * Set cache value
2945 * @global object $CFG
2946 * @global object $USER
2947 * @param mixed $param
2948 * @param mixed $val
2950 public function set($param, $val){
2951 global $CFG, $USER;
2952 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2953 $fp = fopen($this->dir.$filename, 'w');
2954 fwrite($fp, serialize($val));
2955 fclose($fp);
2959 * Remove cache files
2961 * @param int $expire The number os seconds before expiry
2963 public function cleanup($expire){
2964 if($dir = opendir($this->dir)){
2965 while (false !== ($file = readdir($dir))) {
2966 if(!is_dir($file) && $file != '.' && $file != '..') {
2967 $lasttime = @filemtime($this->dir.$file);
2968 if(time() - $lasttime > $expire){
2969 @unlink($this->dir.$file);
2976 * delete current user's cache file
2978 * @global object $CFG
2979 * @global object $USER
2981 public function refresh(){
2982 global $CFG, $USER;
2983 if($dir = opendir($this->dir)){
2984 while (false !== ($file = readdir($dir))) {
2985 if(!is_dir($file) && $file != '.' && $file != '..') {
2986 if(strpos($file, 'u'.$USER->id.'_')!==false){
2987 @unlink($this->dir.$file);
2996 * This class is used to parse lib/file/file_types.mm which help get file
2997 * extensions by file types.
2998 * The file_types.mm file can be edited by freemind in graphic environment.
3000 * @package core
3001 * @subpackage file
3002 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
3003 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3005 class filetype_parser {
3007 * Check file_types.mm file, setup variables
3009 * @global object $CFG
3010 * @param string $file
3012 public function __construct($file = '') {
3013 global $CFG;
3014 if (empty($file)) {
3015 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
3016 } else {
3017 $this->file = $file;
3019 $this->tree = array();
3020 $this->result = array();
3024 * A private function to browse xml nodes
3026 * @param array $parent
3027 * @param array $types
3029 private function _browse_nodes($parent, $types) {
3030 $key = (string)$parent['TEXT'];
3031 if(isset($parent->node)) {
3032 $this->tree[$key] = array();
3033 if (in_array((string)$parent['TEXT'], $types)) {
3034 $this->_select_nodes($parent, $this->result);
3035 } else {
3036 foreach($parent->node as $v){
3037 $this->_browse_nodes($v, $types);
3040 } else {
3041 $this->tree[] = $key;
3046 * A private function to select text nodes
3048 * @param array $parent
3050 private function _select_nodes($parent){
3051 if(isset($parent->node)) {
3052 foreach($parent->node as $v){
3053 $this->_select_nodes($v, $this->result);
3055 } else {
3056 $this->result[] = (string)$parent['TEXT'];
3062 * Get file extensions by file types names.
3064 * @param array $types
3065 * @return mixed
3067 public function get_extensions($types) {
3068 if (!is_array($types)) {
3069 $types = array($types);
3071 $this->result = array();
3072 if ((is_array($types) && in_array('*', $types)) ||
3073 $types == '*' || empty($types)) {
3074 return array('*');
3076 foreach ($types as $key=>$value){
3077 if (strpos($value, '.') !== false) {
3078 $this->result[] = $value;
3079 unset($types[$key]);
3082 if (file_exists($this->file)) {
3083 $xml = simplexml_load_file($this->file);
3084 foreach($xml->node->node as $v){
3085 if (in_array((string)$v['TEXT'], $types)) {
3086 $this->_select_nodes($v);
3087 } else {
3088 $this->_browse_nodes($v, $types);
3091 } else {
3092 exit('Failed to open file lib/filestorage/file_types.mm');
3094 return $this->result;