Merge branch 'MDL-29064_21' of git://github.com/timhunt/moodle into MOODLE_21_STABLE
[moodle.git] / lib / filelib.php
blob67ffe13c21c60bdba6cd0064cc9fba212bc56c63
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions for file handling.
21 * @package core
22 * @subpackage file
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** @var string unique string constant. */
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @global object
43 * @param string $urlbase
44 * @param string $path /filearea/itemid/dir/dir/file.exe
45 * @param bool $forcedownload
46 * @param bool $https https url required
47 * @return string encoded file url
49 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
50 global $CFG;
52 //TODO: deprecate this
54 if ($CFG->slasharguments) {
55 $parts = explode('/', $path);
56 $parts = array_map('rawurlencode', $parts);
57 $path = implode('/', $parts);
58 $return = $urlbase.$path;
59 if ($forcedownload) {
60 $return .= '?forcedownload=1';
62 } else {
63 $path = rawurlencode($path);
64 $return = $urlbase.'?file='.$path;
65 if ($forcedownload) {
66 $return .= '&amp;forcedownload=1';
70 if ($https) {
71 $return = str_replace('http://', 'https://', $return);
74 return $return;
77 /**
78 * Prepares 'editor' formslib element from data in database
80 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
81 * function then copies the embedded files into draft area (assigning itemids automatically),
82 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
83 * displayed.
84 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
85 * your mform's set_data() supplying the object returned by this function.
87 * @param object $data database field that holds the html text with embedded media
88 * @param string $field the name of the database field that holds the html text with embedded media
89 * @param array $options editor options (like maxifiles, maxbytes etc.)
90 * @param object $context context of the editor
91 * @param string $component
92 * @param string $filearea file area name
93 * @param int $itemid item id, required if item exists
94 * @return object modified data object
96 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
97 $options = (array)$options;
98 if (!isset($options['trusttext'])) {
99 $options['trusttext'] = false;
101 if (!isset($options['forcehttps'])) {
102 $options['forcehttps'] = false;
104 if (!isset($options['subdirs'])) {
105 $options['subdirs'] = false;
107 if (!isset($options['maxfiles'])) {
108 $options['maxfiles'] = 0; // no files by default
110 if (!isset($options['noclean'])) {
111 $options['noclean'] = false;
114 //sanity check for passed context. This function doesn't expect $option['context'] to be set
115 //But this function is called before creating editor hence, this is one of the best places to check
116 //if context is used properly. This check notify developer that they missed passing context to editor.
117 if (isset($context) && !isset($options['context'])) {
118 //if $context is not null then make sure $option['context'] is also set.
119 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
120 } else if (isset($options['context']) && isset($context)) {
121 //If both are passed then they should be equal.
122 if ($options['context']->id != $context->id) {
123 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
124 throw new coding_exception($exceptionmsg);
128 if (is_null($itemid) or is_null($context)) {
129 $contextid = null;
130 $itemid = null;
131 if (!isset($data->{$field})) {
132 $data->{$field} = '';
134 if (!isset($data->{$field.'format'})) {
135 $data->{$field.'format'} = editors_get_preferred_format();
137 if (!$options['noclean']) {
138 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
141 } else {
142 if ($options['trusttext']) {
143 // noclean ignored if trusttext enabled
144 if (!isset($data->{$field.'trust'})) {
145 $data->{$field.'trust'} = 0;
147 $data = trusttext_pre_edit($data, $field, $context);
148 } else {
149 if (!$options['noclean']) {
150 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
153 $contextid = $context->id;
156 if ($options['maxfiles'] != 0) {
157 $draftid_editor = file_get_submitted_draft_itemid($field);
158 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
159 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
160 } else {
161 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
164 return $data;
168 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
170 * This function moves files from draft area to the destination area and
171 * encodes URLs to the draft files so they can be safely saved into DB. The
172 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
173 * is the name of the database field to hold the wysiwyg editor content. The
174 * editor data comes as an array with text, format and itemid properties. This
175 * function automatically adds $data properties foobar, foobarformat and
176 * foobartrust, where foobar has URL to embedded files encoded.
178 * @param object $data raw data submitted by the form
179 * @param string $field name of the database field containing the html with embedded media files
180 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
181 * @param object $context context, required for existing data
182 * @param string component
183 * @param string $filearea file area name
184 * @param int $itemid item id, required if item exists
185 * @return object modified data object
187 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
188 $options = (array)$options;
189 if (!isset($options['trusttext'])) {
190 $options['trusttext'] = false;
192 if (!isset($options['forcehttps'])) {
193 $options['forcehttps'] = false;
195 if (!isset($options['subdirs'])) {
196 $options['subdirs'] = false;
198 if (!isset($options['maxfiles'])) {
199 $options['maxfiles'] = 0; // no files by default
201 if (!isset($options['maxbytes'])) {
202 $options['maxbytes'] = 0; // unlimited
205 if ($options['trusttext']) {
206 $data->{$field.'trust'} = trusttext_trusted($context);
207 } else {
208 $data->{$field.'trust'} = 0;
211 $editor = $data->{$field.'_editor'};
213 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
214 $data->{$field} = $editor['text'];
215 } else {
216 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
218 $data->{$field.'format'} = $editor['format'];
220 return $data;
224 * Saves text and files modified by Editor formslib element
226 * @param object $data $database entry field
227 * @param string $field name of data field
228 * @param array $options various options
229 * @param object $context context - must already exist
230 * @param string $component
231 * @param string $filearea file area name
232 * @param int $itemid must already exist, usually means data is in db
233 * @return object modified data obejct
235 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
236 $options = (array)$options;
237 if (!isset($options['subdirs'])) {
238 $options['subdirs'] = false;
240 if (is_null($itemid) or is_null($context)) {
241 $itemid = null;
242 $contextid = null;
243 } else {
244 $contextid = $context->id;
247 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
248 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
249 $data->{$field.'_filemanager'} = $draftid_editor;
251 return $data;
255 * Saves files modified by File manager formslib element
257 * @param object $data $database entry field
258 * @param string $field name of data field
259 * @param array $options various options
260 * @param object $context context - must already exist
261 * @param string $component
262 * @param string $filearea file area name
263 * @param int $itemid must already exist, usually means data is in db
264 * @return object modified data obejct
266 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
267 $options = (array)$options;
268 if (!isset($options['subdirs'])) {
269 $options['subdirs'] = false;
271 if (!isset($options['maxfiles'])) {
272 $options['maxfiles'] = -1; // unlimited
274 if (!isset($options['maxbytes'])) {
275 $options['maxbytes'] = 0; // unlimited
278 if (empty($data->{$field.'_filemanager'})) {
279 $data->$field = '';
281 } else {
282 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
283 $fs = get_file_storage();
285 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
286 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
287 } else {
288 $data->$field = '';
292 return $data;
297 * @global object
298 * @global object
299 * @return int a random but available draft itemid that can be used to create a new draft
300 * file area.
302 function file_get_unused_draft_itemid() {
303 global $DB, $USER;
305 if (isguestuser() or !isloggedin()) {
306 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
307 print_error('noguest');
310 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
312 $fs = get_file_storage();
313 $draftitemid = rand(1, 999999999);
314 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
315 $draftitemid = rand(1, 999999999);
318 return $draftitemid;
322 * Initialise a draft file area from a real one by copying the files. A draft
323 * area will be created if one does not already exist. Normally you should
324 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
326 * @global object
327 * @global object
328 * @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.
329 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
330 * @param string $component
331 * @param string $filearea helps indentify the file area.
332 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
333 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
334 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
335 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
337 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
338 global $CFG, $USER, $CFG;
340 $options = (array)$options;
341 if (!isset($options['subdirs'])) {
342 $options['subdirs'] = false;
344 if (!isset($options['forcehttps'])) {
345 $options['forcehttps'] = false;
348 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
349 $fs = get_file_storage();
351 if (empty($draftitemid)) {
352 // create a new area and copy existing files into
353 $draftitemid = file_get_unused_draft_itemid();
354 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
355 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
356 foreach ($files as $file) {
357 if ($file->is_directory() and $file->get_filepath() === '/') {
358 // we need a way to mark the age of each draft area,
359 // by not copying the root dir we force it to be created automatically with current timestamp
360 continue;
362 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
363 continue;
365 $fs->create_file_from_storedfile($file_record, $file);
368 if (!is_null($text)) {
369 // at this point there should not be any draftfile links yet,
370 // because this is a new text from database that should still contain the @@pluginfile@@ links
371 // this happens when developers forget to post process the text
372 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
374 } else {
375 // nothing to do
378 if (is_null($text)) {
379 return null;
382 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
383 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
387 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
389 * @global object
390 * @param string $text The content that may contain ULRs in need of rewriting.
391 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
392 * @param integer $contextid This parameter and the next two identify the file area to use.
393 * @param string $component
394 * @param string $filearea helps identify the file area.
395 * @param integer $itemid helps identify the file area.
396 * @param array $options text and file options ('forcehttps'=>false)
397 * @return string the processed text.
399 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
400 global $CFG;
402 $options = (array)$options;
403 if (!isset($options['forcehttps'])) {
404 $options['forcehttps'] = false;
407 if (!$CFG->slasharguments) {
408 $file = $file . '?file=';
411 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
413 if ($itemid !== null) {
414 $baseurl .= "$itemid/";
417 if ($options['forcehttps']) {
418 $baseurl = str_replace('http://', 'https://', $baseurl);
421 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
425 * Returns information about files in a draft area.
427 * @global object
428 * @global object
429 * @param integer $draftitemid the draft area item id.
430 * @return array with the following entries:
431 * 'filecount' => number of files in the draft area.
432 * (more information will be added as needed).
434 function file_get_draft_area_info($draftitemid) {
435 global $CFG, $USER;
437 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
438 $fs = get_file_storage();
440 $results = array();
442 // The number of files
443 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
444 $results['filecount'] = count($draftfiles);
445 $results['filesize'] = 0;
446 foreach ($draftfiles as $file) {
447 $results['filesize'] += $file->get_filesize();
450 return $results;
454 * Get used space of files
455 * @return int total bytes
457 function file_get_user_used_space() {
458 global $DB, $USER;
460 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
461 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
462 JOIN (SELECT contenthash, filename, MAX(id) AS id
463 FROM {files}
464 WHERE contextid = ? AND component = ? AND filearea != ?
465 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
466 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
467 $record = $DB->get_record_sql($sql, $params);
468 return (int)$record->totalbytes;
472 * Convert any string to a valid filepath
473 * @param string $str
474 * @return string path
476 function file_correct_filepath($str) { //TODO: what is this? (skodak)
477 if ($str == '/' or empty($str)) {
478 return '/';
479 } else {
480 return '/'.trim($str, './@#$ ').'/';
485 * Generate a folder tree of draft area of current USER recursively
486 * @param int $itemid
487 * @param string $filepath
488 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
490 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
491 global $USER, $OUTPUT, $CFG;
492 $data->children = array();
493 $context = get_context_instance(CONTEXT_USER, $USER->id);
494 $fs = get_file_storage();
495 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
496 foreach ($files as $file) {
497 if ($file->is_directory()) {
498 $item = new stdClass();
499 $item->sortorder = $file->get_sortorder();
500 $item->filepath = $file->get_filepath();
502 $foldername = explode('/', trim($item->filepath, '/'));
503 $item->fullname = trim(array_pop($foldername), '/');
505 $item->id = uniqid();
506 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
507 $data->children[] = $item;
508 } else {
509 continue;
516 * Listing all files (including folders) in current path (draft area)
517 * used by file manager
518 * @param int $draftitemid
519 * @param string $filepath
520 * @return mixed
522 function file_get_drafarea_files($draftitemid, $filepath = '/') {
523 global $USER, $OUTPUT, $CFG;
525 $context = get_context_instance(CONTEXT_USER, $USER->id);
526 $fs = get_file_storage();
528 $data = new stdClass();
529 $data->path = array();
530 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
532 // will be used to build breadcrumb
533 $trail = '';
534 if ($filepath !== '/') {
535 $filepath = file_correct_filepath($filepath);
536 $parts = explode('/', $filepath);
537 foreach ($parts as $part) {
538 if ($part != '' && $part != null) {
539 $trail .= ('/'.$part.'/');
540 $data->path[] = array('name'=>$part, 'path'=>$trail);
545 $list = array();
546 $maxlength = 12;
547 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
548 foreach ($files as $file) {
549 $item = new stdClass();
550 $item->filename = $file->get_filename();
551 $item->filepath = $file->get_filepath();
552 $item->fullname = trim($item->filename, '/');
553 $filesize = $file->get_filesize();
554 $item->filesize = $filesize ? display_size($filesize) : '';
556 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
557 $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
558 $item->sortorder = $file->get_sortorder();
560 if ($icon == 'zip') {
561 $item->type = 'zip';
562 } else {
563 $item->type = 'file';
566 if ($file->is_directory()) {
567 $item->filesize = 0;
568 $item->icon = $OUTPUT->pix_url('f/folder')->out();
569 $item->type = 'folder';
570 $foldername = explode('/', trim($item->filepath, '/'));
571 $item->fullname = trim(array_pop($foldername), '/');
572 } else {
573 // do NOT use file browser here!
574 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
576 $list[] = $item;
579 $data->itemid = $draftitemid;
580 $data->list = $list;
581 return $data;
585 * Returns draft area itemid for a given element.
587 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
588 * @return integer the itemid, or 0 if there is not one yet.
590 function file_get_submitted_draft_itemid($elname) {
591 $param = optional_param($elname, 0, PARAM_INT);
592 if ($param) {
593 require_sesskey();
595 if (is_array($param)) {
596 if (!empty($param['itemid'])) {
597 $param = $param['itemid'];
598 } else {
599 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
600 return false;
603 return $param;
607 * Saves files from a draft file area to a real one (merging the list of files).
608 * Can rewrite URLs in some content at the same time if desired.
610 * @global object
611 * @global object
612 * @param integer $draftitemid the id of the draft area to use. Normally obtained
613 * from file_get_submitted_draft_itemid('elementname') or similar.
614 * @param integer $contextid This parameter and the next two identify the file area to save to.
615 * @param string $component
616 * @param string $filearea indentifies the file area.
617 * @param integer $itemid helps identifies the file area.
618 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
619 * @param string $text some html content that needs to have embedded links rewritten
620 * to the @@PLUGINFILE@@ form for saving in the database.
621 * @param boolean $forcehttps force https urls.
622 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
624 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
625 global $USER;
627 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
628 $fs = get_file_storage();
630 $options = (array)$options;
631 if (!isset($options['subdirs'])) {
632 $options['subdirs'] = false;
634 if (!isset($options['maxfiles'])) {
635 $options['maxfiles'] = -1; // unlimited
637 if (!isset($options['maxbytes'])) {
638 $options['maxbytes'] = 0; // unlimited
641 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
642 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
644 if (count($draftfiles) < 2) {
645 // means there are no files - one file means root dir only ;-)
646 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
648 } else if (count($oldfiles) < 2) {
649 $filecount = 0;
650 // there were no files before - one file means root dir only ;-)
651 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
652 foreach ($draftfiles as $file) {
653 if (!$options['subdirs']) {
654 if ($file->get_filepath() !== '/' or $file->is_directory()) {
655 continue;
658 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
659 // oversized file - should not get here at all
660 continue;
662 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
663 // more files - should not get here at all
664 break;
666 if (!$file->is_directory()) {
667 $filecount++;
669 $fs->create_file_from_storedfile($file_record, $file);
672 } else {
673 // we have to merge old and new files - we want to keep file ids for files that were not changed
674 // we change time modified for all new and changed files, we keep time created as is
675 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
677 $newhashes = array();
678 foreach ($draftfiles as $file) {
679 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
680 $newhashes[$newhash] = $file;
682 $filecount = 0;
683 foreach ($oldfiles as $oldfile) {
684 $oldhash = $oldfile->get_pathnamehash();
685 if (!isset($newhashes[$oldhash])) {
686 // delete files not needed any more - deleted by user
687 $oldfile->delete();
688 continue;
690 $newfile = $newhashes[$oldhash];
691 if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
692 or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
693 or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
694 // file was changed, use updated with new timemodified data
695 $oldfile->delete();
696 continue;
698 // unchanged file or directory - we keep it as is
699 unset($newhashes[$oldhash]);
700 if (!$oldfile->is_directory()) {
701 $filecount++;
705 // now add new/changed files
706 // the size and subdirectory tests are extra safety only, the UI should prevent it
707 foreach ($newhashes as $file) {
708 if (!$options['subdirs']) {
709 if ($file->get_filepath() !== '/' or $file->is_directory()) {
710 continue;
713 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
714 // oversized file - should not get here at all
715 continue;
717 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
718 // more files - should not get here at all
719 break;
721 if (!$file->is_directory()) {
722 $filecount++;
724 $fs->create_file_from_storedfile($file_record, $file);
728 // note: do not purge the draft area - we clean up areas later in cron,
729 // the reason is that user might press submit twice and they would loose the files,
730 // also sometimes we might want to use hacks that save files into two different areas
732 if (is_null($text)) {
733 return null;
734 } else {
735 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
740 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
741 * ready to be saved in the database. Normally, this is done automatically by
742 * {@link file_save_draft_area_files()}.
743 * @param string $text the content to process.
744 * @param int $draftitemid the draft file area the content was using.
745 * @param bool $forcehttps whether the content contains https URLs. Default false.
746 * @return string the processed content.
748 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
749 global $CFG, $USER;
751 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
753 $wwwroot = $CFG->wwwroot;
754 if ($forcehttps) {
755 $wwwroot = str_replace('http://', 'https://', $wwwroot);
758 // relink embedded files if text submitted - no absolute links allowed in database!
759 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
761 if (strpos($text, 'draftfile.php?file=') !== false) {
762 $matches = array();
763 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
764 if ($matches) {
765 foreach ($matches[0] as $match) {
766 $replace = str_ireplace('%2F', '/', $match);
767 $text = str_replace($match, $replace, $text);
770 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
773 return $text;
777 * Set file sort order
778 * @global object $DB
779 * @param integer $contextid the context id
780 * @param string $component
781 * @param string $filearea file area.
782 * @param integer $itemid itemid.
783 * @param string $filepath file path.
784 * @param string $filename file name.
785 * @param integer $sortorer the sort order of file.
786 * @return boolean
788 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
789 global $DB;
790 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
791 if ($file_record = $DB->get_record('files', $conditions)) {
792 $sortorder = (int)$sortorder;
793 $file_record->sortorder = $sortorder;
794 $DB->update_record('files', $file_record);
795 return true;
797 return false;
801 * reset file sort order number to 0
802 * @global object $DB
803 * @param integer $contextid the context id
804 * @param string $component
805 * @param string $filearea file area.
806 * @param integer $itemid itemid.
807 * @return boolean
809 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
810 global $DB;
812 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
813 if ($itemid !== false) {
814 $conditions['itemid'] = $itemid;
817 $file_records = $DB->get_records('files', $conditions);
818 foreach ($file_records as $file_record) {
819 $file_record->sortorder = 0;
820 $DB->update_record('files', $file_record);
822 return true;
826 * Returns description of upload error
828 * @param int $errorcode found in $_FILES['filename.ext']['error']
829 * @return string error description string, '' if ok
831 function file_get_upload_error($errorcode) {
833 switch ($errorcode) {
834 case 0: // UPLOAD_ERR_OK - no error
835 $errmessage = '';
836 break;
838 case 1: // UPLOAD_ERR_INI_SIZE
839 $errmessage = get_string('uploadserverlimit');
840 break;
842 case 2: // UPLOAD_ERR_FORM_SIZE
843 $errmessage = get_string('uploadformlimit');
844 break;
846 case 3: // UPLOAD_ERR_PARTIAL
847 $errmessage = get_string('uploadpartialfile');
848 break;
850 case 4: // UPLOAD_ERR_NO_FILE
851 $errmessage = get_string('uploadnofilefound');
852 break;
854 // Note: there is no error with a value of 5
856 case 6: // UPLOAD_ERR_NO_TMP_DIR
857 $errmessage = get_string('uploadnotempdir');
858 break;
860 case 7: // UPLOAD_ERR_CANT_WRITE
861 $errmessage = get_string('uploadcantwrite');
862 break;
864 case 8: // UPLOAD_ERR_EXTENSION
865 $errmessage = get_string('uploadextension');
866 break;
868 default:
869 $errmessage = get_string('uploadproblem');
872 return $errmessage;
876 * Recursive function formating an array in POST parameter
877 * @param array $arraydata - the array that we are going to format and add into &$data array
878 * @param string $currentdata - a row of the final postdata array at instant T
879 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
880 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
882 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
883 foreach ($arraydata as $k=>$v) {
884 $newcurrentdata = $currentdata;
885 if (is_array($v)) { //the value is an array, call the function recursively
886 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
887 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
888 } else { //add the POST parameter to the $data array
889 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
895 * Transform a PHP array into POST parameter
896 * (see the recursive function format_array_postdata_for_curlcall)
897 * @param array $postdata
898 * @return array containing all POST parameters (1 row = 1 POST parameter)
900 function format_postdata_for_curlcall($postdata) {
901 $data = array();
902 foreach ($postdata as $k=>$v) {
903 if (is_array($v)) {
904 $currentdata = urlencode($k);
905 format_array_postdata_for_curlcall($v, $currentdata, $data);
906 } else {
907 $data[] = urlencode($k).'='.urlencode($v);
910 $convertedpostdata = implode('&', $data);
911 return $convertedpostdata;
918 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
919 * Due to security concerns only downloads from http(s) sources are supported.
921 * @param string $url file url starting with http(s)://
922 * @param array $headers http headers, null if none. If set, should be an
923 * associative array of header name => value pairs.
924 * @param array $postdata array means use POST request with given parameters
925 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
926 * (if false, just returns content)
927 * @param int $timeout timeout for complete download process including all file transfer
928 * (default 5 minutes)
929 * @param int $connecttimeout timeout for connection to server; this is the timeout that
930 * usually happens if the remote server is completely down (default 20 seconds);
931 * may not work when using proxy
932 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
933 * Only use this when already in a trusted location.
934 * @param string $tofile store the downloaded content to file instead of returning it.
935 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
936 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
937 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
939 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
940 global $CFG;
942 // some extra security
943 $newlines = array("\r", "\n");
944 if (is_array($headers) ) {
945 foreach ($headers as $key => $value) {
946 $headers[$key] = str_replace($newlines, '', $value);
949 $url = str_replace($newlines, '', $url);
950 if (!preg_match('|^https?://|i', $url)) {
951 if ($fullresponse) {
952 $response = new stdClass();
953 $response->status = 0;
954 $response->headers = array();
955 $response->response_code = 'Invalid protocol specified in url';
956 $response->results = '';
957 $response->error = 'Invalid protocol specified in url';
958 return $response;
959 } else {
960 return false;
964 // check if proxy (if used) should be bypassed for this url
965 $proxybypass = is_proxybypass($url);
967 if (!$ch = curl_init($url)) {
968 debugging('Can not init curl.');
969 return false;
972 // set extra headers
973 if (is_array($headers) ) {
974 $headers2 = array();
975 foreach ($headers as $key => $value) {
976 $headers2[] = "$key: $value";
978 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
981 if ($skipcertverify) {
982 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
985 // use POST if requested
986 if (is_array($postdata)) {
987 $postdata = format_postdata_for_curlcall($postdata);
988 curl_setopt($ch, CURLOPT_POST, true);
989 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
992 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
993 curl_setopt($ch, CURLOPT_HEADER, false);
994 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
996 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
997 // TODO: add version test for '7.10.5'
998 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
999 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1002 if (!empty($CFG->proxyhost) and !$proxybypass) {
1003 // SOCKS supported in PHP5 only
1004 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
1005 if (defined('CURLPROXY_SOCKS5')) {
1006 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1007 } else {
1008 curl_close($ch);
1009 if ($fullresponse) {
1010 $response = new stdClass();
1011 $response->status = '0';
1012 $response->headers = array();
1013 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
1014 $response->results = '';
1015 $response->error = 'SOCKS5 proxy is not supported in PHP4';
1016 return $response;
1017 } else {
1018 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
1019 return false;
1024 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
1026 if (empty($CFG->proxyport)) {
1027 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
1028 } else {
1029 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
1032 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1033 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
1034 if (defined('CURLOPT_PROXYAUTH')) {
1035 // any proxy authentication if PHP 5.1
1036 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
1041 // set up header and content handlers
1042 $received = new stdClass();
1043 $received->headers = array(); // received headers array
1044 $received->tofile = $tofile;
1045 $received->fh = null;
1046 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
1047 if ($tofile) {
1048 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
1051 if (!isset($CFG->curltimeoutkbitrate)) {
1052 //use very slow rate of 56kbps as a timeout speed when not set
1053 $bitrate = 56;
1054 } else {
1055 $bitrate = $CFG->curltimeoutkbitrate;
1058 // try to calculate the proper amount for timeout from remote file size.
1059 // if disabled or zero, we won't do any checks nor head requests.
1060 if ($calctimeout && $bitrate > 0) {
1061 //setup header request only options
1062 curl_setopt_array ($ch, array(
1063 CURLOPT_RETURNTRANSFER => false,
1064 CURLOPT_NOBODY => true)
1067 curl_exec($ch);
1068 $info = curl_getinfo($ch);
1069 $err = curl_error($ch);
1071 if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
1072 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
1074 //reinstate affected curl options
1075 curl_setopt_array ($ch, array(
1076 CURLOPT_RETURNTRANSFER => true,
1077 CURLOPT_NOBODY => false)
1081 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1082 $result = curl_exec($ch);
1084 // try to detect encoding problems
1085 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1086 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1087 $result = curl_exec($ch);
1090 if ($received->fh) {
1091 fclose($received->fh);
1094 if (curl_errno($ch)) {
1095 $error = curl_error($ch);
1096 $error_no = curl_errno($ch);
1097 curl_close($ch);
1099 if ($fullresponse) {
1100 $response = new stdClass();
1101 if ($error_no == 28) {
1102 $response->status = '-100'; // mimic snoopy
1103 } else {
1104 $response->status = '0';
1106 $response->headers = array();
1107 $response->response_code = $error;
1108 $response->results = false;
1109 $response->error = $error;
1110 return $response;
1111 } else {
1112 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1113 return false;
1116 } else {
1117 $info = curl_getinfo($ch);
1118 curl_close($ch);
1120 if (empty($info['http_code'])) {
1121 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1122 $response = new stdClass();
1123 $response->status = '0';
1124 $response->headers = array();
1125 $response->response_code = 'Unknown cURL error';
1126 $response->results = false; // do NOT change this, we really want to ignore the result!
1127 $response->error = 'Unknown cURL error';
1129 } else {
1130 $response = new stdClass();;
1131 $response->status = (string)$info['http_code'];
1132 $response->headers = $received->headers;
1133 $response->response_code = $received->headers[0];
1134 $response->results = $result;
1135 $response->error = '';
1138 if ($fullresponse) {
1139 return $response;
1140 } else if ($info['http_code'] != 200) {
1141 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1142 return false;
1143 } else {
1144 return $response->results;
1150 * internal implementation
1152 function download_file_content_header_handler($received, $ch, $header) {
1153 $received->headers[] = $header;
1154 return strlen($header);
1158 * internal implementation
1160 function download_file_content_write_handler($received, $ch, $data) {
1161 if (!$received->fh) {
1162 $received->fh = fopen($received->tofile, 'w');
1163 if ($received->fh === false) {
1164 // bad luck, file creation or overriding failed
1165 return 0;
1168 if (fwrite($received->fh, $data) === false) {
1169 // bad luck, write failed, let's abort completely
1170 return 0;
1172 return strlen($data);
1176 * @return array List of information about file types based on extensions.
1177 * Associative array of extension (lower-case) to associative array
1178 * from 'element name' to data. Current element names are 'type' and 'icon'.
1179 * Unknown types should use the 'xxx' entry which includes defaults.
1181 function get_mimetypes_array() {
1182 static $mimearray = array (
1183 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1184 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1185 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
1186 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1187 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1188 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1189 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1190 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1191 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1192 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1193 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1194 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1195 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1196 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1197 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1198 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1199 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1200 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1201 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1202 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1203 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1205 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1206 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1207 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1208 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1209 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1211 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1212 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1213 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1214 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1215 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1216 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1217 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1218 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1219 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1220 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1221 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1222 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1223 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1224 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1225 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1226 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1227 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1228 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1229 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1230 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1231 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1232 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1233 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1234 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1235 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1236 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1237 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1238 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1239 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1240 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1241 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1242 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1243 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1244 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1245 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1246 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1247 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1248 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1249 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1250 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1251 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1252 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1253 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1254 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1255 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1256 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1257 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1258 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1260 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1261 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1262 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1263 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1264 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1265 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1266 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1267 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1268 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1269 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1270 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1271 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1272 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1273 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1274 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1275 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
1276 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
1278 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1279 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1280 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1281 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1282 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1283 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1285 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1286 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1287 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1288 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1289 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1290 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1291 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1292 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1293 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1295 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1296 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1297 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1298 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1299 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1300 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1301 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
1302 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1303 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1304 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
1305 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1306 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1307 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1308 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1309 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1310 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1311 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1312 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1313 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1314 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1316 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1317 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1318 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1319 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1320 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1321 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1322 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1323 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1324 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1325 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1327 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1328 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1329 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1330 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1331 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1332 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1333 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1334 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1335 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1336 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
1337 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1338 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1339 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1340 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1341 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1343 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1344 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1345 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1346 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1347 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1348 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1349 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1351 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1352 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1353 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1355 return $mimearray;
1359 * Obtains information about a filetype based on its extension. Will
1360 * use a default if no information is present about that particular
1361 * extension.
1363 * @param string $element Desired information (usually 'icon'
1364 * for icon filename or 'type' for MIME type)
1365 * @param string $filename Filename we're looking up
1366 * @return string Requested piece of information from array
1368 function mimeinfo($element, $filename) {
1369 global $CFG;
1370 $mimeinfo = get_mimetypes_array();
1372 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1373 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1374 return $mimeinfo[strtolower($match[1])][$element];
1375 } else {
1376 if ($element == 'icon32') {
1377 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1378 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1379 } else {
1380 $filename = 'unknown';
1382 $filename .= '-32';
1383 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1384 return $filename;
1385 } else {
1386 return 'unknown-32';
1388 } else {
1389 return $mimeinfo['xxx'][$element]; // By default
1392 } else {
1393 if ($element == 'icon32') {
1394 return 'unknown-32';
1396 return $mimeinfo['xxx'][$element]; // By default
1401 * Obtains information about a filetype based on the MIME type rather than
1402 * the other way around.
1404 * @param string $element Desired information (usually 'icon')
1405 * @param string $mimetype MIME type we're looking up
1406 * @return string Requested piece of information from array
1408 function mimeinfo_from_type($element, $mimetype) {
1409 $mimeinfo = get_mimetypes_array();
1411 foreach($mimeinfo as $values) {
1412 if ($values['type']==$mimetype) {
1413 if (isset($values[$element])) {
1414 return $values[$element];
1416 break;
1419 return $mimeinfo['xxx'][$element]; // Default
1423 * Get information about a filetype based on the icon file.
1425 * @param string $element Desired information (usually 'icon')
1426 * @param string $icon Icon file name without extension
1427 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1428 * @return string Requested piece of information from array
1430 function mimeinfo_from_icon($element, $icon, $all=false) {
1431 $mimeinfo = get_mimetypes_array();
1433 if (preg_match("/\/(.*)/", $icon, $matches)) {
1434 $icon = $matches[1];
1436 // Try to get the extension
1437 $extension = '';
1438 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1439 $extension = substr($icon, $cutat + 1);
1441 $info = array($mimeinfo['xxx'][$element]); // Default
1442 foreach($mimeinfo as $key => $values) {
1443 if ($values['icon']==$icon) {
1444 if (isset($values[$element])) {
1445 $info[$key] = $values[$element];
1447 //No break, for example for 'excel' we don't want 'csv'!
1450 if ($all) {
1451 if (count($info) > 1) {
1452 array_shift($info); // take off document/unknown if we have better options
1454 return array_values($info); // Keep keys out when requesting all
1457 // Requested only one, try to get the best by extension coincidence, else return the last
1458 if ($extension && isset($info[$extension])) {
1459 return $info[$extension];
1462 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1466 * Returns the relative icon path for a given mime type
1468 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1469 * a return the full path to an icon.
1471 * <code>
1472 * $mimetype = 'image/jpg';
1473 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1474 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1475 * </code>
1477 * @todo When an $OUTPUT->icon method is available this function should be altered
1478 * to conform with that.
1480 * @param string $mimetype The mimetype to fetch an icon for
1481 * @param int $size The size of the icon. Not yet implemented
1482 * @return string The relative path to the icon
1484 function file_mimetype_icon($mimetype, $size = NULL) {
1485 global $CFG;
1487 $icon = mimeinfo_from_type('icon', $mimetype);
1488 if ($size) {
1489 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1490 $icon = "$icon-$size";
1493 return 'f/'.$icon;
1497 * Returns the relative icon path for a given file name
1499 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1500 * a return the full path to an icon.
1502 * <code>
1503 * $filename = 'jpg';
1504 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1505 * echo '<img src="'.$icon.'" alt="blah" />';
1506 * </code>
1508 * @todo When an $OUTPUT->icon method is available this function should be altered
1509 * to conform with that.
1510 * @todo Implement $size
1512 * @param string filename The filename to get the icon for
1513 * @param int $size The size of the icon. Defaults to null can also be 32
1514 * @return string
1516 function file_extension_icon($filename, $size = NULL) {
1517 global $CFG;
1519 $icon = mimeinfo('icon', $filename);
1520 if ($size) {
1521 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1522 $icon = "$icon-$size";
1525 return 'f/'.$icon;
1529 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1530 * mimetypes.php language file.
1532 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1533 * @param bool $capitalise If true, capitalises first character of result
1534 * @return string Text description
1536 function get_mimetype_description($mimetype, $capitalise=false) {
1537 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1538 $result = get_string($mimetype, 'mimetypes');
1539 } else {
1540 $result = get_string('document/unknown','mimetypes');
1542 if ($capitalise) {
1543 $result=ucfirst($result);
1545 return $result;
1549 * Requested file is not found or not accessible
1551 * @return does not return, terminates script
1553 function send_file_not_found() {
1554 global $CFG, $COURSE;
1555 header('HTTP/1.0 404 not found');
1556 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1560 * Check output buffering settings before sending file.
1561 * Please note you should not send any other headers after calling this function.
1563 * @private to be called only from lib/filelib.php !
1564 * @return void
1566 function prepare_file_content_sending() {
1567 // We needed to be able to send headers up until now
1568 if (headers_sent()) {
1569 throw new file_serving_exception('Headers already sent, can not serve file.');
1572 $olddebug = error_reporting(0);
1574 // IE compatibility HACK - it does not like zlib compression much
1575 // there is also a problem with the length header in older PHP versions
1576 if (ini_get_bool('zlib.output_compression')) {
1577 ini_set('zlib.output_compression', 'Off');
1580 // flush and close all buffers if possible
1581 while(ob_get_level()) {
1582 if (!ob_end_flush()) {
1583 // prevent infinite loop when buffer can not be closed
1584 break;
1588 error_reporting($olddebug);
1590 //NOTE: we can not reliable test headers_sent() here because
1591 // the headers might be sent which trying to close the buffers,
1592 // this happens especially if browser does not support gzip or deflate
1596 * Handles the sending of temporary file to user, download is forced.
1597 * File is deleted after abort or successful sending.
1599 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1600 * @param string $filename proposed file name when saving file
1601 * @param bool $path is content of file
1602 * @return does not return, script terminated
1604 function send_temp_file($path, $filename, $pathisstring=false) {
1605 global $CFG;
1607 // close session - not needed anymore
1608 @session_get_instance()->write_close();
1610 if (!$pathisstring) {
1611 if (!file_exists($path)) {
1612 header('HTTP/1.0 404 not found');
1613 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1615 // executed after normal finish or abort
1616 @register_shutdown_function('send_temp_file_finished', $path);
1619 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1620 if (check_browser_version('MSIE')) {
1621 $filename = urlencode($filename);
1624 $filesize = $pathisstring ? strlen($path) : filesize($path);
1626 header('Content-Disposition: attachment; filename='.$filename);
1627 header('Content-Length: '.$filesize);
1628 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1629 header('Cache-Control: max-age=10');
1630 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1631 header('Pragma: ');
1632 } else { //normal http - prevent caching at all cost
1633 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1634 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1635 header('Pragma: no-cache');
1637 header('Accept-Ranges: none'); // Do not allow byteserving
1639 //flush the buffers - save memory and disable sid rewrite
1640 // this also disables zlib compression
1641 prepare_file_content_sending();
1643 // send the contents
1644 if ($pathisstring) {
1645 echo $path;
1646 } else {
1647 @readfile($path);
1650 die; //no more chars to output
1654 * Internal callback function used by send_temp_file()
1656 function send_temp_file_finished($path) {
1657 if (file_exists($path)) {
1658 @unlink($path);
1663 * Handles the sending of file data to the user's browser, including support for
1664 * byteranges etc.
1666 * @global object
1667 * @global object
1668 * @global object
1669 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1670 * @param string $filename Filename to send
1671 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1672 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1673 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1674 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1675 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1676 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1677 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1678 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1679 * and should not be reopened.
1680 * @return no return or void, script execution stopped unless $dontdie is true
1682 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1683 global $CFG, $COURSE, $SESSION;
1685 if ($dontdie) {
1686 ignore_user_abort(true);
1689 // MDL-11789, apply $CFG->filelifetime here
1690 if ($lifetime === 'default') {
1691 if (!empty($CFG->filelifetime)) {
1692 $lifetime = $CFG->filelifetime;
1693 } else {
1694 $lifetime = 86400;
1698 session_get_instance()->write_close(); // unlock session during fileserving
1700 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1701 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1702 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1703 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1704 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1705 ($mimetype ? $mimetype : mimeinfo('type', $filename));
1707 $lastmodified = $pathisstring ? time() : filemtime($path);
1708 $filesize = $pathisstring ? strlen($path) : filesize($path);
1710 /* - MDL-13949
1711 //Adobe Acrobat Reader XSS prevention
1712 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1713 //please note that it prevents opening of pdfs in browser when http referer disabled
1714 //or file linked from another site; browser caching of pdfs is now disabled too
1715 if (!empty($_SERVER['HTTP_RANGE'])) {
1716 //already byteserving
1717 $lifetime = 1; // >0 needed for byteserving
1718 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1719 $mimetype = 'application/x-forcedownload';
1720 $forcedownload = true;
1721 $lifetime = 0;
1722 } else {
1723 $lifetime = 1; // >0 needed for byteserving
1728 //try to disable automatic sid rewrite in cookieless mode
1729 @ini_set("session.use_trans_sid", "false");
1731 if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1732 // get unixtime of request header; clip extra junk off first
1733 $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1734 if ($since && $since >= $lastmodified) {
1735 header('HTTP/1.1 304 Not Modified');
1736 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1737 header('Cache-Control: max-age='.$lifetime);
1738 header('Content-Type: '.$mimetype);
1739 if ($dontdie) {
1740 return;
1742 die;
1746 //do not put '@' before the next header to detect incorrect moodle configurations,
1747 //error should be better than "weird" empty lines for admins/users
1748 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1750 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1751 if (check_browser_version('MSIE')) {
1752 $filename = rawurlencode($filename);
1755 if ($forcedownload) {
1756 header('Content-Disposition: attachment; filename="'.$filename.'"');
1757 } else {
1758 header('Content-Disposition: inline; filename="'.$filename.'"');
1761 if ($lifetime > 0) {
1762 header('Cache-Control: max-age='.$lifetime);
1763 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1764 header('Pragma: ');
1766 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1768 header('Accept-Ranges: bytes');
1770 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1771 // byteserving stuff - for acrobat reader and download accelerators
1772 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1773 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1774 $ranges = false;
1775 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1776 foreach ($ranges as $key=>$value) {
1777 if ($ranges[$key][1] == '') {
1778 //suffix case
1779 $ranges[$key][1] = $filesize - $ranges[$key][2];
1780 $ranges[$key][2] = $filesize - 1;
1781 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1782 //fix range length
1783 $ranges[$key][2] = $filesize - 1;
1785 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1786 //invalid byte-range ==> ignore header
1787 $ranges = false;
1788 break;
1790 //prepare multipart header
1791 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1792 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1794 } else {
1795 $ranges = false;
1797 if ($ranges) {
1798 $handle = fopen($path, 'rb');
1799 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1802 } else {
1803 /// Do not byteserve (disabled, strings, text and html files).
1804 header('Accept-Ranges: none');
1806 } else { // Do not cache files in proxies and browsers
1807 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1808 header('Cache-Control: max-age=10');
1809 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1810 header('Pragma: ');
1811 } else { //normal http - prevent caching at all cost
1812 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1813 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1814 header('Pragma: no-cache');
1816 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1819 if (empty($filter)) {
1820 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
1821 //cookieless mode - rewrite links
1822 header('Content-Type: text/html');
1823 $path = $pathisstring ? $path : implode('', file($path));
1824 $path = sid_ob_rewrite($path);
1825 $filesize = strlen($path);
1826 $pathisstring = true;
1827 } else if ($mimetype == 'text/plain') {
1828 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1829 } else {
1830 header('Content-Type: '.$mimetype);
1832 header('Content-Length: '.$filesize);
1834 //flush the buffers - save memory and disable sid rewrite
1835 //this also disables zlib compression
1836 prepare_file_content_sending();
1838 // send the contents
1839 if ($pathisstring) {
1840 echo $path;
1841 } else {
1842 @readfile($path);
1845 } else { // Try to put the file through filters
1846 if ($mimetype == 'text/html') {
1847 $options = new stdClass();
1848 $options->noclean = true;
1849 $options->nocache = true; // temporary workaround for MDL-5136
1850 $text = $pathisstring ? $path : implode('', file($path));
1852 $text = file_modify_html_header($text);
1853 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1854 if (!empty($CFG->usesid)) {
1855 //cookieless mode - rewrite links
1856 $output = sid_ob_rewrite($output);
1859 header('Content-Length: '.strlen($output));
1860 header('Content-Type: text/html');
1862 //flush the buffers - save memory and disable sid rewrite
1863 //this also disables zlib compression
1864 prepare_file_content_sending();
1866 // send the contents
1867 echo $output;
1868 // only filter text if filter all files is selected
1869 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1870 $options = new stdClass();
1871 $options->newlines = false;
1872 $options->noclean = true;
1873 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1874 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1875 if (!empty($CFG->usesid)) {
1876 //cookieless mode - rewrite links
1877 $output = sid_ob_rewrite($output);
1880 header('Content-Length: '.strlen($output));
1881 header('Content-Type: text/html; charset=utf-8'); //add encoding
1883 //flush the buffers - save memory and disable sid rewrite
1884 //this also disables zlib compression
1885 prepare_file_content_sending();
1887 // send the contents
1888 echo $output;
1890 } else { // Just send it out raw
1891 header('Content-Length: '.$filesize);
1892 header('Content-Type: '.$mimetype);
1894 //flush the buffers - save memory and disable sid rewrite
1895 //this also disables zlib compression
1896 prepare_file_content_sending();
1898 // send the contents
1899 if ($pathisstring) {
1900 echo $path;
1901 }else {
1902 @readfile($path);
1906 if ($dontdie) {
1907 return;
1909 die; //no more chars to output!!!
1913 * Handles the sending of file data to the user's browser, including support for
1914 * byteranges etc.
1916 * @global object
1917 * @global object
1918 * @global object
1919 * @param object $stored_file local file object
1920 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1921 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1922 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1923 * @param string $filename Override filename
1924 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1925 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1926 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1927 * and should not be reopened.
1928 * @return void no return or void, script execution stopped unless $dontdie is true
1930 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1931 global $CFG, $COURSE, $SESSION;
1933 if (!$stored_file or $stored_file->is_directory()) {
1934 // nothing to serve
1935 if ($dontdie) {
1936 return;
1938 die;
1941 if ($dontdie) {
1942 ignore_user_abort(true);
1945 session_get_instance()->write_close(); // unlock session during fileserving
1947 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1948 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1949 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1950 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1951 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1952 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1953 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1955 $lastmodified = $stored_file->get_timemodified();
1956 $filesize = $stored_file->get_filesize();
1958 //try to disable automatic sid rewrite in cookieless mode
1959 @ini_set("session.use_trans_sid", "false");
1961 if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
1962 // get unixtime of request header; clip extra junk off first
1963 $since = strtotime(preg_replace('/;.*$/','',$_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1964 if ($since && $since >= $lastmodified) {
1965 header('HTTP/1.1 304 Not Modified');
1966 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1967 header('Cache-Control: max-age='.$lifetime);
1968 header('Content-Type: '.$mimetype);
1969 if ($dontdie) {
1970 return;
1972 die;
1976 //do not put '@' before the next header to detect incorrect moodle configurations,
1977 //error should be better than "weird" empty lines for admins/users
1978 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1979 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1981 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1982 if (check_browser_version('MSIE')) {
1983 $filename = rawurlencode($filename);
1986 if ($forcedownload) {
1987 header('Content-Disposition: attachment; filename="'.$filename.'"');
1988 } else {
1989 header('Content-Disposition: inline; filename="'.$filename.'"');
1992 if ($lifetime > 0) {
1993 header('Cache-Control: max-age='.$lifetime);
1994 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1995 header('Pragma: ');
1997 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1999 header('Accept-Ranges: bytes');
2001 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2002 // byteserving stuff - for acrobat reader and download accelerators
2003 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2004 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2005 $ranges = false;
2006 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2007 foreach ($ranges as $key=>$value) {
2008 if ($ranges[$key][1] == '') {
2009 //suffix case
2010 $ranges[$key][1] = $filesize - $ranges[$key][2];
2011 $ranges[$key][2] = $filesize - 1;
2012 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2013 //fix range length
2014 $ranges[$key][2] = $filesize - 1;
2016 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2017 //invalid byte-range ==> ignore header
2018 $ranges = false;
2019 break;
2021 //prepare multipart header
2022 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2023 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2025 } else {
2026 $ranges = false;
2028 if ($ranges) {
2029 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
2032 } else {
2033 /// Do not byteserve (disabled, strings, text and html files).
2034 header('Accept-Ranges: none');
2036 } else { // Do not cache files in proxies and browsers
2037 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2038 header('Cache-Control: max-age=10');
2039 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2040 header('Pragma: ');
2041 } else { //normal http - prevent caching at all cost
2042 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2043 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2044 header('Pragma: no-cache');
2046 header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
2049 if (empty($filter)) {
2050 $filtered = false;
2051 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
2052 //cookieless mode - rewrite links
2053 header('Content-Type: text/html');
2054 $text = $stored_file->get_content();
2055 $text = sid_ob_rewrite($text);
2056 $filesize = strlen($text);
2057 $filtered = true;
2058 } else if ($mimetype == 'text/plain') {
2059 header('Content-Type: Text/plain; charset=utf-8'); //add encoding
2060 } else {
2061 header('Content-Type: '.$mimetype);
2063 header('Content-Length: '.$filesize);
2065 //flush the buffers - save memory and disable sid rewrite
2066 //this also disables zlib compression
2067 prepare_file_content_sending();
2069 // send the contents
2070 if ($filtered) {
2071 echo $text;
2072 } else {
2073 $stored_file->readfile();
2076 } else { // Try to put the file through filters
2077 if ($mimetype == 'text/html') {
2078 $options = new stdClass();
2079 $options->noclean = true;
2080 $options->nocache = true; // temporary workaround for MDL-5136
2081 $text = $stored_file->get_content();
2082 $text = file_modify_html_header($text);
2083 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2084 if (!empty($CFG->usesid)) {
2085 //cookieless mode - rewrite links
2086 $output = sid_ob_rewrite($output);
2089 header('Content-Length: '.strlen($output));
2090 header('Content-Type: text/html');
2092 //flush the buffers - save memory and disable sid rewrite
2093 //this also disables zlib compression
2094 prepare_file_content_sending();
2096 // send the contents
2097 echo $output;
2099 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2100 // only filter text if filter all files is selected
2101 $options = new stdClass();
2102 $options->newlines = false;
2103 $options->noclean = true;
2104 $text = $stored_file->get_content();
2105 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2106 if (!empty($CFG->usesid)) {
2107 //cookieless mode - rewrite links
2108 $output = sid_ob_rewrite($output);
2111 header('Content-Length: '.strlen($output));
2112 header('Content-Type: text/html; charset=utf-8'); //add encoding
2114 //flush the buffers - save memory and disable sid rewrite
2115 //this also disables zlib compression
2116 prepare_file_content_sending();
2118 // send the contents
2119 echo $output;
2121 } else { // Just send it out raw
2122 header('Content-Length: '.$filesize);
2123 header('Content-Type: '.$mimetype);
2125 //flush the buffers - save memory and disable sid rewrite
2126 //this also disables zlib compression
2127 prepare_file_content_sending();
2129 // send the contents
2130 $stored_file->readfile();
2133 if ($dontdie) {
2134 return;
2136 die; //no more chars to output!!!
2140 * Retrieves an array of records from a CSV file and places
2141 * them into a given table structure
2143 * @global object
2144 * @global object
2145 * @param string $file The path to a CSV file
2146 * @param string $table The table to retrieve columns from
2147 * @return bool|array Returns an array of CSV records or false
2149 function get_records_csv($file, $table) {
2150 global $CFG, $DB;
2152 if (!$metacolumns = $DB->get_columns($table)) {
2153 return false;
2156 if(!($handle = @fopen($file, 'r'))) {
2157 print_error('get_records_csv failed to open '.$file);
2160 $fieldnames = fgetcsv($handle, 4096);
2161 if(empty($fieldnames)) {
2162 fclose($handle);
2163 return false;
2166 $columns = array();
2168 foreach($metacolumns as $metacolumn) {
2169 $ord = array_search($metacolumn->name, $fieldnames);
2170 if(is_int($ord)) {
2171 $columns[$metacolumn->name] = $ord;
2175 $rows = array();
2177 while (($data = fgetcsv($handle, 4096)) !== false) {
2178 $item = new stdClass;
2179 foreach($columns as $name => $ord) {
2180 $item->$name = $data[$ord];
2182 $rows[] = $item;
2185 fclose($handle);
2186 return $rows;
2191 * @global object
2192 * @global object
2193 * @param string $file The file to put the CSV content into
2194 * @param array $records An array of records to write to a CSV file
2195 * @param string $table The table to get columns from
2196 * @return bool success
2198 function put_records_csv($file, $records, $table = NULL) {
2199 global $CFG, $DB;
2201 if (empty($records)) {
2202 return true;
2205 $metacolumns = NULL;
2206 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2207 return false;
2210 echo "x";
2212 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
2213 print_error('put_records_csv failed to open '.$file);
2216 $proto = reset($records);
2217 if(is_object($proto)) {
2218 $fields_records = array_keys(get_object_vars($proto));
2220 else if(is_array($proto)) {
2221 $fields_records = array_keys($proto);
2223 else {
2224 return false;
2226 echo "x";
2228 if(!empty($metacolumns)) {
2229 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2230 $fields = array_intersect($fields_records, $fields_table);
2232 else {
2233 $fields = $fields_records;
2236 fwrite($fp, implode(',', $fields));
2237 fwrite($fp, "\r\n");
2239 foreach($records as $record) {
2240 $array = (array)$record;
2241 $values = array();
2242 foreach($fields as $field) {
2243 if(strpos($array[$field], ',')) {
2244 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2246 else {
2247 $values[] = $array[$field];
2250 fwrite($fp, implode(',', $values)."\r\n");
2253 fclose($fp);
2254 return true;
2259 * Recursively delete the file or folder with path $location. That is,
2260 * if it is a file delete it. If it is a folder, delete all its content
2261 * then delete it. If $location does not exist to start, that is not
2262 * considered an error.
2264 * @param string $location the path to remove.
2265 * @return bool
2267 function fulldelete($location) {
2268 if (empty($location)) {
2269 // extra safety against wrong param
2270 return false;
2272 if (is_dir($location)) {
2273 $currdir = opendir($location);
2274 while (false !== ($file = readdir($currdir))) {
2275 if ($file <> ".." && $file <> ".") {
2276 $fullfile = $location."/".$file;
2277 if (is_dir($fullfile)) {
2278 if (!fulldelete($fullfile)) {
2279 return false;
2281 } else {
2282 if (!unlink($fullfile)) {
2283 return false;
2288 closedir($currdir);
2289 if (! rmdir($location)) {
2290 return false;
2293 } else if (file_exists($location)) {
2294 if (!unlink($location)) {
2295 return false;
2298 return true;
2302 * Send requested byterange of file.
2304 * @param object $handle A file handle
2305 * @param string $mimetype The mimetype for the output
2306 * @param array $ranges An array of ranges to send
2307 * @param string $filesize The size of the content if only one range is used
2309 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2310 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2311 if ($handle === false) {
2312 die;
2314 if (count($ranges) == 1) { //only one range requested
2315 $length = $ranges[0][2] - $ranges[0][1] + 1;
2316 header('HTTP/1.1 206 Partial content');
2317 header('Content-Length: '.$length);
2318 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2319 header('Content-Type: '.$mimetype);
2321 //flush the buffers - save memory and disable sid rewrite
2322 //this also disables zlib compression
2323 prepare_file_content_sending();
2325 $buffer = '';
2326 fseek($handle, $ranges[0][1]);
2327 while (!feof($handle) && $length > 0) {
2328 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2329 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2330 echo $buffer;
2331 flush();
2332 $length -= strlen($buffer);
2334 fclose($handle);
2335 die;
2336 } else { // multiple ranges requested - not tested much
2337 $totallength = 0;
2338 foreach($ranges as $range) {
2339 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2341 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2342 header('HTTP/1.1 206 Partial content');
2343 header('Content-Length: '.$totallength);
2344 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2345 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2347 //flush the buffers - save memory and disable sid rewrite
2348 //this also disables zlib compression
2349 prepare_file_content_sending();
2351 foreach($ranges as $range) {
2352 $length = $range[2] - $range[1] + 1;
2353 echo $range[0];
2354 $buffer = '';
2355 fseek($handle, $range[1]);
2356 while (!feof($handle) && $length > 0) {
2357 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2358 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2359 echo $buffer;
2360 flush();
2361 $length -= strlen($buffer);
2364 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2365 fclose($handle);
2366 die;
2371 * add includes (js and css) into uploaded files
2372 * before returning them, useful for themes and utf.js includes
2374 * @global object
2375 * @param string $text text to search and replace
2376 * @return string text with added head includes
2378 function file_modify_html_header($text) {
2379 // first look for <head> tag
2380 global $CFG;
2382 $stylesheetshtml = '';
2383 /* foreach ($CFG->stylesheets as $stylesheet) {
2384 //TODO: MDL-21120
2385 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2388 $ufo = '';
2389 if (filter_is_enabled('filter/mediaplugin')) {
2390 // this script is needed by most media filter plugins.
2391 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2392 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2395 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2396 if ($matches) {
2397 $replacement = '<head>'.$ufo.$stylesheetshtml;
2398 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2399 return $text;
2402 // if not, look for <html> tag, and stick <head> right after
2403 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2404 if ($matches) {
2405 // replace <html> tag with <html><head>includes</head>
2406 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2407 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2408 return $text;
2411 // if not, look for <body> tag, and stick <head> before body
2412 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2413 if ($matches) {
2414 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2415 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2416 return $text;
2419 // if not, just stick a <head> tag at the beginning
2420 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2421 return $text;
2425 * RESTful cURL class
2427 * This is a wrapper class for curl, it is quite easy to use:
2428 * <code>
2429 * $c = new curl;
2430 * // enable cache
2431 * $c = new curl(array('cache'=>true));
2432 * // enable cookie
2433 * $c = new curl(array('cookie'=>true));
2434 * // enable proxy
2435 * $c = new curl(array('proxy'=>true));
2437 * // HTTP GET Method
2438 * $html = $c->get('http://example.com');
2439 * // HTTP POST Method
2440 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2441 * // HTTP PUT Method
2442 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2443 * </code>
2445 * @package core
2446 * @subpackage file
2447 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2448 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2451 class curl {
2452 /** @var bool */
2453 public $cache = false;
2454 public $proxy = false;
2455 /** @var string */
2456 public $version = '0.4 dev';
2457 /** @var array */
2458 public $response = array();
2459 public $header = array();
2460 /** @var string */
2461 public $info;
2462 public $error;
2464 /** @var array */
2465 private $options;
2466 /** @var string */
2467 private $proxy_host = '';
2468 private $proxy_auth = '';
2469 private $proxy_type = '';
2470 /** @var bool */
2471 private $debug = false;
2472 private $cookie = false;
2475 * @global object
2476 * @param array $options
2478 public function __construct($options = array()){
2479 global $CFG;
2480 if (!function_exists('curl_init')) {
2481 $this->error = 'cURL module must be enabled!';
2482 trigger_error($this->error, E_USER_ERROR);
2483 return false;
2485 // the options of curl should be init here.
2486 $this->resetopt();
2487 if (!empty($options['debug'])) {
2488 $this->debug = true;
2490 if(!empty($options['cookie'])) {
2491 if($options['cookie'] === true) {
2492 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2493 } else {
2494 $this->cookie = $options['cookie'];
2497 if (!empty($options['cache'])) {
2498 if (class_exists('curl_cache')) {
2499 if (!empty($options['module_cache'])) {
2500 $this->cache = new curl_cache($options['module_cache']);
2501 } else {
2502 $this->cache = new curl_cache('misc');
2506 if (!empty($CFG->proxyhost)) {
2507 if (empty($CFG->proxyport)) {
2508 $this->proxy_host = $CFG->proxyhost;
2509 } else {
2510 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2512 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2513 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2514 $this->setopt(array(
2515 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2516 'proxyuserpwd'=>$this->proxy_auth));
2518 if (!empty($CFG->proxytype)) {
2519 if ($CFG->proxytype == 'SOCKS5') {
2520 $this->proxy_type = CURLPROXY_SOCKS5;
2521 } else {
2522 $this->proxy_type = CURLPROXY_HTTP;
2523 $this->setopt(array('httpproxytunnel'=>false));
2525 $this->setopt(array('proxytype'=>$this->proxy_type));
2528 if (!empty($this->proxy_host)) {
2529 $this->proxy = array('proxy'=>$this->proxy_host);
2533 * Resets the CURL options that have already been set
2535 public function resetopt(){
2536 $this->options = array();
2537 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2538 // True to include the header in the output
2539 $this->options['CURLOPT_HEADER'] = 0;
2540 // True to Exclude the body from the output
2541 $this->options['CURLOPT_NOBODY'] = 0;
2542 // TRUE to follow any "Location: " header that the server
2543 // sends as part of the HTTP header (note this is recursive,
2544 // PHP will follow as many "Location: " headers that it is sent,
2545 // unless CURLOPT_MAXREDIRS is set).
2546 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2547 $this->options['CURLOPT_MAXREDIRS'] = 10;
2548 $this->options['CURLOPT_ENCODING'] = '';
2549 // TRUE to return the transfer as a string of the return
2550 // value of curl_exec() instead of outputting it out directly.
2551 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2552 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2553 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2554 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2555 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2559 * Reset Cookie
2561 public function resetcookie() {
2562 if (!empty($this->cookie)) {
2563 if (is_file($this->cookie)) {
2564 $fp = fopen($this->cookie, 'w');
2565 if (!empty($fp)) {
2566 fwrite($fp, '');
2567 fclose($fp);
2574 * Set curl options
2576 * @param array $options If array is null, this function will
2577 * reset the options to default value.
2580 public function setopt($options = array()) {
2581 if (is_array($options)) {
2582 foreach($options as $name => $val){
2583 if (stripos($name, 'CURLOPT_') === false) {
2584 $name = strtoupper('CURLOPT_'.$name);
2586 $this->options[$name] = $val;
2591 * Reset http method
2594 public function cleanopt(){
2595 unset($this->options['CURLOPT_HTTPGET']);
2596 unset($this->options['CURLOPT_POST']);
2597 unset($this->options['CURLOPT_POSTFIELDS']);
2598 unset($this->options['CURLOPT_PUT']);
2599 unset($this->options['CURLOPT_INFILE']);
2600 unset($this->options['CURLOPT_INFILESIZE']);
2601 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2605 * Set HTTP Request Header
2607 * @param array $headers
2610 public function setHeader($header) {
2611 if (is_array($header)){
2612 foreach ($header as $v) {
2613 $this->setHeader($v);
2615 } else {
2616 $this->header[] = $header;
2620 * Set HTTP Response Header
2623 public function getResponse(){
2624 return $this->response;
2627 * private callback function
2628 * Formatting HTTP Response Header
2630 * @param mixed $ch Apparently not used
2631 * @param string $header
2632 * @return int The strlen of the header
2634 private function formatHeader($ch, $header)
2636 $this->count++;
2637 if (strlen($header) > 2) {
2638 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2639 $key = rtrim($key, ':');
2640 if (!empty($this->response[$key])) {
2641 if (is_array($this->response[$key])){
2642 $this->response[$key][] = $value;
2643 } else {
2644 $tmp = $this->response[$key];
2645 $this->response[$key] = array();
2646 $this->response[$key][] = $tmp;
2647 $this->response[$key][] = $value;
2650 } else {
2651 $this->response[$key] = $value;
2654 return strlen($header);
2658 * Set options for individual curl instance
2660 * @param object $curl A curl handle
2661 * @param array $options
2662 * @return object The curl handle
2664 private function apply_opt($curl, $options) {
2665 // Clean up
2666 $this->cleanopt();
2667 // set cookie
2668 if (!empty($this->cookie) || !empty($options['cookie'])) {
2669 $this->setopt(array('cookiejar'=>$this->cookie,
2670 'cookiefile'=>$this->cookie
2674 // set proxy
2675 if (!empty($this->proxy) || !empty($options['proxy'])) {
2676 $this->setopt($this->proxy);
2678 $this->setopt($options);
2679 // reset before set options
2680 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2681 // set headers
2682 if (empty($this->header)){
2683 $this->setHeader(array(
2684 'User-Agent: MoodleBot/1.0',
2685 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2686 'Connection: keep-alive'
2689 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2691 if ($this->debug){
2692 echo '<h1>Options</h1>';
2693 var_dump($this->options);
2694 echo '<h1>Header</h1>';
2695 var_dump($this->header);
2698 // set options
2699 foreach($this->options as $name => $val) {
2700 if (is_string($name)) {
2701 $name = constant(strtoupper($name));
2703 curl_setopt($curl, $name, $val);
2705 return $curl;
2708 * Download multiple files in parallel
2710 * Calls {@link multi()} with specific download headers
2712 * <code>
2713 * $c = new curl;
2714 * $c->download(array(
2715 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2716 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2717 * ));
2718 * </code>
2720 * @param array $requests An array of files to request
2721 * @param array $options An array of options to set
2722 * @return array An array of results
2724 public function download($requests, $options = array()) {
2725 $options['CURLOPT_BINARYTRANSFER'] = 1;
2726 $options['RETURNTRANSFER'] = false;
2727 return $this->multi($requests, $options);
2730 * Mulit HTTP Requests
2731 * This function could run multi-requests in parallel.
2733 * @param array $requests An array of files to request
2734 * @param array $options An array of options to set
2735 * @return array An array of results
2737 protected function multi($requests, $options = array()) {
2738 $count = count($requests);
2739 $handles = array();
2740 $results = array();
2741 $main = curl_multi_init();
2742 for ($i = 0; $i < $count; $i++) {
2743 $url = $requests[$i];
2744 foreach($url as $n=>$v){
2745 $options[$n] = $url[$n];
2747 $handles[$i] = curl_init($url['url']);
2748 $this->apply_opt($handles[$i], $options);
2749 curl_multi_add_handle($main, $handles[$i]);
2751 $running = 0;
2752 do {
2753 curl_multi_exec($main, $running);
2754 } while($running > 0);
2755 for ($i = 0; $i < $count; $i++) {
2756 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
2757 $results[] = true;
2758 } else {
2759 $results[] = curl_multi_getcontent($handles[$i]);
2761 curl_multi_remove_handle($main, $handles[$i]);
2763 curl_multi_close($main);
2764 return $results;
2767 * Single HTTP Request
2769 * @param string $url The URL to request
2770 * @param array $options
2771 * @return bool
2773 protected function request($url, $options = array()){
2774 // create curl instance
2775 $curl = curl_init($url);
2776 $options['url'] = $url;
2777 $this->apply_opt($curl, $options);
2778 if ($this->cache && $ret = $this->cache->get($this->options)) {
2779 return $ret;
2780 } else {
2781 $ret = curl_exec($curl);
2782 if ($this->cache) {
2783 $this->cache->set($this->options, $ret);
2787 $this->info = curl_getinfo($curl);
2788 $this->error = curl_error($curl);
2790 if ($this->debug){
2791 echo '<h1>Return Data</h1>';
2792 var_dump($ret);
2793 echo '<h1>Info</h1>';
2794 var_dump($this->info);
2795 echo '<h1>Error</h1>';
2796 var_dump($this->error);
2799 curl_close($curl);
2801 if (empty($this->error)){
2802 return $ret;
2803 } else {
2804 return $this->error;
2805 // exception is not ajax friendly
2806 //throw new moodle_exception($this->error, 'curl');
2811 * HTTP HEAD method
2813 * @see request()
2815 * @param string $url
2816 * @param array $options
2817 * @return bool
2819 public function head($url, $options = array()){
2820 $options['CURLOPT_HTTPGET'] = 0;
2821 $options['CURLOPT_HEADER'] = 1;
2822 $options['CURLOPT_NOBODY'] = 1;
2823 return $this->request($url, $options);
2827 * HTTP POST method
2829 * @param string $url
2830 * @param array|string $params
2831 * @param array $options
2832 * @return bool
2834 public function post($url, $params = '', $options = array()){
2835 $options['CURLOPT_POST'] = 1;
2836 if (is_array($params)) {
2837 $this->_tmp_file_post_params = array();
2838 foreach ($params as $key => $value) {
2839 if ($value instanceof stored_file) {
2840 $value->add_to_curl_request($this, $key);
2841 } else {
2842 $this->_tmp_file_post_params[$key] = $value;
2845 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2846 unset($this->_tmp_file_post_params);
2847 } else {
2848 // $params is the raw post data
2849 $options['CURLOPT_POSTFIELDS'] = $params;
2851 return $this->request($url, $options);
2855 * HTTP GET method
2857 * @param string $url
2858 * @param array $params
2859 * @param array $options
2860 * @return bool
2862 public function get($url, $params = array(), $options = array()){
2863 $options['CURLOPT_HTTPGET'] = 1;
2865 if (!empty($params)){
2866 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2867 $url .= http_build_query($params, '', '&');
2869 return $this->request($url, $options);
2873 * HTTP PUT method
2875 * @param string $url
2876 * @param array $params
2877 * @param array $options
2878 * @return bool
2880 public function put($url, $params = array(), $options = array()){
2881 $file = $params['file'];
2882 if (!is_file($file)){
2883 return null;
2885 $fp = fopen($file, 'r');
2886 $size = filesize($file);
2887 $options['CURLOPT_PUT'] = 1;
2888 $options['CURLOPT_INFILESIZE'] = $size;
2889 $options['CURLOPT_INFILE'] = $fp;
2890 if (!isset($this->options['CURLOPT_USERPWD'])){
2891 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2893 $ret = $this->request($url, $options);
2894 fclose($fp);
2895 return $ret;
2899 * HTTP DELETE method
2901 * @param string $url
2902 * @param array $params
2903 * @param array $options
2904 * @return bool
2906 public function delete($url, $param = array(), $options = array()){
2907 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2908 if (!isset($options['CURLOPT_USERPWD'])) {
2909 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2911 $ret = $this->request($url, $options);
2912 return $ret;
2915 * HTTP TRACE method
2917 * @param string $url
2918 * @param array $options
2919 * @return bool
2921 public function trace($url, $options = array()){
2922 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2923 $ret = $this->request($url, $options);
2924 return $ret;
2927 * HTTP OPTIONS method
2929 * @param string $url
2930 * @param array $options
2931 * @return bool
2933 public function options($url, $options = array()){
2934 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2935 $ret = $this->request($url, $options);
2936 return $ret;
2938 public function get_info() {
2939 return $this->info;
2944 * This class is used by cURL class, use case:
2946 * <code>
2947 * $CFG->repositorycacheexpire = 120;
2948 * $CFG->curlcache = 120;
2950 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2951 * $ret = $c->get('http://www.google.com');
2952 * </code>
2954 * @package core
2955 * @subpackage file
2956 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2957 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2959 class curl_cache {
2960 /** @var string */
2961 public $dir = '';
2964 * @global object
2965 * @param string @module which module is using curl_cache
2968 function __construct($module = 'repository'){
2969 global $CFG;
2970 if (!empty($module)) {
2971 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2972 } else {
2973 $this->dir = $CFG->dataroot.'/cache/misc/';
2975 if (!file_exists($this->dir)) {
2976 mkdir($this->dir, $CFG->directorypermissions, true);
2978 if ($module == 'repository') {
2979 if (empty($CFG->repositorycacheexpire)) {
2980 $CFG->repositorycacheexpire = 120;
2982 $this->ttl = $CFG->repositorycacheexpire;
2983 } else {
2984 if (empty($CFG->curlcache)) {
2985 $CFG->curlcache = 120;
2987 $this->ttl = $CFG->curlcache;
2992 * Get cached value
2994 * @global object
2995 * @global object
2996 * @param mixed $param
2997 * @return bool|string
2999 public function get($param){
3000 global $CFG, $USER;
3001 $this->cleanup($this->ttl);
3002 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3003 if(file_exists($this->dir.$filename)) {
3004 $lasttime = filemtime($this->dir.$filename);
3005 if(time()-$lasttime > $this->ttl)
3007 return false;
3008 } else {
3009 $fp = fopen($this->dir.$filename, 'r');
3010 $size = filesize($this->dir.$filename);
3011 $content = fread($fp, $size);
3012 return unserialize($content);
3015 return false;
3019 * Set cache value
3021 * @global object $CFG
3022 * @global object $USER
3023 * @param mixed $param
3024 * @param mixed $val
3026 public function set($param, $val){
3027 global $CFG, $USER;
3028 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
3029 $fp = fopen($this->dir.$filename, 'w');
3030 fwrite($fp, serialize($val));
3031 fclose($fp);
3035 * Remove cache files
3037 * @param int $expire The number os seconds before expiry
3039 public function cleanup($expire){
3040 if($dir = opendir($this->dir)){
3041 while (false !== ($file = readdir($dir))) {
3042 if(!is_dir($file) && $file != '.' && $file != '..') {
3043 $lasttime = @filemtime($this->dir.$file);
3044 if(time() - $lasttime > $expire){
3045 @unlink($this->dir.$file);
3052 * delete current user's cache file
3054 * @global object $CFG
3055 * @global object $USER
3057 public function refresh(){
3058 global $CFG, $USER;
3059 if($dir = opendir($this->dir)){
3060 while (false !== ($file = readdir($dir))) {
3061 if(!is_dir($file) && $file != '.' && $file != '..') {
3062 if(strpos($file, 'u'.$USER->id.'_')!==false){
3063 @unlink($this->dir.$file);
3072 * This class is used to parse lib/file/file_types.mm which help get file
3073 * extensions by file types.
3074 * The file_types.mm file can be edited by freemind in graphic environment.
3076 * @package core
3077 * @subpackage file
3078 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
3079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3081 class filetype_parser {
3083 * Check file_types.mm file, setup variables
3085 * @global object $CFG
3086 * @param string $file
3088 public function __construct($file = '') {
3089 global $CFG;
3090 if (empty($file)) {
3091 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
3092 } else {
3093 $this->file = $file;
3095 $this->tree = array();
3096 $this->result = array();
3100 * A private function to browse xml nodes
3102 * @param array $parent
3103 * @param array $types
3105 private function _browse_nodes($parent, $types) {
3106 $key = (string)$parent['TEXT'];
3107 if(isset($parent->node)) {
3108 $this->tree[$key] = array();
3109 if (in_array((string)$parent['TEXT'], $types)) {
3110 $this->_select_nodes($parent, $this->result);
3111 } else {
3112 foreach($parent->node as $v){
3113 $this->_browse_nodes($v, $types);
3116 } else {
3117 $this->tree[] = $key;
3122 * A private function to select text nodes
3124 * @param array $parent
3126 private function _select_nodes($parent){
3127 if(isset($parent->node)) {
3128 foreach($parent->node as $v){
3129 $this->_select_nodes($v, $this->result);
3131 } else {
3132 $this->result[] = (string)$parent['TEXT'];
3138 * Get file extensions by file types names.
3140 * @param array $types
3141 * @return mixed
3143 public function get_extensions($types) {
3144 if (!is_array($types)) {
3145 $types = array($types);
3147 $this->result = array();
3148 if ((is_array($types) && in_array('*', $types)) ||
3149 $types == '*' || empty($types)) {
3150 return array('*');
3152 foreach ($types as $key=>$value){
3153 if (strpos($value, '.') !== false) {
3154 $this->result[] = $value;
3155 unset($types[$key]);
3158 if (file_exists($this->file)) {
3159 $xml = simplexml_load_file($this->file);
3160 foreach($xml->node->node as $v){
3161 if (in_array((string)$v['TEXT'], $types)) {
3162 $this->_select_nodes($v);
3163 } else {
3164 $this->_browse_nodes($v, $types);
3167 } else {
3168 exit('Failed to open file lib/filestorage/file_types.mm');
3170 return $this->result;