Automatic installer lang files (20100904)
[moodle.git] / lib / filelib.php
blobd030df0424ba47ab083eb9687ebb038ca5aefdb3
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions for file handling.
21 * @package core
22 * @subpackage file
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** @var string unique string constant. */
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
32 require_once("$CFG->libdir/filestorage/file_exceptions.php");
33 require_once("$CFG->libdir/filestorage/file_storage.php");
34 require_once("$CFG->libdir/filestorage/zip_packer.php");
35 require_once("$CFG->libdir/filebrowser/file_browser.php");
37 /**
38 * Encodes file serving url
40 * @deprecated use moodle_url factory methods instead
42 * @global object
43 * @param string $urlbase
44 * @param string $path /filearea/itemid/dir/dir/file.exe
45 * @param bool $forcedownload
46 * @param bool $https https url required
47 * @return string encoded file url
49 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
50 global $CFG;
52 //TODO: deprecate this
54 if ($CFG->slasharguments) {
55 $parts = explode('/', $path);
56 $parts = array_map('rawurlencode', $parts);
57 $path = implode('/', $parts);
58 $return = $urlbase.$path;
59 if ($forcedownload) {
60 $return .= '?forcedownload=1';
62 } else {
63 $path = rawurlencode($path);
64 $return = $urlbase.'?file='.$path;
65 if ($forcedownload) {
66 $return .= '&amp;forcedownload=1';
70 if ($https) {
71 $return = str_replace('http://', 'https://', $return);
74 return $return;
77 /**
78 * Prepares 'editor' formslib element from data in database
80 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
81 * function then copies the embedded files into draft area (assigning itemids automatically),
82 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
83 * displayed.
84 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
85 * your mform's set_data() supplying the object returned by this function.
87 * @param object $data database field that holds the html text with embedded media
88 * @param string $field the name of the database field that holds the html text with embedded media
89 * @param array $options editor options (like maxifiles, maxbytes etc.)
90 * @param object $context context of the editor
91 * @param string $component
92 * @param string $filearea file area name
93 * @param int $itemid item id, required if item exists
94 * @return object modified data object
96 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
97 $options = (array)$options;
98 if (!isset($options['trusttext'])) {
99 $options['trusttext'] = false;
101 if (!isset($options['forcehttps'])) {
102 $options['forcehttps'] = false;
104 if (!isset($options['subdirs'])) {
105 $options['subdirs'] = false;
107 if (!isset($options['maxfiles'])) {
108 $options['maxfiles'] = 0; // no files by default
110 if (!isset($options['noclean'])) {
111 $options['noclean'] = false;
114 if (is_null($itemid) or is_null($context)) {
115 $contextid = null;
116 $itemid = null;
117 if (!isset($data->{$field})) {
118 $data->{$field} = '';
120 if (!isset($data->{$field.'format'})) {
121 $data->{$field.'format'} = editors_get_preferred_format();
123 if (!$options['noclean']) {
124 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
127 } else {
128 if ($options['trusttext']) {
129 // noclean ignored if trusttext enabled
130 if (!isset($data->{$field.'trust'})) {
131 $data->{$field.'trust'} = 0;
133 $data = trusttext_pre_edit($data, $field, $context);
134 } else {
135 if (!$options['noclean']) {
136 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
139 $contextid = $context->id;
142 if ($options['maxfiles'] != 0) {
143 $draftid_editor = file_get_submitted_draft_itemid($field);
144 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
145 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
146 } else {
147 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
150 return $data;
154 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
156 * This function moves files from draft area to the destination area and
157 * encodes URLs to the draft files so they can be safely saved into DB. The
158 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
159 * is the name of the database field to hold the wysiwyg editor content. The
160 * editor data comes as an array with text, format and itemid properties. This
161 * function automatically adds $data properties foobar, foobarformat and
162 * foobartrust, where foobar has URL to embedded files encoded.
164 * @param object $data raw data submitted by the form
165 * @param string $field name of the database field containing the html with embedded media files
166 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
167 * @param object $context context, required for existing data
168 * @param string component
169 * @param string $filearea file area name
170 * @param int $itemid item id, required if item exists
171 * @return object modified data object
173 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
174 $options = (array)$options;
175 if (!isset($options['trusttext'])) {
176 $options['trusttext'] = false;
178 if (!isset($options['forcehttps'])) {
179 $options['forcehttps'] = false;
181 if (!isset($options['subdirs'])) {
182 $options['subdirs'] = false;
184 if (!isset($options['maxfiles'])) {
185 $options['maxfiles'] = 0; // no files by default
187 if (!isset($options['maxbytes'])) {
188 $options['maxbytes'] = 0; // unlimited
191 if ($options['trusttext']) {
192 $data->{$field.'trust'} = trusttext_trusted($context);
193 } else {
194 $data->{$field.'trust'} = 0;
197 $editor = $data->{$field.'_editor'};
199 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
200 $data->{$field} = $editor['text'];
201 } else {
202 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
204 $data->{$field.'format'} = $editor['format'];
206 return $data;
210 * Saves text and files modified by Editor formslib element
212 * @param object $data $database entry field
213 * @param string $field name of data field
214 * @param array $options various options
215 * @param object $context context - must already exist
216 * @param string $component
217 * @param string $filearea file area name
218 * @param int $itemid must already exist, usually means data is in db
219 * @return object modified data obejct
221 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
222 $options = (array)$options;
223 if (!isset($options['subdirs'])) {
224 $options['subdirs'] = false;
226 if (is_null($itemid) or is_null($context)) {
227 $itemid = null;
228 $contextid = null;
229 } else {
230 $contextid = $context->id;
233 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
234 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
235 $data->{$field.'_filemanager'} = $draftid_editor;
237 return $data;
241 * Saves files modified by File manager formslib element
243 * @param object $data $database entry field
244 * @param string $field name of data field
245 * @param array $options various options
246 * @param object $context context - must already exist
247 * @param string $component
248 * @param string $filearea file area name
249 * @param int $itemid must already exist, usually means data is in db
250 * @return object modified data obejct
252 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
253 $options = (array)$options;
254 if (!isset($options['subdirs'])) {
255 $options['subdirs'] = false;
257 if (!isset($options['maxfiles'])) {
258 $options['maxfiles'] = -1; // unlimited
260 if (!isset($options['maxbytes'])) {
261 $options['maxbytes'] = 0; // unlimited
264 if (empty($data->{$field.'_filemanager'})) {
265 $data->$field = '';
267 } else {
268 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
269 $fs = get_file_storage();
271 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
272 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
273 } else {
274 $data->$field = '';
278 return $data;
283 * @global object
284 * @global object
285 * @return int a random but available draft itemid that can be used to create a new draft
286 * file area.
288 function file_get_unused_draft_itemid() {
289 global $DB, $USER;
291 if (isguestuser() or !isloggedin()) {
292 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
293 print_error('noguest');
296 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
298 $fs = get_file_storage();
299 $draftitemid = rand(1, 999999999);
300 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
301 $draftitemid = rand(1, 999999999);
304 return $draftitemid;
308 * Initialise a draft file area from a real one by copying the files. A draft
309 * area will be created if one does not already exist. Normally you should
310 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
312 * @global object
313 * @global object
314 * @param int &$draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
315 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
316 * @param string $component
317 * @param string $filearea helps indentify the file area.
318 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
319 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
320 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
321 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
323 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
324 global $CFG, $USER;
326 $options = (array)$options;
327 if (!isset($options['subdirs'])) {
328 $options['subdirs'] = false;
330 if (!isset($options['forcehttps'])) {
331 $options['forcehttps'] = false;
334 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
335 $fs = get_file_storage();
337 if (empty($draftitemid)) {
338 // create a new area and copy existing files into
339 $draftitemid = file_get_unused_draft_itemid();
340 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
341 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
342 foreach ($files as $file) {
343 if ($file->is_directory() and $file->get_filepath() === '/') {
344 // we need a way to mark the age of each draft area,
345 // by not copying the root dir we force it to be created automatically with current timestamp
346 continue;
348 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
349 continue;
351 $fs->create_file_from_storedfile($file_record, $file);
354 } else {
355 // nothing to do
358 if (is_null($text)) {
359 return null;
362 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
363 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
367 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
369 * @global object
370 * @param string $text The content that may contain ULRs in need of rewriting.
371 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
372 * @param integer $contextid This parameter and the next two identify the file area to use.
373 * @param string $component
374 * @param string $filearea helps identify the file area.
375 * @param integer $itemid helps identify the file area.
376 * @param array $options text and file options ('forcehttps'=>false)
377 * @return string the processed text.
379 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
380 global $CFG;
382 $options = (array)$options;
383 if (!isset($options['forcehttps'])) {
384 $options['forcehttps'] = false;
387 if (!$CFG->slasharguments) {
388 $file = $file . '?file=';
391 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
393 if ($itemid !== null) {
394 $baseurl .= "$itemid/";
397 if ($options['forcehttps']) {
398 $baseurl = str_replace('http://', 'https://', $baseurl);
401 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
405 * Returns information about files in a draft area.
407 * @global object
408 * @global object
409 * @param integer $draftitemid the draft area item id.
410 * @return array with the following entries:
411 * 'filecount' => number of files in the draft area.
412 * (more information will be added as needed).
414 function file_get_draft_area_info($draftitemid) {
415 global $CFG, $USER;
417 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
418 $fs = get_file_storage();
420 $results = array();
422 // The number of files
423 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
424 $results['filecount'] = count($draftfiles);
425 $results['filesize'] = 0;
426 foreach ($draftfiles as $file) {
427 $results['filesize'] += $file->get_filesize();
430 return $results;
434 * Get used space of files
435 * @return int total bytes
437 function file_get_user_used_space() {
438 global $DB, $USER;
440 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
441 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
442 JOIN (SELECT contenthash, filename, MAX(id) AS id
443 FROM {files}
444 WHERE contextid = ? AND component = ? AND filearea != ?
445 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
446 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
447 $record = $DB->get_record_sql($sql, $params);
448 return (int)$record->totalbytes;
452 * Convert any string to a valid filepath
453 * @param string $str
454 * @return string path
456 function file_correct_filepath($str) { //TODO: what is this? (skodak)
457 if ($str == '/' or empty($str)) {
458 return '/';
459 } else {
460 return '/'.trim($str, './@#$ ').'/';
465 * Generate a folder tree of draft area of current USER recursively
466 * @param int $itemid
467 * @param string $filepath
468 * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
470 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
471 global $USER, $OUTPUT, $CFG;
472 $data->children = array();
473 $context = get_context_instance(CONTEXT_USER, $USER->id);
474 $fs = get_file_storage();
475 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
476 foreach ($files as $file) {
477 if ($file->is_directory()) {
478 $item = new stdclass;
479 $item->sortorder = $file->get_sortorder();
480 $item->filepath = $file->get_filepath();
482 $foldername = explode('/', trim($item->filepath, '/'));
483 $item->fullname = trim(array_pop($foldername), '/');
485 $item->id = uniqid();
486 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
487 $data->children[] = $item;
488 } else {
489 continue;
496 * Listing all files (including folders) in current path (draft area)
497 * used by file manager
498 * @param int $draftitemid
499 * @param string $filepath
500 * @return mixed
502 function file_get_drafarea_files($draftitemid, $filepath = '/') {
503 global $USER, $OUTPUT, $CFG;
505 $context = get_context_instance(CONTEXT_USER, $USER->id);
506 $fs = get_file_storage();
508 $data = new stdclass;
509 $data->path = array();
510 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
512 // will be used to build breadcrumb
513 $trail = '';
514 if ($filepath !== '/') {
515 $filepath = file_correct_filepath($filepath);
516 $parts = explode('/', $filepath);
517 foreach ($parts as $part) {
518 if ($part != '' && $part != null) {
519 $trail .= ('/'.$part.'/');
520 $data->path[] = array('name'=>$part, 'path'=>$trail);
525 $list = array();
526 $maxlength = 12;
527 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
528 foreach ($files as $file) {
529 $item = new stdclass;
530 $item->filename = $file->get_filename();
531 $item->filepath = $file->get_filepath();
532 $item->fullname = trim($item->filename, '/');
533 $filesize = $file->get_filesize();
534 $item->filesize = $filesize ? display_size($filesize) : '';
536 $icon = mimeinfo_from_type('icon', $file->get_mimetype());
537 $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
538 $item->sortorder = $file->get_sortorder();
540 if ($icon == 'zip') {
541 $item->type = 'zip';
542 } else {
543 $item->type = 'file';
546 if ($file->is_directory()) {
547 $item->filesize = 0;
548 $item->icon = $OUTPUT->pix_url('f/folder')->out();
549 $item->type = 'folder';
550 $foldername = explode('/', trim($item->filepath, '/'));
551 $item->fullname = trim(array_pop($foldername), '/');
552 } else {
553 // do NOT use file browser here!
554 $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
556 $list[] = $item;
559 $data->itemid = $draftitemid;
560 $data->list = $list;
561 return $data;
565 * Returns draft area itemid for a given element.
567 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
568 * @return integer the itemid, or 0 if there is not one yet.
570 function file_get_submitted_draft_itemid($elname) {
571 $param = optional_param($elname, 0, PARAM_INT);
572 if ($param) {
573 require_sesskey();
575 if (is_array($param)) {
576 if (!empty($param['itemid'])) {
577 $param = $param['itemid'];
578 } else {
579 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
580 return false;
583 return $param;
587 * Saves files from a draft file area to a real one (merging the list of files).
588 * Can rewrite URLs in some content at the same time if desired.
590 * @global object
591 * @global object
592 * @param integer $draftitemid the id of the draft area to use. Normally obtained
593 * from file_get_submitted_draft_itemid('elementname') or similar.
594 * @param integer $contextid This parameter and the next two identify the file area to save to.
595 * @param string $component
596 * @param string $filearea indentifies the file area.
597 * @param integer $itemid helps identifies the file area.
598 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
599 * @param string $text some html content that needs to have embedded links rewritten
600 * to the @@PLUGINFILE@@ form for saving in the database.
601 * @param boolean $forcehttps force https urls.
602 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
604 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
605 global $CFG, $USER;
607 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
608 $fs = get_file_storage();
610 $options = (array)$options;
611 if (!isset($options['subdirs'])) {
612 $options['subdirs'] = false;
614 if (!isset($options['maxfiles'])) {
615 $options['maxfiles'] = -1; // unlimited
617 if (!isset($options['maxbytes'])) {
618 $options['maxbytes'] = 0; // unlimited
621 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
622 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
624 if (count($draftfiles) < 2) {
625 // means there are no files - one file means root dir only ;-)
626 $fs->delete_area_files($contextid, $component, $filearea, $itemid);
628 } else if (count($oldfiles) < 2) {
629 $filecount = 0;
630 // there were no files before - one file means root dir only ;-)
631 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
632 foreach ($draftfiles as $file) {
633 if (!$options['subdirs']) {
634 if ($file->get_filepath() !== '/' or $file->is_directory()) {
635 continue;
638 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
639 // oversized file - should not get here at all
640 continue;
642 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
643 // more files - should not get here at all
644 break;
646 if (!$file->is_directory()) {
647 $filecount++;
649 $fs->create_file_from_storedfile($file_record, $file);
652 } else {
653 // we have to merge old and new files - we want to keep file ids for files that were not changed
654 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
656 $newhashes = array();
657 foreach ($draftfiles as $file) {
658 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
659 $newhashes[$newhash] = $file;
661 $filecount = 0;
662 foreach ($oldfiles as $file) {
663 $oldhash = $file->get_pathnamehash();
664 // check if sortorder, filename, filepath
665 if (isset($newhashes[$oldhash]) && $file->get_sortorder() == $newhashes[$oldhash]->get_sortorder()) {
666 if (!$file->is_directory()) {
667 $filecount++;
669 // unchanged file already there
670 unset($newhashes[$oldhash]);
671 } else {
672 // delete files not needed any more - deleted by user
673 $file->delete();
677 // now add new files
678 foreach ($newhashes as $file) {
679 if (!$options['subdirs']) {
680 if ($file->get_filepath() !== '/' or $file->is_directory()) {
681 continue;
684 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
685 // oversized file - should not get here at all
686 continue;
688 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
689 // more files - should not get here at all
690 break;
692 if (!$file->is_directory()) {
693 $filecount++;
695 $fs->create_file_from_storedfile($file_record, $file);
699 // note: do not purge the draft area - we clean up areas later in cron,
700 // the reason is that user might press submit twice and they would loose the files,
701 // also sometimes we might want to use hacks that save files into two different areas
703 if (is_null($text)) {
704 return null;
707 // relink embedded files if text submitted - no absolute links allowed in database!
708 if ($CFG->slasharguments) {
709 $draftbase = "$CFG->wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/";
710 } else {
711 $draftbase = "$CFG->wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/";
714 if ($forcehttps) {
715 $draftbase = str_replace('http://', 'https://', $draftbase);
718 $text = str_ireplace($draftbase, '@@PLUGINFILE@@/', $text);
720 return $text;
724 * Set file sort order
725 * @global object $DB
726 * @param integer $contextid the context id
727 * @param string $component
728 * @param string $filearea file area.
729 * @param integer $itemid itemid.
730 * @param string $filepath file path.
731 * @param string $filename file name.
732 * @param integer $sortorer the sort order of file.
733 * @return boolean
735 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
736 global $DB;
737 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
738 if ($file_record = $DB->get_record('files', $conditions)) {
739 $sortorder = (int)$sortorder;
740 $file_record->sortorder = $sortorder;
741 $DB->update_record('files', $file_record);
742 return true;
744 return false;
748 * reset file sort order number to 0
749 * @global object $DB
750 * @param integer $contextid the context id
751 * @param string $component
752 * @param string $filearea file area.
753 * @param integer $itemid itemid.
754 * @return boolean
756 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
757 global $DB;
759 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
760 if ($itemid !== false) {
761 $conditions['itemid'] = $itemid;
764 $file_records = $DB->get_records('files', $conditions);
765 foreach ($file_records as $file_record) {
766 $file_record->sortorder = 0;
767 $DB->update_record('files', $file_record);
769 return true;
773 * Returns description of upload error
775 * @param int $errorcode found in $_FILES['filename.ext']['error']
776 * @return string error description string, '' if ok
778 function file_get_upload_error($errorcode) {
780 switch ($errorcode) {
781 case 0: // UPLOAD_ERR_OK - no error
782 $errmessage = '';
783 break;
785 case 1: // UPLOAD_ERR_INI_SIZE
786 $errmessage = get_string('uploadserverlimit');
787 break;
789 case 2: // UPLOAD_ERR_FORM_SIZE
790 $errmessage = get_string('uploadformlimit');
791 break;
793 case 3: // UPLOAD_ERR_PARTIAL
794 $errmessage = get_string('uploadpartialfile');
795 break;
797 case 4: // UPLOAD_ERR_NO_FILE
798 $errmessage = get_string('uploadnofilefound');
799 break;
801 // Note: there is no error with a value of 5
803 case 6: // UPLOAD_ERR_NO_TMP_DIR
804 $errmessage = get_string('uploadnotempdir');
805 break;
807 case 7: // UPLOAD_ERR_CANT_WRITE
808 $errmessage = get_string('uploadcantwrite');
809 break;
811 case 8: // UPLOAD_ERR_EXTENSION
812 $errmessage = get_string('uploadextension');
813 break;
815 default:
816 $errmessage = get_string('uploadproblem');
819 return $errmessage;
823 * Recursive function formating an array in POST parameter
824 * @param array $arraydata - the array that we are going to format and add into &$data array
825 * @param string $currentdata - a row of the final postdata array at instant T
826 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
827 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
829 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
830 foreach ($arraydata as $k=>$v) {
831 $newcurrentdata = $currentdata;
832 if (is_array($v)) { //the value is an array, call the function recursively
833 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
834 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
835 } else { //add the POST parameter to the $data array
836 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
842 * Transform a PHP array into POST parameter
843 * (see the recursive function format_array_postdata_for_curlcall)
844 * @param array $postdata
845 * @return array containing all POST parameters (1 row = 1 POST parameter)
847 function format_postdata_for_curlcall($postdata) {
848 $data = array();
849 foreach ($postdata as $k=>$v) {
850 if (is_array($v)) {
851 $currentdata = urlencode($k);
852 format_array_postdata_for_curlcall($v, $currentdata, $data);
853 } else {
854 $data[] = urlencode($k).'='.urlencode($v);
857 $convertedpostdata = implode('&', $data);
858 return $convertedpostdata;
865 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
866 * Due to security concerns only downloads from http(s) sources are supported.
868 * @global object
869 * @param string $url file url starting with http(s)://
870 * @param array $headers http headers, null if none. If set, should be an
871 * associative array of header name => value pairs.
872 * @param array $postdata array means use POST request with given parameters
873 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
874 * (if false, just returns content)
875 * @param int $timeout timeout for complete download process including all file transfer
876 * (default 5 minutes)
877 * @param int $connecttimeout timeout for connection to server; this is the timeout that
878 * usually happens if the remote server is completely down (default 20 seconds);
879 * may not work when using proxy
880 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
881 * @param string $tofile store the downloaded content to file instead of returning it
882 * @return mixed false if request failed or content of the file as string if ok. true if file downloaded into $tofile successfully.
884 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL) {
885 global $CFG;
887 // some extra security
888 $newlines = array("\r", "\n");
889 if (is_array($headers) ) {
890 foreach ($headers as $key => $value) {
891 $headers[$key] = str_replace($newlines, '', $value);
894 $url = str_replace($newlines, '', $url);
895 if (!preg_match('|^https?://|i', $url)) {
896 if ($fullresponse) {
897 $response = new object();
898 $response->status = 0;
899 $response->headers = array();
900 $response->response_code = 'Invalid protocol specified in url';
901 $response->results = '';
902 $response->error = 'Invalid protocol specified in url';
903 return $response;
904 } else {
905 return false;
909 // check if proxy (if used) should be bypassed for this url
910 $proxybypass = is_proxybypass($url);
912 if (!$ch = curl_init($url)) {
913 debugging('Can not init curl.');
914 return false;
917 // set extra headers
918 if (is_array($headers) ) {
919 $headers2 = array();
920 foreach ($headers as $key => $value) {
921 $headers2[] = "$key: $value";
923 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
927 if ($skipcertverify) {
928 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
931 // use POST if requested
932 if (is_array($postdata)) {
933 $postdata = format_postdata_for_curlcall($postdata);
934 curl_setopt($ch, CURLOPT_POST, true);
935 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
938 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
939 curl_setopt($ch, CURLOPT_HEADER, false);
940 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
941 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
942 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
943 // TODO: add version test for '7.10.5'
944 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
945 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
948 if (!empty($CFG->proxyhost) and !$proxybypass) {
949 // SOCKS supported in PHP5 only
950 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
951 if (defined('CURLPROXY_SOCKS5')) {
952 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
953 } else {
954 curl_close($ch);
955 if ($fullresponse) {
956 $response = new object();
957 $response->status = '0';
958 $response->headers = array();
959 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
960 $response->results = '';
961 $response->error = 'SOCKS5 proxy is not supported in PHP4';
962 return $response;
963 } else {
964 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
965 return false;
970 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
972 if (empty($CFG->proxyport)) {
973 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
974 } else {
975 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
978 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
979 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
980 if (defined('CURLOPT_PROXYAUTH')) {
981 // any proxy authentication if PHP 5.1
982 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
987 // set up header and content handlers
988 $received = new object();
989 $received->headers = array(); // received headers array
990 $received->tofile = $tofile;
991 $received->fh = null;
992 curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
993 if ($tofile) {
994 curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
997 $result = curl_exec($ch);
999 // try to detect encoding problems
1000 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1001 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1002 $result = curl_exec($ch);
1005 if ($received->fh) {
1006 fclose($received->fh);
1009 if (curl_errno($ch)) {
1010 $error = curl_error($ch);
1011 $error_no = curl_errno($ch);
1012 curl_close($ch);
1014 if ($fullresponse) {
1015 $response = new object();
1016 if ($error_no == 28) {
1017 $response->status = '-100'; // mimic snoopy
1018 } else {
1019 $response->status = '0';
1021 $response->headers = array();
1022 $response->response_code = $error;
1023 $response->results = false;
1024 $response->error = $error;
1025 return $response;
1026 } else {
1027 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1028 return false;
1031 } else {
1032 $info = curl_getinfo($ch);
1033 curl_close($ch);
1035 if (empty($info['http_code'])) {
1036 // for security reasons we support only true http connections (Location: file:// exploit prevention)
1037 $response = new object();
1038 $response->status = '0';
1039 $response->headers = array();
1040 $response->response_code = 'Unknown cURL error';
1041 $response->results = false; // do NOT change this, we really want to ignore the result!
1042 $response->error = 'Unknown cURL error';
1044 } else {
1045 $response = new object();;
1046 $response->status = (string)$info['http_code'];
1047 $response->headers = $received->headers;
1048 $response->response_code = $received->headers[0];
1049 $response->results = $result;
1050 $response->error = '';
1053 if ($fullresponse) {
1054 return $response;
1055 } else if ($info['http_code'] != 200) {
1056 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1057 return false;
1058 } else {
1059 return $response->results;
1065 * internal implementation
1067 function download_file_content_header_handler($received, $ch, $header) {
1068 $received->headers[] = $header;
1069 return strlen($header);
1073 * internal implementation
1075 function download_file_content_write_handler($received, $ch, $data) {
1076 if (!$received->fh) {
1077 $received->fh = fopen($received->tofile, 'w');
1078 if ($received->fh === false) {
1079 // bad luck, file creation or overriding failed
1080 return 0;
1083 if (fwrite($received->fh, $data) === false) {
1084 // bad luck, write failed, let's abort completely
1085 return 0;
1087 return strlen($data);
1091 * @return array List of information about file types based on extensions.
1092 * Associative array of extension (lower-case) to associative array
1093 * from 'element name' to data. Current element names are 'type' and 'icon'.
1094 * Unknown types should use the 'xxx' entry which includes defaults.
1096 function get_mimetypes_array() {
1097 static $mimearray = array (
1098 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1099 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1100 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
1101 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1102 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1103 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
1104 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1105 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
1106 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
1107 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
1108 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
1109 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
1110 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
1111 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1112 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1113 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
1114 'css' => array ('type'=>'text/css', 'icon'=>'text'),
1115 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
1116 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1117 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
1119 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
1120 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
1121 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
1122 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
1123 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
1125 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1126 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
1127 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1128 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1129 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1130 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1131 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
1132 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
1133 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
1134 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1135 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1136 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
1137 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
1138 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
1139 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
1140 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
1141 'html' => array ('type'=>'text/html', 'icon'=>'html'),
1142 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
1143 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
1144 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
1145 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1146 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1147 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1148 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
1149 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
1150 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
1151 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
1152 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
1153 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
1154 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1155 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1156 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
1157 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
1158 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
1159 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1160 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
1161 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1162 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
1163 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
1164 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
1165 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
1166 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
1167 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
1168 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1169 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1170 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
1172 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
1173 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
1174 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
1175 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
1176 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
1177 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
1178 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
1179 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
1180 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
1181 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
1182 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
1183 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
1184 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
1185 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
1187 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
1188 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1189 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
1190 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
1191 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
1192 'png' => array ('type'=>'image/png', 'icon'=>'image'),
1194 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1195 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
1196 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
1197 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
1198 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
1199 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
1200 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
1201 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
1202 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
1204 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1205 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
1206 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
1207 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1208 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
1209 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
1210 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
1211 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1212 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
1213 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
1214 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1215 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1216 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
1217 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1218 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
1219 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1220 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1221 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
1223 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
1224 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
1225 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
1226 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
1227 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
1228 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
1229 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
1230 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
1231 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
1232 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
1234 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
1235 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
1236 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
1237 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1238 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1239 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1240 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1241 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
1242 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
1243 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
1244 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
1245 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1246 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1247 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1249 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
1250 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
1251 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
1252 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
1253 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
1254 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
1255 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
1257 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
1258 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
1259 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
1261 return $mimearray;
1265 * Obtains information about a filetype based on its extension. Will
1266 * use a default if no information is present about that particular
1267 * extension.
1269 * @param string $element Desired information (usually 'icon'
1270 * for icon filename or 'type' for MIME type)
1271 * @param string $filename Filename we're looking up
1272 * @return string Requested piece of information from array
1274 function mimeinfo($element, $filename) {
1275 global $CFG;
1276 $mimeinfo = get_mimetypes_array();
1278 if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
1279 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1280 return $mimeinfo[strtolower($match[1])][$element];
1281 } else {
1282 if ($element == 'icon32') {
1283 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1284 $filename = $mimeinfo[strtolower($match[1])]['icon'];
1285 } else {
1286 $filename = 'unknown';
1288 $filename .= '-32';
1289 if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
1290 return $filename;
1291 } else {
1292 return 'unknown-32';
1294 } else {
1295 return $mimeinfo['xxx'][$element]; // By default
1298 } else {
1299 if ($element == 'icon32') {
1300 return 'unknown-32';
1302 return $mimeinfo['xxx'][$element]; // By default
1307 * Obtains information about a filetype based on the MIME type rather than
1308 * the other way around.
1310 * @param string $element Desired information (usually 'icon')
1311 * @param string $mimetype MIME type we're looking up
1312 * @return string Requested piece of information from array
1314 function mimeinfo_from_type($element, $mimetype) {
1315 $mimeinfo = get_mimetypes_array();
1317 foreach($mimeinfo as $values) {
1318 if ($values['type']==$mimetype) {
1319 if (isset($values[$element])) {
1320 return $values[$element];
1322 break;
1325 return $mimeinfo['xxx'][$element]; // Default
1329 * Get information about a filetype based on the icon file.
1331 * @param string $element Desired information (usually 'icon')
1332 * @param string $icon Icon file name without extension
1333 * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
1334 * @return string Requested piece of information from array
1336 function mimeinfo_from_icon($element, $icon, $all=false) {
1337 $mimeinfo = get_mimetypes_array();
1339 if (preg_match("/\/(.*)/", $icon, $matches)) {
1340 $icon = $matches[1];
1342 // Try to get the extension
1343 $extension = '';
1344 if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
1345 $extension = substr($icon, $cutat + 1);
1347 $info = array($mimeinfo['xxx'][$element]); // Default
1348 foreach($mimeinfo as $key => $values) {
1349 if ($values['icon']==$icon) {
1350 if (isset($values[$element])) {
1351 $info[$key] = $values[$element];
1353 //No break, for example for 'excel' we don't want 'csv'!
1356 if ($all) {
1357 if (count($info) > 1) {
1358 array_shift($info); // take off document/unknown if we have better options
1360 return array_values($info); // Keep keys out when requesting all
1363 // Requested only one, try to get the best by extension coincidence, else return the last
1364 if ($extension && isset($info[$extension])) {
1365 return $info[$extension];
1368 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
1372 * Returns the relative icon path for a given mime type
1374 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1375 * a return the full path to an icon.
1377 * <code>
1378 * $mimetype = 'image/jpg';
1379 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
1380 * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
1381 * </code>
1383 * @todo When an $OUTPUT->icon method is available this function should be altered
1384 * to conform with that.
1386 * @param string $mimetype The mimetype to fetch an icon for
1387 * @param int $size The size of the icon. Not yet implemented
1388 * @return string The relative path to the icon
1390 function file_mimetype_icon($mimetype, $size = NULL) {
1391 global $CFG;
1393 $icon = mimeinfo_from_type('icon', $mimetype);
1394 if ($size) {
1395 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1396 $icon = "$icon-$size";
1399 return 'f/'.$icon;
1403 * Returns the relative icon path for a given file name
1405 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1406 * a return the full path to an icon.
1408 * <code>
1409 * $filename = 'jpg';
1410 * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
1411 * echo '<img src="'.$icon.'" alt="blah" />';
1412 * </code>
1414 * @todo When an $OUTPUT->icon method is available this function should be altered
1415 * to conform with that.
1416 * @todo Implement $size
1418 * @param string filename The filename to get the icon for
1419 * @param int $size The size of the icon. Defaults to null can also be 32
1420 * @return string
1422 function file_extension_icon($filename, $size = NULL) {
1423 global $CFG;
1425 $icon = mimeinfo('icon', $filename);
1426 if ($size) {
1427 if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
1428 $icon = "$icon-$size";
1431 return 'f/'.$icon;
1435 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1436 * mimetypes.php language file.
1438 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1439 * @param bool $capitalise If true, capitalises first character of result
1440 * @return string Text description
1442 function get_mimetype_description($mimetype, $capitalise=false) {
1443 if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
1444 $result = get_string($mimetype, 'mimetypes');
1445 } else {
1446 $result = get_string('document/unknown','mimetypes');
1448 if ($capitalise) {
1449 $result=ucfirst($result);
1451 return $result;
1455 * Requested file is not found or not accessible
1457 * @return does not return, terminates script
1459 function send_file_not_found() {
1460 global $CFG, $COURSE;
1461 header('HTTP/1.0 404 not found');
1462 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1466 * Handles the sending of temporary file to user, download is forced.
1467 * File is deleted after abort or successful sending.
1469 * @global object
1470 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1471 * @param string $filename proposed file name when saving file
1472 * @param bool $path is content of file
1473 * @return does not return, script terminated
1475 function send_temp_file($path, $filename, $pathisstring=false) {
1476 global $CFG;
1478 // close session - not needed anymore
1479 @session_get_instance()->write_close();
1481 if (!$pathisstring) {
1482 if (!file_exists($path)) {
1483 header('HTTP/1.0 404 not found');
1484 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
1486 // executed after normal finish or abort
1487 @register_shutdown_function('send_temp_file_finished', $path);
1490 //IE compatibility HACK!
1491 if (ini_get('zlib.output_compression')) {
1492 ini_set('zlib.output_compression', 'Off');
1495 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1496 if (check_browser_version('MSIE')) {
1497 $filename = urlencode($filename);
1500 $filesize = $pathisstring ? strlen($path) : filesize($path);
1502 @header('Content-Disposition: attachment; filename='.$filename);
1503 @header('Content-Length: '.$filesize);
1504 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1505 @header('Cache-Control: max-age=10');
1506 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1507 @header('Pragma: ');
1508 } else { //normal http - prevent caching at all cost
1509 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1510 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1511 @header('Pragma: no-cache');
1513 @header('Accept-Ranges: none'); // Do not allow byteserving
1515 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1516 if ($pathisstring) {
1517 echo $path;
1518 } else {
1519 @readfile($path);
1522 die; //no more chars to output
1526 * Internal callback function used by send_temp_file()
1528 function send_temp_file_finished($path) {
1529 if (file_exists($path)) {
1530 @unlink($path);
1535 * Handles the sending of file data to the user's browser, including support for
1536 * byteranges etc.
1538 * @global object
1539 * @global object
1540 * @global object
1541 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1542 * @param string $filename Filename to send
1543 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1544 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1545 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1546 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1547 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
1548 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1549 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1550 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1551 * and should not be reopened.
1552 * @return no return or void, script execution stopped unless $dontdie is true
1554 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
1555 global $CFG, $COURSE, $SESSION;
1557 if ($dontdie) {
1558 ignore_user_abort(true);
1561 // MDL-11789, apply $CFG->filelifetime here
1562 if ($lifetime === 'default') {
1563 if (!empty($CFG->filelifetime)) {
1564 $lifetime = $CFG->filelifetime;
1565 } else {
1566 $lifetime = 86400;
1570 session_get_instance()->write_close(); // unlock session during fileserving
1572 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1573 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1574 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1575 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1576 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1577 ($mimetype ? $mimetype : mimeinfo('type', $filename));
1579 $lastmodified = $pathisstring ? time() : filemtime($path);
1580 $filesize = $pathisstring ? strlen($path) : filesize($path);
1582 /* - MDL-13949
1583 //Adobe Acrobat Reader XSS prevention
1584 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1585 //please note that it prevents opening of pdfs in browser when http referer disabled
1586 //or file linked from another site; browser caching of pdfs is now disabled too
1587 if (!empty($_SERVER['HTTP_RANGE'])) {
1588 //already byteserving
1589 $lifetime = 1; // >0 needed for byteserving
1590 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
1591 $mimetype = 'application/x-forcedownload';
1592 $forcedownload = true;
1593 $lifetime = 0;
1594 } else {
1595 $lifetime = 1; // >0 needed for byteserving
1600 //IE compatibiltiy HACK!
1601 if (ini_get('zlib.output_compression')) {
1602 ini_set('zlib.output_compression', 'Off');
1605 //try to disable automatic sid rewrite in cookieless mode
1606 @ini_set("session.use_trans_sid", "false");
1608 //do not put '@' before the next header to detect incorrect moodle configurations,
1609 //error should be better than "weird" empty lines for admins/users
1610 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1611 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1613 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1614 if (check_browser_version('MSIE')) {
1615 $filename = rawurlencode($filename);
1618 if ($forcedownload) {
1619 @header('Content-Disposition: attachment; filename="'.$filename.'"');
1620 } else {
1621 @header('Content-Disposition: inline; filename="'.$filename.'"');
1624 if ($lifetime > 0) {
1625 @header('Cache-Control: max-age='.$lifetime);
1626 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1627 @header('Pragma: ');
1629 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1631 @header('Accept-Ranges: bytes');
1633 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1634 // byteserving stuff - for acrobat reader and download accelerators
1635 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1636 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1637 $ranges = false;
1638 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1639 foreach ($ranges as $key=>$value) {
1640 if ($ranges[$key][1] == '') {
1641 //suffix case
1642 $ranges[$key][1] = $filesize - $ranges[$key][2];
1643 $ranges[$key][2] = $filesize - 1;
1644 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1645 //fix range length
1646 $ranges[$key][2] = $filesize - 1;
1648 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1649 //invalid byte-range ==> ignore header
1650 $ranges = false;
1651 break;
1653 //prepare multipart header
1654 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1655 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1657 } else {
1658 $ranges = false;
1660 if ($ranges) {
1661 $handle = fopen($filename, 'rb');
1662 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1665 } else {
1666 /// Do not byteserve (disabled, strings, text and html files).
1667 @header('Accept-Ranges: none');
1669 } else { // Do not cache files in proxies and browsers
1670 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1671 @header('Cache-Control: max-age=10');
1672 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1673 @header('Pragma: ');
1674 } else { //normal http - prevent caching at all cost
1675 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1676 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1677 @header('Pragma: no-cache');
1679 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1682 if (empty($filter)) {
1683 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
1684 //cookieless mode - rewrite links
1685 @header('Content-Type: text/html');
1686 $path = $pathisstring ? $path : implode('', file($path));
1687 $path = sid_ob_rewrite($path);
1688 $filesize = strlen($path);
1689 $pathisstring = true;
1690 } else if ($mimetype == 'text/plain') {
1691 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1692 } else {
1693 @header('Content-Type: '.$mimetype);
1695 @header('Content-Length: '.$filesize);
1696 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1697 if ($pathisstring) {
1698 echo $path;
1699 } else {
1700 @readfile($path);
1702 } else { // Try to put the file through filters
1703 if ($mimetype == 'text/html') {
1704 $options = new object();
1705 $options->noclean = true;
1706 $options->nocache = true; // temporary workaround for MDL-5136
1707 $text = $pathisstring ? $path : implode('', file($path));
1709 $text = file_modify_html_header($text);
1710 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1711 if (!empty($CFG->usesid)) {
1712 //cookieless mode - rewrite links
1713 $output = sid_ob_rewrite($output);
1716 @header('Content-Length: '.strlen($output));
1717 @header('Content-Type: text/html');
1718 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1719 echo $output;
1720 // only filter text if filter all files is selected
1721 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1722 $options = new object();
1723 $options->newlines = false;
1724 $options->noclean = true;
1725 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
1726 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1727 if (!empty($CFG->usesid)) {
1728 //cookieless mode - rewrite links
1729 $output = sid_ob_rewrite($output);
1732 @header('Content-Length: '.strlen($output));
1733 @header('Content-Type: text/html; charset=utf-8'); //add encoding
1734 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1735 echo $output;
1736 } else { // Just send it out raw
1737 @header('Content-Length: '.$filesize);
1738 @header('Content-Type: '.$mimetype);
1739 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1740 if ($pathisstring) {
1741 echo $path;
1742 }else {
1743 @readfile($path);
1747 if ($dontdie) {
1748 return;
1750 die; //no more chars to output!!!
1754 * Handles the sending of file data to the user's browser, including support for
1755 * byteranges etc.
1757 * @global object
1758 * @global object
1759 * @global object
1760 * @param object $stored_file local file object
1761 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1762 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1763 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1764 * @param string $filename Override filename
1765 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1766 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
1767 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1768 * and should not be reopened.
1769 * @return void no return or void, script execution stopped unless $dontdie is true
1771 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
1772 global $CFG, $COURSE, $SESSION;
1774 if ($dontdie) {
1775 ignore_user_abort(true);
1778 session_get_instance()->write_close(); // unlock session during fileserving
1780 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1781 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1782 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1783 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1784 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1785 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1786 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1788 $lastmodified = $stored_file->get_timemodified();
1789 $filesize = $stored_file->get_filesize();
1791 //IE compatibiltiy HACK!
1792 if (ini_get('zlib.output_compression')) {
1793 ini_set('zlib.output_compression', 'Off');
1796 //try to disable automatic sid rewrite in cookieless mode
1797 @ini_set("session.use_trans_sid", "false");
1799 //do not put '@' before the next header to detect incorrect moodle configurations,
1800 //error should be better than "weird" empty lines for admins/users
1801 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1802 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1804 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1805 if (check_browser_version('MSIE')) {
1806 $filename = rawurlencode($filename);
1809 if ($forcedownload) {
1810 @header('Content-Disposition: attachment; filename="'.$filename.'"');
1811 } else {
1812 @header('Content-Disposition: inline; filename="'.$filename.'"');
1815 if ($lifetime > 0) {
1816 @header('Cache-Control: max-age='.$lifetime);
1817 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1818 @header('Pragma: ');
1820 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1822 @header('Accept-Ranges: bytes');
1824 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1825 // byteserving stuff - for acrobat reader and download accelerators
1826 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1827 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1828 $ranges = false;
1829 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1830 foreach ($ranges as $key=>$value) {
1831 if ($ranges[$key][1] == '') {
1832 //suffix case
1833 $ranges[$key][1] = $filesize - $ranges[$key][2];
1834 $ranges[$key][2] = $filesize - 1;
1835 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1836 //fix range length
1837 $ranges[$key][2] = $filesize - 1;
1839 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1840 //invalid byte-range ==> ignore header
1841 $ranges = false;
1842 break;
1844 //prepare multipart header
1845 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1846 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1848 } else {
1849 $ranges = false;
1851 if ($ranges) {
1852 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1855 } else {
1856 /// Do not byteserve (disabled, strings, text and html files).
1857 @header('Accept-Ranges: none');
1859 } else { // Do not cache files in proxies and browsers
1860 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1861 @header('Cache-Control: max-age=10');
1862 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1863 @header('Pragma: ');
1864 } else { //normal http - prevent caching at all cost
1865 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1866 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1867 @header('Pragma: no-cache');
1869 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1872 if (empty($filter)) {
1873 $filtered = false;
1874 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
1875 //cookieless mode - rewrite links
1876 @header('Content-Type: text/html');
1877 $text = $stored_file->get_content();
1878 $text = sid_ob_rewrite($text);
1879 $filesize = strlen($text);
1880 $filtered = true;
1881 } else if ($mimetype == 'text/plain') {
1882 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1883 } else {
1884 @header('Content-Type: '.$mimetype);
1886 @header('Content-Length: '.$filesize);
1887 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1888 if ($filtered) {
1889 echo $text;
1890 } else {
1891 $stored_file->readfile();
1894 } else { // Try to put the file through filters
1895 if ($mimetype == 'text/html') {
1896 $options = new object();
1897 $options->noclean = true;
1898 $options->nocache = true; // temporary workaround for MDL-5136
1899 $text = $stored_file->get_content();
1900 $text = file_modify_html_header($text);
1901 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1902 if (!empty($CFG->usesid)) {
1903 //cookieless mode - rewrite links
1904 $output = sid_ob_rewrite($output);
1907 @header('Content-Length: '.strlen($output));
1908 @header('Content-Type: text/html');
1909 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1910 echo $output;
1911 // only filter text if filter all files is selected
1912 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1913 $options = new object();
1914 $options->newlines = false;
1915 $options->noclean = true;
1916 $text = $stored_file->get_content();
1917 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1918 if (!empty($CFG->usesid)) {
1919 //cookieless mode - rewrite links
1920 $output = sid_ob_rewrite($output);
1923 @header('Content-Length: '.strlen($output));
1924 @header('Content-Type: text/html; charset=utf-8'); //add encoding
1925 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1926 echo $output;
1927 } else { // Just send it out raw
1928 @header('Content-Length: '.$filesize);
1929 @header('Content-Type: '.$mimetype);
1930 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1931 $stored_file->readfile();
1934 if ($dontdie) {
1935 return;
1937 die; //no more chars to output!!!
1941 * Retrieves an array of records from a CSV file and places
1942 * them into a given table structure
1944 * @global object
1945 * @global object
1946 * @param string $file The path to a CSV file
1947 * @param string $table The table to retrieve columns from
1948 * @return bool|array Returns an array of CSV records or false
1950 function get_records_csv($file, $table) {
1951 global $CFG, $DB;
1953 if (!$metacolumns = $DB->get_columns($table)) {
1954 return false;
1957 if(!($handle = @fopen($file, 'r'))) {
1958 print_error('get_records_csv failed to open '.$file);
1961 $fieldnames = fgetcsv($handle, 4096);
1962 if(empty($fieldnames)) {
1963 fclose($handle);
1964 return false;
1967 $columns = array();
1969 foreach($metacolumns as $metacolumn) {
1970 $ord = array_search($metacolumn->name, $fieldnames);
1971 if(is_int($ord)) {
1972 $columns[$metacolumn->name] = $ord;
1976 $rows = array();
1978 while (($data = fgetcsv($handle, 4096)) !== false) {
1979 $item = new stdClass;
1980 foreach($columns as $name => $ord) {
1981 $item->$name = $data[$ord];
1983 $rows[] = $item;
1986 fclose($handle);
1987 return $rows;
1992 * @global object
1993 * @global object
1994 * @param string $file The file to put the CSV content into
1995 * @param array $records An array of records to write to a CSV file
1996 * @param string $table The table to get columns from
1997 * @return bool success
1999 function put_records_csv($file, $records, $table = NULL) {
2000 global $CFG, $DB;
2002 if (empty($records)) {
2003 return true;
2006 $metacolumns = NULL;
2007 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2008 return false;
2011 echo "x";
2013 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
2014 print_error('put_records_csv failed to open '.$file);
2017 $proto = reset($records);
2018 if(is_object($proto)) {
2019 $fields_records = array_keys(get_object_vars($proto));
2021 else if(is_array($proto)) {
2022 $fields_records = array_keys($proto);
2024 else {
2025 return false;
2027 echo "x";
2029 if(!empty($metacolumns)) {
2030 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2031 $fields = array_intersect($fields_records, $fields_table);
2033 else {
2034 $fields = $fields_records;
2037 fwrite($fp, implode(',', $fields));
2038 fwrite($fp, "\r\n");
2040 foreach($records as $record) {
2041 $array = (array)$record;
2042 $values = array();
2043 foreach($fields as $field) {
2044 if(strpos($array[$field], ',')) {
2045 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2047 else {
2048 $values[] = $array[$field];
2051 fwrite($fp, implode(',', $values)."\r\n");
2054 fclose($fp);
2055 return true;
2060 * Recursively delete the file or folder with path $location. That is,
2061 * if it is a file delete it. If it is a folder, delete all its content
2062 * then delete it. If $location does not exist to start, that is not
2063 * considered an error.
2065 * @param $location the path to remove.
2066 * @return bool
2068 function fulldelete($location) {
2069 if (empty($location)) {
2070 // extra safety against wrong param
2071 return false;
2073 if (is_dir($location)) {
2074 $currdir = opendir($location);
2075 while (false !== ($file = readdir($currdir))) {
2076 if ($file <> ".." && $file <> ".") {
2077 $fullfile = $location."/".$file;
2078 if (is_dir($fullfile)) {
2079 if (!fulldelete($fullfile)) {
2080 return false;
2082 } else {
2083 if (!unlink($fullfile)) {
2084 return false;
2089 closedir($currdir);
2090 if (! rmdir($location)) {
2091 return false;
2094 } else if (file_exists($location)) {
2095 if (!unlink($location)) {
2096 return false;
2099 return true;
2103 * Send requested byterange of file.
2105 * @param object $handle A file handle
2106 * @param string $mimetype The mimetype for the output
2107 * @param array $ranges An array of ranges to send
2108 * @param string $filesize The size of the content if only one range is used
2110 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2111 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2112 if ($handle === false) {
2113 die;
2115 if (count($ranges) == 1) { //only one range requested
2116 $length = $ranges[0][2] - $ranges[0][1] + 1;
2117 @header('HTTP/1.1 206 Partial content');
2118 @header('Content-Length: '.$length);
2119 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2120 @header('Content-Type: '.$mimetype);
2121 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
2122 $buffer = '';
2123 fseek($handle, $ranges[0][1]);
2124 while (!feof($handle) && $length > 0) {
2125 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2126 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2127 echo $buffer;
2128 flush();
2129 $length -= strlen($buffer);
2131 fclose($handle);
2132 die;
2133 } else { // multiple ranges requested - not tested much
2134 $totallength = 0;
2135 foreach($ranges as $range) {
2136 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2138 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2139 @header('HTTP/1.1 206 Partial content');
2140 @header('Content-Length: '.$totallength);
2141 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2142 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2143 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
2144 foreach($ranges as $range) {
2145 $length = $range[2] - $range[1] + 1;
2146 echo $range[0];
2147 $buffer = '';
2148 fseek($handle, $range[1]);
2149 while (!feof($handle) && $length > 0) {
2150 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2151 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2152 echo $buffer;
2153 flush();
2154 $length -= strlen($buffer);
2157 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2158 fclose($handle);
2159 die;
2164 * add includes (js and css) into uploaded files
2165 * before returning them, useful for themes and utf.js includes
2167 * @global object
2168 * @param string $text text to search and replace
2169 * @return string text with added head includes
2171 function file_modify_html_header($text) {
2172 // first look for <head> tag
2173 global $CFG;
2175 $stylesheetshtml = '';
2176 /* foreach ($CFG->stylesheets as $stylesheet) {
2177 //TODO: MDL-21120
2178 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2181 $ufo = '';
2182 if (filter_is_enabled('filter/mediaplugin')) {
2183 // this script is needed by most media filter plugins.
2184 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2185 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2188 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2189 if ($matches) {
2190 $replacement = '<head>'.$ufo.$stylesheetshtml;
2191 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2192 return $text;
2195 // if not, look for <html> tag, and stick <head> right after
2196 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2197 if ($matches) {
2198 // replace <html> tag with <html><head>includes</head>
2199 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2200 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2201 return $text;
2204 // if not, look for <body> tag, and stick <head> before body
2205 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2206 if ($matches) {
2207 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2208 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2209 return $text;
2212 // if not, just stick a <head> tag at the beginning
2213 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2214 return $text;
2218 * RESTful cURL class
2220 * This is a wrapper class for curl, it is quite easy to use:
2221 * <code>
2222 * $c = new curl;
2223 * // enable cache
2224 * $c = new curl(array('cache'=>true));
2225 * // enable cookie
2226 * $c = new curl(array('cookie'=>true));
2227 * // enable proxy
2228 * $c = new curl(array('proxy'=>true));
2230 * // HTTP GET Method
2231 * $html = $c->get('http://example.com');
2232 * // HTTP POST Method
2233 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2234 * // HTTP PUT Method
2235 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2236 * </code>
2238 * @package moodlecore
2239 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2240 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2243 class curl {
2244 /** @var bool */
2245 public $cache = false;
2246 public $proxy = false;
2247 /** @var string */
2248 public $version = '0.4 dev';
2249 /** @var array */
2250 public $response = array();
2251 public $header = array();
2252 /** @var string */
2253 public $info;
2254 public $error;
2256 /** @var array */
2257 private $options;
2258 /** @var string */
2259 private $proxy_host = '';
2260 private $proxy_auth = '';
2261 private $proxy_type = '';
2262 /** @var bool */
2263 private $debug = false;
2264 private $cookie = false;
2267 * @global object
2268 * @param array $options
2270 public function __construct($options = array()){
2271 global $CFG;
2272 if (!function_exists('curl_init')) {
2273 $this->error = 'cURL module must be enabled!';
2274 trigger_error($this->error, E_USER_ERROR);
2275 return false;
2277 // the options of curl should be init here.
2278 $this->resetopt();
2279 if (!empty($options['debug'])) {
2280 $this->debug = true;
2282 if(!empty($options['cookie'])) {
2283 if($options['cookie'] === true) {
2284 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2285 } else {
2286 $this->cookie = $options['cookie'];
2289 if (!empty($options['cache'])) {
2290 if (class_exists('curl_cache')) {
2291 if (!empty($options['module_cache'])) {
2292 $this->cache = new curl_cache($options['module_cache']);
2293 } else {
2294 $this->cache = new curl_cache('misc');
2298 if (!empty($CFG->proxyhost)) {
2299 if (empty($CFG->proxyport)) {
2300 $this->proxy_host = $CFG->proxyhost;
2301 } else {
2302 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2304 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2305 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2306 $this->setopt(array(
2307 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2308 'proxyuserpwd'=>$this->proxy_auth));
2310 if (!empty($CFG->proxytype)) {
2311 if ($CFG->proxytype == 'SOCKS5') {
2312 $this->proxy_type = CURLPROXY_SOCKS5;
2313 } else {
2314 $this->proxy_type = CURLPROXY_HTTP;
2315 $this->setopt(array('httpproxytunnel'=>false));
2317 $this->setopt(array('proxytype'=>$this->proxy_type));
2320 if (!empty($this->proxy_host)) {
2321 $this->proxy = array('proxy'=>$this->proxy_host);
2325 * Resets the CURL options that have already been set
2327 public function resetopt(){
2328 $this->options = array();
2329 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2330 // True to include the header in the output
2331 $this->options['CURLOPT_HEADER'] = 0;
2332 // True to Exclude the body from the output
2333 $this->options['CURLOPT_NOBODY'] = 0;
2334 // TRUE to follow any "Location: " header that the server
2335 // sends as part of the HTTP header (note this is recursive,
2336 // PHP will follow as many "Location: " headers that it is sent,
2337 // unless CURLOPT_MAXREDIRS is set).
2338 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2339 $this->options['CURLOPT_MAXREDIRS'] = 10;
2340 $this->options['CURLOPT_ENCODING'] = '';
2341 // TRUE to return the transfer as a string of the return
2342 // value of curl_exec() instead of outputting it out directly.
2343 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2344 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2345 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2346 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2347 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2351 * Reset Cookie
2353 public function resetcookie() {
2354 if (!empty($this->cookie)) {
2355 if (is_file($this->cookie)) {
2356 $fp = fopen($this->cookie, 'w');
2357 if (!empty($fp)) {
2358 fwrite($fp, '');
2359 fclose($fp);
2366 * Set curl options
2368 * @param array $options If array is null, this function will
2369 * reset the options to default value.
2372 public function setopt($options = array()) {
2373 if (is_array($options)) {
2374 foreach($options as $name => $val){
2375 if (stripos($name, 'CURLOPT_') === false) {
2376 $name = strtoupper('CURLOPT_'.$name);
2378 $this->options[$name] = $val;
2383 * Reset http method
2386 public function cleanopt(){
2387 unset($this->options['CURLOPT_HTTPGET']);
2388 unset($this->options['CURLOPT_POST']);
2389 unset($this->options['CURLOPT_POSTFIELDS']);
2390 unset($this->options['CURLOPT_PUT']);
2391 unset($this->options['CURLOPT_INFILE']);
2392 unset($this->options['CURLOPT_INFILESIZE']);
2393 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2397 * Set HTTP Request Header
2399 * @param array $headers
2402 public function setHeader($header) {
2403 if (is_array($header)){
2404 foreach ($header as $v) {
2405 $this->setHeader($v);
2407 } else {
2408 $this->header[] = $header;
2412 * Set HTTP Response Header
2415 public function getResponse(){
2416 return $this->response;
2419 * private callback function
2420 * Formatting HTTP Response Header
2422 * @param mixed $ch Apparently not used
2423 * @param string $header
2424 * @return int The strlen of the header
2426 private function formatHeader($ch, $header)
2428 $this->count++;
2429 if (strlen($header) > 2) {
2430 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2431 $key = rtrim($key, ':');
2432 if (!empty($this->response[$key])) {
2433 if (is_array($this->response[$key])){
2434 $this->response[$key][] = $value;
2435 } else {
2436 $tmp = $this->response[$key];
2437 $this->response[$key] = array();
2438 $this->response[$key][] = $tmp;
2439 $this->response[$key][] = $value;
2442 } else {
2443 $this->response[$key] = $value;
2446 return strlen($header);
2450 * Set options for individual curl instance
2452 * @param object $curl A curl handle
2453 * @param array $options
2454 * @return object The curl handle
2456 private function apply_opt($curl, $options) {
2457 // Clean up
2458 $this->cleanopt();
2459 // set cookie
2460 if (!empty($this->cookie) || !empty($options['cookie'])) {
2461 $this->setopt(array('cookiejar'=>$this->cookie,
2462 'cookiefile'=>$this->cookie
2466 // set proxy
2467 if (!empty($this->proxy) || !empty($options['proxy'])) {
2468 $this->setopt($this->proxy);
2470 $this->setopt($options);
2471 // reset before set options
2472 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2473 // set headers
2474 if (empty($this->header)){
2475 $this->setHeader(array(
2476 'User-Agent: MoodleBot/1.0',
2477 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2478 'Connection: keep-alive'
2481 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2483 if ($this->debug){
2484 echo '<h1>Options</h1>';
2485 var_dump($this->options);
2486 echo '<h1>Header</h1>';
2487 var_dump($this->header);
2490 // set options
2491 foreach($this->options as $name => $val) {
2492 if (is_string($name)) {
2493 $name = constant(strtoupper($name));
2495 curl_setopt($curl, $name, $val);
2497 return $curl;
2500 * Download multiple files in parallel
2502 * Calls {@link multi()} with specific download headers
2504 * <code>
2505 * $c = new curl;
2506 * $c->download(array(
2507 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
2508 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2509 * ));
2510 * </code>
2512 * @param array $requests An array of files to request
2513 * @param array $options An array of options to set
2514 * @return array An array of results
2516 public function download($requests, $options = array()) {
2517 $options['CURLOPT_BINARYTRANSFER'] = 1;
2518 $options['RETURNTRANSFER'] = false;
2519 return $this->multi($requests, $options);
2522 * Mulit HTTP Requests
2523 * This function could run multi-requests in parallel.
2525 * @param array $requests An array of files to request
2526 * @param array $options An array of options to set
2527 * @return array An array of results
2529 protected function multi($requests, $options = array()) {
2530 $count = count($requests);
2531 $handles = array();
2532 $results = array();
2533 $main = curl_multi_init();
2534 for ($i = 0; $i < $count; $i++) {
2535 $url = $requests[$i];
2536 foreach($url as $n=>$v){
2537 $options[$n] = $url[$n];
2539 $handles[$i] = curl_init($url['url']);
2540 $this->apply_opt($handles[$i], $options);
2541 curl_multi_add_handle($main, $handles[$i]);
2543 $running = 0;
2544 do {
2545 curl_multi_exec($main, $running);
2546 } while($running > 0);
2547 for ($i = 0; $i < $count; $i++) {
2548 if (!empty($optins['CURLOPT_RETURNTRANSFER'])) {
2549 $results[] = true;
2550 } else {
2551 $results[] = curl_multi_getcontent($handles[$i]);
2553 curl_multi_remove_handle($main, $handles[$i]);
2555 curl_multi_close($main);
2556 return $results;
2559 * Single HTTP Request
2561 * @param string $url The URL to request
2562 * @param array $options
2563 * @return bool
2565 protected function request($url, $options = array()){
2566 // create curl instance
2567 $curl = curl_init($url);
2568 $options['url'] = $url;
2569 $this->apply_opt($curl, $options);
2570 if ($this->cache && $ret = $this->cache->get($this->options)) {
2571 return $ret;
2572 } else {
2573 $ret = curl_exec($curl);
2574 if ($this->cache) {
2575 $this->cache->set($this->options, $ret);
2579 $this->info = curl_getinfo($curl);
2580 $this->error = curl_error($curl);
2582 if ($this->debug){
2583 echo '<h1>Return Data</h1>';
2584 var_dump($ret);
2585 echo '<h1>Info</h1>';
2586 var_dump($this->info);
2587 echo '<h1>Error</h1>';
2588 var_dump($this->error);
2591 curl_close($curl);
2593 if (empty($this->error)){
2594 return $ret;
2595 } else {
2596 return $this->error;
2597 // exception is not ajax friendly
2598 //throw new moodle_exception($this->error, 'curl');
2603 * HTTP HEAD method
2605 * @see request()
2607 * @param string $url
2608 * @param array $options
2609 * @return bool
2611 public function head($url, $options = array()){
2612 $options['CURLOPT_HTTPGET'] = 0;
2613 $options['CURLOPT_HEADER'] = 1;
2614 $options['CURLOPT_NOBODY'] = 1;
2615 return $this->request($url, $options);
2619 * HTTP POST method
2621 * @param string $url
2622 * @param array|string $params
2623 * @param array $options
2624 * @return bool
2626 public function post($url, $params = '', $options = array()){
2627 $options['CURLOPT_POST'] = 1;
2628 if (is_array($params)) {
2629 $this->_tmp_file_post_params = array();
2630 foreach ($params as $key => $value) {
2631 if ($value instanceof stored_file) {
2632 $value->add_to_curl_request($this, $key);
2633 } else {
2634 $this->_tmp_file_post_params[$key] = $value;
2637 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2638 unset($this->_tmp_file_post_params);
2639 } else {
2640 // $params is the raw post data
2641 $options['CURLOPT_POSTFIELDS'] = $params;
2643 return $this->request($url, $options);
2647 * HTTP GET method
2649 * @param string $url
2650 * @param array $params
2651 * @param array $options
2652 * @return bool
2654 public function get($url, $params = array(), $options = array()){
2655 $options['CURLOPT_HTTPGET'] = 1;
2657 if (!empty($params)){
2658 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2659 $url .= http_build_query($params, '', '&');
2661 return $this->request($url, $options);
2665 * HTTP PUT method
2667 * @param string $url
2668 * @param array $params
2669 * @param array $options
2670 * @return bool
2672 public function put($url, $params = array(), $options = array()){
2673 $file = $params['file'];
2674 if (!is_file($file)){
2675 return null;
2677 $fp = fopen($file, 'r');
2678 $size = filesize($file);
2679 $options['CURLOPT_PUT'] = 1;
2680 $options['CURLOPT_INFILESIZE'] = $size;
2681 $options['CURLOPT_INFILE'] = $fp;
2682 if (!isset($this->options['CURLOPT_USERPWD'])){
2683 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2685 $ret = $this->request($url, $options);
2686 fclose($fp);
2687 return $ret;
2691 * HTTP DELETE method
2693 * @param string $url
2694 * @param array $params
2695 * @param array $options
2696 * @return bool
2698 public function delete($url, $param = array(), $options = array()){
2699 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2700 if (!isset($options['CURLOPT_USERPWD'])) {
2701 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2703 $ret = $this->request($url, $options);
2704 return $ret;
2707 * HTTP TRACE method
2709 * @param string $url
2710 * @param array $options
2711 * @return bool
2713 public function trace($url, $options = array()){
2714 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2715 $ret = $this->request($url, $options);
2716 return $ret;
2719 * HTTP OPTIONS method
2721 * @param string $url
2722 * @param array $options
2723 * @return bool
2725 public function options($url, $options = array()){
2726 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2727 $ret = $this->request($url, $options);
2728 return $ret;
2730 public function get_info() {
2731 return $this->info;
2736 * This class is used by cURL class, use case:
2738 * <code>
2739 * $CFG->repositorycacheexpire = 120;
2740 * $CFG->curlcache = 120;
2742 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
2743 * $ret = $c->get('http://www.google.com');
2744 * </code>
2746 * @package moodlecore
2747 * @subpackage file
2748 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2751 class curl_cache {
2752 /** @var string */
2753 public $dir = '';
2756 * @global object
2757 * @param string @module which module is using curl_cache
2760 function __construct($module = 'repository'){
2761 global $CFG;
2762 if (!empty($module)) {
2763 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2764 } else {
2765 $this->dir = $CFG->dataroot.'/cache/misc/';
2767 if (!file_exists($this->dir)) {
2768 mkdir($this->dir, $CFG->directorypermissions, true);
2770 if ($module == 'repository') {
2771 if (empty($CFG->repositorycacheexpire)) {
2772 $CFG->repositorycacheexpire = 120;
2774 $this->ttl = $CFG->repositorycacheexpire;
2775 } else {
2776 if (empty($CFG->curlcache)) {
2777 $CFG->curlcache = 120;
2779 $this->ttl = $CFG->curlcache;
2784 * Get cached value
2786 * @global object
2787 * @global object
2788 * @param mixed $param
2789 * @return bool|string
2791 public function get($param){
2792 global $CFG, $USER;
2793 $this->cleanup($this->ttl);
2794 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2795 if(file_exists($this->dir.$filename)) {
2796 $lasttime = filemtime($this->dir.$filename);
2797 if(time()-$lasttime > $this->ttl)
2799 return false;
2800 } else {
2801 $fp = fopen($this->dir.$filename, 'r');
2802 $size = filesize($this->dir.$filename);
2803 $content = fread($fp, $size);
2804 return unserialize($content);
2807 return false;
2811 * Set cache value
2813 * @global object $CFG
2814 * @global object $USER
2815 * @param mixed $param
2816 * @param mixed $val
2818 public function set($param, $val){
2819 global $CFG, $USER;
2820 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
2821 $fp = fopen($this->dir.$filename, 'w');
2822 fwrite($fp, serialize($val));
2823 fclose($fp);
2827 * Remove cache files
2829 * @param int $expire The number os seconds before expiry
2831 public function cleanup($expire){
2832 if($dir = opendir($this->dir)){
2833 while (false !== ($file = readdir($dir))) {
2834 if(!is_dir($file) && $file != '.' && $file != '..') {
2835 $lasttime = @filemtime($this->dir.$file);
2836 if(time() - $lasttime > $expire){
2837 @unlink($this->dir.$file);
2844 * delete current user's cache file
2846 * @global object $CFG
2847 * @global object $USER
2849 public function refresh(){
2850 global $CFG, $USER;
2851 if($dir = opendir($this->dir)){
2852 while (false !== ($file = readdir($dir))) {
2853 if(!is_dir($file) && $file != '.' && $file != '..') {
2854 if(strpos($file, 'u'.$USER->id.'_')!==false){
2855 @unlink($this->dir.$file);
2864 * This class is used to parse lib/file/file_types.mm which help get file
2865 * extensions by file types.
2866 * The file_types.mm file can be edited by freemind in graphic environment.
2868 * @package moodlecore
2869 * @subpackage file
2870 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
2871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2873 class filetype_parser {
2875 * Check file_types.mm file, setup variables
2877 * @global object $CFG
2878 * @param string $file
2880 public function __construct($file = '') {
2881 global $CFG;
2882 if (empty($file)) {
2883 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
2884 } else {
2885 $this->file = $file;
2887 $this->tree = array();
2888 $this->result = array();
2892 * A private function to browse xml nodes
2894 * @param array $parent
2895 * @param array $types
2897 private function _browse_nodes($parent, $types) {
2898 $key = (string)$parent['TEXT'];
2899 if(isset($parent->node)) {
2900 $this->tree[$key] = array();
2901 if (in_array((string)$parent['TEXT'], $types)) {
2902 $this->_select_nodes($parent, $this->result);
2903 } else {
2904 foreach($parent->node as $v){
2905 $this->_browse_nodes($v, $types);
2908 } else {
2909 $this->tree[] = $key;
2914 * A private function to select text nodes
2916 * @param array $parent
2918 private function _select_nodes($parent){
2919 if(isset($parent->node)) {
2920 foreach($parent->node as $v){
2921 $this->_select_nodes($v, $this->result);
2923 } else {
2924 $this->result[] = (string)$parent['TEXT'];
2930 * Get file extensions by file types names.
2932 * @param array $types
2933 * @return mixed
2935 public function get_extensions($types) {
2936 if (!is_array($types)) {
2937 $types = array($types);
2939 $this->result = array();
2940 if ((is_array($types) && in_array('*', $types)) ||
2941 $types == '*' || empty($types)) {
2942 return array('*');
2944 foreach ($types as $key=>$value){
2945 if (strpos($value, '.') !== false) {
2946 $this->result[] = $value;
2947 unset($types[$key]);
2950 if (file_exists($this->file)) {
2951 $xml = simplexml_load_file($this->file);
2952 foreach($xml->node->node as $v){
2953 if (in_array((string)$v['TEXT'], $types)) {
2954 $this->_select_nodes($v);
2955 } else {
2956 $this->_browse_nodes($v, $types);
2959 } else {
2960 exit('Failed to open file lib/filestorage/file_types.mm');
2962 return $this->result;