2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Functions for file handling.
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
28 * BYTESERVING_BOUNDARY - string unique string constant.
30 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
33 * Unlimited area size constant
35 define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
37 require_once("$CFG->libdir/filestorage/file_exceptions.php");
38 require_once("$CFG->libdir/filestorage/file_storage.php");
39 require_once("$CFG->libdir/filestorage/zip_packer.php");
40 require_once("$CFG->libdir/filebrowser/file_browser.php");
43 * Encodes file serving url
45 * @deprecated use moodle_url factory methods instead
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
49 * @param string $urlbase
50 * @param string $path /filearea/itemid/dir/dir/file.exe
51 * @param bool $forcedownload
52 * @param bool $https https url required
53 * @return string encoded file url
55 function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
58 //TODO: deprecate this
60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
66 $return .= '?forcedownload=1';
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
72 $return .= '&forcedownload=1';
77 $return = str_replace('http://', 'https://', $return);
84 * Detects if area contains subdirs,
85 * this is intended for file areas that are attached to content
86 * migrated from 1.x where subdirs were allowed everywhere.
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
94 function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
97 if (!isset($itemid)) {
98 // Not initialised yet.
102 // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
103 $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
104 $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
105 return $DB->record_exists_select('files', $select, $params);
109 * Prepares 'editor' formslib element from data in database
111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
112 * function then copies the embedded files into draft area (assigning itemids automatically),
113 * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
115 * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
116 * your mform's set_data() supplying the object returned by this function.
119 * @param stdClass $data database field that holds the html text with embedded media
120 * @param string $field the name of the database field that holds the html text with embedded media
121 * @param array $options editor options (like maxifiles, maxbytes etc.)
122 * @param stdClass $context context of the editor
123 * @param string $component
124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
126 * @return stdClass modified data object
128 function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
146 //sanity check for passed context. This function doesn't expect $option['context'] to be set
147 //But this function is called before creating editor hence, this is one of the best places to check
148 //if context is used properly. This check notify developer that they missed passing context to editor.
149 if (isset($context) && !isset($options['context'])) {
150 //if $context is not null then make sure $option['context'] is also set.
151 debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
152 } else if (isset($options['context']) && isset($context)) {
153 //If both are passed then they should be equal.
154 if ($options['context']->id != $context->id) {
155 $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
156 throw new coding_exception($exceptionmsg);
160 if (is_null($itemid) or is_null($context)) {
164 $data = new stdClass();
166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
169 if (!isset($data->{$field.'format'})) {
170 $data->{$field.'format'} = editors_get_preferred_format();
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
177 if ($options['trusttext']) {
178 // noclean ignored if trusttext enabled
179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
182 $data = trusttext_pre_edit($data, $field, $context);
184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
188 $contextid = $context->id;
191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
205 * This function moves files from draft area to the destination area and
206 * encodes URLs to the draft files so they can be safely saved into DB. The
207 * form has to contain the 'editor' element named foobar_editor, where 'foobar'
208 * is the name of the database field to hold the wysiwyg editor content. The
209 * editor data comes as an array with text, format and itemid properties. This
210 * function automatically adds $data properties foobar, foobarformat and
211 * foobartrust, where foobar has URL to embedded files encoded.
214 * @param stdClass $data raw data submitted by the form
215 * @param string $field name of the database field containing the html with embedded media files
216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return stdClass modified data object
223 function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
234 if (!isset($options['maxfiles'])) {
235 $options['maxfiles'] = 0; // no files by default
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
241 if ($options['trusttext']) {
242 $data->{$field.'trust'} = trusttext_trusted($context);
244 $data->{$field.'trust'} = 0;
247 $editor = $data->{$field.'_editor'};
249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
250 $data->{$field} = $editor['text'];
252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
254 $data->{$field.'format'} = $editor['format'];
260 * Saves text and files modified by Editor formslib element
263 * @param stdClass $data $database entry field
264 * @param string $field name of data field
265 * @param array $options various options
266 * @param stdClass $context context - must already exist
267 * @param string $component
268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
270 * @return stdClass modified data obejct
272 function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
277 if (is_null($itemid) or is_null($context)) {
281 $contextid = $context->id;
284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
286 $data->{$field.'_filemanager'} = $draftid_editor;
292 * Saves files modified by File manager formslib element
294 * @todo MDL-31073 review this function
296 * @param stdClass $data $database entry field
297 * @param string $field name of data field
298 * @param array $options various options
299 * @param stdClass $context context - must already exist
300 * @param string $component
301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
303 * @return stdClass modified data obejct
305 function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
317 if (empty($data->{$field.'_filemanager'})) {
321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
322 $fs = get_file_storage();
324 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
335 * Generate a draft itemid
338 * @global moodle_database $DB
339 * @global stdClass $USER
340 * @return int a random but available draft itemid that can be used to create a new draft
343 function file_get_unused_draft_itemid() {
346 if (isguestuser() or !isloggedin()) {
347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
348 print_error('noguest');
351 $contextid = context_user::instance($USER->id)->id;
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
356 $draftitemid = rand(1, 999999999);
363 * Initialise a draft file area from a real one by copying the files. A draft
364 * area will be created if one does not already exist. Normally you should
365 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
368 * @global stdClass $CFG
369 * @global stdClass $USER
370 * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
371 * @param int $contextid This parameter and the next two identify the file area to copy files from.
372 * @param string $component
373 * @param string $filearea helps indentify the file area.
374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
379 function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
380 global $CFG, $USER, $CFG;
382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
386 if (!isset($options['forcehttps'])) {
387 $options['forcehttps'] = false;
390 $usercontext = context_user::instance($USER->id);
391 $fs = get_file_storage();
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
395 $draftitemid = file_get_unused_draft_itemid();
396 $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
397 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
398 foreach ($files as $file) {
399 if ($file->is_directory() and $file->get_filepath() === '/') {
400 // we need a way to mark the age of each draft area,
401 // by not copying the root dir we force it to be created automatically with current timestamp
404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
408 // XXX: This is a hack for file manager (MDL-28666)
409 // File manager needs to know the original file information before copying
410 // to draft area, so we append these information in mdl_files.source field
411 // {@link file_storage::search_references()}
412 // {@link file_storage::search_references_count()}
413 $sourcefield = $file->get_source();
414 $newsourcefield = new stdClass;
415 $newsourcefield->source = $sourcefield;
416 $original = new stdClass;
417 $original->contextid = $contextid;
418 $original->component = $component;
419 $original->filearea = $filearea;
420 $original->itemid = $itemid;
421 $original->filename = $file->get_filename();
422 $original->filepath = $file->get_filepath();
423 $newsourcefield->original = file_storage::pack_reference($original);
424 $draftfile->set_source(serialize($newsourcefield));
425 // End of file manager hack
428 if (!is_null($text)) {
429 // at this point there should not be any draftfile links yet,
430 // because this is a new text from database that should still contain the @@pluginfile@@ links
431 // this happens when developers forget to post process the text
432 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
438 if (is_null($text)) {
442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
450 * @global stdClass $CFG
451 * @param string $text The content that may contain ULRs in need of rewriting.
452 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
453 * @param int $contextid This parameter and the next two identify the file area to use.
454 * @param string $component
455 * @param string $filearea helps identify the file area.
456 * @param int $itemid helps identify the file area.
457 * @param array $options text and file options ('forcehttps'=>false)
458 * @return string the processed text.
460 function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
463 $options = (array)$options;
464 if (!isset($options['forcehttps'])) {
465 $options['forcehttps'] = false;
468 if (!$CFG->slasharguments) {
469 $file = $file . '?file=';
472 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
474 if ($itemid !== null) {
475 $baseurl .= "$itemid/";
478 if ($options['forcehttps']) {
479 $baseurl = str_replace('http://', 'https://', $baseurl);
482 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
486 * Returns information about files in a draft area.
488 * @global stdClass $CFG
489 * @global stdClass $USER
490 * @param int $draftitemid the draft area item id.
491 * @param string $filepath path to the directory from which the information have to be retrieved.
492 * @return array with the following entries:
493 * 'filecount' => number of files in the draft area.
494 * 'filesize' => total size of the files in the draft area.
495 * 'foldercount' => number of folders in the draft area.
496 * 'filesize_without_references' => total size of the area excluding file references.
497 * (more information will be added as needed).
499 function file_get_draft_area_info($draftitemid, $filepath = '/') {
502 $usercontext = context_user::instance($USER->id);
503 $fs = get_file_storage();
509 'filesize_without_references' => 0
512 if ($filepath != '/') {
513 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
515 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
517 foreach ($draftfiles as $file) {
518 if ($file->is_directory()) {
519 $results['foldercount'] += 1;
521 $results['filecount'] += 1;
524 $filesize = $file->get_filesize();
525 $results['filesize'] += $filesize;
526 if (!$file->is_external_file()) {
527 $results['filesize_without_references'] += $filesize;
535 * Returns whether a draft area has exceeded/will exceed its size limit.
537 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
539 * @param int $draftitemid the draft area item id.
540 * @param int $areamaxbytes the maximum size allowed in this draft area.
541 * @param int $newfilesize the size that would be added to the current area.
542 * @param bool $includereferences true to include the size of the references in the area size.
543 * @return bool true if the area will/has exceeded its limit.
546 function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
547 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
548 $draftinfo = file_get_draft_area_info($draftitemid);
549 $areasize = $draftinfo['filesize_without_references'];
550 if ($includereferences) {
551 $areasize = $draftinfo['filesize'];
553 if ($areasize + $newfilesize > $areamaxbytes) {
561 * Get used space of files
562 * @global moodle_database $DB
563 * @global stdClass $USER
564 * @return int total bytes
566 function file_get_user_used_space() {
569 $usercontext = context_user::instance($USER->id);
570 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
571 JOIN (SELECT contenthash, filename, MAX(id) AS id
573 WHERE contextid = ? AND component = ? AND filearea != ?
574 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
575 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
576 $record = $DB->get_record_sql($sql, $params);
577 return (int)$record->totalbytes;
581 * Convert any string to a valid filepath
582 * @todo review this function
584 * @return string path
586 function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
587 if ($str == '/' or empty($str)) {
590 return '/'.trim($str, '/').'/';
595 * Generate a folder tree of draft area of current USER recursively
597 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
598 * @param int $draftitemid
599 * @param string $filepath
602 function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
603 global $USER, $OUTPUT, $CFG;
604 $data->children = array();
605 $context = context_user::instance($USER->id);
606 $fs = get_file_storage();
607 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
608 foreach ($files as $file) {
609 if ($file->is_directory()) {
610 $item = new stdClass();
611 $item->sortorder = $file->get_sortorder();
612 $item->filepath = $file->get_filepath();
614 $foldername = explode('/', trim($item->filepath, '/'));
615 $item->fullname = trim(array_pop($foldername), '/');
617 $item->id = uniqid();
618 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
619 $data->children[] = $item;
628 * Listing all files (including folders) in current path (draft area)
629 * used by file manager
630 * @param int $draftitemid
631 * @param string $filepath
634 function file_get_drafarea_files($draftitemid, $filepath = '/') {
635 global $USER, $OUTPUT, $CFG;
637 $context = context_user::instance($USER->id);
638 $fs = get_file_storage();
640 $data = new stdClass();
641 $data->path = array();
642 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
644 // will be used to build breadcrumb
646 if ($filepath !== '/') {
647 $filepath = file_correct_filepath($filepath);
648 $parts = explode('/', $filepath);
649 foreach ($parts as $part) {
650 if ($part != '' && $part != null) {
651 $trail .= ($part.'/');
652 $data->path[] = array('name'=>$part, 'path'=>$trail);
659 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
660 foreach ($files as $file) {
661 $item = new stdClass();
662 $item->filename = $file->get_filename();
663 $item->filepath = $file->get_filepath();
664 $item->fullname = trim($item->filename, '/');
665 $filesize = $file->get_filesize();
666 $item->size = $filesize ? $filesize : null;
667 $item->filesize = $filesize ? display_size($filesize) : '';
669 $item->sortorder = $file->get_sortorder();
670 $item->author = $file->get_author();
671 $item->license = $file->get_license();
672 $item->datemodified = $file->get_timemodified();
673 $item->datecreated = $file->get_timecreated();
674 $item->isref = $file->is_external_file();
675 if ($item->isref && $file->get_status() == 666) {
676 $item->originalmissing = true;
678 // find the file this draft file was created from and count all references in local
679 // system pointing to that file
680 $source = @unserialize($file->get_source());
681 if (isset($source->original)) {
682 $item->refcount = $fs->search_references_count($source->original);
685 if ($file->is_directory()) {
687 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
688 $item->type = 'folder';
689 $foldername = explode('/', trim($item->filepath, '/'));
690 $item->fullname = trim(array_pop($foldername), '/');
691 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
693 // do NOT use file browser here!
694 $item->mimetype = get_mimetype_description($file);
695 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
698 $item->type = 'file';
700 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
701 $item->url = $itemurl->out();
702 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
703 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
704 if ($imageinfo = $file->get_imageinfo()) {
705 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
706 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
707 $item->image_width = $imageinfo['width'];
708 $item->image_height = $imageinfo['height'];
714 $data->itemid = $draftitemid;
720 * Returns draft area itemid for a given element.
723 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
724 * @return int the itemid, or 0 if there is not one yet.
726 function file_get_submitted_draft_itemid($elname) {
727 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
728 if (!isset($_REQUEST[$elname])) {
731 if (is_array($_REQUEST[$elname])) {
732 $param = optional_param_array($elname, 0, PARAM_INT);
733 if (!empty($param['itemid'])) {
734 $param = $param['itemid'];
736 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
741 $param = optional_param($elname, 0, PARAM_INT);
752 * Restore the original source field from draft files
754 * Do not use this function because it makes field files.source inconsistent
755 * for draft area files. This function will be deprecated in 2.6
757 * @param stored_file $storedfile This only works with draft files
758 * @return stored_file
760 function file_restore_source_field_from_draft_file($storedfile) {
761 $source = @unserialize($storedfile->get_source());
762 if (!empty($source)) {
763 if (is_object($source)) {
764 $restoredsource = $source->source;
765 $storedfile->set_source($restoredsource);
767 throw new moodle_exception('invalidsourcefield', 'error');
773 * Saves files from a draft file area to a real one (merging the list of files).
774 * Can rewrite URLs in some content at the same time if desired.
777 * @global stdClass $USER
778 * @param int $draftitemid the id of the draft area to use. Normally obtained
779 * from file_get_submitted_draft_itemid('elementname') or similar.
780 * @param int $contextid This parameter and the next two identify the file area to save to.
781 * @param string $component
782 * @param string $filearea indentifies the file area.
783 * @param int $itemid helps identifies the file area.
784 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
785 * @param string $text some html content that needs to have embedded links rewritten
786 * to the @@PLUGINFILE@@ form for saving in the database.
787 * @param bool $forcehttps force https urls.
788 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
790 function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
793 $usercontext = context_user::instance($USER->id);
794 $fs = get_file_storage();
796 $options = (array)$options;
797 if (!isset($options['subdirs'])) {
798 $options['subdirs'] = false;
800 if (!isset($options['maxfiles'])) {
801 $options['maxfiles'] = -1; // unlimited
803 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
804 $options['maxbytes'] = 0; // unlimited
806 if (!isset($options['areamaxbytes'])) {
807 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
809 $allowreferences = true;
810 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
811 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
812 // this is not exactly right. BUT there are many places in code where filemanager options
813 // are not passed to file_save_draft_area_files()
814 $allowreferences = false;
817 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
818 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
819 // anything at all in the next area.
820 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
824 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
825 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
827 // One file in filearea means it is empty (it has only top-level directory '.').
828 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
829 // we have to merge old and new files - we want to keep file ids for files that were not changed
830 // we change time modified for all new and changed files, we keep time created as is
832 $newhashes = array();
834 foreach ($draftfiles as $file) {
835 if (!$options['subdirs'] && ($file->get_filepath() !== '/' or $file->is_directory())) {
838 if (!$allowreferences && $file->is_external_file()) {
841 if (!$file->is_directory()) {
842 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
843 // oversized file - should not get here at all
846 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
847 // more files - should not get here at all
852 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
853 $newhashes[$newhash] = $file;
856 // Loop through oldfiles and decide which we need to delete and which to update.
857 // After this cycle the array $newhashes will only contain the files that need to be added.
858 foreach ($oldfiles as $oldfile) {
859 $oldhash = $oldfile->get_pathnamehash();
860 if (!isset($newhashes[$oldhash])) {
861 // delete files not needed any more - deleted by user
866 $newfile = $newhashes[$oldhash];
867 // Now we know that we have $oldfile and $newfile for the same path.
868 // Let's check if we can update this file or we need to delete and create.
869 if ($newfile->is_directory()) {
870 // Directories are always ok to just update.
871 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
872 // File has the 'original' - we need to update the file (it may even have not been changed at all).
873 $original = file_storage::unpack_reference($source->original);
874 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
875 // Very odd, original points to another file. Delete and create file.
880 // The same file name but absence of 'original' means that file was deteled and uploaded again.
881 // By deleting and creating new file we properly manage all existing references.
886 // status changed, we delete old file, and create a new one
887 if ($oldfile->get_status() != $newfile->get_status()) {
888 // file was changed, use updated with new timemodified data
890 // This file will be added later
895 if ($oldfile->get_author() != $newfile->get_author()) {
896 $oldfile->set_author($newfile->get_author());
899 if ($oldfile->get_license() != $newfile->get_license()) {
900 $oldfile->set_license($newfile->get_license());
903 // Updated file source
904 // Field files.source for draftarea files contains serialised object with source and original information.
905 // We only store the source part of it for non-draft file area.
906 $newsource = $newfile->get_source();
907 if ($source = @unserialize($newfile->get_source())) {
908 $newsource = $source->source;
910 if ($oldfile->get_source() !== $newsource) {
911 $oldfile->set_source($newsource);
914 // Updated sort order
915 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
916 $oldfile->set_sortorder($newfile->get_sortorder());
919 // Update file timemodified
920 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
921 $oldfile->set_timemodified($newfile->get_timemodified());
924 // Replaced file content
925 if (!$oldfile->is_directory() &&
926 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
927 $oldfile->get_filesize() != $newfile->get_filesize() ||
928 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
929 $oldfile->get_userid() != $newfile->get_userid())) {
930 $oldfile->replace_file_with($newfile);
931 // push changes to all local files that are referencing this file
932 $fs->update_references_to_storedfile($oldfile);
935 // unchanged file or directory - we keep it as is
936 unset($newhashes[$oldhash]);
939 // Add fresh file or the file which has changed status
940 // the size and subdirectory tests are extra safety only, the UI should prevent it
941 foreach ($newhashes as $file) {
942 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
943 if ($source = @unserialize($file->get_source())) {
944 // Field files.source for draftarea files contains serialised object with source and original information.
945 // We only store the source part of it for non-draft file area.
946 $file_record['source'] = $source->source;
949 if ($file->is_external_file()) {
950 $repoid = $file->get_repository_id();
951 if (!empty($repoid)) {
952 $file_record['repositoryid'] = $repoid;
953 $file_record['reference'] = $file->get_reference();
957 $fs->create_file_from_storedfile($file_record, $file);
961 // note: do not purge the draft area - we clean up areas later in cron,
962 // the reason is that user might press submit twice and they would loose the files,
963 // also sometimes we might want to use hacks that save files into two different areas
965 if (is_null($text)) {
968 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
973 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
974 * ready to be saved in the database. Normally, this is done automatically by
975 * {@link file_save_draft_area_files()}.
978 * @param string $text the content to process.
979 * @param int $draftitemid the draft file area the content was using.
980 * @param bool $forcehttps whether the content contains https URLs. Default false.
981 * @return string the processed content.
983 function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
986 $usercontext = context_user::instance($USER->id);
988 $wwwroot = $CFG->wwwroot;
990 $wwwroot = str_replace('http://', 'https://', $wwwroot);
993 // relink embedded files if text submitted - no absolute links allowed in database!
994 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
996 if (strpos($text, 'draftfile.php?file=') !== false) {
998 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1000 foreach ($matches[0] as $match) {
1001 $replace = str_ireplace('%2F', '/', $match);
1002 $text = str_replace($match, $replace, $text);
1005 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1012 * Set file sort order
1014 * @global moodle_database $DB
1015 * @param int $contextid the context id
1016 * @param string $component file component
1017 * @param string $filearea file area.
1018 * @param int $itemid itemid.
1019 * @param string $filepath file path.
1020 * @param string $filename file name.
1021 * @param int $sortorder the sort order of file.
1024 function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1026 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1027 if ($file_record = $DB->get_record('files', $conditions)) {
1028 $sortorder = (int)$sortorder;
1029 $file_record->sortorder = $sortorder;
1030 $DB->update_record('files', $file_record);
1037 * reset file sort order number to 0
1038 * @global moodle_database $DB
1039 * @param int $contextid the context id
1040 * @param string $component
1041 * @param string $filearea file area.
1042 * @param int|bool $itemid itemid.
1045 function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1048 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1049 if ($itemid !== false) {
1050 $conditions['itemid'] = $itemid;
1053 $file_records = $DB->get_records('files', $conditions);
1054 foreach ($file_records as $file_record) {
1055 $file_record->sortorder = 0;
1056 $DB->update_record('files', $file_record);
1062 * Returns description of upload error
1064 * @param int $errorcode found in $_FILES['filename.ext']['error']
1065 * @return string error description string, '' if ok
1067 function file_get_upload_error($errorcode) {
1069 switch ($errorcode) {
1070 case 0: // UPLOAD_ERR_OK - no error
1074 case 1: // UPLOAD_ERR_INI_SIZE
1075 $errmessage = get_string('uploadserverlimit');
1078 case 2: // UPLOAD_ERR_FORM_SIZE
1079 $errmessage = get_string('uploadformlimit');
1082 case 3: // UPLOAD_ERR_PARTIAL
1083 $errmessage = get_string('uploadpartialfile');
1086 case 4: // UPLOAD_ERR_NO_FILE
1087 $errmessage = get_string('uploadnofilefound');
1090 // Note: there is no error with a value of 5
1092 case 6: // UPLOAD_ERR_NO_TMP_DIR
1093 $errmessage = get_string('uploadnotempdir');
1096 case 7: // UPLOAD_ERR_CANT_WRITE
1097 $errmessage = get_string('uploadcantwrite');
1100 case 8: // UPLOAD_ERR_EXTENSION
1101 $errmessage = get_string('uploadextension');
1105 $errmessage = get_string('uploadproblem');
1112 * Recursive function formating an array in POST parameter
1113 * @param array $arraydata - the array that we are going to format and add into &$data array
1114 * @param string $currentdata - a row of the final postdata array at instant T
1115 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1116 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1118 function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1119 foreach ($arraydata as $k=>$v) {
1120 $newcurrentdata = $currentdata;
1121 if (is_array($v)) { //the value is an array, call the function recursively
1122 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1123 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1124 } else { //add the POST parameter to the $data array
1125 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1131 * Transform a PHP array into POST parameter
1132 * (see the recursive function format_array_postdata_for_curlcall)
1133 * @param array $postdata
1134 * @return array containing all POST parameters (1 row = 1 POST parameter)
1136 function format_postdata_for_curlcall($postdata) {
1138 foreach ($postdata as $k=>$v) {
1140 $currentdata = urlencode($k);
1141 format_array_postdata_for_curlcall($v, $currentdata, $data);
1143 $data[] = urlencode($k).'='.urlencode($v);
1146 $convertedpostdata = implode('&', $data);
1147 return $convertedpostdata;
1151 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1152 * Due to security concerns only downloads from http(s) sources are supported.
1155 * @param string $url file url starting with http(s)://
1156 * @param array $headers http headers, null if none. If set, should be an
1157 * associative array of header name => value pairs.
1158 * @param array $postdata array means use POST request with given parameters
1159 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1160 * (if false, just returns content)
1161 * @param int $timeout timeout for complete download process including all file transfer
1162 * (default 5 minutes)
1163 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1164 * usually happens if the remote server is completely down (default 20 seconds);
1165 * may not work when using proxy
1166 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1167 * Only use this when already in a trusted location.
1168 * @param string $tofile store the downloaded content to file instead of returning it.
1169 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1170 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1171 * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
1173 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1176 // Only http and https links supported.
1177 if (!preg_match('|^https?://|i', $url)) {
1178 if ($fullresponse) {
1179 $response = new stdClass();
1180 $response->status = 0;
1181 $response->headers = array();
1182 $response->response_code = 'Invalid protocol specified in url';
1183 $response->results = '';
1184 $response->error = 'Invalid protocol specified in url';
1193 $headers2 = array();
1194 if (is_array($headers)) {
1195 foreach ($headers as $key => $value) {
1196 if (is_numeric($key)) {
1197 $headers2[] = $value;
1199 $headers2[] = "$key: $value";
1204 if ($skipcertverify) {
1205 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1207 $options['CURLOPT_SSL_VERIFYPEER'] = true;
1210 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1212 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1213 $options['CURLOPT_MAXREDIRS'] = 5;
1215 // Use POST if requested.
1216 if (is_array($postdata)) {
1217 $postdata = format_postdata_for_curlcall($postdata);
1218 } else if (empty($postdata)) {
1222 // Optionally attempt to get more correct timeout by fetching the file size.
1223 if (!isset($CFG->curltimeoutkbitrate)) {
1224 // Use very slow rate of 56kbps as a timeout speed when not set.
1227 $bitrate = $CFG->curltimeoutkbitrate;
1229 if ($calctimeout and !isset($postdata)) {
1231 $curl->setHeader($headers2);
1233 $curl->head($url, $postdata, $options);
1235 $info = $curl->get_info();
1236 $error_no = $curl->get_errno();
1237 if (!$error_no && $info['download_content_length'] > 0) {
1238 // No curl errors - adjust for large files only - take max timeout.
1239 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1244 $curl->setHeader($headers2);
1246 $options['CURLOPT_RETURNTRANSFER'] = true;
1247 $options['CURLOPT_NOBODY'] = false;
1248 $options['CURLOPT_TIMEOUT'] = $timeout;
1251 $fh = fopen($tofile, 'w');
1253 if ($fullresponse) {
1254 $response = new stdClass();
1255 $response->status = 0;
1256 $response->headers = array();
1257 $response->response_code = 'Can not write to file';
1258 $response->results = false;
1259 $response->error = 'Can not write to file';
1265 $options['CURLOPT_FILE'] = $fh;
1268 if (isset($postdata)) {
1269 $content = $curl->post($url, $postdata, $options);
1271 $content = $curl->get($url, null, $options);
1276 @chmod($tofile, $CFG->filepermissions);
1280 // Try to detect encoding problems.
1281 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1282 curl_setopt($ch, CURLOPT_ENCODING, 'none');
1283 $result = curl_exec($ch);
1287 $info = $curl->get_info();
1288 $error_no = $curl->get_errno();
1289 $rawheaders = $curl->get_raw_response();
1293 if (!$fullresponse) {
1294 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1298 $response = new stdClass();
1299 if ($error_no == 28) {
1300 $response->status = '-100'; // Mimic snoopy.
1302 $response->status = '0';
1304 $response->headers = array();
1305 $response->response_code = $error;
1306 $response->results = false;
1307 $response->error = $error;
1315 if (empty($info['http_code'])) {
1316 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1317 $response = new stdClass();
1318 $response->status = '0';
1319 $response->headers = array();
1320 $response->response_code = 'Unknown cURL error';
1321 $response->results = false; // do NOT change this, we really want to ignore the result!
1322 $response->error = 'Unknown cURL error';
1325 $response = new stdClass();
1326 $response->status = (string)$info['http_code'];
1327 $response->headers = $rawheaders;
1328 $response->results = $content;
1329 $response->error = '';
1331 // There might be multiple headers on redirect, find the status of the last one.
1333 foreach ($rawheaders as $line) {
1335 $response->response_code = $line;
1338 if (trim($line, "\r\n") === '') {
1344 if ($fullresponse) {
1348 if ($info['http_code'] != 200) {
1349 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1352 return $response->results;
1356 * Returns a list of information about file types based on extensions.
1358 * The following elements expected in value array for each extension:
1360 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1361 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1362 * also files with bigger sizes under names
1363 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1364 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1365 * commonly used in moodle the following groups:
1366 * - web_image - image that can be included as <img> in HTML
1367 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1368 * - video - file that can be imported as video in text editor
1369 * - audio - file that can be imported as audio in text editor
1370 * - archive - we can extract files from this archive
1371 * - spreadsheet - used for portfolio format
1372 * - document - used for portfolio format
1373 * - presentation - used for portfolio format
1374 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1375 * human-readable description for this filetype;
1376 * Function {@link get_mimetype_description()} first looks at the presence of string for
1377 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1378 * attribute, if not found returns the value of 'type';
1379 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1380 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1381 * this function will return first found icon; Especially usefull for types such as 'text/plain'
1384 * @return array List of information about file types based on extensions.
1385 * Associative array of extension (lower-case) to associative array
1386 * from 'element name' to data. Current element names are 'type' and 'icon'.
1387 * Unknown types should use the 'xxx' entry which includes defaults.
1389 function &get_mimetypes_array() {
1390 static $mimearray = array (
1391 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
1392 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1393 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1394 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
1395 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
1396 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1397 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1398 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1399 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
1400 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1401 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1402 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1403 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
1404 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
1405 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1406 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
1407 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1408 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
1409 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
1410 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1411 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1412 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
1414 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
1415 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1416 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1417 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1418 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
1420 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1421 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1422 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1423 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1424 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
1425 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
1426 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1427 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1428 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1430 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1431 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1432 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1433 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1434 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1435 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1436 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1437 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1438 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1439 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1440 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1441 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
1442 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1443 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
1444 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
1445 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1446 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1447 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1448 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
1449 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1450 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
1451 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1452 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1453 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1454 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1455 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
1456 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1457 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1458 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1459 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
1460 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
1461 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
1462 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1463 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
1464 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
1465 'mht' => array ('type'=>'message/rfc822', 'icon'=>'archive'),
1466 'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
1467 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1468 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1469 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1470 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1471 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1472 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1473 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
1474 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1475 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1476 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1477 'mpr' => array ('type'=>'application/vnd.moodle.profiling', 'icon'=>'moodle'),
1479 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1480 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1482 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1483 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
1484 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
1485 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1486 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1487 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1488 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1489 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1490 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1491 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1492 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1493 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1494 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1495 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1496 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1497 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1498 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1500 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1501 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1502 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1503 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1504 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1505 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1507 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1508 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1509 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1510 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1511 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1512 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1513 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1514 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1515 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
1517 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
1518 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1519 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1520 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1521 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1522 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1523 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1524 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
1525 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
1526 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
1527 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1528 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1529 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1530 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
1531 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1532 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1533 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1534 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1535 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1536 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1538 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1539 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1540 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1541 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1542 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1543 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1544 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1545 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1546 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1547 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1549 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1550 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1551 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1552 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1553 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1554 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1555 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
1556 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
1557 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
1558 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1559 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1560 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1562 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1563 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1564 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1565 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1567 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1568 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1569 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1570 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1571 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1572 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1573 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1575 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1576 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1578 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
1584 * Obtains information about a filetype based on its extension. Will
1585 * use a default if no information is present about that particular
1589 * @param string $element Desired information (usually 'icon'
1590 * for icon filename or 'type' for MIME type. Can also be
1591 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1592 * @param string $filename Filename we're looking up
1593 * @return string Requested piece of information from array
1595 function mimeinfo($element, $filename) {
1597 $mimeinfo = & get_mimetypes_array();
1598 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1600 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1601 if (empty($filetype)) {
1602 $filetype = 'xxx'; // file without extension
1604 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1605 $iconsize = max(array(16, (int)$iconsizematch[1]));
1606 $filenames = array($mimeinfo['xxx']['icon']);
1607 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1608 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1610 // find the file with the closest size, first search for specific icon then for default icon
1611 foreach ($filenames as $filename) {
1612 foreach ($iconpostfixes as $size => $postfix) {
1613 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1614 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1615 return $filename.$postfix;
1619 } else if (isset($mimeinfo[$filetype][$element])) {
1620 return $mimeinfo[$filetype][$element];
1621 } else if (isset($mimeinfo['xxx'][$element])) {
1622 return $mimeinfo['xxx'][$element]; // By default
1629 * Obtains information about a filetype based on the MIME type rather than
1630 * the other way around.
1633 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1634 * @param string $mimetype MIME type we're looking up
1635 * @return string Requested piece of information from array
1637 function mimeinfo_from_type($element, $mimetype) {
1638 /* array of cached mimetype->extension associations */
1639 static $cached = array();
1640 $mimeinfo = & get_mimetypes_array();
1642 if (!array_key_exists($mimetype, $cached)) {
1643 $cached[$mimetype] = null;
1644 foreach($mimeinfo as $filetype => $values) {
1645 if ($values['type'] == $mimetype) {
1646 if ($cached[$mimetype] === null) {
1647 $cached[$mimetype] = '.'.$filetype;
1649 if (!empty($values['defaulticon'])) {
1650 $cached[$mimetype] = '.'.$filetype;
1655 if (empty($cached[$mimetype])) {
1656 $cached[$mimetype] = '.xxx';
1659 if ($element === 'extension') {
1660 return $cached[$mimetype];
1662 return mimeinfo($element, $cached[$mimetype]);
1667 * Return the relative icon path for a given file
1671 * // $file - instance of stored_file or file_info
1672 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1673 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1677 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1680 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1681 * and $file->mimetype are expected)
1682 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1685 function file_file_icon($file, $size = null) {
1686 if (!is_object($file)) {
1687 $file = (object)$file;
1689 if (isset($file->filename)) {
1690 $filename = $file->filename;
1691 } else if (method_exists($file, 'get_filename')) {
1692 $filename = $file->get_filename();
1693 } else if (method_exists($file, 'get_visible_name')) {
1694 $filename = $file->get_visible_name();
1698 if (isset($file->mimetype)) {
1699 $mimetype = $file->mimetype;
1700 } else if (method_exists($file, 'get_mimetype')) {
1701 $mimetype = $file->get_mimetype();
1705 $mimetypes = &get_mimetypes_array();
1707 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1708 if ($extension && !empty($mimetypes[$extension])) {
1709 // if file name has known extension, return icon for this extension
1710 return file_extension_icon($filename, $size);
1713 return file_mimetype_icon($mimetype, $size);
1717 * Return the relative icon path for a folder image
1721 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1722 * echo html_writer::empty_tag('img', array('src' => $icon));
1726 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1729 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1732 function file_folder_icon($iconsize = null) {
1734 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1735 static $cached = array();
1736 $iconsize = max(array(16, (int)$iconsize));
1737 if (!array_key_exists($iconsize, $cached)) {
1738 foreach ($iconpostfixes as $size => $postfix) {
1739 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1740 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1741 $cached[$iconsize] = 'f/folder'.$postfix;
1746 return $cached[$iconsize];
1750 * Returns the relative icon path for a given mime type
1752 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1753 * a return the full path to an icon.
1756 * $mimetype = 'image/jpg';
1757 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1758 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1762 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1763 * to conform with that.
1764 * @param string $mimetype The mimetype to fetch an icon for
1765 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1766 * @return string The relative path to the icon
1768 function file_mimetype_icon($mimetype, $size = NULL) {
1769 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1773 * Returns the relative icon path for a given file name
1775 * This function should be used in conjunction with $OUTPUT->pix_url to produce
1776 * a return the full path to an icon.
1779 * $filename = '.jpg';
1780 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1781 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1784 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1785 * to conform with that.
1786 * @todo MDL-31074 Implement $size
1788 * @param string $filename The filename to get the icon for
1789 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1792 function file_extension_icon($filename, $size = NULL) {
1793 return 'f/'.mimeinfo('icon'.$size, $filename);
1797 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1798 * mimetypes.php language file.
1800 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1801 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1802 * have filename); In case of array/stdClass the field 'mimetype' is optional.
1803 * @param bool $capitalise If true, capitalises first character of result
1804 * @return string Text description
1806 function get_mimetype_description($obj, $capitalise=false) {
1807 $filename = $mimetype = '';
1808 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1809 // this is an instance of stored_file
1810 $mimetype = $obj->get_mimetype();
1811 $filename = $obj->get_filename();
1812 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1813 // this is an instance of file_info
1814 $mimetype = $obj->get_mimetype();
1815 $filename = $obj->get_visible_name();
1816 } else if (is_array($obj) || is_object ($obj)) {
1818 if (!empty($obj['filename'])) {
1819 $filename = $obj['filename'];
1821 if (!empty($obj['mimetype'])) {
1822 $mimetype = $obj['mimetype'];
1827 $mimetypefromext = mimeinfo('type', $filename);
1828 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1829 // if file has a known extension, overwrite the specified mimetype
1830 $mimetype = $mimetypefromext;
1832 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1833 if (empty($extension)) {
1834 $mimetypestr = mimeinfo_from_type('string', $mimetype);
1835 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
1837 $mimetypestr = mimeinfo('string', $filename);
1839 $chunks = explode('/', $mimetype, 2);
1842 'mimetype' => $mimetype,
1843 'ext' => $extension,
1844 'mimetype1' => $chunks[0],
1845 'mimetype2' => $chunks[1],
1848 foreach ($attr as $key => $value) {
1850 $a[strtoupper($key)] = strtoupper($value);
1851 $a[ucfirst($key)] = ucfirst($value);
1854 // MIME types may include + symbol but this is not permitted in string ids.
1855 $safemimetype = str_replace('+', '_', $mimetype);
1856 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1857 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1858 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1859 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1860 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
1861 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1862 $result = get_string('default', 'mimetypes', (object)$a);
1864 $result = $mimetype;
1867 $result=ucfirst($result);
1873 * Returns array of elements of type $element in type group(s)
1875 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1876 * @param string|array $groups one group or array of groups/extensions/mimetypes
1879 function file_get_typegroup($element, $groups) {
1880 static $cached = array();
1881 if (!is_array($groups)) {
1882 $groups = array($groups);
1884 if (!array_key_exists($element, $cached)) {
1885 $cached[$element] = array();
1888 foreach ($groups as $group) {
1889 if (!array_key_exists($group, $cached[$element])) {
1890 // retrieive and cache all elements of type $element for group $group
1891 $mimeinfo = & get_mimetypes_array();
1892 $cached[$element][$group] = array();
1893 foreach ($mimeinfo as $extension => $value) {
1894 $value['extension'] = '.'.$extension;
1895 if (empty($value[$element])) {
1898 if (($group === '.'.$extension || $group === $value['type'] ||
1899 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1900 !in_array($value[$element], $cached[$element][$group])) {
1901 $cached[$element][$group][] = $value[$element];
1905 $result = array_merge($result, $cached[$element][$group]);
1907 return array_values(array_unique($result));
1911 * Checks if file with name $filename has one of the extensions in groups $groups
1913 * @see get_mimetypes_array()
1914 * @param string $filename name of the file to check
1915 * @param string|array $groups one group or array of groups to check
1916 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1917 * file mimetype is in mimetypes in groups $groups
1920 function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1921 $extension = pathinfo($filename, PATHINFO_EXTENSION);
1922 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
1925 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1929 * Checks if mimetype $mimetype belongs to one of the groups $groups
1931 * @see get_mimetypes_array()
1932 * @param string $mimetype
1933 * @param string|array $groups one group or array of groups to check
1936 function file_mimetype_in_typegroup($mimetype, $groups) {
1937 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1941 * Requested file is not found or not accessible, does not return, terminates script
1943 * @global stdClass $CFG
1944 * @global stdClass $COURSE
1946 function send_file_not_found() {
1947 global $CFG, $COURSE;
1949 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1952 * Helper function to send correct 404 for server.
1954 function send_header_404() {
1955 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1956 header("Status: 404 Not Found");
1958 header('HTTP/1.0 404 not found');
1963 * Enhanced readfile() with optional acceleration.
1964 * @param string|stored_file $file
1965 * @param string $mimetype
1966 * @param bool $accelerate
1969 function readfile_accel($file, $mimetype, $accelerate) {
1972 if ($mimetype === 'text/plain') {
1973 // there is no encoding specified in text files, we need something consistent
1974 header('Content-Type: text/plain; charset=utf-8');
1976 header('Content-Type: '.$mimetype);
1979 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1980 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1982 if (is_object($file)) {
1983 header('Etag: "' . $file->get_contenthash() . '"');
1984 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) {
1985 header('HTTP/1.1 304 Not Modified');
1990 // if etag present for stored file rely on it exclusively
1991 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1992 // get unixtime of request header; clip extra junk off first
1993 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1994 if ($since && $since >= $lastmodified) {
1995 header('HTTP/1.1 304 Not Modified');
2000 if ($accelerate and !empty($CFG->xsendfile)) {
2001 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2002 header('Accept-Ranges: bytes');
2004 header('Accept-Ranges: none');
2007 if (is_object($file)) {
2008 $fs = get_file_storage();
2009 if ($fs->xsendfile($file->get_contenthash())) {
2014 require_once("$CFG->libdir/xsendfilelib.php");
2015 if (xsendfile($file)) {
2021 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2023 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2025 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2026 header('Accept-Ranges: bytes');
2028 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2029 // byteserving stuff - for acrobat reader and download accelerators
2030 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2031 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2033 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2034 foreach ($ranges as $key=>$value) {
2035 if ($ranges[$key][1] == '') {
2037 $ranges[$key][1] = $filesize - $ranges[$key][2];
2038 $ranges[$key][2] = $filesize - 1;
2039 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2041 $ranges[$key][2] = $filesize - 1;
2043 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2044 //invalid byte-range ==> ignore header
2048 //prepare multipart header
2049 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2050 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2056 if (is_object($file)) {
2057 $handle = $file->get_content_file_handle();
2059 $handle = fopen($file, 'rb');
2061 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2066 header('Accept-Ranges: none');
2069 header('Content-Length: '.$filesize);
2071 if ($filesize > 10000000) {
2072 // for large files try to flush and close all buffers to conserve memory
2073 while(@ob_get_level()) {
2074 if (!@ob_end_flush()) {
2080 // send the whole file content
2081 if (is_object($file)) {
2089 * Similar to readfile_accel() but designed for strings.
2090 * @param string $string
2091 * @param string $mimetype
2092 * @param bool $accelerate
2095 function readstring_accel($string, $mimetype, $accelerate) {
2098 if ($mimetype === 'text/plain') {
2099 // there is no encoding specified in text files, we need something consistent
2100 header('Content-Type: text/plain; charset=utf-8');
2102 header('Content-Type: '.$mimetype);
2104 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2105 header('Accept-Ranges: none');
2107 if ($accelerate and !empty($CFG->xsendfile)) {
2108 $fs = get_file_storage();
2109 if ($fs->xsendfile(sha1($string))) {
2114 header('Content-Length: '.strlen($string));
2119 * Handles the sending of temporary file to user, download is forced.
2120 * File is deleted after abort or successful sending, does not return, script terminated
2122 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2123 * @param string $filename proposed file name when saving file
2124 * @param bool $pathisstring If the path is string
2126 function send_temp_file($path, $filename, $pathisstring=false) {
2129 if (core_useragent::check_firefox_version('1.5')) {
2130 // only FF is known to correctly save to disk before opening...
2131 $mimetype = mimeinfo('type', $filename);
2133 $mimetype = 'application/x-forcedownload';
2136 // close session - not needed anymore
2137 session_get_instance()->write_close();
2139 if (!$pathisstring) {
2140 if (!file_exists($path)) {
2142 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2144 // executed after normal finish or abort
2145 @register_shutdown_function('send_temp_file_finished', $path);
2148 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2149 if (core_useragent::check_ie_version()) {
2150 $filename = urlencode($filename);
2153 header('Content-Disposition: attachment; filename="'.$filename.'"');
2154 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2155 header('Cache-Control: max-age=10');
2156 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2158 } else { //normal http - prevent caching at all cost
2159 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2160 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2161 header('Pragma: no-cache');
2164 // send the contents - we can not accelerate this because the file will be deleted asap
2165 if ($pathisstring) {
2166 readstring_accel($path, $mimetype, false);
2168 readfile_accel($path, $mimetype, false);
2172 die; //no more chars to output
2176 * Internal callback function used by send_temp_file()
2178 * @param string $path
2180 function send_temp_file_finished($path) {
2181 if (file_exists($path)) {
2187 * Handles the sending of file data to the user's browser, including support for
2191 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2192 * @param string $filename Filename to send
2193 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2194 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2195 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2196 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2197 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2198 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2199 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2200 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2201 * and should not be reopened.
2202 * @return null script execution stopped unless $dontdie is true
2204 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
2205 global $CFG, $COURSE;
2208 ignore_user_abort(true);
2211 // MDL-11789, apply $CFG->filelifetime here
2212 if ($lifetime === 'default') {
2213 if (!empty($CFG->filelifetime)) {
2214 $lifetime = $CFG->filelifetime;
2220 session_get_instance()->write_close(); // unlock session during fileserving
2222 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2223 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2224 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2225 $isFF = core_useragent::check_firefox_version('1.5'); // only FF > 1.5 properly tested
2226 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2227 ($mimetype ? $mimetype : mimeinfo('type', $filename));
2229 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2230 if (core_useragent::check_ie_version()) {
2231 $filename = rawurlencode($filename);
2234 if ($forcedownload) {
2235 header('Content-Disposition: attachment; filename="'.$filename.'"');
2237 header('Content-Disposition: inline; filename="'.$filename.'"');
2240 if ($lifetime > 0) {
2241 $nobyteserving = false;
2242 header('Cache-Control: max-age='.$lifetime);
2243 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2246 } else { // Do not cache files in proxies and browsers
2247 $nobyteserving = true;
2248 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2249 header('Cache-Control: max-age=10');
2250 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2252 } else { //normal http - prevent caching at all cost
2253 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2254 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2255 header('Pragma: no-cache');
2259 if (empty($filter)) {
2260 // send the contents
2261 if ($pathisstring) {
2262 readstring_accel($path, $mimetype, !$dontdie);
2264 readfile_accel($path, $mimetype, !$dontdie);
2268 // Try to put the file through filters
2269 if ($mimetype == 'text/html') {
2270 $options = new stdClass();
2271 $options->noclean = true;
2272 $options->nocache = true; // temporary workaround for MDL-5136
2273 $text = $pathisstring ? $path : implode('', file($path));
2275 $text = file_modify_html_header($text);
2276 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2278 readstring_accel($output, $mimetype, false);
2280 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2281 // only filter text if filter all files is selected
2282 $options = new stdClass();
2283 $options->newlines = false;
2284 $options->noclean = true;
2285 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
2286 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2288 readstring_accel($output, $mimetype, false);
2291 // send the contents
2292 if ($pathisstring) {
2293 readstring_accel($path, $mimetype, !$dontdie);
2295 readfile_accel($path, $mimetype, !$dontdie);
2302 die; //no more chars to output!!!
2306 * Handles the sending of file data to the user's browser, including support for
2309 * The $options parameter supports the following keys:
2310 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2311 * (string|null) filename - overrides the implicit filename
2312 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2313 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2314 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2315 * and should not be reopened.
2318 * @param stored_file $stored_file local file object
2319 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
2320 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2321 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2322 * @param array $options additional options affecting the file serving
2323 * @return null script execution stopped unless $options['dontdie'] is true
2325 function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, array $options=array()) {
2326 global $CFG, $COURSE;
2328 if (empty($options['filename'])) {
2331 $filename = $options['filename'];
2334 if (empty($options['dontdie'])) {
2340 if (!empty($options['preview'])) {
2341 // replace the file with its preview
2342 $fs = get_file_storage();
2343 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2344 if (!$preview_file) {
2345 // unable to create a preview of the file, send its default mime icon instead
2346 if ($options['preview'] === 'tinyicon') {
2348 } else if ($options['preview'] === 'thumb') {
2353 $fileicon = file_file_icon($stored_file, $size);
2354 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2356 // preview images have fixed cache lifetime and they ignore forced download
2357 // (they are generated by GD and therefore they are considered reasonably safe).
2358 $stored_file = $preview_file;
2359 $lifetime = DAYSECS;
2361 $forcedownload = false;
2365 // handle external resource
2366 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2367 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2371 if (!$stored_file or $stored_file->is_directory()) {
2380 ignore_user_abort(true);
2383 session_get_instance()->write_close(); // unlock session during fileserving
2385 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2386 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2387 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2388 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2389 $isFF = core_useragent::check_firefox_version('1.5'); // only FF > 1.5 properly tested
2390 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2391 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
2393 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2394 if (core_useragent::check_ie_version()) {
2395 $filename = rawurlencode($filename);
2398 if ($forcedownload) {
2399 header('Content-Disposition: attachment; filename="'.$filename.'"');
2401 header('Content-Disposition: inline; filename="'.$filename.'"');
2404 if ($lifetime > 0) {
2405 header('Cache-Control: max-age='.$lifetime);
2406 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2409 } else { // Do not cache files in proxies and browsers
2410 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
2411 header('Cache-Control: max-age=10');
2412 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2414 } else { //normal http - prevent caching at all cost
2415 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
2416 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2417 header('Pragma: no-cache');
2421 if (empty($filter)) {
2422 // send the contents
2423 readfile_accel($stored_file, $mimetype, !$dontdie);
2425 } else { // Try to put the file through filters
2426 if ($mimetype == 'text/html') {
2427 $options = new stdClass();
2428 $options->noclean = true;
2429 $options->nocache = true; // temporary workaround for MDL-5136
2430 $text = $stored_file->get_content();
2431 $text = file_modify_html_header($text);
2432 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2434 readstring_accel($output, $mimetype, false);
2436 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2437 // only filter text if filter all files is selected
2438 $options = new stdClass();
2439 $options->newlines = false;
2440 $options->noclean = true;
2441 $text = $stored_file->get_content();
2442 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2444 readstring_accel($output, $mimetype, false);
2446 } else { // Just send it out raw
2447 readfile_accel($stored_file, $mimetype, !$dontdie);
2453 die; //no more chars to output!!!
2457 * Retrieves an array of records from a CSV file and places
2458 * them into a given table structure
2460 * @global stdClass $CFG
2461 * @global moodle_database $DB
2462 * @param string $file The path to a CSV file
2463 * @param string $table The table to retrieve columns from
2464 * @return bool|array Returns an array of CSV records or false
2466 function get_records_csv($file, $table) {
2469 if (!$metacolumns = $DB->get_columns($table)) {
2473 if(!($handle = @fopen($file, 'r'))) {
2474 print_error('get_records_csv failed to open '.$file);
2477 $fieldnames = fgetcsv($handle, 4096);
2478 if(empty($fieldnames)) {
2485 foreach($metacolumns as $metacolumn) {
2486 $ord = array_search($metacolumn->name, $fieldnames);
2488 $columns[$metacolumn->name] = $ord;
2494 while (($data = fgetcsv($handle, 4096)) !== false) {
2495 $item = new stdClass;
2496 foreach($columns as $name => $ord) {
2497 $item->$name = $data[$ord];
2507 * Create a file with CSV contents
2509 * @global stdClass $CFG
2510 * @global moodle_database $DB
2511 * @param string $file The file to put the CSV content into
2512 * @param array $records An array of records to write to a CSV file
2513 * @param string $table The table to get columns from
2514 * @return bool success
2516 function put_records_csv($file, $records, $table = NULL) {
2519 if (empty($records)) {
2523 $metacolumns = NULL;
2524 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
2530 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
2531 print_error('put_records_csv failed to open '.$file);
2534 $proto = reset($records);
2535 if(is_object($proto)) {
2536 $fields_records = array_keys(get_object_vars($proto));
2538 else if(is_array($proto)) {
2539 $fields_records = array_keys($proto);
2546 if(!empty($metacolumns)) {
2547 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2548 $fields = array_intersect($fields_records, $fields_table);
2551 $fields = $fields_records;
2554 fwrite($fp, implode(',', $fields));
2555 fwrite($fp, "\r\n");
2557 foreach($records as $record) {
2558 $array = (array)$record;
2560 foreach($fields as $field) {
2561 if(strpos($array[$field], ',')) {
2562 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
2565 $values[] = $array[$field];
2568 fwrite($fp, implode(',', $values)."\r\n");
2572 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
2578 * Recursively delete the file or folder with path $location. That is,
2579 * if it is a file delete it. If it is a folder, delete all its content
2580 * then delete it. If $location does not exist to start, that is not
2581 * considered an error.
2583 * @param string $location the path to remove.
2586 function fulldelete($location) {
2587 if (empty($location)) {
2588 // extra safety against wrong param
2591 if (is_dir($location)) {
2592 if (!$currdir = opendir($location)) {
2595 while (false !== ($file = readdir($currdir))) {
2596 if ($file <> ".." && $file <> ".") {
2597 $fullfile = $location."/".$file;
2598 if (is_dir($fullfile)) {
2599 if (!fulldelete($fullfile)) {
2603 if (!unlink($fullfile)) {
2610 if (! rmdir($location)) {
2614 } else if (file_exists($location)) {
2615 if (!unlink($location)) {
2623 * Send requested byterange of file.
2625 * @param resource $handle A file handle
2626 * @param string $mimetype The mimetype for the output
2627 * @param array $ranges An array of ranges to send
2628 * @param string $filesize The size of the content if only one range is used
2630 function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2631 // better turn off any kind of compression and buffering
2632 @ini_set('zlib.output_compression', 'Off');
2634 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2635 if ($handle === false) {
2638 if (count($ranges) == 1) { //only one range requested
2639 $length = $ranges[0][2] - $ranges[0][1] + 1;
2640 header('HTTP/1.1 206 Partial content');
2641 header('Content-Length: '.$length);
2642 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2643 header('Content-Type: '.$mimetype);
2645 while(@ob_get_level()) {
2646 if (!@ob_end_flush()) {
2651 fseek($handle, $ranges[0][1]);
2652 while (!feof($handle) && $length > 0) {
2653 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2654 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2657 $length -= strlen($buffer);
2661 } else { // multiple ranges requested - not tested much
2663 foreach($ranges as $range) {
2664 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2666 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2667 header('HTTP/1.1 206 Partial content');
2668 header('Content-Length: '.$totallength);
2669 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2671 while(@ob_get_level()) {
2672 if (!@ob_end_flush()) {
2677 foreach($ranges as $range) {
2678 $length = $range[2] - $range[1] + 1;
2680 fseek($handle, $range[1]);
2681 while (!feof($handle) && $length > 0) {
2682 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2683 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2686 $length -= strlen($buffer);
2689 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2696 * add includes (js and css) into uploaded files
2697 * before returning them, useful for themes and utf.js includes
2699 * @global stdClass $CFG
2700 * @param string $text text to search and replace
2701 * @return string text with added head includes
2704 function file_modify_html_header($text) {
2705 // first look for <head> tag
2708 $stylesheetshtml = '';
2709 /* foreach ($CFG->stylesheets as $stylesheet) {
2711 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2715 if (filter_is_enabled('mediaplugin')) {
2716 // this script is needed by most media filter plugins.
2717 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
2718 $ufo = html_writer::tag('script', '', $attributes) . "\n";
2721 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2723 $replacement = '<head>'.$ufo.$stylesheetshtml;
2724 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
2728 // if not, look for <html> tag, and stick <head> right after
2729 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2731 // replace <html> tag with <html><head>includes</head>
2732 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
2733 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
2737 // if not, look for <body> tag, and stick <head> before body
2738 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2740 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
2741 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
2745 // if not, just stick a <head> tag at the beginning
2746 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2751 * RESTful cURL class
2753 * This is a wrapper class for curl, it is quite easy to use:
2757 * $c = new curl(array('cache'=>true));
2759 * $c = new curl(array('cookie'=>true));
2761 * $c = new curl(array('proxy'=>true));
2763 * // HTTP GET Method
2764 * $html = $c->get('http://example.com');
2765 * // HTTP POST Method
2766 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2767 * // HTTP PUT Method
2768 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
2771 * @package core_files
2773 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2774 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
2777 /** @var bool Caches http request contents */
2778 public $cache = false;
2779 /** @var bool Uses proxy, null means automatic based on URL */
2780 public $proxy = null;
2781 /** @var string library version */
2782 public $version = '0.4 dev';
2783 /** @var array http's response */
2784 public $response = array();
2785 /** @var array Raw response headers, needed for BC in download_file_content(). */
2786 public $rawresponse = array();
2787 /** @var array http header */
2788 public $header = array();
2789 /** @var string cURL information */
2791 /** @var string error */
2793 /** @var int error code */
2795 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2796 public $emulateredirects = null;
2798 /** @var array cURL options */
2800 /** @var string Proxy host */
2801 private $proxy_host = '';
2802 /** @var string Proxy auth */
2803 private $proxy_auth = '';
2804 /** @var string Proxy type */
2805 private $proxy_type = '';
2806 /** @var bool Debug mode on */
2807 private $debug = false;
2808 /** @var bool|string Path to cookie file */
2809 private $cookie = false;
2810 /** @var bool tracks multiple headers in response - redirect detection */
2811 private $responsefinished = false;
2816 * Allowed settings are:
2817 * proxy: (bool) use proxy server, null means autodetect non-local from url
2818 * debug: (bool) use debug output
2819 * cookie: (string) path to cookie file, false if none
2820 * cache: (bool) use cache
2821 * module_cache: (string) type of cache
2823 * @param array $settings
2825 public function __construct($settings = array()) {
2827 if (!function_exists('curl_init')) {
2828 $this->error = 'cURL module must be enabled!';
2829 trigger_error($this->error, E_USER_ERROR);
2833 // All settings of this class should be init here.
2835 if (!empty($settings['debug'])) {
2836 $this->debug = true;
2838 if (!empty($settings['cookie'])) {
2839 if($settings['cookie'] === true) {
2840 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2842 $this->cookie = $settings['cookie'];
2845 if (!empty($settings['cache'])) {
2846 if (class_exists('curl_cache')) {
2847 if (!empty($settings['module_cache'])) {
2848 $this->cache = new curl_cache($settings['module_cache']);
2850 $this->cache = new curl_cache('misc');
2854 if (!empty($CFG->proxyhost)) {
2855 if (empty($CFG->proxyport)) {
2856 $this->proxy_host = $CFG->proxyhost;
2858 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2860 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2861 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2862 $this->setopt(array(
2863 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2864 'proxyuserpwd'=>$this->proxy_auth));
2866 if (!empty($CFG->proxytype)) {
2867 if ($CFG->proxytype == 'SOCKS5') {
2868 $this->proxy_type = CURLPROXY_SOCKS5;
2870 $this->proxy_type = CURLPROXY_HTTP;
2871 $this->setopt(array('httpproxytunnel'=>false));
2873 $this->setopt(array('proxytype'=>$this->proxy_type));
2876 if (isset($settings['proxy'])) {
2877 $this->proxy = $settings['proxy'];
2880 $this->proxy = false;
2883 if (!isset($this->emulateredirects)) {
2884 $this->emulateredirects = (ini_get('open_basedir') or ini_get('safe_mode'));
2889 * Resets the CURL options that have already been set
2891 public function resetopt() {
2892 $this->options = array();
2893 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2894 // True to include the header in the output
2895 $this->options['CURLOPT_HEADER'] = 0;
2896 // True to Exclude the body from the output
2897 $this->options['CURLOPT_NOBODY'] = 0;
2898 // Redirect ny default.
2899 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
2900 $this->options['CURLOPT_MAXREDIRS'] = 10;
2901 $this->options['CURLOPT_ENCODING'] = '';
2902 // TRUE to return the transfer as a string of the return
2903 // value of curl_exec() instead of outputting it out directly.
2904 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2905 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2906 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
2907 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
2909 if ($cacert = self::get_cacert()) {
2910 $this->options['CURLOPT_CAINFO'] = $cacert;
2915 * Get the location of ca certificates.
2916 * @return string absolute file path or empty if default used
2918 public static function get_cacert() {
2921 // Bundle in dataroot always wins.
2922 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2923 return realpath("$CFG->dataroot/moodleorgca.crt");
2926 // Next comes the default from php.ini
2927 $cacert = ini_get('curl.cainfo');
2928 if (!empty($cacert) and is_readable($cacert)) {
2929 return realpath($cacert);
2932 // Windows PHP does not have any certs, we need to use something.
2933 if ($CFG->ostype === 'WINDOWS') {
2934 if (is_readable("$CFG->libdir/cacert.pem")) {
2935 return realpath("$CFG->libdir/cacert.pem");
2939 // Use default, this should work fine on all properly configured *nix systems.
2946 public function resetcookie() {
2947 if (!empty($this->cookie)) {
2948 if (is_file($this->cookie)) {
2949 $fp = fopen($this->cookie, 'w');
2961 * Do not use the curl constants to define the options, pass a string
2962 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2963 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2965 * @param array $options If array is null, this function will reset the options to default value.
2967 * @throws coding_exception If an option uses constant value instead of option name.
2969 public function setopt($options = array()) {
2970 if (is_array($options)) {
2971 foreach ($options as $name => $val) {
2972 if (!is_string($name)) {
2973 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2975 if (stripos($name, 'CURLOPT_') === false) {
2976 $name = strtoupper('CURLOPT_'.$name);
2978 $name = strtoupper($name);
2980 $this->options[$name] = $val;
2988 public function cleanopt() {
2989 unset($this->options['CURLOPT_HTTPGET']);
2990 unset($this->options['CURLOPT_POST']);
2991 unset($this->options['CURLOPT_POSTFIELDS']);
2992 unset($this->options['CURLOPT_PUT']);
2993 unset($this->options['CURLOPT_INFILE']);
2994 unset($this->options['CURLOPT_INFILESIZE']);
2995 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2996 unset($this->options['CURLOPT_FILE']);
3000 * Resets the HTTP Request headers (to prepare for the new request)
3002 public function resetHeader() {
3003 $this->header = array();
3007 * Set HTTP Request Header
3009 * @param array $header
3011 public function setHeader($header) {
3012 if (is_array($header)) {
3013 foreach ($header as $v) {
3014 $this->setHeader($v);
3017 // Remove newlines, they are not allowed in headers.
3018 $this->header[] = preg_replace('/[\r\n]/', '', $header);
3023 * Get HTTP Response Headers
3024 * @return array of arrays
3026 public function getResponse() {
3027 return $this->response;
3031 * Get raw HTTP Response Headers
3032 * @return array of strings
3034 public function get_raw_response() {
3035 return $this->rawresponse;
3039 * private callback function
3040 * Formatting HTTP Response Header
3042 * @param resource $ch Apparently not used
3043 * @param string $header
3044 * @return int The strlen of the header
3046 private function formatHeader($ch, $header) {
3047 $this->rawresponse[] = $header;
3049 if (trim($header, "\r\n") === '') {
3050 if ($this->responsefinished) {
3051 // Multiple headers means redirect, keep just the latest one.
3052 $this->response = array();
3053 return strlen($header);
3055 $this->responsefinished = true;
3058 if (strlen($header) > 2) {
3059 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3060 $key = rtrim($key, ':');
3061 if (!empty($this->response[$key])) {
3062 if (is_array($this->response[$key])) {
3063 $this->response[$key][] = $value;
3065 $tmp = $this->response[$key];
3066 $this->response[$key] = array();
3067 $this->response[$key][] = $tmp;
3068 $this->response[$key][] = $value;
3072 $this->response[$key] = $value;
3075 return strlen($header);
3079 * Set options for individual curl instance
3081 * @param resource $curl A curl handle
3082 * @param array $options
3083 * @return resource The curl handle
3085 private function apply_opt($curl, $options) {
3086 // Some more security first.
3087 if (defined('CURLOPT_PROTOCOLS')) {
3088 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3090 if (defined('CURLOPT_REDIR_PROTOCOLS')) {
3091 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3097 if (!empty($this->cookie) || !empty($options['cookie'])) {
3098 $this->setopt(array('cookiejar'=>$this->cookie,
3099 'cookiefile'=>$this->cookie
3103 // Bypass proxy if required.
3104 if ($this->proxy === null) {
3105 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3111 $proxy = (bool)$this->proxy;
3116 $options['CURLOPT_PROXY'] = $this->proxy_host;
3118 unset($this->options['CURLOPT_PROXY']);
3121 $this->setopt($options);
3122 // reset before set options
3123 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3125 if (empty($this->header)) {
3126 $this->setHeader(array(
3127 'User-Agent: MoodleBot/1.0',
3128 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3129 'Connection: keep-alive'
3132 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3135 echo '<h1>Options</h1>';
3136 var_dump($this->options);
3137 echo '<h1>Header</h1>';
3138 var_dump($this->header);
3141 // Do not allow infinite redirects.
3142 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3143 $this->options['CURLOPT_MAXREDIRS'] = 0;
3144 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3145 $this->options['CURLOPT_MAXREDIRS'] = 100;
3147 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3150 // Make sure we always know if redirects expected.
3151 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3152 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3156 foreach($this->options as $name => $val) {
3157 if ($name === 'CURLOPT_PROTOCOLS' or $name === 'CURLOPT_REDIR_PROTOCOLS') {
3158 // These can not be changed, sorry.
3161 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3162 // The redirects are emulated elsewhere.
3163 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3166 $name = constant($name);
3167 curl_setopt($curl, $name, $val);
3174 * Download multiple files in parallel
3176 * Calls {@link multi()} with specific download headers
3180 * $file1 = fopen('a', 'wb');
3181 * $file2 = fopen('b', 'wb');
3182 * $c->download(array(
3183 * array('url'=>'http://localhost/', 'file'=>$file1),
3184 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3194 * $c->download(array(
3195 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3196 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3200 * @param array $requests An array of files to request {
3201 * url => url to download the file [required]
3202 * file => file handler, or
3203 * filepath => file path
3205 * If 'file' and 'filepath' parameters are both specified in one request, the
3206 * open file handle in the 'file' parameter will take precedence and 'filepath'
3209 * @param array $options An array of options to set
3210 * @return array An array of results
3212 public function download($requests, $options = array()) {
3213 $options['RETURNTRANSFER'] = false;
3214 return $this->multi($requests, $options);
3218 * Multi HTTP Requests
3219 * This function could run multi-requests in parallel.
3221 * @param array $requests An array of files to request
3222 * @param array $options An array of options to set
3223 * @return array An array of results
3225 protected function multi($requests, $options = array()) {
3226 $count = count($requests);
3229 $main = curl_multi_init();
3230 for ($i = 0; $i < $count; $i++) {
3231 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3233 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3234 $requests[$i]['auto-handle'] = true;
3236 foreach($requests[$i] as $n=>$v) {
3239 $handles[$i] = curl_init($requests[$i]['url']);
3240 $this->apply_opt($handles[$i], $options);
3241 curl_multi_add_handle($main, $handles[$i]);
3245 curl_multi_exec($main, $running);
3246 } while($running > 0);
3247 for ($i = 0; $i < $count; $i++) {
3248 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3251 $results[] = curl_multi_getcontent($handles[$i]);
3253 curl_multi_remove_handle($main, $handles[$i]);
3255 curl_multi_close($main);
3257 for ($i = 0; $i < $count; $i++) {
3258 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3259 // close file handler if file is opened in this function
3260 fclose($requests[$i]['file']);
3267 * Single HTTP Request
3269 * @param string $url The URL to request
3270 * @param array $options
3273 protected function request($url, $options = array()) {
3274 // create curl instance
3275 $curl = curl_init($url);
3276 $options['url'] = $url;
3278 // Reset here so that the data is valid when result returned from cache.
3279 $this->info = array();
3282 $this->response = array();
3283 $this->rawresponse = array();
3284 $this->responsefinished = false;
3286 $this->apply_opt($curl, $options);
3287 if ($this->cache && $ret = $this->cache->get($this->options)) {
3291 $ret = curl_exec($curl);
3292 $this->info = curl_getinfo($curl);
3293 $this->error = curl_error($curl);
3294 $this->errno = curl_errno($curl);
3295 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3297 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3300 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3302 if ($this->info['http_code'] == 301) {
3303 // Moved Permanently - repeat the same request on new URL.
3305 } else if ($this->info['http_code'] == 302) {
3306 // Found - the standard redirect - repeat the same request on new URL.
3308 } else if ($this->info['http_code'] == 303) {
3309 // 303 See Other - repeat only if GET, do not bother with POSTs.
3310 if (empty($this->options['CURLOPT_HTTPGET'])) {
3314 } else if ($this->info['http_code'] == 307) {
3315 // Temporary Redirect - must repeat using the same request type.
3317 } else if ($this->info['http_code'] == 308) {
3318 // Permanent Redirect - must repeat using the same request type.
3321 // Some other http code means do not retry!
3327 $redirecturl = null;
3328 if (isset($this->info['redirect_url'])) {
3329 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3330 $redirecturl = $this->info['redirect_url'];
3333 if (!$redirecturl) {
3334 foreach ($this->response as $k => $v) {
3335 if (strtolower($k) === 'location') {
3340 if (preg_match('|^https?://|i', $redirecturl)) {
3341 // Great, this is the correct location format!
3343 } else if ($redirecturl) {
3344 $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3345 if (strpos($redirecturl, '/') === 0) {
3346 // Relative to server root - just guess.
3347 $pos = strpos('/', $current, 8);
3348 if ($pos === false) {
3349 $redirecturl = $current.$redirecturl;
3351 $redirecturl = substr($current, 0, $pos).$redirecturl;
3354 // Relative to current script.
3355 $redirecturl = dirname($current).'/'.$redirecturl;
3360 $this->responsefinished = false;
3361 $this->response = array();
3363 curl_setopt($curl, CURLOPT_URL, $redirecturl);
3364 $ret = curl_exec($curl);
3366 $this->info = curl_getinfo($curl);
3367 $this->error = curl_error($curl);
3368 $this->errno = curl_errno($curl);
3370 $this->info['redirect_count'] = $redirects;
3372 if ($this->info['http_code'] === 200) {
3373 // Finally this is what we wanted.
3376 if ($this->errno != CURLE_OK) {
3377 // Something wrong is going on.
3381 if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3382 $this->errno = CURLE_TOO_MANY_REDIRECTS;
3383 $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3388 $this->cache->set($this->options, $ret);
3392 echo '<h1>Return Data</h1>';
3394 echo '<h1>Info</h1>';
3395 var_dump($this->info);
3396 echo '<h1>Error</h1>';
3397 var_dump($this->error);
3402 if (empty($this->error)) {
3405 return $this->error;
3406 // exception is not ajax friendly
3407 //throw new moodle_exception($this->error, 'curl');
3416 * @param string $url
3417 * @param array $options
3420 public function head($url, $options = array()) {
3421 $options['CURLOPT_HTTPGET'] = 0;
3422 $options['CURLOPT_HEADER'] = 1;
3423 $options['CURLOPT_NOBODY'] = 1;
3424 return $this->request($url, $options);
3430 * @param string $url
3431 * @param array|string $params
3432 * @param array $options
3435 public function post($url, $params = '', $options = array()) {
3436 $options['CURLOPT_POST'] = 1;
3437 if (is_array($params)) {
3438 $this->_tmp_file_post_params = array();
3439 foreach ($params as $key => $value) {
3440 if ($value instanceof stored_file) {
3441 $value->add_to_curl_request($this, $key);
3443 $this->_tmp_file_post_params[$key] = $value;
3446 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3447 unset($this->_tmp_file_post_params);
3449 // $params is the raw post data
3450 $options['CURLOPT_POSTFIELDS'] = $params;
3452 return $this->request($url, $options);
3458 * @param string $url
3459 * @param array $params
3460 * @param array $options
3463 public function get($url, $params = array(), $options = array()) {
3464 $options['CURLOPT_HTTPGET'] = 1;
3466 if (!empty($params)) {
3467 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3468 $url .= http_build_query($params, '', '&');
3470 return $this->request($url, $options);
3474 * Downloads one file and writes it to the specified file handler
3478 * $file = fopen('savepath', 'w');
3479 * $result = $c->download_one('http://localhost/', null,
3480 * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3482 * $download_info = $c->get_info();
3483 * if ($result === true) {
3484 * // file downloaded successfully
3486 * $error_text = $result;
3487 * $error_code = $c->get_errno();
3493 * $result = $c->download_one('http://localhost/', null,
3494 * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3495 * // ... see above, no need to close handle and remove file if unsuccessful
3498 * @param string $url
3499 * @param array|null $params key-value pairs to be added to $url as query string
3500 * @param array $options request options. Must include either 'file' or 'filepath'
3501 * @return bool|string true on success or error string on failure
3503 public function download_one($url, $params, $options = array()) {
3504 $options['CURLOPT_HTTPGET'] = 1;
3505 if (!empty($params)) {
3506 $url .= (stripos($url, '?') !== false) ? '&' : '?';
3507 $url .= http_build_query($params, '', '&');
3509 if (!empty($options['filepath']) && empty($options['file'])) {
3511 if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3513 return get_string('cannotwritefile