MDL-43063 core: fix phpdoc comment codechecker issue.
[moodle.git] / lib / filelib.php
CommitLineData
64a19b38 1<?php
64a19b38 2// This file is part of Moodle - http://moodle.org/
3//
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.
8//
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.
13//
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/>.
edc0c493 16
17/**
18 * Functions for file handling.
19 *
d2b7803e
DC
20 * @package core_files
21 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
edc0c493 23 */
24
64f93798
PS
25defined('MOODLE_INTERNAL') || die();
26
d2b7803e
DC
27/**
28 * BYTESERVING_BOUNDARY - string unique string constant.
29 */
edc0c493 30define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
4c8c65ec 31
68acd115
FM
32/**
33 * Unlimited area size constant
34 */
35define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
36
64f93798
PS
37require_once("$CFG->libdir/filestorage/file_exceptions.php");
38require_once("$CFG->libdir/filestorage/file_storage.php");
39require_once("$CFG->libdir/filestorage/zip_packer.php");
40require_once("$CFG->libdir/filebrowser/file_browser.php");
172dd12c 41
4eef1399 42/**
43 * Encodes file serving url
ba21c9d4 44 *
f28ee49e
PS
45 * @deprecated use moodle_url factory methods instead
46 *
d2b7803e
DC
47 * @todo MDL-31071 deprecate this function
48 * @global stdClass $CFG
4eef1399 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
54 */
55function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
56 global $CFG;
57
f28ee49e
PS
58//TODO: deprecate this
59
4eef1399 60 if ($CFG->slasharguments) {
61 $parts = explode('/', $path);
62 $parts = array_map('rawurlencode', $parts);
63 $path = implode('/', $parts);
64 $return = $urlbase.$path;
65 if ($forcedownload) {
66 $return .= '?forcedownload=1';
67 }
68 } else {
69 $path = rawurlencode($path);
70 $return = $urlbase.'?file='.$path;
71 if ($forcedownload) {
72 $return .= '&amp;forcedownload=1';
73 }
74 }
75
76 if ($https) {
77 $return = str_replace('http://', 'https://', $return);
78 }
79
80 return $return;
81}
82
4db9d482
PS
83/**
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.
87 *
88 * @param context $context
89 * @param string $component
90 * @param string $filearea
91 * @param string $itemid
92 * @return bool
93 */
94function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
95 global $DB;
96
97 if (!isset($itemid)) {
98 // Not initialised yet.
99 return false;
100 }
101
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);
106}
107
c94882ff 108/**
db2cc99b 109 * Prepares 'editor' formslib element from data in database
ba21c9d4 110 *
db2cc99b 111 * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
34ff25a6
PS
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
db2cc99b 114 * displayed.
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.
117 *
d2b7803e
DC
118 * @category files
119 * @param stdClass $data database field that holds the html text with embedded media
34ff25a6 120 * @param string $field the name of the database field that holds the html text with embedded media
db2cc99b 121 * @param array $options editor options (like maxifiles, maxbytes etc.)
d2b7803e 122 * @param stdClass $context context of the editor
64f93798 123 * @param string $component
c94882ff 124 * @param string $filearea file area name
125 * @param int $itemid item id, required if item exists
d2b7803e 126 * @return stdClass modified data object
c94882ff 127 */
64f93798 128function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
c94882ff 129 $options = (array)$options;
130 if (!isset($options['trusttext'])) {
131 $options['trusttext'] = false;
132 }
133 if (!isset($options['forcehttps'])) {
134 $options['forcehttps'] = false;
135 }
136 if (!isset($options['subdirs'])) {
137 $options['subdirs'] = false;
138 }
989c16ee 139 if (!isset($options['maxfiles'])) {
140 $options['maxfiles'] = 0; // no files by default
141 }
b96ddb7d 142 if (!isset($options['noclean'])) {
143 $options['noclean'] = false;
144 }
c94882ff 145
f9157eb7
RT
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);
157 }
158 }
32dc8ecd 159
d5934b35 160 if (is_null($itemid) or is_null($context)) {
c94882ff 161 $contextid = null;
d5934b35 162 $itemid = null;
b85b25eb
PS
163 if (!isset($data)) {
164 $data = new stdClass();
165 }
c94882ff 166 if (!isset($data->{$field})) {
167 $data->{$field} = '';
168 }
169 if (!isset($data->{$field.'format'})) {
20e5da7d 170 $data->{$field.'format'} = editors_get_preferred_format();
b96ddb7d 171 }
172 if (!$options['noclean']) {
173 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
c94882ff 174 }
c94882ff 175
176 } else {
177 if ($options['trusttext']) {
b96ddb7d 178 // noclean ignored if trusttext enabled
c94882ff 179 if (!isset($data->{$field.'trust'})) {
180 $data->{$field.'trust'} = 0;
181 }
182 $data = trusttext_pre_edit($data, $field, $context);
183 } else {
b96ddb7d 184 if (!$options['noclean']) {
185 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
186 }
c94882ff 187 }
188 $contextid = $context->id;
189 }
190
989c16ee 191 if ($options['maxfiles'] != 0) {
192 $draftid_editor = file_get_submitted_draft_itemid($field);
64f93798 193 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
989c16ee 194 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
195 } else {
8302aae1 196 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
989c16ee 197 }
c94882ff 198
199 return $data;
200}
201
202/**
34ff25a6 203 * Prepares the content of the 'editor' form element with embedded media files to be saved in database
ba21c9d4 204 *
19fbc617 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
34ff25a6 211 * foobartrust, where foobar has URL to embedded files encoded.
19fbc617 212 *
d2b7803e
DC
213 * @category files
214 * @param stdClass $data raw data submitted by the form
34ff25a6 215 * @param string $field name of the database field containing the html with embedded media files
19fbc617 216 * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
d2b7803e
DC
217 * @param stdClass $context context, required for existing data
218 * @param string $component file component
c94882ff 219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
d2b7803e 221 * @return stdClass modified data object
c94882ff 222 */
64f93798 223function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
c94882ff 224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
227 }
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
230 }
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
233 }
234 if (!isset($options['maxfiles'])) {
85db95e7 235 $options['maxfiles'] = 0; // no files by default
c94882ff 236 }
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
239 }
240
241 if ($options['trusttext']) {
19fbc617 242 $data->{$field.'trust'} = trusttext_trusted($context);
c94882ff 243 } else {
19fbc617 244 $data->{$field.'trust'} = 0;
c94882ff 245 }
246
85db95e7 247 $editor = $data->{$field.'_editor'};
c94882ff 248
9057a848 249 if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
989c16ee 250 $data->{$field} = $editor['text'];
7f0fedc0 251 } else {
64f93798 252 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
989c16ee 253 }
c94882ff 254 $data->{$field.'format'} = $editor['format'];
255
256 return $data;
257}
258
259/**
260 * Saves text and files modified by Editor formslib element
ba21c9d4 261 *
d2b7803e
DC
262 * @category files
263 * @param stdClass $data $database entry field
c94882ff 264 * @param string $field name of data field
265 * @param array $options various options
d2b7803e 266 * @param stdClass $context context - must already exist
64f93798 267 * @param string $component
c94882ff 268 * @param string $filearea file area name
269 * @param int $itemid must already exist, usually means data is in db
d2b7803e 270 * @return stdClass modified data obejct
c94882ff 271 */
64f93798 272function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
c94882ff 273 $options = (array)$options;
274 if (!isset($options['subdirs'])) {
275 $options['subdirs'] = false;
276 }
d5934b35 277 if (is_null($itemid) or is_null($context)) {
278 $itemid = null;
c94882ff 279 $contextid = null;
280 } else {
281 $contextid = $context->id;
282 }
283
85db95e7 284 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
64f93798 285 file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
85db95e7 286 $data->{$field.'_filemanager'} = $draftid_editor;
c94882ff 287
288 return $data;
289}
290
291/**
292 * Saves files modified by File manager formslib element
ba21c9d4 293 *
d2b7803e
DC
294 * @todo MDL-31073 review this function
295 * @category files
296 * @param stdClass $data $database entry field
c94882ff 297 * @param string $field name of data field
298 * @param array $options various options
d2b7803e 299 * @param stdClass $context context - must already exist
64f93798 300 * @param string $component
c94882ff 301 * @param string $filearea file area name
302 * @param int $itemid must already exist, usually means data is in db
d2b7803e 303 * @return stdClass modified data obejct
c94882ff 304 */
64f93798 305function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
c94882ff 306 $options = (array)$options;
307 if (!isset($options['subdirs'])) {
308 $options['subdirs'] = false;
309 }
310 if (!isset($options['maxfiles'])) {
311 $options['maxfiles'] = -1; // unlimited
312 }
313 if (!isset($options['maxbytes'])) {
314 $options['maxbytes'] = 0; // unlimited
315 }
316
85db95e7 317 if (empty($data->{$field.'_filemanager'})) {
c94882ff 318 $data->$field = '';
319
320 } else {
64f93798 321 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
c94882ff 322 $fs = get_file_storage();
323
64f93798
PS
324 if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
325 $data->$field = '1'; // TODO: this is an ugly hack (skodak)
c94882ff 326 } else {
327 $data->$field = '';
328 }
329 }
330
331 return $data;
332}
333
8546def3 334/**
d2b7803e 335 * Generate a draft itemid
ba21c9d4 336 *
d2b7803e
DC
337 * @category files
338 * @global moodle_database $DB
339 * @global stdClass $USER
509f67e3 340 * @return int a random but available draft itemid that can be used to create a new draft
edc0c493 341 * file area.
8546def3 342 */
edc0c493 343function file_get_unused_draft_itemid() {
8546def3 344 global $DB, $USER;
345
346 if (isguestuser() or !isloggedin()) {
85db95e7 347 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
8546def3 348 print_error('noguest');
349 }
350
b0c6dc1c 351 $contextid = context_user::instance($USER->id)->id;
8546def3 352
353 $fs = get_file_storage();
354 $draftitemid = rand(1, 999999999);
64f93798 355 while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
8546def3 356 $draftitemid = rand(1, 999999999);
357 }
358
b933a139 359 return $draftitemid;
8546def3 360}
361
7983d682 362/**
edc0c493 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');
ba21c9d4 366 *
d2b7803e
DC
367 * @category files
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.
64f93798 372 * @param string $component
edc0c493 373 * @param string $filearea helps indentify the file area.
d2b7803e 374 * @param int $itemid helps identify the file area. Can be null if there are no files yet.
33374f76 375 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
edc0c493 376 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
d2b7803e 377 * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
7983d682 378 */
64f93798 379function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
893fe4b6 380 global $CFG, $USER, $CFG;
7983d682 381
a19a06d0 382 $options = (array)$options;
383 if (!isset($options['subdirs'])) {
384 $options['subdirs'] = false;
385 }
33374f76 386 if (!isset($options['forcehttps'])) {
a19a06d0 387 $options['forcehttps'] = false;
388 }
389
b0c6dc1c 390 $usercontext = context_user::instance($USER->id);
b933a139 391 $fs = get_file_storage();
392
393 if (empty($draftitemid)) {
394 // create a new area and copy existing files into
edc0c493 395 $draftitemid = file_get_unused_draft_itemid();
64f93798
PS
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)) {
b933a139 398 foreach ($files as $file) {
64f93798
PS
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
402 continue;
403 }
a19a06d0 404 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
b5b188ce 405 continue;
406 }
67233725 407 $draftfile = $fs->create_file_from_storedfile($file_record, $file);
61506a0a 408 // XXX: This is a hack for file manager (MDL-28666)
67233725
DC
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
b933a139 426 }
427 }
893fe4b6
PS
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);
433 }
b933a139 434 } else {
435 // nothing to do
436 }
437
438 if (is_null($text)) {
439 return null;
440 }
441
edc0c493 442 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
64f93798 443 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
644d506a 444}
445
446/**
edc0c493 447 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
ba21c9d4 448 *
d2b7803e
DC
449 * @category files
450 * @global stdClass $CFG
edc0c493 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.
d2b7803e 453 * @param int $contextid This parameter and the next two identify the file area to use.
64f93798 454 * @param string $component
34ff25a6 455 * @param string $filearea helps identify the file area.
d2b7803e 456 * @param int $itemid helps identify the file area.
33374f76 457 * @param array $options text and file options ('forcehttps'=>false)
edc0c493 458 * @return string the processed text.
644d506a 459 */
64f93798 460function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
644d506a 461 global $CFG;
b933a139 462
33374f76
MH
463 $options = (array)$options;
464 if (!isset($options['forcehttps'])) {
465 $options['forcehttps'] = false;
466 }
467
edc0c493 468 if (!$CFG->slasharguments) {
469 $file = $file . '?file=';
b933a139 470 }
8546def3 471
64f93798 472 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
7d2948bd 473
474 if ($itemid !== null) {
475 $baseurl .= "$itemid/";
476 }
edc0c493 477
33374f76 478 if ($options['forcehttps']) {
edc0c493 479 $baseurl = str_replace('http://', 'https://', $baseurl);
b933a139 480 }
481
edc0c493 482 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
b933a139 483}
484
12fab708 485/**
edc0c493 486 * Returns information about files in a draft area.
ba21c9d4 487 *
d2b7803e
DC
488 * @global stdClass $CFG
489 * @global stdClass $USER
490 * @param int $draftitemid the draft area item id.
638d72cd 491 * @param string $filepath path to the directory from which the information have to be retrieved.
edc0c493 492 * @return array with the following entries:
493 * 'filecount' => number of files in the draft area.
638d72cd
FM
494 * 'filesize' => total size of the files in the draft area.
495 * 'foldercount' => number of folders in the draft area.
7aff4683 496 * 'filesize_without_references' => total size of the area excluding file references.
edc0c493 497 * (more information will be added as needed).
12fab708 498 */
638d72cd 499function file_get_draft_area_info($draftitemid, $filepath = '/') {
12fab708 500 global $CFG, $USER;
501
b0c6dc1c 502 $usercontext = context_user::instance($USER->id);
12fab708 503 $fs = get_file_storage();
504
638d72cd
FM
505 $results = array(
506 'filecount' => 0,
507 'foldercount' => 0,
7aff4683 508 'filesize' => 0,
212dac27 509 'filesize_without_references' => 0
638d72cd 510 );
edc0c493 511
638d72cd
FM
512 if ($filepath != '/') {
513 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
514 } else {
515 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
516 }
529377b5 517 foreach ($draftfiles as $file) {
638d72cd
FM
518 if ($file->is_directory()) {
519 $results['foldercount'] += 1;
520 } else {
521 $results['filecount'] += 1;
522 }
7aff4683
FM
523
524 $filesize = $file->get_filesize();
525 $results['filesize'] += $filesize;
526 if (!$file->is_external_file()) {
527 $results['filesize_without_references'] += $filesize;
528 }
529377b5 529 }
b6accf69
DC
530
531 return $results;
532}
533
21e3ea77
FM
534/**
535 * Returns whether a draft area has exceeded/will exceed its size limit.
536 *
68acd115
FM
537 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
538 *
21e3ea77
FM
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.
7aff4683 542 * @param bool $includereferences true to include the size of the references in the area size.
21e3ea77 543 * @return bool true if the area will/has exceeded its limit.
5bcfd504 544 * @since Moodle 2.4
21e3ea77 545 */
7aff4683 546function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
68acd115 547 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
21e3ea77 548 $draftinfo = file_get_draft_area_info($draftitemid);
7aff4683
FM
549 $areasize = $draftinfo['filesize_without_references'];
550 if ($includereferences) {
551 $areasize = $draftinfo['filesize'];
552 }
553 if ($areasize + $newfilesize > $areamaxbytes) {
21e3ea77
FM
554 return true;
555 }
556 }
557 return false;
558}
559
ea1780ad
DC
560/**
561 * Get used space of files
d2b7803e
DC
562 * @global moodle_database $DB
563 * @global stdClass $USER
34ff25a6 564 * @return int total bytes
ea1780ad
DC
565 */
566function file_get_user_used_space() {
e35194be 567 global $DB, $USER;
ea1780ad 568
b0c6dc1c 569 $usercontext = context_user::instance($USER->id);
e35194be
DC
570 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
571 JOIN (SELECT contenthash, filename, MAX(id) AS id
572 FROM {files}
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;
ea1780ad 578}
f0e5f031 579
580/**
581 * Convert any string to a valid filepath
d2b7803e 582 * @todo review this function
f0e5f031 583 * @param string $str
584 * @return string path
585 */
caf16a57 586function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
f36cb951
DC
587 if ($str == '/' or empty($str)) {
588 return '/';
589 } else {
caf16a57 590 return '/'.trim($str, '/').'/';
f36cb951 591 }
f0e5f031 592}
593
594/**
34ff25a6 595 * Generate a folder tree of draft area of current USER recursively
d2b7803e
DC
596 *
597 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
598 * @param int $draftitemid
f0e5f031 599 * @param string $filepath
d2b7803e 600 * @param mixed $data
f0e5f031 601 */
64f93798 602function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
f0e5f031 603 global $USER, $OUTPUT, $CFG;
604 $data->children = array();
b0c6dc1c 605 $context = context_user::instance($USER->id);
f0e5f031 606 $fs = get_file_storage();
64f93798 607 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
f0e5f031 608 foreach ($files as $file) {
609 if ($file->is_directory()) {
6bdfef5d 610 $item = new stdClass();
f79321f1 611 $item->sortorder = $file->get_sortorder();
f0e5f031 612 $item->filepath = $file->get_filepath();
613
614 $foldername = explode('/', trim($item->filepath, '/'));
615 $item->fullname = trim(array_pop($foldername), '/');
616
617 $item->id = uniqid();
64f93798 618 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
f0e5f031 619 $data->children[] = $item;
620 } else {
621 continue;
622 }
623 }
624 }
625}
626
627/**
628 * Listing all files (including folders) in current path (draft area)
629 * used by file manager
630 * @param int $draftitemid
631 * @param string $filepath
d2b7803e 632 * @return stdClass
f0e5f031 633 */
64f93798 634function file_get_drafarea_files($draftitemid, $filepath = '/') {
f0e5f031 635 global $USER, $OUTPUT, $CFG;
636
b0c6dc1c 637 $context = context_user::instance($USER->id);
f0e5f031 638 $fs = get_file_storage();
639
6bdfef5d 640 $data = new stdClass();
f0e5f031 641 $data->path = array();
642 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
643
644 // will be used to build breadcrumb
e709ddd2 645 $trail = '/';
f0e5f031 646 if ($filepath !== '/') {
647 $filepath = file_correct_filepath($filepath);
648 $parts = explode('/', $filepath);
649 foreach ($parts as $part) {
650 if ($part != '' && $part != null) {
e709ddd2 651 $trail .= ($part.'/');
f0e5f031 652 $data->path[] = array('name'=>$part, 'path'=>$trail);
653 }
654 }
655 }
656
657 $list = array();
f79321f1 658 $maxlength = 12;
64f93798 659 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
f0e5f031 660 foreach ($files as $file) {
6bdfef5d 661 $item = new stdClass();
f0e5f031 662 $item->filename = $file->get_filename();
663 $item->filepath = $file->get_filepath();
664 $item->fullname = trim($item->filename, '/');
665 $filesize = $file->get_filesize();
e709ddd2 666 $item->size = $filesize ? $filesize : null;
f0e5f031 667 $item->filesize = $filesize ? display_size($filesize) : '';
668
f79321f1 669 $item->sortorder = $file->get_sortorder();
e709ddd2
MG
670 $item->author = $file->get_author();
671 $item->license = $file->get_license();
672 $item->datemodified = $file->get_timemodified();
673 $item->datecreated = $file->get_timecreated();
9a62f779 674 $item->isref = $file->is_external_file();
0b2bfbd1
MG
675 if ($item->isref && $file->get_status() == 666) {
676 $item->originalmissing = true;
677 }
6dd299be
MG
678 // find the file this draft file was created from and count all references in local
679 // system pointing to that file
83d2700e 680 $source = @unserialize($file->get_source());
6dd299be
MG
681 if (isset($source->original)) {
682 $item->refcount = $fs->search_references_count($source->original);
683 }
f0e5f031 684
f0e5f031 685 if ($file->is_directory()) {
686 $item->filesize = 0;
559276b1 687 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
f0e5f031 688 $item->type = 'folder';
689 $foldername = explode('/', trim($item->filepath, '/'));
690 $item->fullname = trim(array_pop($foldername), '/');
559276b1 691 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
f0e5f031 692 } else {
64f93798 693 // do NOT use file browser here!
559276b1 694 $item->mimetype = get_mimetype_description($file);
ff32444a 695 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
559276b1
MG
696 $item->type = 'zip';
697 } else {
698 $item->type = 'file';
699 }
dafe1296
DM
700 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
701 $item->url = $itemurl->out();
559276b1
MG
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);
dafe1296 704 if ($imageinfo = $file->get_imageinfo()) {
3333e7e2
DM
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()));
dafe1296
DM
707 $item->image_width = $imageinfo['width'];
708 $item->image_height = $imageinfo['height'];
709 }
f0e5f031 710 }
711 $list[] = $item;
712 }
713 }
714 $data->itemid = $draftitemid;
715 $data->list = $list;
716 return $data;
717}
718
3156b8ca 719/**
edc0c493 720 * Returns draft area itemid for a given element.
ba21c9d4 721 *
d2b7803e 722 * @category files
edc0c493 723 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
d2b7803e 724 * @return int the itemid, or 0 if there is not one yet.
3156b8ca 725 */
edc0c493 726function file_get_submitted_draft_itemid($elname) {
18bd7573
PS
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])) {
729 return 0;
edc0c493 730 }
18bd7573
PS
731 if (is_array($_REQUEST[$elname])) {
732 $param = optional_param_array($elname, 0, PARAM_INT);
56a7bf68 733 if (!empty($param['itemid'])) {
734 $param = $param['itemid'];
735 } else {
736 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
737 return false;
738 }
18bd7573
PS
739
740 } else {
741 $param = optional_param($elname, 0, PARAM_INT);
3156b8ca 742 }
18bd7573
PS
743
744 if ($param) {
745 require_sesskey();
746 }
747
edc0c493 748 return $param;
3156b8ca 749}
750
67233725
DC
751/**
752 * Restore the original source field from draft files
753 *
935429af
MG
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
756 *
67233725
DC
757 * @param stored_file $storedfile This only works with draft files
758 * @return stored_file
759 */
760function file_restore_source_field_from_draft_file($storedfile) {
83d2700e 761 $source = @unserialize($storedfile->get_source());
61506a0a
DC
762 if (!empty($source)) {
763 if (is_object($source)) {
764 $restoredsource = $source->source;
765 $storedfile->set_source($restoredsource);
766 } else {
767 throw new moodle_exception('invalidsourcefield', 'error');
768 }
67233725
DC
769 }
770 return $storedfile;
771}
b933a139 772/**
edc0c493 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.
ba21c9d4 775 *
d2b7803e
DC
776 * @category files
777 * @global stdClass $USER
778 * @param int $draftitemid the id of the draft area to use. Normally obtained
edc0c493 779 * from file_get_submitted_draft_itemid('elementname') or similar.
d2b7803e 780 * @param int $contextid This parameter and the next two identify the file area to save to.
64f93798 781 * @param string $component
a08171c5 782 * @param string $filearea indentifies the file area.
d2b7803e 783 * @param int $itemid helps identifies the file area.
ba21c9d4 784 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
edc0c493 785 * @param string $text some html content that needs to have embedded links rewritten
786 * to the @@PLUGINFILE@@ form for saving in the database.
d2b7803e
DC
787 * @param bool $forcehttps force https urls.
788 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
b933a139 789 */
64f93798 790function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
c08643da 791 global $USER;
b933a139 792
b0c6dc1c 793 $usercontext = context_user::instance($USER->id);
8546def3 794 $fs = get_file_storage();
b933a139 795
a08171c5 796 $options = (array)$options;
797 if (!isset($options['subdirs'])) {
798 $options['subdirs'] = false;
799 }
800 if (!isset($options['maxfiles'])) {
801 $options['maxfiles'] = -1; // unlimited
802 }
3b6629c0 803 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
a08171c5 804 $options['maxbytes'] = 0; // unlimited
805 }
68acd115
FM
806 if (!isset($options['areamaxbytes'])) {
807 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
808 }
3b6629c0
MG
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;
815 }
a08171c5 816
68acd115
FM
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'])) {
821 return null;
822 }
823
64f93798
PS
824 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
825 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
b933a139 826
489bd32b
MG
827 // One file in filearea means it is empty (it has only top-level directory '.').
828 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
b933a139 829 // we have to merge old and new files - we want to keep file ids for files that were not changed
656e1184 830 // we change time modified for all new and changed files, we keep time created as is
a08171c5 831
832 $newhashes = array();
32495c06 833 $filecount = 0;
b933a139 834 foreach ($draftfiles as $file) {
d90c8115 835 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
32495c06
MG
836 continue;
837 }
838 if (!$allowreferences && $file->is_external_file()) {
839 continue;
840 }
841 if (!$file->is_directory()) {
842 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
843 // oversized file - should not get here at all
844 continue;
845 }
846 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
847 // more files - should not get here at all
848 continue;
849 }
850 $filecount++;
851 }
64f93798 852 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
a08171c5 853 $newhashes[$newhash] = $file;
854 }
32495c06 855
489bd32b
MG
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.
656e1184
PS
858 foreach ($oldfiles as $oldfile) {
859 $oldhash = $oldfile->get_pathnamehash();
860 if (!isset($newhashes[$oldhash])) {
64f93798 861 // delete files not needed any more - deleted by user
656e1184
PS
862 $oldfile->delete();
863 continue;
864 }
67233725 865
656e1184 866 $newfile = $newhashes[$oldhash];
0e7fd52e
MG
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.
876 $oldfile->delete();
877 continue;
878 }
879 } else {
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.
882 $oldfile->delete();
883 continue;
884 }
885
67233725
DC
886 // status changed, we delete old file, and create a new one
887 if ($oldfile->get_status() != $newfile->get_status()) {
656e1184
PS
888 // file was changed, use updated with new timemodified data
889 $oldfile->delete();
67233725 890 // This file will be added later
656e1184
PS
891 continue;
892 }
67233725 893
67233725
DC
894 // Updated author
895 if ($oldfile->get_author() != $newfile->get_author()) {
896 $oldfile->set_author($newfile->get_author());
897 }
898 // Updated license
899 if ($oldfile->get_license() != $newfile->get_license()) {
900 $oldfile->set_license($newfile->get_license());
901 }
902
903 // Updated file source
935429af
MG
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.
0e7fd52e
MG
906 $newsource = $newfile->get_source();
907 if ($source = @unserialize($newfile->get_source())) {
908 $newsource = $source->source;
909 }
910 if ($oldfile->get_source() !== $newsource) {
911 $oldfile->set_source($newsource);
67233725
DC
912 }
913
914 // Updated sort order
915 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
916 $oldfile->set_sortorder($newfile->get_sortorder());
917 }
918
f653c9d8
DM
919 // Update file timemodified
920 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
921 $oldfile->set_timemodified($newfile->get_timemodified());
922 }
923
14b7e500 924 // Replaced file content
0e7fd52e
MG
925 if (!$oldfile->is_directory() &&
926 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
e9e32b1d 927 $oldfile->get_filesize() != $newfile->get_filesize() ||
6dd92c02
MG
928 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
929 $oldfile->get_userid() != $newfile->get_userid())) {
e9e32b1d 930 $oldfile->replace_file_with($newfile);
14b7e500
MG
931 }
932
656e1184
PS
933 // unchanged file or directory - we keep it as is
934 unset($newhashes[$oldhash]);
b933a139 935 }
a08171c5 936
67233725 937 // Add fresh file or the file which has changed status
656e1184 938 // the size and subdirectory tests are extra safety only, the UI should prevent it
a08171c5 939 foreach ($newhashes as $file) {
65fead53 940 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
0e7fd52e
MG
941 if ($source = @unserialize($file->get_source())) {
942 // Field files.source for draftarea files contains serialised object with source and original information.
935429af 943 // We only store the source part of it for non-draft file area.
0e7fd52e
MG
944 $file_record['source'] = $source->source;
945 }
67233725
DC
946
947 if ($file->is_external_file()) {
948 $repoid = $file->get_repository_id();
949 if (!empty($repoid)) {
950 $file_record['repositoryid'] = $repoid;
951 $file_record['reference'] = $file->get_reference();
952 }
953 }
954
a08171c5 955 $fs->create_file_from_storedfile($file_record, $file);
8546def3 956 }
957 }
958
64f93798 959 // note: do not purge the draft area - we clean up areas later in cron,
42776c94
PS
960 // the reason is that user might press submit twice and they would loose the files,
961 // also sometimes we might want to use hacks that save files into two different areas
b933a139 962
8546def3 963 if (is_null($text)) {
964 return null;
c08643da
TH
965 } else {
966 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
8546def3 967 }
c08643da
TH
968}
969
970/**
971 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
972 * ready to be saved in the database. Normally, this is done automatically by
973 * {@link file_save_draft_area_files()}.
d2b7803e
DC
974 *
975 * @category files
c08643da
TH
976 * @param string $text the content to process.
977 * @param int $draftitemid the draft file area the content was using.
978 * @param bool $forcehttps whether the content contains https URLs. Default false.
979 * @return string the processed content.
980 */
981function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
982 global $CFG, $USER;
983
b0c6dc1c 984 $usercontext = context_user::instance($USER->id);
8546def3 985
9337cf32
PS
986 $wwwroot = $CFG->wwwroot;
987 if ($forcehttps) {
988 $wwwroot = str_replace('http://', 'https://', $wwwroot);
7983d682 989 }
990
9337cf32
PS
991 // relink embedded files if text submitted - no absolute links allowed in database!
992 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
993
994 if (strpos($text, 'draftfile.php?file=') !== false) {
995 $matches = array();
996 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
997 if ($matches) {
998 foreach ($matches[0] as $match) {
999 $replace = str_ireplace('%2F', '/', $match);
1000 $text = str_replace($match, $replace, $text);
1001 }
1002 }
1003 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
7983d682 1004 }
1005
7983d682 1006 return $text;
1007}
1008
f79321f1
DC
1009/**
1010 * Set file sort order
d2b7803e
DC
1011 *
1012 * @global moodle_database $DB
1013 * @param int $contextid the context id
1014 * @param string $component file component
f79321f1 1015 * @param string $filearea file area.
d2b7803e 1016 * @param int $itemid itemid.
f79321f1
DC
1017 * @param string $filepath file path.
1018 * @param string $filename file name.
d2b7803e
DC
1019 * @param int $sortorder the sort order of file.
1020 * @return bool
f79321f1 1021 */
64f93798 1022function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
f79321f1 1023 global $DB;
64f93798 1024 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
f79321f1
DC
1025 if ($file_record = $DB->get_record('files', $conditions)) {
1026 $sortorder = (int)$sortorder;
1027 $file_record->sortorder = $sortorder;
1028 $DB->update_record('files', $file_record);
1029 return true;
1030 }
1031 return false;
1032}
1033
1034/**
1035 * reset file sort order number to 0
d2b7803e
DC
1036 * @global moodle_database $DB
1037 * @param int $contextid the context id
64f93798 1038 * @param string $component
f79321f1 1039 * @param string $filearea file area.
d2b7803e
DC
1040 * @param int|bool $itemid itemid.
1041 * @return bool
f79321f1 1042 */
64f93798 1043function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
f79321f1
DC
1044 global $DB;
1045
64f93798 1046 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
f79321f1
DC
1047 if ($itemid !== false) {
1048 $conditions['itemid'] = $itemid;
1049 }
1050
1051 $file_records = $DB->get_records('files', $conditions);
1052 foreach ($file_records as $file_record) {
1053 $file_record->sortorder = 0;
1054 $DB->update_record('files', $file_record);
1055 }
1056 return true;
1057}
1058
a83ad946 1059/**
1060 * Returns description of upload error
ba21c9d4 1061 *
a83ad946 1062 * @param int $errorcode found in $_FILES['filename.ext']['error']
ba21c9d4 1063 * @return string error description string, '' if ok
a83ad946 1064 */
1065function file_get_upload_error($errorcode) {
a08171c5 1066
a83ad946 1067 switch ($errorcode) {
1068 case 0: // UPLOAD_ERR_OK - no error
1069 $errmessage = '';
1070 break;
a08171c5 1071
a83ad946 1072 case 1: // UPLOAD_ERR_INI_SIZE
1073 $errmessage = get_string('uploadserverlimit');
1074 break;
a08171c5 1075
a83ad946 1076 case 2: // UPLOAD_ERR_FORM_SIZE
1077 $errmessage = get_string('uploadformlimit');
1078 break;
a08171c5 1079
a83ad946 1080 case 3: // UPLOAD_ERR_PARTIAL
1081 $errmessage = get_string('uploadpartialfile');
1082 break;
a08171c5 1083
a83ad946 1084 case 4: // UPLOAD_ERR_NO_FILE
1085 $errmessage = get_string('uploadnofilefound');
1086 break;
a08171c5 1087
a83ad946 1088 // Note: there is no error with a value of 5
1089
1090 case 6: // UPLOAD_ERR_NO_TMP_DIR
1091 $errmessage = get_string('uploadnotempdir');
1092 break;
1093
1094 case 7: // UPLOAD_ERR_CANT_WRITE
1095 $errmessage = get_string('uploadcantwrite');
1096 break;
1097
1098 case 8: // UPLOAD_ERR_EXTENSION
1099 $errmessage = get_string('uploadextension');
1100 break;
1101
1102 default:
1103 $errmessage = get_string('uploadproblem');
1104 }
1105
1106 return $errmessage;
1107}
1108
5db608f4 1109/**
1110 * Recursive function formating an array in POST parameter
1111 * @param array $arraydata - the array that we are going to format and add into &$data array
1112 * @param string $currentdata - a row of the final postdata array at instant T
1113 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1114 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1115 */
1116function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1117 foreach ($arraydata as $k=>$v) {
277c7a40 1118 $newcurrentdata = $currentdata;
5db608f4 1119 if (is_array($v)) { //the value is an array, call the function recursively
277c7a40 1120 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1121 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
5db608f4 1122 } else { //add the POST parameter to the $data array
277c7a40 1123 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
5db608f4 1124 }
1125 }
1126}
1127
1128/**
1129 * Transform a PHP array into POST parameter
1130 * (see the recursive function format_array_postdata_for_curlcall)
1131 * @param array $postdata
1132 * @return array containing all POST parameters (1 row = 1 POST parameter)
1133 */
1134function format_postdata_for_curlcall($postdata) {
1135 $data = array();
1136 foreach ($postdata as $k=>$v) {
1137 if (is_array($v)) {
1138 $currentdata = urlencode($k);
1139 format_array_postdata_for_curlcall($v, $currentdata, $data);
1140 } else {
ea1780ad 1141 $data[] = urlencode($k).'='.urlencode($v);
5db608f4 1142 }
1143 }
1144 $convertedpostdata = implode('&', $data);
1145 return $convertedpostdata;
1146}
1147
8ee88311 1148/**
5f8bdc17 1149 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
599f06cf 1150 * Due to security concerns only downloads from http(s) sources are supported.
1151 *
d2b7803e 1152 * @category files
599f06cf 1153 * @param string $url file url starting with http(s)://
5ef082df 1154 * @param array $headers http headers, null if none. If set, should be an
1155 * associative array of header name => value pairs.
6bf55889 1156 * @param array $postdata array means use POST request with given parameters
1157 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
5ef082df 1158 * (if false, just returns content)
1159 * @param int $timeout timeout for complete download process including all file transfer
44e02d79 1160 * (default 5 minutes)
1161 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1162 * usually happens if the remote server is completely down (default 20 seconds);
1163 * may not work when using proxy
98eaf27e 1164 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
5f1c825d
SH
1165 * Only use this when already in a trusted location.
1166 * @param string $tofile store the downloaded content to file instead of returning it.
98eaf27e 1167 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
5f1c825d 1168 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
feff774a
SL
1169 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1170 * if file downloaded into $tofile successfully or the file content as a string.
8ee88311 1171 */
60b5a2fe 1172function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
e27f0765 1173 global $CFG;
1174
220eef0e 1175 // Only http and https links supported.
599f06cf 1176 if (!preg_match('|^https?://|i', $url)) {
1177 if ($fullresponse) {
365a5941 1178 $response = new stdClass();
599f06cf 1179 $response->status = 0;
1180 $response->headers = array();
1181 $response->response_code = 'Invalid protocol specified in url';
1182 $response->results = '';
1183 $response->error = 'Invalid protocol specified in url';
1184 return $response;
1185 } else {
1186 return false;
1187 }
1188 }
1189
220eef0e 1190 $options = array();
599f06cf 1191
220eef0e
PS
1192 $headers2 = array();
1193 if (is_array($headers)) {
6bf55889 1194 foreach ($headers as $key => $value) {
220eef0e
PS
1195 if (is_numeric($key)) {
1196 $headers2[] = $value;
1197 } else {
1198 $headers2[] = "$key: $value";
1199 }
6bf55889 1200 }
6bf55889 1201 }
1202
83947a36 1203 if ($skipcertverify) {
220eef0e
PS
1204 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1205 } else {
1206 $options['CURLOPT_SSL_VERIFYPEER'] = true;
83947a36 1207 }
bb2c046d 1208
220eef0e
PS
1209 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1210
1211 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1212 $options['CURLOPT_MAXREDIRS'] = 5;
1213
1214 // Use POST if requested.
6bf55889 1215 if (is_array($postdata)) {
5db608f4 1216 $postdata = format_postdata_for_curlcall($postdata);
220eef0e
PS
1217 } else if (empty($postdata)) {
1218 $postdata = null;
5f8bdc17 1219 }
ea1780ad 1220
220eef0e
PS
1221 // Optionally attempt to get more correct timeout by fetching the file size.
1222 if (!isset($CFG->curltimeoutkbitrate)) {
1223 // Use very slow rate of 56kbps as a timeout speed when not set.
1224 $bitrate = 56;
1225 } else {
1226 $bitrate = $CFG->curltimeoutkbitrate;
c2140b5d 1227 }
220eef0e
PS
1228 if ($calctimeout and !isset($postdata)) {
1229 $curl = new curl();
1230 $curl->setHeader($headers2);
c2140b5d 1231
220eef0e 1232 $curl->head($url, $postdata, $options);
6bf55889 1233
220eef0e
PS
1234 $info = $curl->get_info();
1235 $error_no = $curl->get_errno();
1236 if (!$error_no && $info['download_content_length'] > 0) {
1237 // No curl errors - adjust for large files only - take max timeout.
1238 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
5f8bdc17 1239 }
220eef0e 1240 }
5f8bdc17 1241
220eef0e
PS
1242 $curl = new curl();
1243 $curl->setHeader($headers2);
08ec989f 1244
220eef0e
PS
1245 $options['CURLOPT_RETURNTRANSFER'] = true;
1246 $options['CURLOPT_NOBODY'] = false;
1247 $options['CURLOPT_TIMEOUT'] = $timeout;
5f8bdc17 1248
220eef0e
PS
1249 if ($tofile) {
1250 $fh = fopen($tofile, 'w');
1251 if (!$fh) {
1252 if ($fullresponse) {
1253 $response = new stdClass();
1254 $response->status = 0;
1255 $response->headers = array();
1256 $response->response_code = 'Can not write to file';
1257 $response->results = false;
1258 $response->error = 'Can not write to file';
1259 return $response;
1260 } else {
1261 return false;
5f8bdc17 1262 }
8ee88311 1263 }
220eef0e 1264 $options['CURLOPT_FILE'] = $fh;
8ee88311 1265 }
6bf55889 1266
220eef0e
PS
1267 if (isset($postdata)) {
1268 $content = $curl->post($url, $postdata, $options);
60b5a2fe 1269 } else {
220eef0e 1270 $content = $curl->get($url, null, $options);
60b5a2fe
AB
1271 }
1272
220eef0e
PS
1273 if ($tofile) {
1274 fclose($fh);
1275 @chmod($tofile, $CFG->filepermissions);
60b5a2fe
AB
1276 }
1277
220eef0e
PS
1278/*
1279 // Try to detect encoding problems.
6bf55889 1280 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1281 curl_setopt($ch, CURLOPT_ENCODING, 'none');
3a1055a5
PS
1282 $result = curl_exec($ch);
1283 }
220eef0e 1284*/
3a1055a5 1285
220eef0e
PS
1286 $info = $curl->get_info();
1287 $error_no = $curl->get_errno();
1288 $rawheaders = $curl->get_raw_response();
6bf55889 1289
220eef0e
PS
1290 if ($error_no) {
1291 $error = $content;
1292 if (!$fullresponse) {
599f06cf 1293 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
6bf55889 1294 return false;
1295 }
5f8bdc17 1296
220eef0e
PS
1297 $response = new stdClass();
1298 if ($error_no == 28) {
1299 $response->status = '-100'; // Mimic snoopy.
599f06cf 1300 } else {
220eef0e 1301 $response->status = '0';
599f06cf 1302 }
220eef0e
PS
1303 $response->headers = array();
1304 $response->response_code = $error;
1305 $response->results = false;
1306 $response->error = $error;
1307 return $response;
1308 }
6bf55889 1309
220eef0e
PS
1310 if ($tofile) {
1311 $content = true;
08ec989f 1312 }
8ee88311 1313
220eef0e
PS
1314 if (empty($info['http_code'])) {
1315 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1316 $response = new stdClass();
1317 $response->status = '0';
1318 $response->headers = array();
1319 $response->response_code = 'Unknown cURL error';
1320 $response->results = false; // do NOT change this, we really want to ignore the result!
1321 $response->error = 'Unknown cURL error';
3a1055a5 1322
220eef0e
PS
1323 } else {
1324 $response = new stdClass();
1325 $response->status = (string)$info['http_code'];
1326 $response->headers = $rawheaders;
1327 $response->results = $content;
1328 $response->error = '';
1329
1330 // There might be multiple headers on redirect, find the status of the last one.
1331 $firstline = true;
1332 foreach ($rawheaders as $line) {
1333 if ($firstline) {
1334 $response->response_code = $line;
1335 $firstline = false;
1336 }
1337 if (trim($line, "\r\n") === '') {
1338 $firstline = true;
1339 }
3a1055a5
PS
1340 }
1341 }
220eef0e
PS
1342
1343 if ($fullresponse) {
1344 return $response;
3a1055a5 1345 }
220eef0e
PS
1346
1347 if ($info['http_code'] != 200) {
1348 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1349 return false;
1350 }
1351 return $response->results;
3a1055a5
PS
1352}
1353
3ce73b14 1354/**
559276b1
MG
1355 * Returns a list of information about file types based on extensions.
1356 *
1357 * The following elements expected in value array for each extension:
1358 * 'type' - mimetype
1359 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1360 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1361 * also files with bigger sizes under names
1362 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1363 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1364 * commonly used in moodle the following groups:
1365 * - web_image - image that can be included as <img> in HTML
1366 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1367 * - video - file that can be imported as video in text editor
1368 * - audio - file that can be imported as audio in text editor
1369 * - archive - we can extract files from this archive
1370 * - spreadsheet - used for portfolio format
1371 * - document - used for portfolio format
1372 * - presentation - used for portfolio format
1373 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1374 * human-readable description for this filetype;
1375 * Function {@link get_mimetype_description()} first looks at the presence of string for
1376 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1377 * attribute, if not found returns the value of 'type';
1378 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1379 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1380 * this function will return first found icon; Especially usefull for types such as 'text/plain'
d2b7803e
DC
1381 *
1382 * @category files
ba21c9d4 1383 * @return array List of information about file types based on extensions.
3ce73b14 1384 * Associative array of extension (lower-case) to associative array
1385 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 1386 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 1387 */
559276b1 1388function &get_mimetypes_array() {
172dd12c 1389 static $mimearray = array (
ede72522 1390 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
5a322c8c
BR
1391 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1392 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
96aeb5be 1393 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
0f1bdd0d 1394 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
559276b1
MG
1395 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1396 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1397 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
ede72522 1398 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
5a322c8c
BR
1399 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1400 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
559276b1 1401 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
ae7f35b9 1402 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
0f1bdd0d 1403 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
5a322c8c 1404 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
ede72522 1405 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
5a322c8c
BR
1406 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1407 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
559276b1 1408 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
5a322c8c
BR
1409 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1410 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
1411 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
ede72522 1412
5a322c8c 1413 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
ecdb94d3
KV
1414 'bdoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
1415 'cdoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
1416 'ddoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
5a322c8c
BR
1417 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
1418 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
1419 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
1420 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
ede72522
PS
1421
1422 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
5a322c8c 1423 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
ede72522
PS
1424 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
1425 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
0f1bdd0d 1426 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
ed0f5a95 1427 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
ede72522 1428 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
ae7f35b9
MG
1429 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
1430 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
58b1904f
FM
1431
1432 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
5961512a 1433 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
58b1904f 1434 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
0f1bdd0d 1435 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
5a322c8c
BR
1436 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1437 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1438 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1439 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1440 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1441 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
1442 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
1443 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
386a862f 1444 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
c7aed1e1 1445 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
386a862f 1446 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
559276b1 1447 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
ede72522
PS
1448 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
1449 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
1450 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
5a322c8c 1451 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
aebe9db0 1452 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
5a322c8c
BR
1453 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
1454 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
1455 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
1456 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
1457 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
fd43a49b 1458 'jnlp' => array ('type'=>'application/x-java-jnlp-file', 'icon'=>'markup'),
a8d6dda4
MG
1459 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1460 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
1461 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
5a322c8c 1462 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
559276b1 1463 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
ede72522 1464 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
5a322c8c 1465 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
b3ea9cb2 1466 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
96aeb5be 1467 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
41fdbc0d
DW
1468 'mht' => array ('type'=>'message/rfc822', 'icon'=>'archive'),
1469 'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
5a322c8c
BR
1470 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
1471 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
c746c608
HB
1472 'mw' => array ('type'=>'application/maple', 'icon'=>'math'),
1473 'mws' => array ('type'=>'application/maple', 'icon'=>'math'),
a8d6dda4 1474 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
ae7f35b9
MG
1475 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
1476 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1477 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
a8d6dda4 1478 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
ae7f35b9
MG
1479 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1480 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
1481 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
2e746b72 1482 'mpr' => array ('type'=>'application/vnd.moodle.profiling', 'icon'=>'moodle'),
0f1bdd0d 1483
58b1904f
FM
1484 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1485 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
1486
5a322c8c
BR
1487 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
1488 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
ca9875db 1489 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
5a322c8c
BR
1490 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
1491 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
1492 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
1493 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
1494 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
1495 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1496 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
1497 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
1498 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
1499 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
1500 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
1501 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1502 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1503 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
ede72522 1504
559276b1 1505 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
ede72522 1506 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
5a322c8c 1507 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
559276b1
MG
1508 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
1509 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
0f1bdd0d 1510 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
5a322c8c
BR
1511 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1512 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
1513 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
1514 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
1515 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
1516 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
1517 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
1518 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
1519 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
ede72522 1520 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
855d8a2c
JM
1521 'pub' => array ('type'=>'application/x-mspublisher', 'icon'=>'publisher', 'groups'=>array('presentation')),
1522
5a322c8c 1523 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
ae7f35b9 1524 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
559276b1 1525 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
5a322c8c 1526 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
559276b1
MG
1527 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
1528 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
1529 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
ede72522 1530 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
0f1bdd0d 1531 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
5a322c8c
BR
1532 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
1533 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
ede72522
PS
1534 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
1535 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
5a322c8c 1536 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
ae7f35b9
MG
1537 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
1538 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
ede72522 1539 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
ae7f35b9
MG
1540 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
1541 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
ede72522 1542
5a322c8c
BR
1543 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
1544 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
1545 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
1546 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
1547 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
1548 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
1549 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
1550 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
1551 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
1552 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
1553
1554 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
0f1bdd0d
BR
1555 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
1556 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
ede72522
PS
1557 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
1558 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1559 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
1560 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
559276b1 1561 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
0f1bdd0d 1562 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
5a322c8c 1563 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
0f1bdd0d
BR
1564 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1565 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
1349800d 1566 'wma' => array ('type'=>'audio/x-ms-wma', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
58b1904f
FM
1567
1568 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
ede72522
PS
1569 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1570 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1571 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
1572
5a322c8c
BR
1573 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1574 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
1575 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
1576 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
1577 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
1578 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
1579 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
1580
1581 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
1582 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
58b1904f 1583
5a322c8c 1584 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
f1e0649c 1585 );
172dd12c 1586 return $mimearray;
3ce73b14 1587}
1588
76ca1ff1 1589/**
3ce73b14 1590 * Obtains information about a filetype based on its extension. Will
1591 * use a default if no information is present about that particular
1592 * extension.
ba21c9d4 1593 *
d2b7803e 1594 * @category files
76ca1ff1 1595 * @param string $element Desired information (usually 'icon'
559276b1
MG
1596 * for icon filename or 'type' for MIME type. Can also be
1597 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
76ca1ff1 1598 * @param string $filename Filename we're looking up
3ce73b14 1599 * @return string Requested piece of information from array
1600 */
1601function mimeinfo($element, $filename) {
0ef98843 1602 global $CFG;
559276b1
MG
1603 $mimeinfo = & get_mimetypes_array();
1604 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1605
1606 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1607 if (empty($filetype)) {
1608 $filetype = 'xxx'; // file without extension
1609 }
1610 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1611 $iconsize = max(array(16, (int)$iconsizematch[1]));
1612 $filenames = array($mimeinfo['xxx']['icon']);
1613 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1614 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1615 }
1616 // find the file with the closest size, first search for specific icon then for default icon
1617 foreach ($filenames as $filename) {
1618 foreach ($iconpostfixes as $size => $postfix) {
1619 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1620 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1621 return $filename.$postfix;
72aa74ce 1622 }
0ef98843 1623 }
f1e0649c 1624 }
559276b1
MG
1625 } else if (isset($mimeinfo[$filetype][$element])) {
1626 return $mimeinfo[$filetype][$element];
1627 } else if (isset($mimeinfo['xxx'][$element])) {
a370c895 1628 return $mimeinfo['xxx'][$element]; // By default
559276b1
MG
1629 } else {
1630 return null;
f1e0649c 1631 }
1632}
1633
76ca1ff1 1634/**
3ce73b14 1635 * Obtains information about a filetype based on the MIME type rather than
1636 * the other way around.
ba21c9d4 1637 *
d2b7803e 1638 * @category files
559276b1 1639 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
76ca1ff1 1640 * @param string $mimetype MIME type we're looking up
3ce73b14 1641 * @return string Requested piece of information from array
1642 */
1643function mimeinfo_from_type($element, $mimetype) {
559276b1
MG
1644 /* array of cached mimetype->extension associations */
1645 static $cached = array();
1646 $mimeinfo = & get_mimetypes_array();
1647
1648 if (!array_key_exists($mimetype, $cached)) {
1082e7da 1649 $cached[$mimetype] = null;
559276b1
MG
1650 foreach($mimeinfo as $filetype => $values) {
1651 if ($values['type'] == $mimetype) {
1652 if ($cached[$mimetype] === null) {
e5635827 1653 $cached[$mimetype] = '.'.$filetype;
559276b1
MG
1654 }
1655 if (!empty($values['defaulticon'])) {
e5635827 1656 $cached[$mimetype] = '.'.$filetype;
559276b1
MG
1657 break;
1658 }
3ce73b14 1659 }
3ce73b14 1660 }
a8d6dda4 1661 if (empty($cached[$mimetype])) {
e5635827 1662 $cached[$mimetype] = '.xxx';
559276b1 1663 }
a8d6dda4
MG
1664 }
1665 if ($element === 'extension') {
1666 return $cached[$mimetype];
559276b1 1667 } else {
e5635827 1668 return mimeinfo($element, $cached[$mimetype]);
559276b1 1669 }
3ce73b14 1670}
b9709b76 1671
42ead7d7 1672/**
559276b1 1673 * Return the relative icon path for a given file
ba21c9d4 1674 *
559276b1
MG
1675 * Usage:
1676 * <code>
1677 * // $file - instance of stored_file or file_info
1678 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1679 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1680 * </code>
1681 * or
1682 * <code>
1683 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1684 * </code>
1685 *
1686 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1687 * and $file->mimetype are expected)
1688 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1689 * @return string
42ead7d7 1690 */
559276b1
MG
1691function file_file_icon($file, $size = null) {
1692 if (!is_object($file)) {
1693 $file = (object)$file;
1694 }
1695 if (isset($file->filename)) {
1696 $filename = $file->filename;
1697 } else if (method_exists($file, 'get_filename')) {
1698 $filename = $file->get_filename();
1699 } else if (method_exists($file, 'get_visible_name')) {
1700 $filename = $file->get_visible_name();
1701 } else {
1702 $filename = '';
637a60dc 1703 }
559276b1
MG
1704 if (isset($file->mimetype)) {
1705 $mimetype = $file->mimetype;
1706 } else if (method_exists($file, 'get_mimetype')) {
1707 $mimetype = $file->get_mimetype();
1708 } else {
1709 $mimetype = '';
42ead7d7 1710 }
ae7f35b9
MG
1711 $mimetypes = &get_mimetypes_array();
1712 if ($filename) {
1713 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1714 if ($extension && !empty($mimetypes[$extension])) {
1715 // if file name has known extension, return icon for this extension
1716 return file_extension_icon($filename, $size);
1717 }
0b46f19e 1718 }
ae7f35b9 1719 return file_mimetype_icon($mimetype, $size);
559276b1 1720}
637a60dc 1721
559276b1
MG
1722/**
1723 * Return the relative icon path for a folder image
1724 *
1725 * Usage:
1726 * <code>
1727 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1728 * echo html_writer::empty_tag('img', array('src' => $icon));
1729 * </code>
1730 * or
1731 * <code>
1732 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1733 * </code>
1734 *
1735 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1736 * @return string
1737 */
1738function file_folder_icon($iconsize = null) {
1739 global $CFG;
1740 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
ae7f35b9 1741 static $cached = array();
559276b1 1742 $iconsize = max(array(16, (int)$iconsize));
ae7f35b9
MG
1743 if (!array_key_exists($iconsize, $cached)) {
1744 foreach ($iconpostfixes as $size => $postfix) {
1745 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1746 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1747 $cached[$iconsize] = 'f/folder'.$postfix;
1748 break;
1749 }
559276b1 1750 }
637a60dc 1751 }
ae7f35b9 1752 return $cached[$iconsize];
42ead7d7 1753}
1754
9dffa7af 1755/**
1756 * Returns the relative icon path for a given mime type
1757 *
34ff25a6 1758 * This function should be used in conjunction with $OUTPUT->pix_url to produce
9dffa7af 1759 * a return the full path to an icon.
1760 *
1761 * <code>
1762 * $mimetype = 'image/jpg';
559276b1
MG
1763 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1764 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
9dffa7af 1765 * </code>
1766 *
d2b7803e
DC
1767 * @category files
1768 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
9dffa7af 1769 * to conform with that.
9dffa7af 1770 * @param string $mimetype The mimetype to fetch an icon for
559276b1 1771 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
9dffa7af 1772 * @return string The relative path to the icon
1773 */
ede72522 1774function file_mimetype_icon($mimetype, $size = NULL) {
559276b1 1775 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
9dffa7af 1776}
1777
1778/**
2dcb7d0b 1779 * Returns the relative icon path for a given file name
9dffa7af 1780 *
34ff25a6 1781 * This function should be used in conjunction with $OUTPUT->pix_url to produce
9dffa7af 1782 * a return the full path to an icon.
1783 *
9dffa7af 1784 * <code>
559276b1
MG
1785 * $filename = '.jpg';
1786 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1787 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
9dffa7af 1788 * </code>
1789 *
d2b7803e 1790 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
9dffa7af 1791 * to conform with that.
d2b7803e
DC
1792 * @todo MDL-31074 Implement $size
1793 * @category files
1794 * @param string $filename The filename to get the icon for
559276b1 1795 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
9dffa7af 1796 * @return string
1797 */
ede72522 1798function file_extension_icon($filename, $size = NULL) {
559276b1 1799 return 'f/'.mimeinfo('icon'.$size, $filename);
9dffa7af 1800}
1801
c0381e22 1802/**
76ca1ff1 1803 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1804 * mimetypes.php language file.
ba21c9d4 1805 *
559276b1
MG
1806 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1807 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1808 * have filename); In case of array/stdClass the field 'mimetype' is optional.
c0381e22 1809 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 1810 * @return string Text description
c0381e22 1811 */
559276b1 1812function get_mimetype_description($obj, $capitalise=false) {
ae7f35b9 1813 $filename = $mimetype = '';
559276b1
MG
1814 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1815 // this is an instance of stored_file
1816 $mimetype = $obj->get_mimetype();
1817 $filename = $obj->get_filename();
1818 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1819 // this is an instance of file_info
1820 $mimetype = $obj->get_mimetype();
1821 $filename = $obj->get_visible_name();
1822 } else if (is_array($obj) || is_object ($obj)) {
1823 $obj = (array)$obj;
1824 if (!empty($obj['filename'])) {
1825 $filename = $obj['filename'];
559276b1
MG
1826 }
1827 if (!empty($obj['mimetype'])) {
1828 $mimetype = $obj['mimetype'];
559276b1
MG
1829 }
1830 } else {
1831 $mimetype = $obj;
ae7f35b9
MG
1832 }
1833 $mimetypefromext = mimeinfo('type', $filename);
1834 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1835 // if file has a known extension, overwrite the specified mimetype
1836 $mimetype = $mimetypefromext;
559276b1
MG
1837 }
1838 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1839 if (empty($extension)) {
1840 $mimetypestr = mimeinfo_from_type('string', $mimetype);
ae7f35b9 1841 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
559276b1
MG
1842 } else {
1843 $mimetypestr = mimeinfo('string', $filename);
1844 }
1845 $chunks = explode('/', $mimetype, 2);
1846 $chunks[] = '';
1847 $attr = array(
1848 'mimetype' => $mimetype,
1849 'ext' => $extension,
1850 'mimetype1' => $chunks[0],
1851 'mimetype2' => $chunks[1],
1852 );
1853 $a = array();
1854 foreach ($attr as $key => $value) {
1855 $a[$key] = $value;
1856 $a[strtoupper($key)] = strtoupper($value);
1857 $a[ucfirst($key)] = ucfirst($value);
1858 }
ed0f5a95 1859
1860 // MIME types may include + symbol but this is not permitted in string ids.
1861 $safemimetype = str_replace('+', '_', $mimetype);
1862 $safemimetypestr = str_replace('+', '_', $mimetypestr);
1863 if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
1864 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1865 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1866 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
559276b1
MG
1867 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1868 $result = get_string('default', 'mimetypes', (object)$a);
1b80c913 1869 } else {
559276b1 1870 $result = $mimetype;
76ca1ff1 1871 }
ede72522 1872 if ($capitalise) {
c0381e22 1873 $result=ucfirst($result);
1874 }
1875 return $result;
1876}
1877
559276b1
MG
1878/**
1879 * Returns array of elements of type $element in type group(s)
1880 *
1881 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1882 * @param string|array $groups one group or array of groups/extensions/mimetypes
1883 * @return array
1884 */
1885function file_get_typegroup($element, $groups) {
1886 static $cached = array();
1887 if (!is_array($groups)) {
1888 $groups = array($groups);
1889 }
1890 if (!array_key_exists($element, $cached)) {
1891 $cached[$element] = array();
1892 }
1893 $result = array();
1894 foreach ($groups as $group) {
1895 if (!array_key_exists($group, $cached[$element])) {
1896 // retrieive and cache all elements of type $element for group $group
1897 $mimeinfo = & get_mimetypes_array();
1898 $cached[$element][$group] = array();
1899 foreach ($mimeinfo as $extension => $value) {
e5635827 1900 $value['extension'] = '.'.$extension;
559276b1
MG
1901 if (empty($value[$element])) {
1902 continue;
1903 }
ae7f35b9 1904 if (($group === '.'.$extension || $group === $value['type'] ||
559276b1
MG
1905 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1906 !in_array($value[$element], $cached[$element][$group])) {
1907 $cached[$element][$group][] = $value[$element];
1908 }
1909 }
1910 }
1911 $result = array_merge($result, $cached[$element][$group]);
1912 }
41340f04 1913 return array_values(array_unique($result));
559276b1
MG
1914}
1915
1916/**
1917 * Checks if file with name $filename has one of the extensions in groups $groups
1918 *
1919 * @see get_mimetypes_array()
1920 * @param string $filename name of the file to check
1921 * @param string|array $groups one group or array of groups to check
1922 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1923 * file mimetype is in mimetypes in groups $groups
1924 * @return bool
1925 */
1926function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1927 $extension = pathinfo($filename, PATHINFO_EXTENSION);
e5635827 1928 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
559276b1
MG
1929 return true;
1930 }
1931 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1932}
1933
1934/**
1935 * Checks if mimetype $mimetype belongs to one of the groups $groups
1936 *
1937 * @see get_mimetypes_array()
1938 * @param string $mimetype
1939 * @param string|array $groups one group or array of groups to check
1940 * @return bool
1941 */
1942function file_mimetype_in_typegroup($mimetype, $groups) {
1943 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1944}
1945
9e5fa330 1946/**
d2b7803e 1947 * Requested file is not found or not accessible, does not return, terminates script
ba21c9d4 1948 *
d2b7803e
DC
1949 * @global stdClass $CFG
1950 * @global stdClass $COURSE
9e5fa330 1951 */
1952function send_file_not_found() {
1953 global $CFG, $COURSE;
dbdc7355 1954 send_header_404();
9e5fa330 1955 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1956}
dbdc7355
DM
1957/**
1958 * Helper function to send correct 404 for server.
1959 */
1960function send_header_404() {
1961 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1962 header("Status: 404 Not Found");
1963 } else {
1964 header('HTTP/1.0 404 not found');
1965 }
1966}
9e5fa330 1967
137885b7 1968/**
1969 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1970 * platforms). This wrapper uses readfile for small files and custom code for
1971 * large ones.
1972 *
1973 * @param string $path Path to file
1974 * @param int $filesize Size of file (if left out, will get it automatically)
1975 * @return int|bool Size read (will always be $filesize) or false if failed
1976 */
1977function readfile_allow_large($path, $filesize = -1) {
1978 // Automatically get size if not specified.
1979 if ($filesize === -1) {
1980 $filesize = filesize($path);
1981 }
1982 if ($filesize <= 2147483647) {
1983 // If the file is up to 2^31 - 1, send it normally using readfile.
1984 return readfile($path);
1985 } else {
1986 // For large files, read and output in 64KB chunks.
1987 $handle = fopen($path, 'r');
1988 if ($handle === false) {
1989 return false;
1990 }
1991 $left = $filesize;
1992 while ($left > 0) {
1993 $size = min($left, 65536);
1994 $buffer = fread($handle, $size);
1995 if ($buffer === false) {
1996 return false;
1997 }
1998 echo $buffer;
1999 $left -= $size;
2000 }
2001 return $filesize;
2002 }
2003}
2004
cbad562e 2005/**
d5dd0540
PS
2006 * Enhanced readfile() with optional acceleration.
2007 * @param string|stored_file $file
2008 * @param string $mimetype
2009 * @param bool $accelerate
2010 * @return void
cbad562e 2011 */
d5dd0540
PS
2012function readfile_accel($file, $mimetype, $accelerate) {
2013 global $CFG;
2014
2015 if ($mimetype === 'text/plain') {
2016 // there is no encoding specified in text files, we need something consistent
2017 header('Content-Type: text/plain; charset=utf-8');
2018 } else {
2019 header('Content-Type: '.$mimetype);
596c7115
PS
2020 }
2021
d5dd0540
PS
2022 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2023 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
116ee3e4 2024
d5dd0540 2025 if (is_object($file)) {
78030f9d 2026 header('Etag: "' . $file->get_contenthash() . '"');
9cc5f32b 2027 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
d5dd0540
PS
2028 header('HTTP/1.1 304 Not Modified');
2029 return;
2030 }
2031 }
2032
2033 // if etag present for stored file rely on it exclusively
2034 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2035 // get unixtime of request header; clip extra junk off first
2036 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2037 if ($since && $since >= $lastmodified) {
2038 header('HTTP/1.1 304 Not Modified');
2039 return;
2040 }
2041 }
2042
2043 if ($accelerate and !empty($CFG->xsendfile)) {
2044 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2045 header('Accept-Ranges: bytes');
2046 } else {
2047 header('Accept-Ranges: none');
2048 }
2049
2050 if (is_object($file)) {
2051 $fs = get_file_storage();
2052 if ($fs->xsendfile($file->get_contenthash())) {
2053 return;
2054 }
2055
2056 } else {
2057 require_once("$CFG->libdir/xsendfilelib.php");
2058 if (xsendfile($file)) {
2059 return;
2060 }
2061 }
2062 }
2063
2064 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2065
2066 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2067
2068 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2069 header('Accept-Ranges: bytes');
2070
2071 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2072 // byteserving stuff - for acrobat reader and download accelerators
2073 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2074 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2075 $ranges = false;
2076 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2077 foreach ($ranges as $key=>$value) {
2078 if ($ranges[$key][1] == '') {
2079 //suffix case
2080 $ranges[$key][1] = $filesize - $ranges[$key][2];
2081 $ranges[$key][2] = $filesize - 1;
2082 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2083 //fix range length
2084 $ranges[$key][2] = $filesize - 1;
2085 }
2086 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2087 //invalid byte-range ==> ignore header
2088 $ranges = false;
2089 break;
2090 }
2091 //prepare multipart header
2092 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2093 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2094 }
2095 } else {
2096 $ranges = false;
2097 }
2098 if ($ranges) {
2099 if (is_object($file)) {
2100 $handle = $file->get_content_file_handle();
2101 } else {
2102 $handle = fopen($file, 'rb');
2103 }
2104 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2105 }
2106 }
2107 } else {
2108 // Do not byteserve
2109 header('Accept-Ranges: none');
2110 }
2111
2112 header('Content-Length: '.$filesize);
2113
2114 if ($filesize > 10000000) {
2115 // for large files try to flush and close all buffers to conserve memory
2116 while(@ob_get_level()) {
2117 if (!@ob_end_flush()) {
2118 break;
2119 }
cbad562e
PS
2120 }
2121 }
2122
d5dd0540
PS
2123 // send the whole file content
2124 if (is_object($file)) {
2125 $file->readfile();
2126 } else {
137885b7 2127 readfile_allow_large($file, $filesize);
d5dd0540
PS
2128 }
2129}
2130
2131/**
2132 * Similar to readfile_accel() but designed for strings.
2133 * @param string $string
2134 * @param string $mimetype
2135 * @param bool $accelerate
2136 * @return void
2137 */
2138function readstring_accel($string, $mimetype, $accelerate) {
2139 global $CFG;
2140
2141 if ($mimetype === 'text/plain') {
2142 // there is no encoding specified in text files, we need something consistent
2143 header('Content-Type: text/plain; charset=utf-8');
2144 } else {
2145 header('Content-Type: '.$mimetype);
2146 }
2147 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2148 header('Accept-Ranges: none');
2149
2150 if ($accelerate and !empty($CFG->xsendfile)) {
2151 $fs = get_file_storage();
2152 if ($fs->xsendfile(sha1($string))) {
2153 return;
2154 }
2155 }
cbad562e 2156
d5dd0540
PS
2157 header('Content-Length: '.strlen($string));
2158 echo $string;
cbad562e
PS
2159}
2160
c87c428e 2161/**
2162 * Handles the sending of temporary file to user, download is forced.
d2b7803e 2163 * File is deleted after abort or successful sending, does not return, script terminated
ba21c9d4 2164 *
c87c428e 2165 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2166 * @param string $filename proposed file name when saving file
d2b7803e 2167 * @param bool $pathisstring If the path is string
c87c428e 2168 */
45c0d224 2169function send_temp_file($path, $filename, $pathisstring=false) {
c87c428e 2170 global $CFG;
2171
378b3eac 2172 if (core_useragent::is_firefox()) {
d5dd0540
PS
2173 // only FF is known to correctly save to disk before opening...
2174 $mimetype = mimeinfo('type', $filename);
2175 } else {
2176 $mimetype = 'application/x-forcedownload';
2177 }
2178
c87c428e 2179 // close session - not needed anymore
d79d5ac2 2180 \core\session\manager::write_close();
c87c428e 2181
2182 if (!$pathisstring) {
2183 if (!file_exists($path)) {
dbdc7355 2184 send_header_404();
45c0d224 2185 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
c87c428e 2186 }
2187 // executed after normal finish or abort
38fc0130 2188 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
c87c428e 2189 }
2190
c87c428e 2191 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
378b3eac 2192 if (core_useragent::is_ie()) {
c87c428e 2193 $filename = urlencode($filename);
2194 }
2195
66969d50 2196 header('Content-Disposition: attachment; filename="'.$filename.'"');
c87c428e 2197 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
c3a3f540 2198 header('Cache-Control: private, max-age=10, no-transform');
cbad562e
PS
2199 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2200 header('Pragma: ');
c87c428e 2201 } else { //normal http - prevent caching at all cost
c3a3f540 2202 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
cbad562e
PS
2203 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2204 header('Pragma: no-cache');
c87c428e 2205 }
c87c428e 2206
d5dd0540 2207 // send the contents - we can not accelerate this because the file will be deleted asap
c87c428e 2208 if ($pathisstring) {
d5dd0540 2209 readstring_accel($path, $mimetype, false);
c87c428e 2210 } else {
d5dd0540
PS
2211 readfile_accel($path, $mimetype, false);
2212 @unlink($path);
c87c428e 2213 }
2214
2215 die; //no more chars to output
2216}
2217
2218/**
34ff25a6 2219 * Internal callback function used by send_temp_file()
d2b7803e
DC
2220 *
2221 * @param string $path
c87c428e 2222 */
2223function send_temp_file_finished($path) {
2224 if (file_exists($path)) {
2225 @unlink($path);
2226 }
2227}
2228
76ca1ff1 2229/**
2230 * Handles the sending of file data to the user's browser, including support for
2231 * byteranges etc.
ba21c9d4 2232 *
d2b7803e 2233 * @category files
ba75ad94 2234 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2235 * @param string $filename Filename to send
0c431257 2236 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
ba75ad94 2237 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2238 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2239 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2240 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 2241 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2242 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 2243 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2244 * and should not be reopened.
d2b7803e 2245 * @return null script execution stopped unless $dontdie is true
b9709b76 2246 */
0c431257 2247function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
d5dd0540 2248 global $CFG, $COURSE;
50f95991 2249
b379f7d9 2250 if ($dontdie) {
15325f55 2251 ignore_user_abort(true);
b379f7d9 2252 }
2253
0c431257
PS
2254 if ($lifetime === 'default' or is_null($lifetime)) {
2255 $lifetime = $CFG->filelifetime;
c8a5c6a4 2256 }
2257
d79d5ac2 2258 \core\session\manager::write_close(); // Unlock session during file serving.
172dd12c 2259
ba4e0b05 2260 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2261 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2262 // only Firefox saves all files locally before opening when content-disposition: attachment stated
378b3eac 2263 $isFF = core_useragent::is_firefox(); // only FF properly tested
76ca1ff1 2264 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 2265 ($mimetype ? $mimetype : mimeinfo('type', $filename));
b5bbeaf0 2266
4f047de2 2267 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
378b3eac 2268 if (core_useragent::is_ie()) {
4638009b 2269 $filename = rawurlencode($filename);
4f047de2 2270 }
2271
4c8c65ec 2272 if ($forcedownload) {
cbad562e 2273 header('Content-Disposition: attachment; filename="'.$filename.'"');
4c8c65ec 2274 } else {
cbad562e 2275 header('Content-Disposition: inline; filename="'.$filename.'"');
4c8c65ec 2276 }
2277
f1e0649c 2278 if ($lifetime > 0) {
29c43343
PS
2279 $private = '';
2280 if (isloggedin() and !isguestuser()) {
2281 $private = ' private,';
2282 }
d5dd0540 2283 $nobyteserving = false;
c3a3f540 2284 header('Cache-Control:'.$private.' max-age='.$lifetime.', no-transform');
cbad562e
PS
2285 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2286 header('Pragma: ');
4c8c65ec 2287
4c8c65ec 2288 } else { // Do not cache files in proxies and browsers
d5dd0540 2289 $nobyteserving = true;
85e00626 2290 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
c3a3f540 2291 header('Cache-Control: private, max-age=10, no-transform');
cbad562e
PS
2292 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2293 header('Pragma: ');
85e00626 2294 } else { //normal http - prevent caching at all cost
c3a3f540 2295 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
cbad562e
PS
2296 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2297 header('Pragma: no-cache');
85e00626 2298 }
69faecce 2299 }
f1e0649c 2300
b9709b76 2301 if (empty($filter)) {
cbad562e 2302 // send the contents
f1e0649c 2303 if ($pathisstring) {
d5dd0540 2304 readstring_accel($path, $mimetype, !$dontdie);
4c8c65ec 2305 } else {
d5dd0540 2306 readfile_accel($path, $mimetype, !$dontdie);
f1e0649c 2307 }
cbad562e 2308
d5dd0540
PS
2309 } else {
2310 // Try to put the file through filters
f1e0649c 2311 if ($mimetype == 'text/html') {
365a5941 2312 $options = new stdClass();
f1e0649c 2313 $options->noclean = true;
a17c57b5 2314 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 2315 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 2316
3ace5ee4 2317 $text = file_modify_html_header($text);
60f9e36e 2318 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
f1e0649c 2319
d5dd0540 2320 readstring_accel($output, $mimetype, false);
c4cef1fe 2321
b9709b76 2322 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
d5dd0540 2323 // only filter text if filter all files is selected
365a5941 2324 $options = new stdClass();
f1e0649c 2325 $options->newlines = false;
2326 $options->noclean = true;
1a4596e4 2327 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
60f9e36e 2328 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
f1e0649c 2329
d5dd0540 2330 readstring_accel($output, $mimetype, false);
c4cef1fe 2331
d5dd0540 2332 } else {
cbad562e 2333 // send the contents
f1e0649c 2334 if ($pathisstring) {
d5dd0540
PS
2335 readstring_accel($path, $mimetype, !$dontdie);
2336 } else {
2337 readfile_accel($path, $mimetype, !$dontdie);
f1e0649c 2338 }
2339 }
2340 }
b379f7d9 2341 if ($dontdie) {
2342 return;
2343 }
f1e0649c 2344 die; //no more chars to output!!!
2345}
2346
172dd12c 2347/**
2348 * Handles the sending of file data to the user's browser, including support for
2349 * byteranges etc.
ba21c9d4 2350 *
796495fe
DM
2351 * The $options parameter supports the following keys:
2352 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2353 * (string|null) filename - overrides the implicit filename
2354 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2355 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2356 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2357 * and should not be reopened.
2358 *
d2b7803e 2359 * @category files
d2b7803e 2360 * @param stored_file $stored_file local file object
0c431257 2361 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
172dd12c 2362 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2363 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
796495fe
DM
2364 * @param array $options additional options affecting the file serving
2365 * @return null script execution stopped unless $options['dontdie'] is true
172dd12c 2366 */
0c431257 2367function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
d5dd0540 2368 global $CFG, $COURSE;
172dd12c 2369
796495fe
DM
2370 if (empty($options['filename'])) {
2371 $filename = null;
2372 } else {
2373 $filename = $options['filename'];
2374 }
2375
2376 if (empty($options['dontdie'])) {
2377 $dontdie = false;
2378 } else {
2379 $dontdie = true;
2380 }
2381
0c431257
PS
2382 if ($lifetime === 'default' or is_null($lifetime)) {
2383 $lifetime = $CFG->filelifetime;
2384 }
2385
82c224ee
DM
2386 if (!empty($options['preview'])) {
2387 // replace the file with its preview
2388 $fs = get_file_storage();
77a43933
DM
2389 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2390 if (!$preview_file) {
2391 // unable to create a preview of the file, send its default mime icon instead
2392 if ($options['preview'] === 'tinyicon') {
2393 $size = 24;
2394 } else if ($options['preview'] === 'thumb') {
2395 $size = 90;
2396 } else {
2397 $size = 256;
2398 }
2399 $fileicon = file_file_icon($stored_file, $size);
2400 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
82c224ee
DM
2401 } else {
2402 // preview images have fixed cache lifetime and they ignore forced download
2403 // (they are generated by GD and therefore they are considered reasonably safe).
77a43933 2404 $stored_file = $preview_file;
82c224ee
DM
2405 $lifetime = DAYSECS;
2406 $filter = 0;
2407 $forcedownload = false;
2408 }
2409 }
2410
67233725 2411 // handle external resource
bc6f241c 2412 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
67233725
DC
2413 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2414 die;
2415 }
2416
2f657978
PS
2417 if (!$stored_file or $stored_file->is_directory()) {
2418 // nothing to serve
2419 if ($dontdie) {
2420 return;
2421 }
2422 die;
2423 }
2424
b379f7d9 2425 if ($dontdie) {
15325f55 2426 ignore_user_abort(true);
b379f7d9 2427 }
2428
d79d5ac2 2429 \core\session\manager::write_close(); // Unlock session during file serving.
172dd12c 2430
2431 // Use given MIME type if specified, otherwise guess it using mimeinfo.
2432 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
2433 // only Firefox saves all files locally before opening when content-disposition: attachment stated
2434 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
378b3eac 2435 $isFF = core_useragent::is_firefox(); // only FF properly tested
172dd12c 2436 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
2437 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
b5bbeaf0 2438
172dd12c 2439 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
378b3eac 2440 if (core_useragent::is_ie()) {
172dd12c 2441 $filename = rawurlencode($filename);
2442 }
2443
2444 if ($forcedownload) {
cbad562e 2445 header('Content-Disposition: attachment; filename="'.$filename.'"');
172dd12c 2446 } else {
cbad562e 2447 header('Content-Disposition: inline; filename="'.$filename.'"');
172dd12c 2448 }
2449
2450 if ($lifetime > 0) {
29c43343
PS
2451 $private = '';
2452 if (isloggedin() and !isguestuser()) {
2453 $private = ' private,';
2454 }
c3a3f540 2455 header('Cache-Control:'.$private.' max-age='.$lifetime.', no-transform');
cbad562e
PS
2456 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2457 header('Pragma: ');
172dd12c 2458
172dd12c 2459 } else { // Do not cache files in proxies and browsers
2460 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
c3a3f540 2461 header('Cache-Control: private, max-age=10, no-transform');
cbad562e
PS
2462 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2463 header('Pragma: ');
172dd12c 2464 } else { //normal http - prevent caching at all cost
c3a3f540 2465 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
cbad562e
PS
2466 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2467 header('Pragma: no-cache');
172dd12c 2468 }
172dd12c 2469 }
2470
2471 if (empty($filter)) {
cbad562e 2472 // send the contents
d5dd0540 2473 readfile_accel($stored_file, $mimetype, !$dontdie);
172dd12c 2474
2475 } else { // Try to put the file through filters
2476 if ($mimetype == 'text/html') {
365a5941 2477 $options = new stdClass();
172dd12c 2478 $options->noclean = true;
2479 $options->nocache = true; // temporary workaround for MDL-5136
2480 $text = $stored_file->get_content();
2481 $text = file_modify_html_header($text);
2482 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
172dd12c 2483
d5dd0540 2484 readstring_accel($output, $mimetype, false);
c4cef1fe 2485
172dd12c 2486 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
c4cef1fe 2487 // only filter text if filter all files is selected
365a5941 2488 $options = new stdClass();
172dd12c 2489 $options->newlines = false;
2490 $options->noclean = true;
2491 $text = $stored_file->get_content();
2492 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
172dd12c 2493
d5dd0540 2494 readstring_accel($output, $mimetype, false);
c4cef1fe 2495
172dd12c 2496 } else { // Just send it out raw
d5dd0540 2497 readfile_accel($stored_file, $mimetype, !$dontdie);
172dd12c 2498 }
2499 }
b379f7d9 2500 if ($dontdie) {
2501 return;
2502 }
172dd12c 2503 die; //no more chars to output!!!
2504}
2505
ba21c9d4 2506/**
34ff25a6 2507 * Retrieves an array of records from a CSV file and places
ba21c9d4 2508 * them into a given table structure
2509 *
d2b7803e
DC
2510 * @global stdClass $CFG
2511 * @global moodle_database $DB
ba21c9d4 2512 * @param string $file The path to a CSV file
2513 * @param string $table The table to retrieve columns from
2514 * @return bool|array Returns an array of CSV records or false
2515 */
a43b5308 2516function get_records_csv($file, $table) {
f33e1ed4 2517 global $CFG, $DB;
599f38f9 2518
f33e1ed4 2519 if (!$metacolumns = $DB->get_columns($table)) {
599f38f9 2520 return false;
2521 }
2522
a77b98eb 2523 if(!($handle = @fopen($file, 'r'))) {
5a2a5331 2524 print_error('get_records_csv failed to open '.$file);
599f38f9 2525 }
2526
2527 $fieldnames = fgetcsv($handle, 4096);
2528 if(empty($fieldnames)) {
2529 fclose($handle);
2530 return false;
2531 }
2532
2533 $columns = array();
2534
2535 foreach($metacolumns as $metacolumn) {
2536 $ord = array_search($metacolumn->name, $fieldnames);
2537 if(is_int($ord)) {
2538 $columns[$metacolumn->name] = $ord;
2539 }
2540 }
2541
2542 $rows = array();
2543
2544 while (($data = fgetcsv($handle, 4096)) !== false) {
2545 $item = new stdClass;
2546 foreach($columns as $name => $ord) {
2547 $item->$name = $data[$ord];
2548 }
2549 $rows[] = $item;
2550 }
2551
2552 fclose($handle);
2553 return $rows;
2554}
2555
ba21c9d4 2556/**
d2b7803e 2557 * Create a file with CSV contents
117bd748 2558 *
d2b7803e
DC
2559 * @global stdClass $CFG
2560 * @global moodle_database $DB
ba21c9d4 2561 * @param string $file The file to put the CSV content into
2562 * @param array $records An array of records to write to a CSV file
2563 * @param string $table The table to get columns from
2564 * @return bool success
2565 */
a77b98eb 2566function put_records_csv($file, $records, $table = NULL) {
f33e1ed4 2567 global $CFG, $DB;
a77b98eb 2568
a1e93da2 2569 if (empty($records)) {
a77b98eb 2570 return true;
2571 }
2572
2573 $metacolumns = NULL;
f33e1ed4 2574 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
a77b98eb 2575 return false;
2576 }
2577
a1e93da2 2578 echo "x";
2579
7aa06e6d 2580 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
5a2a5331 2581 print_error('put_records_csv failed to open '.$file);
a77b98eb 2582 }
2583
a43b5308 2584 $proto = reset($records);
2585 if(is_object($proto)) {
2586 $fields_records = array_keys(get_object_vars($proto));
2587 }
2588 else if(is_array($proto)) {
2589 $fields_records = array_keys($proto);
2590 }
2591 else {
2592 return false;
2593 }
a1e93da2 2594 echo "x";
a77b98eb 2595
2596 if(!empty($metacolumns)) {
2597 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2598 $fields = array_intersect($fields_records, $fields_table);
2599 }
2600 else {
2601 $fields = $fields_records;
2602 }
2603
2604 fwrite($fp, implode(',', $fields));
2605 fwrite($fp, "\r\n");
2606
2607 foreach($records as $record) {
a43b5308 2608 $array = (array)$record;
a77b98eb 2609 $values = array();
2610 foreach($fields as $field) {
a43b5308 2611 if(strpos($array[$field], ',')) {
2612 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 2613 }
2614 else {
a43b5308 2615 $values[] = $array[$field];
a77b98eb 2616 }
2617 }
2618 fwrite($fp, implode(',', $values)."\r\n");
2619 }
2620
2621 fclose($fp);
eb459f71 2622 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
a77b98eb 2623 return true;
2624}
2625
f401cc97 2626
34763a79 2627/**
76ca1ff1 2628 * Recursively delete the file or folder with path $location. That is,
34763a79 2629 * if it is a file delete it. If it is a folder, delete all its content
db3a0b34 2630 * then delete it. If $location does not exist to start, that is not
2631 * considered an error.
76ca1ff1 2632 *
eab8ed9f 2633 * @param string $location the path to remove.
ba21c9d4 2634 * @return bool
34763a79 2635 */
4c8c65ec 2636function fulldelete($location) {
1e06adb4
PS
2637 if (empty($location)) {
2638 // extra safety against wrong param
2639 return false;
2640 }
f401cc97 2641 if (is_dir($location)) {
80c27aab
CF
2642 if (!$currdir = opendir($location)) {
2643 return false;
2644 }
f401cc97 2645 while (false !== ($file = readdir($currdir))) {
2646 if ($file <> ".." && $file <> ".") {
2647 $fullfile = $location."/".$file;
4c8c65ec 2648 if (is_dir($fullfile)) {
f401cc97 2649 if (!fulldelete($fullfile)) {
2650 return false;
2651 }
2652 } else {
2653 if (!unlink($fullfile)) {
2654 return false;
2655 }
4c8c65ec 2656 }
f401cc97 2657 }
4c8c65ec 2658 }
f401cc97 2659 closedir($currdir);
2660 if (! rmdir($location)) {
2661 return false;
2662 }
2663
34763a79 2664 } else if (file_exists($location)) {
f401cc97 2665 if (!unlink($location)) {
2666 return false;
2667 }
2668 }
2669 return true;
2670}
2671
4c8c65ec 2672/**
2673 * Send requested byterange of file.
ba21c9d4 2674 *
d2b7803e 2675 * @param resource $handle A file handle
ba21c9d4 2676 * @param string $mimetype The mimetype for the output
2677 * @param array $ranges An array of ranges to send
2678 * @param string $filesize The size of the content if only one range is used
4c8c65ec 2679 */
172dd12c 2680function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
d5dd0540 2681 // better turn off any kind of compression and buffering
b19d75a2 2682 ini_set('zlib.output_compression', 'Off');
d5dd0540 2683
4c8c65ec 2684 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
4c8c65ec 2685 if ($handle === false) {
2686 die;
2687 }
2688 if (count($ranges) == 1) { //only one range requested
2689 $length = $ranges[0][2] - $ranges[0][1] + 1;
cbad562e
PS
2690 header('HTTP/1.1 206 Partial content');
2691 header('Content-Length: '.$length);
2692 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2693 header('Content-Type: '.$mimetype);
c4cef1fe 2694
d5dd0540
PS
2695 while(@ob_get_level()) {
2696 if (!@ob_end_flush()) {
2697 break;
2698 }
2699 }
c4cef1fe 2700
4c8c65ec 2701 fseek($handle, $ranges[0][1]);
2702 while (!feof($handle) && $length > 0) {
3ef7279f 2703 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 2704 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2705 echo $buffer;
2706 flush();
2707 $length -= strlen($buffer);
2708 }
2709 fclose($handle);
2710 die;
2711 } else { // multiple ranges requested - not tested much
2712 $totallength = 0;
2713 foreach($ranges as $range) {
aba588a7 2714 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 2715 }
aba588a7 2716 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
cbad562e
PS
2717 header('HTTP/1.1 206 Partial content');
2718 header('Content-Length: '.$totallength);
2719 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
c4cef1fe 2720
d5dd0540
PS
2721 while(@ob_get_level()) {
2722 if (!@ob_end_flush()) {
2723 break;
2724 }
2725 }
c4cef1fe 2726
4c8c65ec 2727 foreach($ranges as $range) {
2728 $length = $range[2] - $range[1] + 1;
2729 echo $range[0];
4c8c65ec 2730 fseek($handle, $range[1]);
2731 while (!feof($handle) && $length > 0) {
3ef7279f 2732 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 2733 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2734 echo $buffer;
2735 flush();
2736 $length -= strlen($buffer);
2737 }
2738 }
2739 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2740 fclose($handle);
2741 die;
2742 }
2743}
f401cc97 2744
3ace5ee4 2745/**
2746 * add includes (js and css) into uploaded files
2747 * before returning them, useful for themes and utf.js includes
ba21c9d4 2748 *
d2b7803e 2749 * @global stdClass $CFG
ba21c9d4 2750 * @param string $text text to search and replace
2751 * @return string text with added head includes
d2b7803e 2752 * @todo MDL-21120
3ace5ee4 2753 */
2754function file_modify_html_header($text) {
2755 // first look for <head> tag
2756 global $CFG;
76ca1ff1 2757
3ace5ee4 2758 $stylesheetshtml = '';
78946b9b
PS
2759/* foreach ($CFG->stylesheets as $stylesheet) {
2760 //TODO: MDL-21120
3ace5ee4 2761 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
78946b9b 2762 }*/
76ca1ff1 2763
5b8fa09b 2764 $ufo = '';
0662bd67 2765 if (filter_is_enabled('mediaplugin')) {
76ca1ff1 2766 // this script is needed by most media filter plugins.
f2ab0d06 2767 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
26acc814 2768 $ufo = html_writer::tag('script', '', $attributes) . "\n";
3ace5ee4 2769 }
76ca1ff1 2770
3ace5ee4 2771 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2772 if ($matches) {
2773 $replacement = '<head>'.$ufo.$stylesheetshtml;
2774 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 2775 return $text;
3ace5ee4 2776 }
76ca1ff1 2777
3ace5ee4 2778 // if not, look for <html> tag, and stick <head> right after
2779 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2780 if ($matches) {
2781 // replace <html> tag with <html><head>includes</head>
13534ef7 2782 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 2783 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 2784 return $text;
3ace5ee4 2785 }
76ca1ff1 2786
3ace5ee4 2787 // if not, look for <body> tag, and stick <head> before body
2788 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2789 if ($matches) {
13534ef7 2790 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 2791 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 2792 return $text;
2793 }
2794
3ace5ee4 2795 // if not, just stick a <head> tag at the beginning
2796 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2797 return $text;
2798}
2799
bb2c046d 2800/**
2801 * RESTful cURL class
2802 *
2803 * This is a wrapper class for curl, it is quite easy to use:
ba21c9d4 2804 * <code>
bb2c046d 2805 * $c = new curl;
2806 * // enable cache
2807 * $c = new curl(array('cache'=>true));
2808 * // enable cookie
2809 * $c = new curl(array('cookie'=>true));
2810 * // enable proxy
2811 * $c = new curl(array('proxy'=>true));
2812 *
2813 * // HTTP GET Method
2814 * $html = $c->get('http://example.com');
2815 * // HTTP POST Method
2816 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2817 * // HTTP PUT Method
2818 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
ba21c9d4 2819 * </code>
bb2c046d 2820 *
d2b7803e
DC
2821 * @package core_files
2822 * @category files
2823 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2824 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
bb2c046d 2825 */
bb2c046d 2826class curl {
d2b7803e 2827 /** @var bool Caches http request contents */
bb2c046d 2828 public $cache = false;
220eef0e
PS
2829 /** @var bool Uses proxy, null means automatic based on URL */
2830 public $proxy = null;
d2b7803e 2831 /** @var string library version */
bb2c046d 2832 public $version = '0.4 dev';
d2b7803e 2833 /** @var array http's response */
bb2c046d 2834 public $response = array();
220eef0e
PS
2835 /** @var array Raw response headers, needed for BC in download_file_content(). */
2836 public $rawresponse = array();
d2b7803e 2837 /** @var array http header */
bb2c046d 2838 public $header = array();
d2b7803e 2839 /** @var string cURL information */
bb2c046d 2840 public $info;
d2b7803e 2841 /** @var string error */
bb2c046d 2842 public $error;
a3c94686
MG
2843 /** @var int error code */
2844 public $errno;
220eef0e
PS
2845 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2846 public $emulateredirects = null;
117bd748 2847
d2b7803e 2848 /** @var array cURL options */
bb2c046d 2849 private $options;
d2b7803e 2850 /** @var string Proxy host */
bb2c046d 2851 private $proxy_host = '';
d2b7803e 2852 /** @var string Proxy auth */
bb2c046d 2853 private $proxy_auth = '';
d2b7803e 2854 /** @var string Proxy type */
bb2c046d 2855 private $proxy_type = '';
d2b7803e 2856 /** @var bool Debug mode on */
bb2c046d 2857 private $debug = false;
d2b7803e 2858 /** @var bool|string Path to cookie file */
bb2c046d 2859 private $cookie = false;
220eef0e
PS
2860 /** @var bool tracks multiple headers in response - redirect detection */
2861 private $responsefinished = false;
bb2c046d 2862
ba21c9d4 2863 /**
220eef0e 2864 * Curl constructor.
d2b7803e 2865 *
220eef0e
PS
2866 * Allowed settings are:
2867 * proxy: (bool) use proxy server, null means autodetect non-local from url
2868 * debug: (bool) use debug output
2869 * cookie: (string) path to cookie file, false if none
2870 * cache: (bool) use cache
2871 * module_cache: (string) type of cache
2872 *
2873 * @param array $settings
ba21c9d4 2874 */
220eef0e 2875 public function __construct($settings = array()) {
bb2c046d 2876 global $CFG;
2877 if (!function_exists('curl_init')) {
2878 $this->error = 'cURL module must be enabled!';
2879 trigger_error($this->error, E_USER_ERROR);
2880 return false;
2881 }
220eef0e
PS
2882
2883 // All settings of this class should be init here.
bb2c046d 2884 $this->resetopt();
220eef0e 2885 if (!empty($settings['debug'])) {
bb2c046d 2886 $this->debug = true;
2887 }
220eef0e
PS
2888 if (!empty($settings['cookie'])) {
2889 if($settings['cookie'] === true) {
bb2c046d 2890 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2891 } else {
220eef0e 2892 $this->cookie = $settings['cookie'];
bb2c046d 2893 }
2894 }
220eef0e 2895 if (!empty($settings['cache'])) {
bb2c046d 2896 if (class_exists('curl_cache')) {
220eef0e
PS
2897 if (!empty($settings['module_cache'])) {
2898 $this->cache = new curl_cache($settings['module_cache']);
5430f05b 2899 } else {
2900 $this->cache = new curl_cache('misc');
2901 }
bb2c046d 2902 }
2903 }
d04ce87f 2904 if (!empty($CFG->proxyhost)) {
2905 if (empty($CFG->proxyport)) {
2906 $this->proxy_host = $CFG->proxyhost;
2907 } else {
2908 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2909 }
2910 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2911 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2912 $this->setopt(array(
2913 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2914 'proxyuserpwd'=>$this->proxy_auth));
2915 }
2916 if (!empty($CFG->proxytype)) {
2917 if ($CFG->proxytype == 'SOCKS5') {
2918 $this->proxy_type = CURLPROXY_SOCKS5;
bb2c046d 2919 } else {
d04ce87f 2920 $this->proxy_type = CURLPROXY_HTTP;
f6d3e2c4 2921 $this->setopt(array('httpproxytunnel'=>false));
bb2c046d 2922 }
d04ce87f 2923 $this->setopt(array('proxytype'=>$this->proxy_type));
bb2c046d 2924 }
220eef0e
PS
2925
2926 if (isset($settings['proxy'])) {
2927 $this->proxy = $settings['proxy'];
2928 }
2929 } else {
2930 $this->proxy = false;
d04ce87f 2931 }
220eef0e
PS
2932
2933 if (!isset($this->emulateredirects)) {
90627d9d 2934 $this->emulateredirects = ini_get('open_basedir');
bb2c046d 2935 }
2936 }
220eef0e 2937
ba21c9d4 2938 /**
2939 * Resets the CURL options that have already been set
2940 */
9936c2a5 2941 public function resetopt() {
bb2c046d 2942 $this->options = array();
2943 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2944 // True to include the header in the output
2945 $this->options['CURLOPT_HEADER'] = 0;
2946 // True to Exclude the body from the output
2947 $this->options['CURLOPT_NOBODY'] = 0;
220eef0e
PS
2948 // Redirect ny default.
2949 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
bb2c046d 2950 $this->options['CURLOPT_MAXREDIRS'] = 10;
2951 $this->options['CURLOPT_ENCODING'] = '';
2952 // TRUE to return the transfer as a string of the return
2953 // value of curl_exec() instead of outputting it out directly.
2954 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
bb2c046d 2955 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2956 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
6135bd45 2957 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
c2140b5d
PS
2958
2959 if ($cacert = self::get_cacert()) {
2960 $this->options['CURLOPT_CAINFO'] = $cacert;
2961 }
2962 }
2963
2964 /**
2965 * Get the location of ca certificates.
2966 * @return string absolute file path or empty if default used
2967 */
2968 public static function get_cacert() {
2969 global $CFG;
2970
2971 // Bundle in dataroot always wins.
2972 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2973 return realpath("$CFG->dataroot/moodleorgca.crt");
2974 }
2975
2976 // Next comes the default from php.ini
2977 $cacert = ini_get('curl.cainfo');
2978 if (!empty($cacert) and is_readable($cacert)) {
2979 return realpath($cacert);
2980 }
2981
2982 // Windows PHP does not have any certs, we need to use something.
2983 if ($CFG->ostype === 'WINDOWS') {
2984 if (is_readable("$CFG->libdir/cacert.pem")) {
2985 return realpath("$CFG->libdir/cacert.pem");
2986 }
2987 }
2988
2989 // Use default, this should work fine on all properly configured *nix systems.
2990 return null;
bb2c046d 2991 }
2992
2993 /**
2994 * Reset Cookie
bb2c046d 2995 */
2996 public function resetcookie() {
2997 if (!empty($this->cookie)) {
2998 if (is_file($this->cookie)) {
2999 $fp = fopen($this->cookie, 'w');
3000 if (!empty($fp)) {
3001 fwrite($fp, '');
3002 fclose($fp);
3003 }
3004 }
3005 }
3006 }
3007
3008 /**
91c8cf99 3009 * Set curl options.
bb2c046d 3010 *
91c8cf99
F
3011 * Do not use the curl constants to define the options, pass a string
3012 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3013 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3014 *
3015 * @param array $options If array is null, this function will reset the options to default value.
3016 * @return void
3017 * @throws coding_exception If an option uses constant value instead of option name.
bb2c046d 3018 */
3019 public function setopt($options = array()) {
3020 if (is_array($options)) {
9936c2a5 3021 foreach ($options as $name => $val) {
91c8cf99
F
3022 if (!is_string($name)) {
3023 throw new coding_exception('Curl options should be defined using strings, not constant values.');
3024 }
bb2c046d 3025 if (stripos($name, 'CURLOPT_') === false) {
3026 $name = strtoupper('CURLOPT_'.$name);
220eef0e
PS
3027 } else {
3028 $name = strtoupper($name);
bb2c046d 3029 }
3030 $this->options[$name] = $val;
3031 }
3032 }
3033 }
d2b7803e 3034
bb2c046d 3035 /**
3036 * Reset http method
bb2c046d 3037 */
9936c2a5 3038 public function cleanopt() {
bb2c046d 3039 unset($this->options['CURLOPT_HTTPGET']);
3040 unset($this->options['CURLOPT_POST']);
3041 unset($this->options['CURLOPT_POSTFIELDS']);
3042 unset($this->options['CURLOPT_PUT']);
3043 unset($this->options['CURLOPT_INFILE']);
3044 unset($this->options['CURLOPT_INFILESIZE']);
3045 unset($this->options['CURLOPT_CUSTOMREQUEST']);
a3c94686 3046 unset($this->options['CURLOPT_FILE']);
bb2c046d 3047 }
3048
7e1e775f
MG
3049 /**
3050 * Resets the HTTP Request headers (to prepare for the new request)
3051 */
3052 public function resetHeader() {
3053 $this->header = array();
3054 }
3055
bb2c046d 3056 /**
3057 * Set HTTP Request Header
3058 *
d2b7803e 3059 * @param array $header
bb2c046d 3060 */
3061 public function setHeader($header) {
9936c2a5 3062 if (is_array($header)) {
bb2c046d 3063 foreach ($header as $v) {
3064 $this->setHeader($v);
3065 }
3066 } else {
220eef0e
PS
3067 // Remove newlines, they are not allowed in headers.
3068 $this->header[] = preg_replace('/[\r\n]/', '', $header);
bb2c046d 3069 }
3070 }
d2b7803e 3071
bb2c046d 3072 /**
220eef0e
PS
3073 * Get HTTP Response Headers
3074 * @return array of arrays
bb2c046d 3075 */
9936c2a5 3076 public function getResponse() {
bb2c046d 3077 return $this->response;
3078 }
d2b7803e 3079
220eef0e
PS
3080 /**
3081 * Get raw HTTP Response Headers
3082 * @return array of strings
3083 */
3084 public function get_raw_response() {
3085 return $this->rawresponse;
3086 }
3087
bb2c046d 3088 /**
3089 * private callback function
3090 * Formatting HTTP Response Header
3091 *
102230b2
FM
3092 * We only keep the last headers returned. For example during a redirect the
3093 * redirect headers will not appear in {@link self::getResponse()}, if you need
3094 * to use those headers, refer to {@link self::get_raw_response()}.
3095 *
d2b7803e 3096 * @param resource $ch Apparently not used
ba21c9d4 3097 * @param string $header
3098 * @return int The strlen of the header
bb2c046d 3099 */
9936c2a5 3100 private function formatHeader($ch, $header) {
220eef0e
PS
3101 $this->rawresponse[] = $header;
3102
3103 if (trim($header, "\r\n") === '') {
102230b2 3104 // This must be the last header.
220eef0e
PS
3105 $this->responsefinished = true;
3106 }
3107
bb2c046d 3108 if (strlen($header) > 2) {
102230b2
FM
3109 if ($this->responsefinished) {
3110 // We still have headers after the supposedly last header, we must be
3111 // in a redirect so let's empty the response to keep the last headers.
3112 $this->responsefinished = false;
3113 $this->response = array();
3114 }
bb2c046d 3115 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3116 $key = rtrim($key, ':');
3117 if (!empty($this->response[$key])) {
9936c2a5 3118 if (is_array($this->response[$key])) {
bb2c046d 3119 $this->response[$key][] = $value;
3120 } else {
3121 $tmp = $this->response[$key];
3122 $this->response[$key] = array();
3123 $this->response[$key][] = $tmp;
3124 $this->response[$key][] = $value;
3125
3126 }
3127 } else {
3128 $this->response[$key] = $value;
3129 }
3130 }
3131 return strlen($header);
3132 }
3133
3134 /**
3135 * Set options for individual curl instance
ba21c9d4 3136 *
d2b7803e 3137 * @param resource $curl A curl handle
ba21c9d4 3138 * @param array $options
d2b7803e 3139 * @return resource The curl handle
bb2c046d 3140 */
3141 private function apply_opt($curl, $options) {
220eef0e
PS
3142 // Some more security first.
3143 if (defined('CURLOPT_PROTOCOLS')) {
3144 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3145 }
3146 if (defined('CURLOPT_REDIR_PROTOCOLS')) {
3147 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3148 }
3149
bb2c046d 3150 // Clean up
3151 $this->cleanopt();
3152 // set cookie
3153 if (!empty($this->cookie) || !empty($options['cookie'])) {
3154 $this->setopt(array('cookiejar'=>$this->cookie,
3155 'cookiefile'=>$this->cookie
3156 ));
3157 }
3158
220eef0e
PS
3159 // Bypass proxy if required.
3160 if ($this->proxy === null) {
3161 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3162 $proxy = false;
3163 } else {
3164 $proxy = true;
3165 }
3166 } else {
3167 $proxy = (bool)$this->proxy;
3168 }
3169
3170 // Set proxy.
3171 if ($proxy) {
3172 $options['CURLOPT_PROXY'] = $this->proxy_host;
3173 } else {
3174 unset($this->options['CURLOPT_PROXY']);
bb2c046d 3175 }
220eef0e 3176
bb2c046d 3177 $this->setopt($options);
3178 // reset before set options
3179 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3180 // set headers
9936c2a5 3181 if (empty($this->header)) {
bb2c046d 3182 $this->setHeader(array(
3183 'User-Agent: MoodleBot/1.0',
3184 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3185 'Connection: keep-alive'
3186 ));