MDL-55445 files: Helper functions related to serving and caching
[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.
296ab1e2
JL
448 * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
449 * in the @@PLUGINFILE@@ form.
ba21c9d4 450 *
d2b7803e
DC
451 * @category files
452 * @global stdClass $CFG
edc0c493 453 * @param string $text The content that may contain ULRs in need of rewriting.
454 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
d2b7803e 455 * @param int $contextid This parameter and the next two identify the file area to use.
64f93798 456 * @param string $component
34ff25a6 457 * @param string $filearea helps identify the file area.
d2b7803e 458 * @param int $itemid helps identify the file area.
296ab1e2 459 * @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function.
edc0c493 460 * @return string the processed text.
644d506a 461 */
64f93798 462function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
644d506a 463 global $CFG;
b933a139 464
33374f76
MH
465 $options = (array)$options;
466 if (!isset($options['forcehttps'])) {
467 $options['forcehttps'] = false;
468 }
469
edc0c493 470 if (!$CFG->slasharguments) {
471 $file = $file . '?file=';
b933a139 472 }
8546def3 473
64f93798 474 $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
7d2948bd 475
476 if ($itemid !== null) {
477 $baseurl .= "$itemid/";
478 }
edc0c493 479
33374f76 480 if ($options['forcehttps']) {
edc0c493 481 $baseurl = str_replace('http://', 'https://', $baseurl);
b933a139 482 }
483
296ab1e2
JL
484 if (!empty($options['reverse'])) {
485 return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
486 } else {
487 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
488 }
b933a139 489}
490
12fab708 491/**
edc0c493 492 * Returns information about files in a draft area.
ba21c9d4 493 *
d2b7803e
DC
494 * @global stdClass $CFG
495 * @global stdClass $USER
496 * @param int $draftitemid the draft area item id.
638d72cd 497 * @param string $filepath path to the directory from which the information have to be retrieved.
edc0c493 498 * @return array with the following entries:
499 * 'filecount' => number of files in the draft area.
638d72cd
FM
500 * 'filesize' => total size of the files in the draft area.
501 * 'foldercount' => number of folders in the draft area.
7aff4683 502 * 'filesize_without_references' => total size of the area excluding file references.
edc0c493 503 * (more information will be added as needed).
12fab708 504 */
638d72cd 505function file_get_draft_area_info($draftitemid, $filepath = '/') {
12fab708 506 global $CFG, $USER;
507
b0c6dc1c 508 $usercontext = context_user::instance($USER->id);
12fab708 509 $fs = get_file_storage();
510
638d72cd
FM
511 $results = array(
512 'filecount' => 0,
513 'foldercount' => 0,
7aff4683 514 'filesize' => 0,
212dac27 515 'filesize_without_references' => 0
638d72cd 516 );
edc0c493 517
638d72cd
FM
518 if ($filepath != '/') {
519 $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
520 } else {
521 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
522 }
529377b5 523 foreach ($draftfiles as $file) {
638d72cd
FM
524 if ($file->is_directory()) {
525 $results['foldercount'] += 1;
526 } else {
527 $results['filecount'] += 1;
528 }
7aff4683
FM
529
530 $filesize = $file->get_filesize();
531 $results['filesize'] += $filesize;
532 if (!$file->is_external_file()) {
533 $results['filesize_without_references'] += $filesize;
534 }
529377b5 535 }
b6accf69
DC
536
537 return $results;
538}
539
21e3ea77
FM
540/**
541 * Returns whether a draft area has exceeded/will exceed its size limit.
542 *
68acd115
FM
543 * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
544 *
21e3ea77
FM
545 * @param int $draftitemid the draft area item id.
546 * @param int $areamaxbytes the maximum size allowed in this draft area.
547 * @param int $newfilesize the size that would be added to the current area.
7aff4683 548 * @param bool $includereferences true to include the size of the references in the area size.
21e3ea77 549 * @return bool true if the area will/has exceeded its limit.
5bcfd504 550 * @since Moodle 2.4
21e3ea77 551 */
7aff4683 552function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
68acd115 553 if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
21e3ea77 554 $draftinfo = file_get_draft_area_info($draftitemid);
7aff4683
FM
555 $areasize = $draftinfo['filesize_without_references'];
556 if ($includereferences) {
557 $areasize = $draftinfo['filesize'];
558 }
559 if ($areasize + $newfilesize > $areamaxbytes) {
21e3ea77
FM
560 return true;
561 }
562 }
563 return false;
564}
565
ea1780ad
DC
566/**
567 * Get used space of files
d2b7803e
DC
568 * @global moodle_database $DB
569 * @global stdClass $USER
34ff25a6 570 * @return int total bytes
ea1780ad
DC
571 */
572function file_get_user_used_space() {
e35194be 573 global $DB, $USER;
ea1780ad 574
b0c6dc1c 575 $usercontext = context_user::instance($USER->id);
e35194be
DC
576 $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
577 JOIN (SELECT contenthash, filename, MAX(id) AS id
578 FROM {files}
579 WHERE contextid = ? AND component = ? AND filearea != ?
580 GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
581 $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
582 $record = $DB->get_record_sql($sql, $params);
583 return (int)$record->totalbytes;
ea1780ad 584}
f0e5f031 585
586/**
587 * Convert any string to a valid filepath
d2b7803e 588 * @todo review this function
f0e5f031 589 * @param string $str
590 * @return string path
591 */
caf16a57 592function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
f36cb951
DC
593 if ($str == '/' or empty($str)) {
594 return '/';
595 } else {
caf16a57 596 return '/'.trim($str, '/').'/';
f36cb951 597 }
f0e5f031 598}
599
600/**
34ff25a6 601 * Generate a folder tree of draft area of current USER recursively
d2b7803e
DC
602 *
603 * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
604 * @param int $draftitemid
f0e5f031 605 * @param string $filepath
d2b7803e 606 * @param mixed $data
f0e5f031 607 */
64f93798 608function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
f0e5f031 609 global $USER, $OUTPUT, $CFG;
610 $data->children = array();
b0c6dc1c 611 $context = context_user::instance($USER->id);
f0e5f031 612 $fs = get_file_storage();
64f93798 613 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
f0e5f031 614 foreach ($files as $file) {
615 if ($file->is_directory()) {
6bdfef5d 616 $item = new stdClass();
f79321f1 617 $item->sortorder = $file->get_sortorder();
f0e5f031 618 $item->filepath = $file->get_filepath();
619
620 $foldername = explode('/', trim($item->filepath, '/'));
621 $item->fullname = trim(array_pop($foldername), '/');
622
623 $item->id = uniqid();
64f93798 624 file_get_drafarea_folders($draftitemid, $item->filepath, $item);
f0e5f031 625 $data->children[] = $item;
626 } else {
627 continue;
628 }
629 }
630 }
631}
632
633/**
634 * Listing all files (including folders) in current path (draft area)
635 * used by file manager
636 * @param int $draftitemid
637 * @param string $filepath
d2b7803e 638 * @return stdClass
f0e5f031 639 */
64f93798 640function file_get_drafarea_files($draftitemid, $filepath = '/') {
f0e5f031 641 global $USER, $OUTPUT, $CFG;
642
b0c6dc1c 643 $context = context_user::instance($USER->id);
f0e5f031 644 $fs = get_file_storage();
645
6bdfef5d 646 $data = new stdClass();
f0e5f031 647 $data->path = array();
648 $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
649
650 // will be used to build breadcrumb
e709ddd2 651 $trail = '/';
f0e5f031 652 if ($filepath !== '/') {
653 $filepath = file_correct_filepath($filepath);
654 $parts = explode('/', $filepath);
655 foreach ($parts as $part) {
656 if ($part != '' && $part != null) {
e709ddd2 657 $trail .= ($part.'/');
f0e5f031 658 $data->path[] = array('name'=>$part, 'path'=>$trail);
659 }
660 }
661 }
662
663 $list = array();
f79321f1 664 $maxlength = 12;
64f93798 665 if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
f0e5f031 666 foreach ($files as $file) {
6bdfef5d 667 $item = new stdClass();
f0e5f031 668 $item->filename = $file->get_filename();
669 $item->filepath = $file->get_filepath();
670 $item->fullname = trim($item->filename, '/');
671 $filesize = $file->get_filesize();
e709ddd2 672 $item->size = $filesize ? $filesize : null;
f0e5f031 673 $item->filesize = $filesize ? display_size($filesize) : '';
674
f79321f1 675 $item->sortorder = $file->get_sortorder();
e709ddd2
MG
676 $item->author = $file->get_author();
677 $item->license = $file->get_license();
678 $item->datemodified = $file->get_timemodified();
679 $item->datecreated = $file->get_timecreated();
9a62f779 680 $item->isref = $file->is_external_file();
0b2bfbd1
MG
681 if ($item->isref && $file->get_status() == 666) {
682 $item->originalmissing = true;
683 }
6dd299be
MG
684 // find the file this draft file was created from and count all references in local
685 // system pointing to that file
83d2700e 686 $source = @unserialize($file->get_source());
6dd299be
MG
687 if (isset($source->original)) {
688 $item->refcount = $fs->search_references_count($source->original);
689 }
f0e5f031 690
f0e5f031 691 if ($file->is_directory()) {
692 $item->filesize = 0;
559276b1 693 $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
f0e5f031 694 $item->type = 'folder';
695 $foldername = explode('/', trim($item->filepath, '/'));
696 $item->fullname = trim(array_pop($foldername), '/');
559276b1 697 $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
f0e5f031 698 } else {
64f93798 699 // do NOT use file browser here!
559276b1 700 $item->mimetype = get_mimetype_description($file);
ff32444a 701 if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
559276b1
MG
702 $item->type = 'zip';
703 } else {
704 $item->type = 'file';
705 }
dafe1296
DM
706 $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
707 $item->url = $itemurl->out();
559276b1
MG
708 $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
709 $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
dafe1296 710 if ($imageinfo = $file->get_imageinfo()) {
3333e7e2
DM
711 $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
712 $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
dafe1296
DM
713 $item->image_width = $imageinfo['width'];
714 $item->image_height = $imageinfo['height'];
715 }
f0e5f031 716 }
717 $list[] = $item;
718 }
719 }
720 $data->itemid = $draftitemid;
721 $data->list = $list;
722 return $data;
723}
724
3156b8ca 725/**
edc0c493 726 * Returns draft area itemid for a given element.
ba21c9d4 727 *
d2b7803e 728 * @category files
edc0c493 729 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
d2b7803e 730 * @return int the itemid, or 0 if there is not one yet.
3156b8ca 731 */
edc0c493 732function file_get_submitted_draft_itemid($elname) {
18bd7573
PS
733 // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
734 if (!isset($_REQUEST[$elname])) {
735 return 0;
edc0c493 736 }
18bd7573
PS
737 if (is_array($_REQUEST[$elname])) {
738 $param = optional_param_array($elname, 0, PARAM_INT);
56a7bf68 739 if (!empty($param['itemid'])) {
740 $param = $param['itemid'];
741 } else {
742 debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
743 return false;
744 }
18bd7573
PS
745
746 } else {
747 $param = optional_param($elname, 0, PARAM_INT);
3156b8ca 748 }
18bd7573
PS
749
750 if ($param) {
751 require_sesskey();
752 }
753
edc0c493 754 return $param;
3156b8ca 755}
756
67233725
DC
757/**
758 * Restore the original source field from draft files
759 *
935429af
MG
760 * Do not use this function because it makes field files.source inconsistent
761 * for draft area files. This function will be deprecated in 2.6
762 *
67233725
DC
763 * @param stored_file $storedfile This only works with draft files
764 * @return stored_file
765 */
766function file_restore_source_field_from_draft_file($storedfile) {
83d2700e 767 $source = @unserialize($storedfile->get_source());
61506a0a
DC
768 if (!empty($source)) {
769 if (is_object($source)) {
770 $restoredsource = $source->source;
771 $storedfile->set_source($restoredsource);
772 } else {
773 throw new moodle_exception('invalidsourcefield', 'error');
774 }
67233725
DC
775 }
776 return $storedfile;
777}
b933a139 778/**
edc0c493 779 * Saves files from a draft file area to a real one (merging the list of files).
780 * Can rewrite URLs in some content at the same time if desired.
ba21c9d4 781 *
d2b7803e
DC
782 * @category files
783 * @global stdClass $USER
784 * @param int $draftitemid the id of the draft area to use. Normally obtained
edc0c493 785 * from file_get_submitted_draft_itemid('elementname') or similar.
d2b7803e 786 * @param int $contextid This parameter and the next two identify the file area to save to.
64f93798 787 * @param string $component
a08171c5 788 * @param string $filearea indentifies the file area.
d2b7803e 789 * @param int $itemid helps identifies the file area.
ba21c9d4 790 * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
edc0c493 791 * @param string $text some html content that needs to have embedded links rewritten
792 * to the @@PLUGINFILE@@ form for saving in the database.
d2b7803e
DC
793 * @param bool $forcehttps force https urls.
794 * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
b933a139 795 */
64f93798 796function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
c08643da 797 global $USER;
b933a139 798
b0c6dc1c 799 $usercontext = context_user::instance($USER->id);
8546def3 800 $fs = get_file_storage();
b933a139 801
a08171c5 802 $options = (array)$options;
803 if (!isset($options['subdirs'])) {
804 $options['subdirs'] = false;
805 }
806 if (!isset($options['maxfiles'])) {
807 $options['maxfiles'] = -1; // unlimited
808 }
3b6629c0 809 if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
a08171c5 810 $options['maxbytes'] = 0; // unlimited
811 }
68acd115
FM
812 if (!isset($options['areamaxbytes'])) {
813 $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
814 }
3b6629c0
MG
815 $allowreferences = true;
816 if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
817 // we assume that if $options['return_types'] is NOT specified, we DO allow references.
818 // this is not exactly right. BUT there are many places in code where filemanager options
819 // are not passed to file_save_draft_area_files()
820 $allowreferences = false;
821 }
a08171c5 822
68acd115
FM
823 // Check if the draft area has exceeded the authorised limit. This should never happen as validation
824 // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
825 // anything at all in the next area.
826 if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
827 return null;
828 }
829
64f93798
PS
830 $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
831 $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
b933a139 832
489bd32b
MG
833 // One file in filearea means it is empty (it has only top-level directory '.').
834 if (count($draftfiles) > 1 || count($oldfiles) > 1) {
b933a139 835 // we have to merge old and new files - we want to keep file ids for files that were not changed
656e1184 836 // we change time modified for all new and changed files, we keep time created as is
a08171c5 837
838 $newhashes = array();
32495c06 839 $filecount = 0;
b933a139 840 foreach ($draftfiles as $file) {
d90c8115 841 if (!$options['subdirs'] && $file->get_filepath() !== '/') {
32495c06
MG
842 continue;
843 }
844 if (!$allowreferences && $file->is_external_file()) {
845 continue;
846 }
847 if (!$file->is_directory()) {
848 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
849 // oversized file - should not get here at all
850 continue;
851 }
852 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
853 // more files - should not get here at all
854 continue;
855 }
856 $filecount++;
857 }
64f93798 858 $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
a08171c5 859 $newhashes[$newhash] = $file;
860 }
32495c06 861
489bd32b
MG
862 // Loop through oldfiles and decide which we need to delete and which to update.
863 // After this cycle the array $newhashes will only contain the files that need to be added.
656e1184
PS
864 foreach ($oldfiles as $oldfile) {
865 $oldhash = $oldfile->get_pathnamehash();
866 if (!isset($newhashes[$oldhash])) {
64f93798 867 // delete files not needed any more - deleted by user
656e1184
PS
868 $oldfile->delete();
869 continue;
870 }
67233725 871
656e1184 872 $newfile = $newhashes[$oldhash];
0e7fd52e
MG
873 // Now we know that we have $oldfile and $newfile for the same path.
874 // Let's check if we can update this file or we need to delete and create.
875 if ($newfile->is_directory()) {
876 // Directories are always ok to just update.
877 } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
878 // File has the 'original' - we need to update the file (it may even have not been changed at all).
879 $original = file_storage::unpack_reference($source->original);
880 if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
881 // Very odd, original points to another file. Delete and create file.
882 $oldfile->delete();
883 continue;
884 }
885 } else {
886 // The same file name but absence of 'original' means that file was deteled and uploaded again.
887 // By deleting and creating new file we properly manage all existing references.
888 $oldfile->delete();
889 continue;
890 }
891
67233725
DC
892 // status changed, we delete old file, and create a new one
893 if ($oldfile->get_status() != $newfile->get_status()) {
656e1184
PS
894 // file was changed, use updated with new timemodified data
895 $oldfile->delete();
67233725 896 // This file will be added later
656e1184
PS
897 continue;
898 }
67233725 899
67233725
DC
900 // Updated author
901 if ($oldfile->get_author() != $newfile->get_author()) {
902 $oldfile->set_author($newfile->get_author());
903 }
904 // Updated license
905 if ($oldfile->get_license() != $newfile->get_license()) {
906 $oldfile->set_license($newfile->get_license());
907 }
908
909 // Updated file source
935429af
MG
910 // Field files.source for draftarea files contains serialised object with source and original information.
911 // We only store the source part of it for non-draft file area.
0e7fd52e
MG
912 $newsource = $newfile->get_source();
913 if ($source = @unserialize($newfile->get_source())) {
914 $newsource = $source->source;
915 }
916 if ($oldfile->get_source() !== $newsource) {
917 $oldfile->set_source($newsource);
67233725
DC
918 }
919
920 // Updated sort order
921 if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
922 $oldfile->set_sortorder($newfile->get_sortorder());
923 }
924
f653c9d8
DM
925 // Update file timemodified
926 if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
927 $oldfile->set_timemodified($newfile->get_timemodified());
928 }
929
14b7e500 930 // Replaced file content
0e7fd52e
MG
931 if (!$oldfile->is_directory() &&
932 ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
e9e32b1d 933 $oldfile->get_filesize() != $newfile->get_filesize() ||
6dd92c02
MG
934 $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
935 $oldfile->get_userid() != $newfile->get_userid())) {
e9e32b1d 936 $oldfile->replace_file_with($newfile);
14b7e500
MG
937 }
938
656e1184
PS
939 // unchanged file or directory - we keep it as is
940 unset($newhashes[$oldhash]);
b933a139 941 }
a08171c5 942
67233725 943 // Add fresh file or the file which has changed status
656e1184 944 // the size and subdirectory tests are extra safety only, the UI should prevent it
a08171c5 945 foreach ($newhashes as $file) {
65fead53 946 $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
0e7fd52e
MG
947 if ($source = @unserialize($file->get_source())) {
948 // Field files.source for draftarea files contains serialised object with source and original information.
935429af 949 // We only store the source part of it for non-draft file area.
0e7fd52e
MG
950 $file_record['source'] = $source->source;
951 }
67233725
DC
952
953 if ($file->is_external_file()) {
954 $repoid = $file->get_repository_id();
955 if (!empty($repoid)) {
956 $file_record['repositoryid'] = $repoid;
957 $file_record['reference'] = $file->get_reference();
958 }
959 }
960
a08171c5 961 $fs->create_file_from_storedfile($file_record, $file);
8546def3 962 }
963 }
964
64f93798 965 // note: do not purge the draft area - we clean up areas later in cron,
42776c94
PS
966 // the reason is that user might press submit twice and they would loose the files,
967 // also sometimes we might want to use hacks that save files into two different areas
b933a139 968
8546def3 969 if (is_null($text)) {
970 return null;
c08643da
TH
971 } else {
972 return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
8546def3 973 }
c08643da
TH
974}
975
976/**
977 * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
978 * ready to be saved in the database. Normally, this is done automatically by
979 * {@link file_save_draft_area_files()}.
d2b7803e
DC
980 *
981 * @category files
c08643da
TH
982 * @param string $text the content to process.
983 * @param int $draftitemid the draft file area the content was using.
984 * @param bool $forcehttps whether the content contains https URLs. Default false.
985 * @return string the processed content.
986 */
987function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
988 global $CFG, $USER;
989
b0c6dc1c 990 $usercontext = context_user::instance($USER->id);
8546def3 991
9337cf32
PS
992 $wwwroot = $CFG->wwwroot;
993 if ($forcehttps) {
994 $wwwroot = str_replace('http://', 'https://', $wwwroot);
7983d682 995 }
996
9337cf32
PS
997 // relink embedded files if text submitted - no absolute links allowed in database!
998 $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
999
1000 if (strpos($text, 'draftfile.php?file=') !== false) {
1001 $matches = array();
1002 preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1003 if ($matches) {
1004 foreach ($matches[0] as $match) {
1005 $replace = str_ireplace('%2F', '/', $match);
1006 $text = str_replace($match, $replace, $text);
1007 }
1008 }
1009 $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
7983d682 1010 }
1011
7983d682 1012 return $text;
1013}
1014
f79321f1
DC
1015/**
1016 * Set file sort order
d2b7803e
DC
1017 *
1018 * @global moodle_database $DB
1019 * @param int $contextid the context id
1020 * @param string $component file component
f79321f1 1021 * @param string $filearea file area.
d2b7803e 1022 * @param int $itemid itemid.
f79321f1
DC
1023 * @param string $filepath file path.
1024 * @param string $filename file name.
d2b7803e
DC
1025 * @param int $sortorder the sort order of file.
1026 * @return bool
f79321f1 1027 */
64f93798 1028function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
f79321f1 1029 global $DB;
64f93798 1030 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
f79321f1
DC
1031 if ($file_record = $DB->get_record('files', $conditions)) {
1032 $sortorder = (int)$sortorder;
1033 $file_record->sortorder = $sortorder;
1034 $DB->update_record('files', $file_record);
1035 return true;
1036 }
1037 return false;
1038}
1039
1040/**
1041 * reset file sort order number to 0
d2b7803e
DC
1042 * @global moodle_database $DB
1043 * @param int $contextid the context id
64f93798 1044 * @param string $component
f79321f1 1045 * @param string $filearea file area.
d2b7803e
DC
1046 * @param int|bool $itemid itemid.
1047 * @return bool
f79321f1 1048 */
64f93798 1049function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
f79321f1
DC
1050 global $DB;
1051
64f93798 1052 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
f79321f1
DC
1053 if ($itemid !== false) {
1054 $conditions['itemid'] = $itemid;
1055 }
1056
1057 $file_records = $DB->get_records('files', $conditions);
1058 foreach ($file_records as $file_record) {
1059 $file_record->sortorder = 0;
1060 $DB->update_record('files', $file_record);
1061 }
1062 return true;
1063}
1064
a83ad946 1065/**
1066 * Returns description of upload error
ba21c9d4 1067 *
a83ad946 1068 * @param int $errorcode found in $_FILES['filename.ext']['error']
ba21c9d4 1069 * @return string error description string, '' if ok
a83ad946 1070 */
1071function file_get_upload_error($errorcode) {
a08171c5 1072
a83ad946 1073 switch ($errorcode) {
1074 case 0: // UPLOAD_ERR_OK - no error
1075 $errmessage = '';
1076 break;
a08171c5 1077
a83ad946 1078 case 1: // UPLOAD_ERR_INI_SIZE
1079 $errmessage = get_string('uploadserverlimit');
1080 break;
a08171c5 1081
a83ad946 1082 case 2: // UPLOAD_ERR_FORM_SIZE
1083 $errmessage = get_string('uploadformlimit');
1084 break;
a08171c5 1085
a83ad946 1086 case 3: // UPLOAD_ERR_PARTIAL
1087 $errmessage = get_string('uploadpartialfile');
1088 break;
a08171c5 1089
a83ad946 1090 case 4: // UPLOAD_ERR_NO_FILE
1091 $errmessage = get_string('uploadnofilefound');
1092 break;
a08171c5 1093
a83ad946 1094 // Note: there is no error with a value of 5
1095
1096 case 6: // UPLOAD_ERR_NO_TMP_DIR
1097 $errmessage = get_string('uploadnotempdir');
1098 break;
1099
1100 case 7: // UPLOAD_ERR_CANT_WRITE
1101 $errmessage = get_string('uploadcantwrite');
1102 break;
1103
1104 case 8: // UPLOAD_ERR_EXTENSION
1105 $errmessage = get_string('uploadextension');
1106 break;
1107
1108 default:
1109 $errmessage = get_string('uploadproblem');
1110 }
1111
1112 return $errmessage;
1113}
1114
5db608f4 1115/**
1116 * Recursive function formating an array in POST parameter
1117 * @param array $arraydata - the array that we are going to format and add into &$data array
1118 * @param string $currentdata - a row of the final postdata array at instant T
1119 * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1120 * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1121 */
1122function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1123 foreach ($arraydata as $k=>$v) {
277c7a40 1124 $newcurrentdata = $currentdata;
5db608f4 1125 if (is_array($v)) { //the value is an array, call the function recursively
277c7a40 1126 $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1127 format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
5db608f4 1128 } else { //add the POST parameter to the $data array
277c7a40 1129 $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
5db608f4 1130 }
1131 }
1132}
1133
1134/**
1135 * Transform a PHP array into POST parameter
1136 * (see the recursive function format_array_postdata_for_curlcall)
1137 * @param array $postdata
1138 * @return array containing all POST parameters (1 row = 1 POST parameter)
1139 */
1140function format_postdata_for_curlcall($postdata) {
1141 $data = array();
1142 foreach ($postdata as $k=>$v) {
1143 if (is_array($v)) {
1144 $currentdata = urlencode($k);
1145 format_array_postdata_for_curlcall($v, $currentdata, $data);
1146 } else {
ea1780ad 1147 $data[] = urlencode($k).'='.urlencode($v);
5db608f4 1148 }
1149 }
1150 $convertedpostdata = implode('&', $data);
1151 return $convertedpostdata;
1152}
1153
8ee88311 1154/**
5f8bdc17 1155 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
599f06cf 1156 * Due to security concerns only downloads from http(s) sources are supported.
1157 *
d2b7803e 1158 * @category files
599f06cf 1159 * @param string $url file url starting with http(s)://
5ef082df 1160 * @param array $headers http headers, null if none. If set, should be an
1161 * associative array of header name => value pairs.
6bf55889 1162 * @param array $postdata array means use POST request with given parameters
1163 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
5ef082df 1164 * (if false, just returns content)
1165 * @param int $timeout timeout for complete download process including all file transfer
44e02d79 1166 * (default 5 minutes)
1167 * @param int $connecttimeout timeout for connection to server; this is the timeout that
1168 * usually happens if the remote server is completely down (default 20 seconds);
1169 * may not work when using proxy
98eaf27e 1170 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
5f1c825d
SH
1171 * Only use this when already in a trusted location.
1172 * @param string $tofile store the downloaded content to file instead of returning it.
98eaf27e 1173 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
5f1c825d 1174 * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
feff774a
SL
1175 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1176 * if file downloaded into $tofile successfully or the file content as a string.
8ee88311 1177 */
60b5a2fe 1178function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
e27f0765 1179 global $CFG;
1180
220eef0e 1181 // Only http and https links supported.
599f06cf 1182 if (!preg_match('|^https?://|i', $url)) {
1183 if ($fullresponse) {
365a5941 1184 $response = new stdClass();
599f06cf 1185 $response->status = 0;
1186 $response->headers = array();
1187 $response->response_code = 'Invalid protocol specified in url';
1188 $response->results = '';
1189 $response->error = 'Invalid protocol specified in url';
1190 return $response;
1191 } else {
1192 return false;
1193 }
1194 }
1195
220eef0e 1196 $options = array();
599f06cf 1197
220eef0e
PS
1198 $headers2 = array();
1199 if (is_array($headers)) {
6bf55889 1200 foreach ($headers as $key => $value) {
220eef0e
PS
1201 if (is_numeric($key)) {
1202 $headers2[] = $value;
1203 } else {
1204 $headers2[] = "$key: $value";
1205 }
6bf55889 1206 }
6bf55889 1207 }
1208
83947a36 1209 if ($skipcertverify) {
220eef0e
PS
1210 $options['CURLOPT_SSL_VERIFYPEER'] = false;
1211 } else {
1212 $options['CURLOPT_SSL_VERIFYPEER'] = true;
83947a36 1213 }
bb2c046d 1214
220eef0e
PS
1215 $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1216
1217 $options['CURLOPT_FOLLOWLOCATION'] = 1;
1218 $options['CURLOPT_MAXREDIRS'] = 5;
1219
1220 // Use POST if requested.
6bf55889 1221 if (is_array($postdata)) {
5db608f4 1222 $postdata = format_postdata_for_curlcall($postdata);
220eef0e
PS
1223 } else if (empty($postdata)) {
1224 $postdata = null;
5f8bdc17 1225 }
ea1780ad 1226
220eef0e
PS
1227 // Optionally attempt to get more correct timeout by fetching the file size.
1228 if (!isset($CFG->curltimeoutkbitrate)) {
1229 // Use very slow rate of 56kbps as a timeout speed when not set.
1230 $bitrate = 56;
1231 } else {
1232 $bitrate = $CFG->curltimeoutkbitrate;
c2140b5d 1233 }
220eef0e
PS
1234 if ($calctimeout and !isset($postdata)) {
1235 $curl = new curl();
1236 $curl->setHeader($headers2);
c2140b5d 1237
220eef0e 1238 $curl->head($url, $postdata, $options);
6bf55889 1239
220eef0e
PS
1240 $info = $curl->get_info();
1241 $error_no = $curl->get_errno();
1242 if (!$error_no && $info['download_content_length'] > 0) {
1243 // No curl errors - adjust for large files only - take max timeout.
1244 $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
5f8bdc17 1245 }
220eef0e 1246 }
5f8bdc17 1247
220eef0e
PS
1248 $curl = new curl();
1249 $curl->setHeader($headers2);
08ec989f 1250
220eef0e
PS
1251 $options['CURLOPT_RETURNTRANSFER'] = true;
1252 $options['CURLOPT_NOBODY'] = false;
1253 $options['CURLOPT_TIMEOUT'] = $timeout;
5f8bdc17 1254
220eef0e
PS
1255 if ($tofile) {
1256 $fh = fopen($tofile, 'w');
1257 if (!$fh) {
1258 if ($fullresponse) {
1259 $response = new stdClass();
1260 $response->status = 0;
1261 $response->headers = array();
1262 $response->response_code = 'Can not write to file';
1263 $response->results = false;
1264 $response->error = 'Can not write to file';
1265 return $response;
1266 } else {
1267 return false;
5f8bdc17 1268 }
8ee88311 1269 }
220eef0e 1270 $options['CURLOPT_FILE'] = $fh;
8ee88311 1271 }
6bf55889 1272
220eef0e
PS
1273 if (isset($postdata)) {
1274 $content = $curl->post($url, $postdata, $options);
60b5a2fe 1275 } else {
220eef0e 1276 $content = $curl->get($url, null, $options);
60b5a2fe
AB
1277 }
1278
220eef0e
PS
1279 if ($tofile) {
1280 fclose($fh);
1281 @chmod($tofile, $CFG->filepermissions);
60b5a2fe
AB
1282 }
1283
220eef0e
PS
1284/*
1285 // Try to detect encoding problems.
6bf55889 1286 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1287 curl_setopt($ch, CURLOPT_ENCODING, 'none');
3a1055a5
PS
1288 $result = curl_exec($ch);
1289 }
220eef0e 1290*/
3a1055a5 1291
220eef0e
PS
1292 $info = $curl->get_info();
1293 $error_no = $curl->get_errno();
1294 $rawheaders = $curl->get_raw_response();
6bf55889 1295
220eef0e
PS
1296 if ($error_no) {
1297 $error = $content;
1298 if (!$fullresponse) {
599f06cf 1299 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
6bf55889 1300 return false;
1301 }
5f8bdc17 1302
220eef0e
PS
1303 $response = new stdClass();
1304 if ($error_no == 28) {
1305 $response->status = '-100'; // Mimic snoopy.
599f06cf 1306 } else {
220eef0e 1307 $response->status = '0';
599f06cf 1308 }
220eef0e
PS
1309 $response->headers = array();
1310 $response->response_code = $error;
1311 $response->results = false;
1312 $response->error = $error;
1313 return $response;
1314 }
6bf55889 1315
220eef0e
PS
1316 if ($tofile) {
1317 $content = true;
08ec989f 1318 }
8ee88311 1319
220eef0e
PS
1320 if (empty($info['http_code'])) {
1321 // For security reasons we support only true http connections (Location: file:// exploit prevention).
1322 $response = new stdClass();
1323 $response->status = '0';
1324 $response->headers = array();
1325 $response->response_code = 'Unknown cURL error';
1326 $response->results = false; // do NOT change this, we really want to ignore the result!
1327 $response->error = 'Unknown cURL error';
3a1055a5 1328
220eef0e
PS
1329 } else {
1330 $response = new stdClass();
1331 $response->status = (string)$info['http_code'];
1332 $response->headers = $rawheaders;
1333 $response->results = $content;
1334 $response->error = '';
1335
1336 // There might be multiple headers on redirect, find the status of the last one.
1337 $firstline = true;
1338 foreach ($rawheaders as $line) {
1339 if ($firstline) {
1340 $response->response_code = $line;
1341 $firstline = false;
1342 }
1343 if (trim($line, "\r\n") === '') {
1344 $firstline = true;
1345 }
3a1055a5
PS
1346 }
1347 }
220eef0e
PS
1348
1349 if ($fullresponse) {
1350 return $response;
3a1055a5 1351 }
220eef0e
PS
1352
1353 if ($info['http_code'] != 200) {
1354 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1355 return false;
1356 }
1357 return $response->results;
3a1055a5
PS
1358}
1359
3ce73b14 1360/**
559276b1
MG
1361 * Returns a list of information about file types based on extensions.
1362 *
1363 * The following elements expected in value array for each extension:
1364 * 'type' - mimetype
1365 * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1366 * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1367 * also files with bigger sizes under names
1368 * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1369 * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1370 * commonly used in moodle the following groups:
1371 * - web_image - image that can be included as <img> in HTML
1372 * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1373 * - video - file that can be imported as video in text editor
1374 * - audio - file that can be imported as audio in text editor
1375 * - archive - we can extract files from this archive
1376 * - spreadsheet - used for portfolio format
1377 * - document - used for portfolio format
1378 * - presentation - used for portfolio format
1379 * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1380 * human-readable description for this filetype;
1381 * Function {@link get_mimetype_description()} first looks at the presence of string for
1382 * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1383 * attribute, if not found returns the value of 'type';
1384 * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1385 * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1386 * this function will return first found icon; Especially usefull for types such as 'text/plain'
d2b7803e
DC
1387 *
1388 * @category files
ba21c9d4 1389 * @return array List of information about file types based on extensions.
3ce73b14 1390 * Associative array of extension (lower-case) to associative array
1391 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 1392 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 1393 */
559276b1 1394function &get_mimetypes_array() {
91fed57a 1395 // Get types from the core_filetypes function, which includes caching.
1396 return core_filetypes::get_types();
3ce73b14 1397}
1398
0c4c3b9a
JP
1399/**
1400 * Determine a file's MIME type based on the given filename using the function mimeinfo.
1401 *
1402 * This function retrieves a file's MIME type for a file that will be sent to the user.
1403 * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1404 * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1405 * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1406 *
1407 * @param string $filename The file's filename.
1408 * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1409 */
1410function get_mimetype_for_sending($filename = '') {
1411 // Guess the file's MIME type using mimeinfo.
1412 $mimetype = mimeinfo('type', $filename);
1413
1414 // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1415 if (!$mimetype || $mimetype === 'document/unknown') {
1416 $mimetype = 'application/octet-stream';
1417 }
1418
1419 return $mimetype;
1420}
1421
76ca1ff1 1422/**
3ce73b14 1423 * Obtains information about a filetype based on its extension. Will
1424 * use a default if no information is present about that particular
1425 * extension.
ba21c9d4 1426 *
d2b7803e 1427 * @category files
76ca1ff1 1428 * @param string $element Desired information (usually 'icon'
559276b1
MG
1429 * for icon filename or 'type' for MIME type. Can also be
1430 * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
76ca1ff1 1431 * @param string $filename Filename we're looking up
3ce73b14 1432 * @return string Requested piece of information from array
1433 */
1434function mimeinfo($element, $filename) {
0ef98843 1435 global $CFG;
559276b1
MG
1436 $mimeinfo = & get_mimetypes_array();
1437 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1438
1439 $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1440 if (empty($filetype)) {
1441 $filetype = 'xxx'; // file without extension
1442 }
1443 if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1444 $iconsize = max(array(16, (int)$iconsizematch[1]));
1445 $filenames = array($mimeinfo['xxx']['icon']);
1446 if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1447 array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1448 }
1449 // find the file with the closest size, first search for specific icon then for default icon
1450 foreach ($filenames as $filename) {
1451 foreach ($iconpostfixes as $size => $postfix) {
1452 $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1453 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1454 return $filename.$postfix;
72aa74ce 1455 }
0ef98843 1456 }
f1e0649c 1457 }
559276b1
MG
1458 } else if (isset($mimeinfo[$filetype][$element])) {
1459 return $mimeinfo[$filetype][$element];
1460 } else if (isset($mimeinfo['xxx'][$element])) {
a370c895 1461 return $mimeinfo['xxx'][$element]; // By default
559276b1
MG
1462 } else {
1463 return null;
f1e0649c 1464 }
1465}
1466
76ca1ff1 1467/**
3ce73b14 1468 * Obtains information about a filetype based on the MIME type rather than
1469 * the other way around.
ba21c9d4 1470 *
d2b7803e 1471 * @category files
559276b1 1472 * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
76ca1ff1 1473 * @param string $mimetype MIME type we're looking up
3ce73b14 1474 * @return string Requested piece of information from array
1475 */
1476function mimeinfo_from_type($element, $mimetype) {
559276b1
MG
1477 /* array of cached mimetype->extension associations */
1478 static $cached = array();
1479 $mimeinfo = & get_mimetypes_array();
1480
1481 if (!array_key_exists($mimetype, $cached)) {
1082e7da 1482 $cached[$mimetype] = null;
559276b1
MG
1483 foreach($mimeinfo as $filetype => $values) {
1484 if ($values['type'] == $mimetype) {
1485 if ($cached[$mimetype] === null) {
e5635827 1486 $cached[$mimetype] = '.'.$filetype;
559276b1
MG
1487 }
1488 if (!empty($values['defaulticon'])) {
e5635827 1489 $cached[$mimetype] = '.'.$filetype;
559276b1
MG
1490 break;
1491 }
3ce73b14 1492 }
3ce73b14 1493 }
a8d6dda4 1494 if (empty($cached[$mimetype])) {
e5635827 1495 $cached[$mimetype] = '.xxx';
559276b1 1496 }
a8d6dda4
MG
1497 }
1498 if ($element === 'extension') {
1499 return $cached[$mimetype];
559276b1 1500 } else {
e5635827 1501 return mimeinfo($element, $cached[$mimetype]);
559276b1 1502 }
3ce73b14 1503}
b9709b76 1504
42ead7d7 1505/**
559276b1 1506 * Return the relative icon path for a given file
ba21c9d4 1507 *
559276b1
MG
1508 * Usage:
1509 * <code>
1510 * // $file - instance of stored_file or file_info
1511 * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
1512 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1513 * </code>
1514 * or
1515 * <code>
1516 * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1517 * </code>
1518 *
1519 * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1520 * and $file->mimetype are expected)
1521 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1522 * @return string
42ead7d7 1523 */
559276b1
MG
1524function file_file_icon($file, $size = null) {
1525 if (!is_object($file)) {
1526 $file = (object)$file;
1527 }
1528 if (isset($file->filename)) {
1529 $filename = $file->filename;
1530 } else if (method_exists($file, 'get_filename')) {
1531 $filename = $file->get_filename();
1532 } else if (method_exists($file, 'get_visible_name')) {
1533 $filename = $file->get_visible_name();
1534 } else {
1535 $filename = '';
637a60dc 1536 }
559276b1
MG
1537 if (isset($file->mimetype)) {
1538 $mimetype = $file->mimetype;
1539 } else if (method_exists($file, 'get_mimetype')) {
1540 $mimetype = $file->get_mimetype();
1541 } else {
1542 $mimetype = '';
42ead7d7 1543 }
ae7f35b9
MG
1544 $mimetypes = &get_mimetypes_array();
1545 if ($filename) {
1546 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1547 if ($extension && !empty($mimetypes[$extension])) {
1548 // if file name has known extension, return icon for this extension
1549 return file_extension_icon($filename, $size);
1550 }
0b46f19e 1551 }
ae7f35b9 1552 return file_mimetype_icon($mimetype, $size);
559276b1 1553}
637a60dc 1554
559276b1
MG
1555/**
1556 * Return the relative icon path for a folder image
1557 *
1558 * Usage:
1559 * <code>
1560 * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
1561 * echo html_writer::empty_tag('img', array('src' => $icon));
1562 * </code>
1563 * or
1564 * <code>
1565 * echo $OUTPUT->pix_icon(file_folder_icon(32));
1566 * </code>
1567 *
1568 * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1569 * @return string
1570 */
1571function file_folder_icon($iconsize = null) {
1572 global $CFG;
1573 static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
ae7f35b9 1574 static $cached = array();
559276b1 1575 $iconsize = max(array(16, (int)$iconsize));
ae7f35b9
MG
1576 if (!array_key_exists($iconsize, $cached)) {
1577 foreach ($iconpostfixes as $size => $postfix) {
1578 $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1579 if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1580 $cached[$iconsize] = 'f/folder'.$postfix;
1581 break;
1582 }
559276b1 1583 }
637a60dc 1584 }
ae7f35b9 1585 return $cached[$iconsize];
42ead7d7 1586}
1587
9dffa7af 1588/**
1589 * Returns the relative icon path for a given mime type
1590 *
34ff25a6 1591 * This function should be used in conjunction with $OUTPUT->pix_url to produce
9dffa7af 1592 * a return the full path to an icon.
1593 *
1594 * <code>
1595 * $mimetype = 'image/jpg';
559276b1
MG
1596 * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
1597 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
9dffa7af 1598 * </code>
1599 *
d2b7803e
DC
1600 * @category files
1601 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
9dffa7af 1602 * to conform with that.
9dffa7af 1603 * @param string $mimetype The mimetype to fetch an icon for
559276b1 1604 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
9dffa7af 1605 * @return string The relative path to the icon
1606 */
ede72522 1607function file_mimetype_icon($mimetype, $size = NULL) {
559276b1 1608 return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
9dffa7af 1609}
1610
1611/**
2dcb7d0b 1612 * Returns the relative icon path for a given file name
9dffa7af 1613 *
34ff25a6 1614 * This function should be used in conjunction with $OUTPUT->pix_url to produce
9dffa7af 1615 * a return the full path to an icon.
1616 *
9dffa7af 1617 * <code>
559276b1
MG
1618 * $filename = '.jpg';
1619 * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
1620 * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
9dffa7af 1621 * </code>
1622 *
d2b7803e 1623 * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
9dffa7af 1624 * to conform with that.
d2b7803e
DC
1625 * @todo MDL-31074 Implement $size
1626 * @category files
1627 * @param string $filename The filename to get the icon for
559276b1 1628 * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
9dffa7af 1629 * @return string
1630 */
ede72522 1631function file_extension_icon($filename, $size = NULL) {
559276b1 1632 return 'f/'.mimeinfo('icon'.$size, $filename);
9dffa7af 1633}
1634
c0381e22 1635/**
76ca1ff1 1636 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1637 * mimetypes.php language file.
ba21c9d4 1638 *
559276b1
MG
1639 * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1640 * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1641 * have filename); In case of array/stdClass the field 'mimetype' is optional.
c0381e22 1642 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 1643 * @return string Text description
c0381e22 1644 */
559276b1 1645function get_mimetype_description($obj, $capitalise=false) {
ae7f35b9 1646 $filename = $mimetype = '';
559276b1
MG
1647 if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1648 // this is an instance of stored_file
1649 $mimetype = $obj->get_mimetype();
1650 $filename = $obj->get_filename();
1651 } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1652 // this is an instance of file_info
1653 $mimetype = $obj->get_mimetype();
1654 $filename = $obj->get_visible_name();
1655 } else if (is_array($obj) || is_object ($obj)) {
1656 $obj = (array)$obj;
1657 if (!empty($obj['filename'])) {
1658 $filename = $obj['filename'];
559276b1
MG
1659 }
1660 if (!empty($obj['mimetype'])) {
1661 $mimetype = $obj['mimetype'];
559276b1
MG
1662 }
1663 } else {
1664 $mimetype = $obj;
ae7f35b9
MG
1665 }
1666 $mimetypefromext = mimeinfo('type', $filename);
1667 if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1668 // if file has a known extension, overwrite the specified mimetype
1669 $mimetype = $mimetypefromext;
559276b1
MG
1670 }
1671 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1672 if (empty($extension)) {
1673 $mimetypestr = mimeinfo_from_type('string', $mimetype);
ae7f35b9 1674 $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
559276b1
MG
1675 } else {
1676 $mimetypestr = mimeinfo('string', $filename);
1677 }
1678 $chunks = explode('/', $mimetype, 2);
1679 $chunks[] = '';
1680 $attr = array(
1681 'mimetype' => $mimetype,
1682 'ext' => $extension,
1683 'mimetype1' => $chunks[0],
1684 'mimetype2' => $chunks[1],
1685 );
1686 $a = array();
1687 foreach ($attr as $key => $value) {
1688 $a[$key] = $value;
1689 $a[strtoupper($key)] = strtoupper($value);
1690 $a[ucfirst($key)] = ucfirst($value);
1691 }
ed0f5a95 1692
1693 // MIME types may include + symbol but this is not permitted in string ids.
1694 $safemimetype = str_replace('+', '_', $mimetype);
1695 $safemimetypestr = str_replace('+', '_', $mimetypestr);
91fed57a 1696 $customdescription = mimeinfo('customdescription', $filename);
1697 if ($customdescription) {
1698 // Call format_string on the custom description so that multilang
b3d7eb6e 1699 // filter can be used (if enabled on system context). We use system
1700 // context because it is possible that the page context might not have
1701 // been defined yet.
1702 $result = format_string($customdescription, true,
1703 array('context' => context_system::instance()));
91fed57a 1704 } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
ed0f5a95 1705 $result = get_string($safemimetype, 'mimetypes', (object)$a);
1706 } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
1707 $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
559276b1
MG
1708 } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
1709 $result = get_string('default', 'mimetypes', (object)$a);
1b80c913 1710 } else {
559276b1 1711 $result = $mimetype;
76ca1ff1 1712 }
ede72522 1713 if ($capitalise) {
c0381e22 1714 $result=ucfirst($result);
1715 }
1716 return $result;
1717}
1718
559276b1
MG
1719/**
1720 * Returns array of elements of type $element in type group(s)
1721 *
1722 * @param string $element name of the element we are interested in, usually 'type' or 'extension'
1723 * @param string|array $groups one group or array of groups/extensions/mimetypes
1724 * @return array
1725 */
1726function file_get_typegroup($element, $groups) {
1727 static $cached = array();
1728 if (!is_array($groups)) {
1729 $groups = array($groups);
1730 }
1731 if (!array_key_exists($element, $cached)) {
1732 $cached[$element] = array();
1733 }
1734 $result = array();
1735 foreach ($groups as $group) {
1736 if (!array_key_exists($group, $cached[$element])) {
1737 // retrieive and cache all elements of type $element for group $group
1738 $mimeinfo = & get_mimetypes_array();
1739 $cached[$element][$group] = array();
1740 foreach ($mimeinfo as $extension => $value) {
e5635827 1741 $value['extension'] = '.'.$extension;
559276b1
MG
1742 if (empty($value[$element])) {
1743 continue;
1744 }
ae7f35b9 1745 if (($group === '.'.$extension || $group === $value['type'] ||
559276b1
MG
1746 (!empty($value['groups']) && in_array($group, $value['groups']))) &&
1747 !in_array($value[$element], $cached[$element][$group])) {
1748 $cached[$element][$group][] = $value[$element];
1749 }
1750 }
1751 }
1752 $result = array_merge($result, $cached[$element][$group]);
1753 }
41340f04 1754 return array_values(array_unique($result));
559276b1
MG
1755}
1756
1757/**
1758 * Checks if file with name $filename has one of the extensions in groups $groups
1759 *
1760 * @see get_mimetypes_array()
1761 * @param string $filename name of the file to check
1762 * @param string|array $groups one group or array of groups to check
1763 * @param bool $checktype if true and extension check fails, find the mimetype and check if
1764 * file mimetype is in mimetypes in groups $groups
1765 * @return bool
1766 */
1767function file_extension_in_typegroup($filename, $groups, $checktype = false) {
1768 $extension = pathinfo($filename, PATHINFO_EXTENSION);
e5635827 1769 if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
559276b1
MG
1770 return true;
1771 }
1772 return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
1773}
1774
1775/**
1776 * Checks if mimetype $mimetype belongs to one of the groups $groups
1777 *
1778 * @see get_mimetypes_array()
1779 * @param string $mimetype
1780 * @param string|array $groups one group or array of groups to check
1781 * @return bool
1782 */
1783function file_mimetype_in_typegroup($mimetype, $groups) {
1784 return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
1785}
1786
9e5fa330 1787/**
d2b7803e 1788 * Requested file is not found or not accessible, does not return, terminates script
ba21c9d4 1789 *
d2b7803e
DC
1790 * @global stdClass $CFG
1791 * @global stdClass $COURSE
9e5fa330 1792 */
1793function send_file_not_found() {
1794 global $CFG, $COURSE;
3ca3d259
JL
1795
1796 // Allow cross-origin requests only for Web Services.
1797 // This allow to receive requests done by Web Workers or webapps in different domains.
1798 if (WS_SERVER) {
1799 header('Access-Control-Allow-Origin: *');
1800 }
1801
dbdc7355 1802 send_header_404();
9e5fa330 1803 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1804}
dbdc7355
DM
1805/**
1806 * Helper function to send correct 404 for server.
1807 */
1808function send_header_404() {
1809 if (substr(php_sapi_name(), 0, 3) == 'cgi') {
1810 header("Status: 404 Not Found");
1811 } else {
1812 header('HTTP/1.0 404 not found');
1813 }
1814}
9e5fa330 1815
137885b7 1816/**
1817 * The readfile function can fail when files are larger than 2GB (even on 64-bit
1818 * platforms). This wrapper uses readfile for small files and custom code for
1819 * large ones.
1820 *
1821 * @param string $path Path to file
1822 * @param int $filesize Size of file (if left out, will get it automatically)
1823 * @return int|bool Size read (will always be $filesize) or false if failed
1824 */
1825function readfile_allow_large($path, $filesize = -1) {
1826 // Automatically get size if not specified.
1827 if ($filesize === -1) {
1828 $filesize = filesize($path);
1829 }
1830 if ($filesize <= 2147483647) {
1831 // If the file is up to 2^31 - 1, send it normally using readfile.
1832 return readfile($path);
1833 } else {
1834 // For large files, read and output in 64KB chunks.
1835 $handle = fopen($path, 'r');
1836 if ($handle === false) {
1837 return false;
1838 }
1839 $left = $filesize;
1840 while ($left > 0) {
1841 $size = min($left, 65536);
1842 $buffer = fread($handle, $size);
1843 if ($buffer === false) {
1844 return false;
1845 }
1846 echo $buffer;
1847 $left -= $size;
1848 }
1849 return $filesize;
1850 }
1851}
1852
cbad562e 1853/**
d5dd0540
PS
1854 * Enhanced readfile() with optional acceleration.
1855 * @param string|stored_file $file
1856 * @param string $mimetype
1857 * @param bool $accelerate
1858 * @return void
cbad562e 1859 */
d5dd0540
PS
1860function readfile_accel($file, $mimetype, $accelerate) {
1861 global $CFG;
1862
1863 if ($mimetype === 'text/plain') {
1864 // there is no encoding specified in text files, we need something consistent
1865 header('Content-Type: text/plain; charset=utf-8');
1866 } else {
1867 header('Content-Type: '.$mimetype);
596c7115
PS
1868 }
1869
d5dd0540
PS
1870 $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
1871 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
116ee3e4 1872
d5dd0540 1873 if (is_object($file)) {
78030f9d 1874 header('Etag: "' . $file->get_contenthash() . '"');
9cc5f32b 1875 if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
d5dd0540
PS
1876 header('HTTP/1.1 304 Not Modified');
1877 return;
1878 }
1879 }
1880
1881 // if etag present for stored file rely on it exclusively
1882 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
1883 // get unixtime of request header; clip extra junk off first
1884 $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
1885 if ($since && $since >= $lastmodified) {
1886 header('HTTP/1.1 304 Not Modified');
1887 return;
1888 }
1889 }
1890
1891 if ($accelerate and !empty($CFG->xsendfile)) {
1892 if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1893 header('Accept-Ranges: bytes');
1894 } else {
1895 header('Accept-Ranges: none');
1896 }
1897
1898 if (is_object($file)) {
1899 $fs = get_file_storage();
1900 if ($fs->xsendfile($file->get_contenthash())) {
1901 return;
1902 }
1903
1904 } else {
1905 require_once("$CFG->libdir/xsendfilelib.php");
1906 if (xsendfile($file)) {
1907 return;
1908 }
1909 }
1910 }
1911
1912 $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
1913
1914 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1915
1916 if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
1917 header('Accept-Ranges: bytes');
1918
1919 if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1920 // byteserving stuff - for acrobat reader and download accelerators
1921 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1922 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1923 $ranges = false;
1924 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1925 foreach ($ranges as $key=>$value) {
1926 if ($ranges[$key][1] == '') {
1927 //suffix case
1928 $ranges[$key][1] = $filesize - $ranges[$key][2];
1929 $ranges[$key][2] = $filesize - 1;
1930 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1931 //fix range length
1932 $ranges[$key][2] = $filesize - 1;
1933 }
1934 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1935 //invalid byte-range ==> ignore header
1936 $ranges = false;
1937 break;
1938 }
1939 //prepare multipart header
1940 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1941 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1942 }
1943 } else {
1944 $ranges = false;
1945 }
1946 if ($ranges) {
1947 if (is_object($file)) {
1948 $handle = $file->get_content_file_handle();
1949 } else {
1950 $handle = fopen($file, 'rb');
1951 }
1952 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
1953 }
1954 }
1955 } else {
1956 // Do not byteserve
1957 header('Accept-Ranges: none');
1958 }
1959
1960 header('Content-Length: '.$filesize);
1961
1962 if ($filesize > 10000000) {
1963 // for large files try to flush and close all buffers to conserve memory
1964 while(@ob_get_level()) {
1965 if (!@ob_end_flush()) {
1966 break;
1967 }
cbad562e
PS
1968 }
1969 }
1970
d5dd0540
PS
1971 // send the whole file content
1972 if (is_object($file)) {
1973 $file->readfile();
1974 } else {
137885b7 1975 readfile_allow_large($file, $filesize);
d5dd0540
PS
1976 }
1977}
1978
1979/**
1980 * Similar to readfile_accel() but designed for strings.
1981 * @param string $string
1982 * @param string $mimetype
1983 * @param bool $accelerate
1984 * @return void
1985 */
1986function readstring_accel($string, $mimetype, $accelerate) {
1987 global $CFG;
1988
1989 if ($mimetype === 'text/plain') {
1990 // there is no encoding specified in text files, we need something consistent
1991 header('Content-Type: text/plain; charset=utf-8');
1992 } else {
1993 header('Content-Type: '.$mimetype);
1994 }
1995 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
1996 header('Accept-Ranges: none');
1997
1998 if ($accelerate and !empty($CFG->xsendfile)) {
1999 $fs = get_file_storage();
2000 if ($fs->xsendfile(sha1($string))) {
2001 return;
2002 }
2003 }
cbad562e 2004
d5dd0540
PS
2005 header('Content-Length: '.strlen($string));
2006 echo $string;
cbad562e
PS
2007}
2008
c87c428e 2009/**
2010 * Handles the sending of temporary file to user, download is forced.
d2b7803e 2011 * File is deleted after abort or successful sending, does not return, script terminated
ba21c9d4 2012 *
c87c428e 2013 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2014 * @param string $filename proposed file name when saving file
d2b7803e 2015 * @param bool $pathisstring If the path is string
c87c428e 2016 */
45c0d224 2017function send_temp_file($path, $filename, $pathisstring=false) {
c87c428e 2018 global $CFG;
2019
0c4c3b9a
JP
2020 // Guess the file's MIME type.
2021 $mimetype = get_mimetype_for_sending($filename);
d5dd0540 2022
c87c428e 2023 // close session - not needed anymore
d79d5ac2 2024 \core\session\manager::write_close();
c87c428e 2025
2026 if (!$pathisstring) {
2027 if (!file_exists($path)) {
dbdc7355 2028 send_header_404();
45c0d224 2029 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
c87c428e 2030 }
2031 // executed after normal finish or abort
38fc0130 2032 core_shutdown_manager::register_function('send_temp_file_finished', array($path));
c87c428e 2033 }
2034
c87c428e 2035 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
378b3eac 2036 if (core_useragent::is_ie()) {
c87c428e 2037 $filename = urlencode($filename);
2038 }
2039
66969d50 2040 header('Content-Disposition: attachment; filename="'.$filename.'"');
1e31f118 2041 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
c3a3f540 2042 header('Cache-Control: private, max-age=10, no-transform');
cbad562e
PS
2043 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2044 header('Pragma: ');
c87c428e 2045 } else { //normal http - prevent caching at all cost
c3a3f540 2046 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
cbad562e
PS
2047 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2048 header('Pragma: no-cache');
c87c428e 2049 }
c87c428e 2050
d5dd0540 2051 // send the contents - we can not accelerate this because the file will be deleted asap
c87c428e 2052 if ($pathisstring) {
d5dd0540 2053 readstring_accel($path, $mimetype, false);
c87c428e 2054 } else {
d5dd0540
PS
2055 readfile_accel($path, $mimetype, false);
2056 @unlink($path);
c87c428e 2057 }
2058
2059 die; //no more chars to output
2060}
2061
2062/**
34ff25a6 2063 * Internal callback function used by send_temp_file()
d2b7803e
DC
2064 *
2065 * @param string $path
c87c428e 2066 */
2067function send_temp_file_finished($path) {
2068 if (file_exists($path)) {
2069 @unlink($path);
2070 }
2071}
19efee14
FM
2072
2073/**
2074 * Serve content which is not meant to be cached.
2075 *
2076 * This is only intended to be used for volatile public files, for instance
2077 * when development is enabled, or when caching is not required on a public resource.
2078 *
2079 * @param string $content Raw content.
2080 * @param string $filename The file name.
2081 * @return void
2082 */
2083function send_content_uncached($content, $filename) {
2084 $mimetype = mimeinfo('type', $filename);
2085 $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2086
2087 header('Content-Disposition: inline; filename="' . $filename . '"');
2088 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2089 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2090 header('Pragma: ');
2091 header('Accept-Ranges: none');
2092 header('Content-Type: ' . $mimetype . $charset);
2093 header('Content-Length: ' . strlen($content));
2094
2095 echo $content;
2096 die();
2097}
2098
2099/**
2100 * Safely save content to a certain path.
2101 *
2102 * This function tries hard to be atomic by first copying the content
2103 * to a separate file, and then moving the file across. It also prevents
2104 * the user to abort a request to prevent half-safed files.
2105 *
2106 * This function is intended to be used when saving some content to cache like
2107 * $CFG->localcachedir. If you're not caching a file you should use the File API.
2108 *
2109 * @param string $content The file content.
2110 * @param string $destination The absolute path of the final file.
2111 * @return void
2112 */
2113function file_safe_save_content($content, $destination) {
2114 global $CFG;
2115
2116 clearstatcache();
2117 if (!file_exists(dirname($destination))) {
2118 @mkdir(dirname($destination), $CFG->directorypermissions, true);
2119 }
2120
2121 // Prevent serving of incomplete file from concurrent request,
2122 // the rename() should be more atomic than fwrite().
2123 ignore_user_abort(true);
2124 if ($fp = fopen($destination . '.tmp', 'xb')) {
2125 fwrite($fp, $content);
2126 fclose($fp);
2127 rename($destination . '.tmp', $destination);
2128 @chmod($destination, $CFG->filepermissions);
2129 @unlink($destination . '.tmp'); // Just in case anything fails.
2130 }
2131 ignore_user_abort(false);
2132 if (connection_aborted()) {
2133 die();
2134 }
2135}
c87c428e 2136
76ca1ff1 2137/**
2138 * Handles the sending of file data to the user's browser, including support for
2139 * byteranges etc.
ba21c9d4 2140 *
d2b7803e 2141 * @category files
ba75ad94 2142 * @param string $path Path of file on disk (including real filename), or actual content of file as string
2143 * @param string $filename Filename to send
0c431257 2144 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
ba75ad94 2145 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2146 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
2147 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2148 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 2149 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2150 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 2151 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
2152 * and should not be reopened.
0eb97bfa
FM
2153 * @param array $options An array of options, currently accepts:
2154 * - (string) cacheability: public, or private.
d2b7803e 2155 * @return null script execution stopped unless $dontdie is true
b9709b76 2156 */
0eb97bfa
FM
2157function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2158 $dontdie=false, array $options = array()) {
d5dd0540 2159 global $CFG, $COURSE;
50f95991 2160
b379f7d9 2161 if ($dontdie) {
15325f55 2162 ignore_user_abort(true);
b379f7d9 2163 }
2164
0c431257
PS
2165 if ($lifetime === 'default' or is_null($lifetime)) {
2166 $lifetime = $CFG->filelifetime;
c8a5c6a4 2167 }
2168
d79d5ac2 2169 \core\session\manager::write_close(); // Unlock session during file serving.
172dd12c 2170
0c4c3b9a
JP
2171 // Use given MIME type if specified, otherwise guess it.
2172 if (!$mimetype || $mimetype === 'document/unknown') {
2173 $mimetype = get_mimetype_for_sending($filename);
2174 }
b5bbeaf0 2175
4f047de2 2176 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
378b3eac 2177 if (core_useragent::is_ie()) {
4638009b 2178 $filename = rawurlencode($filename);
4f047de2 2179 }
2180
4c8c65ec 2181 if ($forcedownload) {
cbad562e 2182 header('Content-Disposition: attachment; filename="'.$filename.'"');
7f68cc65
DM
2183 } else if ($mimetype !== 'application/x-shockwave-flash') {
2184 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2185 // as an upload and enforces security that may prevent the file from being loaded.
2186
cbad562e 2187 header('Content-Disposition: inline; filename="'.$filename.'"');
4c8c65ec 2188 }
2189
f1e0649c 2190 if ($lifetime > 0) {
bb8ed60a 2191 $cacheability = ' public,';
0eb97bfa
FM
2192 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2193 // This file must be cache-able by both browsers and proxies.
2194 $cacheability = ' public,';
2195 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2196 // This file must be cache-able only by browsers.
2197 $cacheability = ' private,';
2198 } else if (isloggedin() and !isguestuser()) {
bb8ed60a
MS
2199 // By default, under the conditions above, this file must be cache-able only by browsers.
2200 $cacheability = ' private,';
29c43343 2201 }
d5dd0540 2202 $nobyteserving = false;
bb8ed60a 2203 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
cbad562e
PS
2204 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2205 header('Pragma: ');
4c8c65ec 2206
4c8c65ec 2207 } else { // Do not cache files in proxies and browsers
d5dd0540 2208 $nobyteserving = true;
1e31f118 2209 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
c3a3f540 2210 header('Cache-Control: private, max-age=10, no-transform');
cbad562e
PS
2211 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2212 header('Pragma: ');
85e00626 2213 } else { //normal http - prevent caching at all cost
c3a3f540 2214 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
cbad562e
PS
2215 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2216 header('Pragma: no-cache');
85e00626 2217 }
69faecce 2218 }
f1e0649c 2219
b9709b76 2220 if (empty($filter)) {
cbad562e 2221 // send the contents
f1e0649c 2222 if ($pathisstring) {
d5dd0540 2223 readstring_accel($path, $mimetype, !$dontdie);
4c8c65ec 2224 } else {
d5dd0540 2225 readfile_accel($path, $mimetype, !$dontdie);
f1e0649c 2226 }
cbad562e 2227
d5dd0540
PS
2228 } else {
2229 // Try to put the file through filters
112aed60 2230 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
365a5941 2231 $options = new stdClass();
f1e0649c 2232 $options->noclean = true;
a17c57b5 2233 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 2234 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 2235
60f9e36e 2236 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
f1e0649c 2237
d5dd0540 2238 readstring_accel($output, $mimetype, false);
c4cef1fe 2239
b9709b76 2240 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
d5dd0540 2241 // only filter text if filter all files is selected
365a5941 2242 $options = new stdClass();
f1e0649c 2243 $options->newlines = false;
2244 $options->noclean = true;
1a4596e4 2245 $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
60f9e36e 2246 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
f1e0649c 2247
d5dd0540 2248 readstring_accel($output, $mimetype, false);
c4cef1fe 2249
d5dd0540 2250 } else {
cbad562e 2251 // send the contents
f1e0649c 2252 if ($pathisstring) {
d5dd0540
PS
2253 readstring_accel($path, $mimetype, !$dontdie);
2254 } else {
2255 readfile_accel($path, $mimetype, !$dontdie);
f1e0649c 2256 }
2257 }
2258 }
b379f7d9 2259 if ($dontdie) {
2260 return;
2261 }
f1e0649c 2262 die; //no more chars to output!!!
2263}
2264
172dd12c 2265/**
2266 * Handles the sending of file data to the user's browser, including support for
2267 * byteranges etc.
ba21c9d4 2268 *
796495fe
DM
2269 * The $options parameter supports the following keys:
2270 * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2271 * (string|null) filename - overrides the implicit filename
2272 * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2273 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
2274 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
bb8ed60a
MS
2275 * and should not be reopened
2276 * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2277 * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2278 * defaults to "public".
796495fe 2279 *
d2b7803e 2280 * @category files
d2b7803e 2281 * @param stored_file $stored_file local file object
0c431257 2282 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
172dd12c 2283 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2284 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
796495fe
DM
2285 * @param array $options additional options affecting the file serving
2286 * @return null script execution stopped unless $options['dontdie'] is true
172dd12c 2287 */
0c431257 2288function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
d5dd0540 2289 global $CFG, $COURSE;
172dd12c 2290
796495fe
DM
2291 if (empty($options['filename'])) {
2292 $filename = null;
2293 } else {
2294 $filename = $options['filename'];
2295 }
2296
2297 if (empty($options['dontdie'])) {
2298 $dontdie = false;
2299 } else {
2300 $dontdie = true;
2301 }
2302
0c431257
PS
2303 if ($lifetime === 'default' or is_null($lifetime)) {
2304 $lifetime = $CFG->filelifetime;
2305 }
2306
82c224ee
DM
2307 if (!empty($options['preview'])) {
2308 // replace the file with its preview
2309 $fs = get_file_storage();
77a43933
DM
2310 $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2311 if (!$preview_file) {
2312 // unable to create a preview of the file, send its default mime icon instead
2313 if ($options['preview'] === 'tinyicon') {
2314 $size = 24;
2315 } else if ($options['preview'] === 'thumb') {
2316 $size = 90;
2317 } else {
2318 $size = 256;
2319 }
2320 $fileicon = file_file_icon($stored_file, $size);
2321 send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
82c224ee
DM
2322 } else {
2323 // preview images have fixed cache lifetime and they ignore forced download
2324 // (they are generated by GD and therefore they are considered reasonably safe).
77a43933 2325 $stored_file = $preview_file;
82c224ee
DM
2326 $lifetime = DAYSECS;
2327 $filter = 0;
2328 $forcedownload = false;
2329 }
2330 }
2331
67233725 2332 // handle external resource
bc6f241c 2333 if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
67233725
DC
2334 $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2335 die;
2336 }
2337
2f657978
PS
2338 if (!$stored_file or $stored_file->is_directory()) {
2339 // nothing to serve
2340 if ($dontdie) {
2341 return;
2342 }
2343 die;
2344 }
2345
b379f7d9 2346 if ($dontdie) {
15325f55 2347 ignore_user_abort(true);
b379f7d9 2348 }
2349
d79d5ac2 2350 \core\session\manager::write_close(); // Unlock session during file serving.
172dd12c 2351
172dd12c 2352 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
0c4c3b9a
JP
2353
2354 // Use given MIME type if specified.
2355 $mimetype = $stored_file->get_mimetype();
2356
2357 // Otherwise guess it.
2358 if (!$mimetype || $mimetype === 'document/unknown') {
2359 $mimetype = get_mimetype_for_sending($filename);
2360 }
b5bbeaf0 2361
172dd12c 2362 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
378b3eac 2363 if (core_useragent::is_ie()) {
172dd12c 2364 $filename = rawurlencode($filename);
2365 }
2366
2367 if ($forcedownload) {
cbad562e 2368 header('Content-Disposition: attachment; filename="'.$filename.'"');
9528f643
DM
2369 } else if ($mimetype !== 'application/x-shockwave-flash') {
2370 // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2371 // as an upload and enforces security that may prevent the file from being loaded.
2372
cbad562e 2373 header('Content-Disposition: inline; filename="'.$filename.'"');
172dd12c 2374 }
2375
2376 if ($lifetime > 0) {
bb8ed60a
MS
2377 $cacheability = ' public,';
2378 if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2379 // This file must be cache-able by both browsers and proxies.
2380 $cacheability = ' public,';
2381 } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2382 // This file must be cache-able only by browsers.
2383 $cacheability = ' private,';
2384 } else if (isloggedin() and !isguestuser()) {
2385 $cacheability = ' private,';
2386 }
2387 header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform');
cbad562e
PS
2388 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2389 header('Pragma: ');
172dd12c 2390
172dd12c 2391 } else { // Do not cache files in proxies and browsers
1e31f118 2392 if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
c3a3f540 2393 header('Cache-Control: private, max-age=10, no-transform');
cbad562e
PS
2394 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2395 header('Pragma: ');
172dd12c 2396 } else { //normal http - prevent caching at all cost
c3a3f540 2397 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
cbad562e
PS
2398 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2399 header('Pragma: no-cache');
172dd12c 2400 }
172dd12c 2401 }
2402
3ca3d259
JL
2403 // Allow cross-origin requests only for Web Services.
2404 // This allow to receive requests done by Web Workers or webapps in different domains.
2405 if (WS_SERVER) {
2406 header('Access-Control-Allow-Origin: *');
2407 }
2408
172dd12c 2409 if (empty($filter)) {
cbad562e 2410 // send the contents
d5dd0540 2411 readfile_accel($stored_file, $mimetype, !$dontdie);
172dd12c 2412
2413 } else { // Try to put the file through filters
112aed60 2414 if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
365a5941 2415 $options = new stdClass();
172dd12c 2416 $options->noclean = true;
2417 $options->nocache = true; // temporary workaround for MDL-5136
2418 $text = $stored_file->get_content();
172dd12c 2419 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
172dd12c 2420
d5dd0540 2421 readstring_accel($output, $mimetype, false);
c4cef1fe 2422
172dd12c 2423 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
c4cef1fe 2424 // only filter text if filter all files is selected
365a5941 2425 $options = new stdClass();
172dd12c 2426 $options->newlines = false;
2427 $options->noclean = true;
2428 $text = $stored_file->get_content();
2429 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
172dd12c 2430
d5dd0540 2431 readstring_accel($output, $mimetype, false);
c4cef1fe 2432
172dd12c 2433 } else { // Just send it out raw
d5dd0540 2434 readfile_accel($stored_file, $mimetype, !$dontdie);
172dd12c 2435 }
2436 }
b379f7d9 2437 if ($dontdie) {
2438 return;
2439 }
172dd12c 2440 die; //no more chars to output!!!
2441}
2442
34763a79 2443/**
76ca1ff1 2444 * Recursively delete the file or folder with path $location. That is,
34763a79 2445 * if it is a file delete it. If it is a folder, delete all its content
db3a0b34 2446 * then delete it. If $location does not exist to start, that is not
2447 * considered an error.
76ca1ff1 2448 *
eab8ed9f 2449 * @param string $location the path to remove.
ba21c9d4 2450 * @return bool
34763a79 2451 */
4c8c65ec 2452function fulldelete($location) {
1e06adb4
PS
2453 if (empty($location)) {
2454 // extra safety against wrong param
2455 return false;
2456 }
f401cc97 2457 if (is_dir($location)) {
80c27aab
CF
2458 if (!$currdir = opendir($location)) {
2459 return false;
2460 }
f401cc97 2461 while (false !== ($file = readdir($currdir))) {
2462 if ($file <> ".." && $file <> ".") {
2463 $fullfile = $location."/".$file;
4c8c65ec 2464 if (is_dir($fullfile)) {
f401cc97 2465 if (!fulldelete($fullfile)) {
2466 return false;
2467 }
2468 } else {
2469 if (!unlink($fullfile)) {
2470 return false;
2471 }
4c8c65ec 2472 }
f401cc97 2473 }
4c8c65ec 2474 }
f401cc97 2475 closedir($currdir);
2476 if (! rmdir($location)) {
2477 return false;
2478 }
2479
34763a79 2480 } else if (file_exists($location)) {
f401cc97 2481 if (!unlink($location)) {
2482 return false;
2483 }
2484 }
2485 return true;
2486}
2487
4c8c65ec 2488/**
2489 * Send requested byterange of file.
ba21c9d4 2490 *
d2b7803e 2491 * @param resource $handle A file handle
ba21c9d4 2492 * @param string $mimetype The mimetype for the output
2493 * @param array $ranges An array of ranges to send
2494 * @param string $filesize The size of the content if only one range is used
4c8c65ec 2495 */
172dd12c 2496function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
d5dd0540 2497 // better turn off any kind of compression and buffering
b19d75a2 2498 ini_set('zlib.output_compression', 'Off');
d5dd0540 2499
4c8c65ec 2500 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
4c8c65ec 2501 if ($handle === false) {
2502 die;
2503 }
2504 if (count($ranges) == 1) { //only one range requested
2505 $length = $ranges[0][2] - $ranges[0][1] + 1;
cbad562e
PS
2506 header('HTTP/1.1 206 Partial content');
2507 header('Content-Length: '.$length);
2508 header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2509 header('Content-Type: '.$mimetype);
c4cef1fe 2510
d5dd0540
PS
2511 while(@ob_get_level()) {
2512 if (!@ob_end_flush()) {
2513 break;
2514 }
2515 }
c4cef1fe 2516
4c8c65ec 2517 fseek($handle, $ranges[0][1]);
2518 while (!feof($handle) && $length > 0) {
3ef7279f 2519 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 2520 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2521 echo $buffer;
2522 flush();
2523 $length -= strlen($buffer);
2524 }
2525 fclose($handle);
2526 die;
2527 } else { // multiple ranges requested - not tested much
2528 $totallength = 0;
2529 foreach($ranges as $range) {
aba588a7 2530 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 2531 }
aba588a7 2532 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
cbad562e
PS
2533 header('HTTP/1.1 206 Partial content');
2534 header('Content-Length: '.$totallength);
2535 header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
c4cef1fe 2536
d5dd0540
PS
2537 while(@ob_get_level()) {
2538 if (!@ob_end_flush()) {
2539 break;
2540 }
2541 }
c4cef1fe 2542
4c8c65ec 2543 foreach($ranges as $range) {
2544 $length = $range[2] - $range[1] + 1;
2545 echo $range[0];
4c8c65ec 2546 fseek($handle, $range[1]);
2547 while (!feof($handle) && $length > 0) {
3ef7279f 2548 core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 2549 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2550 echo $buffer;
2551 flush();
2552 $length -= strlen($buffer);
2553 }
2554 }
2555 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2556 fclose($handle);
2557 die;
2558 }
2559}
f401cc97 2560
bc219382
MS
2561/**
2562 * Tells whether the filename is executable.
2563 *
2564 * @link http://php.net/manual/en/function.is-executable.php
2565 * @link https://bugs.php.net/bug.php?id=41062
2566 * @param string $filename Path to the file.
2567 * @return bool True if the filename exists and is executable; otherwise, false.
2568 */
2569function file_is_executable($filename) {
2570 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2571 if (is_executable($filename)) {
2572 return true;
2573 } else {
2574 $fileext = strrchr($filename, '.');
2575 // If we have an extension we can check if it is listed as executable.
2576 if ($fileext && file_exists($filename) && !is_dir($filename)) {
2577 $winpathext = strtolower(getenv('PATHEXT'));
2578 $winpathexts = explode(';', $winpathext);
2579
2580 return in_array(strtolower($fileext), $winpathexts);
2581 }
2582
2583 return false;
2584 }
2585 } else {
2586 return is_executable($filename);
2587 }
2588}
2589
46089705
JL
2590/**
2591 * Overwrite an existing file in a draft area.
2592 *
2593 * @param stored_file $newfile the new file with the new content and meta-data
2594 * @param stored_file $existingfile the file that will be overwritten
2595 * @throws moodle_exception
2596 * @since Moodle 3.2
2597 */
2598function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2599 if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2600 throw new coding_exception('The file to overwrite is not in a draft area.');
2601 }
2602
2603 $fs = get_file_storage();
2604 // Remember original file source field.
2605 $source = @unserialize($existingfile->get_source());
2606 // Remember the original sortorder.
2607 $sortorder = $existingfile->get_sortorder();
2608 if ($newfile->is_external_file()) {
2609 // New file is a reference. Check that existing file does not have any other files referencing to it
2610 if (isset($source->original) && $fs->search_references_count($source->original)) {
2611 throw new moodle_exception('errordoublereference', 'repository');
2612 }
2613 }
2614
2615 // Delete existing file to release filename.
2616 $newfilerecord = array(
2617 'contextid' => $existingfile->get_contextid(),
2618 'component' => 'user',
2619 'filearea' => 'draft',
2620 'itemid' => $existingfile->get_itemid(),
2621 'timemodified' => time()
2622 );
2623 $existingfile->delete();
2624
2625 // Create new file.
2626 $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2627 // Preserve original file location (stored in source field) for handling references.
2628 if (isset($source->original)) {
2629 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2630 $newfilesource = new stdClass();
2631 }
2632 $newfilesource->original = $source->original;
2633 $newfile->set_source(serialize($newfilesource));
2634 }
2635 $newfile->set_sortorder($sortorder);
2636}
2637
2638/**
2639 * Add files from a draft area into a final area.
2640 *
2641 * Most of the time you do not want to use this. It is intended to be used
2642 * by asynchronous services which cannot direcly manipulate a final
2643 * area through a draft area. Instead they add files to a new draft
2644 * area and merge that new draft into the final area when ready.
2645 *
2646 * @param int $draftitemid the id of the draft area to use.
2647 * @param int $contextid this parameter and the next two identify the file area to save to.
2648 * @param string $component component name
2649 * @param string $filearea indentifies the file area
2650 * @param int $itemid identifies the item id or false for all items in the file area
2651 * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2652 * @see file_save_draft_area_files
2653 * @since Moodle 3.2
2654 */
2655function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2656 array $options = null) {
2657 // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2658 $finaldraftid = 0;
2659 file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2660 file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2661 file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2662}
2663
2664/**
2665 * Merge files from two draftarea areas.
2666 *
2667 * This does not handle conflict resolution, files in the destination area which appear
2668 * to be more recent will be kept disregarding the intended ones.
2669 *
2670 * @param int $getfromdraftid the id of the draft area where are the files to merge.
2671 * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2672 * @throws coding_exception
2673 * @since Moodle 3.2
2674 */
2675function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2676 global $USER;
2677
2678 $fs = get_file_storage();
2679 $contextid = context_user::instance($USER->id)->id;
2680
2681 if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2682 throw new coding_exception('Nothing to merge or area does not belong to current user');
2683 }
2684
2685 $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2686
2687 // Get hashes of the files to merge.
2688 $newhashes = array();
2689 foreach ($filestomerge as $filetomerge) {
2690 $filepath = $filetomerge->get_filepath();
2691 $filename = $filetomerge->get_filename();
2692
2693 $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2694 $newhashes[$newhash] = $filetomerge;
2695 }
2696
2697 // Calculate wich files must be added.
2698 foreach ($currentfiles as $file) {
2699 $filehash = $file->get_pathnamehash();
2700 // One file to be merged already exists.
2701 if (isset($newhashes[$filehash])) {
2702 $updatedfile = $newhashes[$filehash];
2703
2704 // Avoid race conditions.
2705 if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2706 // The existing file is more recent, do not copy the suposedly "new" one.
2707 unset($newhashes[$filehash]);
2708 continue;
2709 }
2710 // Update existing file (not only content, meta-data too).
2711 file_overwrite_existing_draftfile($updatedfile, $file);
2712 unset($newhashes[$filehash]);
2713 }
2714 }
2715
2716 foreach ($newhashes as $newfile) {
2717 $newfilerecord = array(
2718 'contextid' => $contextid,
2719 'component' => 'user',
2720 'filearea' => 'draft',
2721 'itemid' => $mergeintodraftid,
2722 'timemodified' => time()
2723 );
2724
2725 $fs->create_file_from_storedfile($newfilerecord, $newfile);
2726 }
2727}
2728
bb2c046d 2729/**
2730 * RESTful cURL class
2731 *
2732 * This is a wrapper class for curl, it is quite easy to use:
ba21c9d4 2733 * <code>
bb2c046d 2734 * $c = new curl;
2735 * // enable cache
2736 * $c = new curl(array('cache'=>true));
2737 * // enable cookie
2738 * $c = new curl(array('cookie'=>true));
2739 * // enable proxy
2740 * $c = new curl(array('proxy'=>true));
2741 *
2742 * // HTTP GET Method
2743 * $html = $c->get('http://example.com');
2744 * // HTTP POST Method
2745 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2746 * // HTTP PUT Method
2747 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
ba21c9d4 2748 * </code>
bb2c046d 2749 *
d2b7803e
DC
2750 * @package core_files
2751 * @category files
2752 * @copyright Dongsheng Cai <dongsheng@moodle.com>
2753 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
bb2c046d 2754 */
bb2c046d 2755class curl {
d2b7803e 2756 /** @var bool Caches http request contents */
bb2c046d 2757 public $cache = false;
220eef0e
PS
2758 /** @var bool Uses proxy, null means automatic based on URL */
2759 public $proxy = null;
d2b7803e 2760 /** @var string library version */
bb2c046d 2761 public $version = '0.4 dev';
d2b7803e 2762 /** @var array http's response */
bb2c046d 2763 public $response = array();
220eef0e
PS
2764 /** @var array Raw response headers, needed for BC in download_file_content(). */
2765 public $rawresponse = array();
d2b7803e 2766 /** @var array http header */
bb2c046d 2767 public $header = array();
d2b7803e 2768 /** @var string cURL information */
bb2c046d 2769 public $info;
d2b7803e 2770 /** @var string error */
bb2c046d 2771 public $error;
a3c94686
MG
2772 /** @var int error code */
2773 public $errno;
220eef0e
PS
2774 /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
2775 public $emulateredirects = null;
117bd748 2776
d2b7803e 2777 /** @var array cURL options */
9a1adda5 2778 private $options;
300fcae3 2779
d2b7803e 2780 /** @var string Proxy host */
bb2c046d 2781 private $proxy_host = '';
d2b7803e 2782 /** @var string Proxy auth */
bb2c046d 2783 private $proxy_auth = '';
d2b7803e 2784 /** @var string Proxy type */
bb2c046d 2785 private $proxy_type = '';
d2b7803e 2786 /** @var bool Debug mode on */
bb2c046d 2787 private $debug = false;
d2b7803e 2788 /** @var bool|string Path to cookie file */
bb2c046d 2789 private $cookie = false;
220eef0e
PS
2790 /** @var bool tracks multiple headers in response - redirect detection */
2791 private $responsefinished = false;
bb2c046d 2792
ba21c9d4 2793 /**
220eef0e 2794 * Curl constructor.
d2b7803e 2795 *
220eef0e
PS
2796 * Allowed settings are:
2797 * proxy: (bool) use proxy server, null means autodetect non-local from url
2798 * debug: (bool) use debug output
2799 * cookie: (string) path to cookie file, false if none
2800 * cache: (bool) use cache
2801 * module_cache: (string) type of cache
2802 *
2803 * @param array $settings
ba21c9d4 2804 */
220eef0e 2805 public function __construct($settings = array()) {
bb2c046d 2806 global $CFG;
2807 if (!function_exists('curl_init')) {
2808 $this->error = 'cURL module must be enabled!';
2809 trigger_error($this->error, E_USER_ERROR);
2810 return false;
2811 }
220eef0e
PS
2812
2813 // All settings of this class should be init here.
bb2c046d 2814 $this->resetopt();
220eef0e 2815 if (!empty($settings['debug'])) {
bb2c046d 2816 $this->debug = true;
2817 }
220eef0e
PS
2818 if (!empty($settings['cookie'])) {
2819 if($settings['cookie'] === true) {
bb2c046d 2820 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2821 } else {
220eef0e 2822 $this->cookie = $settings['cookie'];
bb2c046d 2823 }
2824 }
220eef0e 2825 if (!empty($settings['cache'])) {
bb2c046d 2826 if (class_exists('curl_cache')) {
220eef0e
PS
2827 if (!empty($settings['module_cache'])) {
2828 $this->cache = new curl_cache($settings['module_cache']);
5430f05b 2829 } else {
2830 $this->cache = new curl_cache('misc');
2831 }
bb2c046d 2832 }
2833 }
d04ce87f 2834 if (!empty($CFG->proxyhost)) {
2835 if (empty($CFG->proxyport)) {
2836 $this->proxy_host = $CFG->proxyhost;
2837 } else {
2838 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2839 }
2840 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2841 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2842 $this->setopt(array(
2843 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2844 'proxyuserpwd'=>$this->proxy_auth));
2845 }
2846 if (!empty($CFG->proxytype)) {
2847 if ($CFG->proxytype == 'SOCKS5') {
2848 $this->proxy_type = CURLPROXY_SOCKS5;
bb2c046d 2849 } else {
d04ce87f 2850 $this->proxy_type = CURLPROXY_HTTP;
f6d3e2c4 2851 $this->setopt(array('httpproxytunnel'=>false));
bb2c046d 2852 }
d04ce87f 2853 $this->setopt(array('proxytype'=>$this->proxy_type));
bb2c046d 2854 }
220eef0e
PS
2855
2856 if (isset($settings['proxy'])) {
2857 $this->proxy = $settings['proxy'];
2858 }
2859 } else {
2860 $this->proxy = false;
d04ce87f 2861 }
220eef0e
PS
2862
2863 if (!isset($this->emulateredirects)) {
90627d9d 2864 $this->emulateredirects = ini_get('open_basedir');
bb2c046d 2865 }
2866 }
220eef0e 2867
ba21c9d4 2868 /**
2869 * Resets the CURL options that have already been set
2870 */
9936c2a5 2871 public function resetopt() {
bb2c046d 2872 $this->options = array();
2873 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2874 // True to include the header in the output
2875 $this->options['CURLOPT_HEADER'] = 0;
2876 // True to Exclude the body from the output
2877 $this->options['CURLOPT_NOBODY'] = 0;
220eef0e
PS
2878 // Redirect ny default.
2879 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
bb2c046d 2880 $this->options['CURLOPT_MAXREDIRS'] = 10;
2881 $this->options['CURLOPT_ENCODING'] = '';
2882 // TRUE to return the transfer as a string of the return
2883 // value of curl_exec() instead of outputting it out directly.
2884 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
bb2c046d 2885 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2886 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
6135bd45 2887 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
c2140b5d
PS
2888
2889 if ($cacert = self::get_cacert()) {
2890 $this->options['CURLOPT_CAINFO'] = $cacert;
2891 }
2892 }
2893
2894 /**
2895 * Get the location of ca certificates.
2896 * @return string absolute file path or empty if default used
2897 */
2898 public static function get_cacert() {
2899 global $CFG;
2900
2901 // Bundle in dataroot always wins.
2902 if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
2903 return realpath("$CFG->dataroot/moodleorgca.crt");
2904 }
2905
2906 // Next comes the default from php.ini
2907 $cacert = ini_get('curl.cainfo');
2908 if (!empty($cacert) and is_readable($cacert)) {
2909 return realpath($cacert);
2910 }
2911
2912 // Windows PHP does not have any certs, we need to use something.
2913 if ($CFG->ostype === 'WINDOWS') {
2914 if (is_readable("$CFG->libdir/cacert.pem")) {
2915 return realpath("$CFG->libdir/cacert.pem");
2916 }
2917 }
2918
2919 // Use default, this should work fine on all properly configured *nix systems.
2920 return null;
bb2c046d 2921 }
2922
2923 /**
2924 * Reset Cookie
bb2c046d 2925 */
2926 public function resetcookie() {
2927 if (!empty($this->cookie)) {
2928 if (is_file($this->cookie)) {
2929 $fp = fopen($this->cookie, 'w');
2930 if (!empty($fp)) {
2931 fwrite($fp, '');
2932 fclose($fp);
2933 }
2934 }
2935 }
2936 }
2937
2938 /**
91c8cf99 2939 * Set curl options.
bb2c046d 2940 *
91c8cf99
F
2941 * Do not use the curl constants to define the options, pass a string
2942 * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
2943 * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
2944 *
2945 * @param array $options If array is null, this function will reset the options to default value.
2946 * @return void
2947 * @throws coding_exception If an option uses constant value instead of option name.
bb2c046d 2948 */
2949 public function setopt($options = array()) {
2950 if (is_array($options)) {
9936c2a5 2951 foreach ($options as $name => $val) {
91c8cf99
F
2952 if (!is_string($name)) {
2953 throw new coding_exception('Curl options should be defined using strings, not constant values.');
2954 }
bb2c046d 2955 if (stripos($name, 'CURLOPT_') === false) {
2956 $name = strtoupper('CURLOPT_'.$name);
220eef0e
PS
2957 } else {
2958 $name = strtoupper($name);
bb2c046d 2959 }
2960 $this->options[$name] = $val;
2961 }
2962 }
2963 }
d2b7803e 2964
bb2c046d 2965 /**
2966 * Reset http method
bb2c046d 2967 */
9936c2a5 2968 public function cleanopt() {
bb2c046d 2969 unset($this->options['CURLOPT_HTTPGET']);
2970 unset($this->options['CURLOPT_POST']);
2971 unset($this->options['CURLOPT_POSTFIELDS']);
2972 unset($this->options['CURLOPT_PUT']);
2973 unset($this->options['CURLOPT_INFILE']);
2974 unset($this->options['CURLOPT_INFILESIZE']);
2975 unset($this->options['CURLOPT_CUSTOMREQUEST']);
a3c94686 2976 unset($this->options['CURLOPT_FILE']);
bb2c046d 2977 }
2978
7e1e775f
MG
2979 /**
2980 * Resets the HTTP Request headers (to prepare for the new request)
2981 */
2982 public function resetHeader() {
2983 $this->header = array();
2984 }
2985
bb2c046d 2986 /**
2987 * Set HTTP Request Header
2988 *
d2b7803e 2989 * @param array $header
bb2c046d 2990 */
2991 public function setHeader($header) {
9936c2a5 2992 if (is_array($header)) {
bb2c046d 2993 foreach ($header as $v) {
2994 $this->setHeader($v);
2995 }
2996 } else {
220eef0e
PS
2997 // Remove newlines, they are not allowed in headers.
2998 $this->header[] = preg_replace('/[\r\n]/', '', $header);
bb2c046d 2999 }
3000 }
d2b7803e 3001
bb2c046d 3002 /**
220eef0e
PS
3003 * Get HTTP Response Headers
3004 * @return array of arrays
bb2c046d 3005 */
9936c2a5 3006 public function getResponse() {
bb2c046d 3007 return $this->response;
3008 }
d2b7803e 3009
220eef0e
PS
3010 /**
3011 * Get raw HTTP Response Headers
3012 * @return array of strings
3013 */
3014 public function get_raw_response() {
3015 return $this->rawresponse;
3016 }
3017
bb2c046d 3018 /**
3019 * private callback function
3020 * Formatting HTTP Response Header
3021 *
102230b2
FM
3022 * We only keep the last headers returned. For example during a redirect the
3023 * redirect headers will not appear in {@link self::getResponse()}, if you need
3024 * to use those headers, refer to {@link self::get_raw_response()}.
3025 *
d2b7803e 3026 * @param resource $ch Apparently not used
ba21c9d4 3027 * @param string $header
3028 * @return int The strlen of the header
bb2c046d 3029 */
9936c2a5 3030 private function formatHeader($ch, $header) {
220eef0e
PS
3031 $this->rawresponse[] = $header;
3032
3033 if (trim($header, "\r\n") === '') {
102230b2 3034 // This must be the last header.
220eef0e
PS
3035 $this->responsefinished = true;
3036 }
3037
bb2c046d 3038 if (strlen($header) > 2) {
102230b2
FM
3039 if ($this->responsefinished) {
3040 // We still have headers after the supposedly last header, we must be
3041 // in a redirect so let's empty the response to keep the last headers.
3042 $this->responsefinished = false;
3043 $this->response = array();
3044 }
bb2c046d 3045 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
3046 $key = rtrim($key, ':');
3047 if (!empty($this->response[$key])) {
9936c2a5 3048 if (is_array($this->response[$key])) {
bb2c046d 3049 $this->response[$key][] = $value;
3050 } else {
3051 $tmp = $this->response[$key];
3052 $this->response[$key] = array();
3053 $this->response[$key][] = $tmp;
3054 $this->response[$key][] = $value;
3055
3056 }
3057 } else {
3058 $this->response[$key] = $value;
3059 }
3060 }
3061 return strlen($header);
3062 }
3063
3064 /**
3065 * Set options for individual curl instance
ba21c9d4 3066 *
d2b7803e 3067 * @param resource $curl A curl handle
ba21c9d4 3068 * @param array $options
d2b7803e 3069 * @return resource The curl handle
bb2c046d 3070 */
9a1adda5 3071 private function apply_opt($curl, $options) {
bb2c046d 3072 // Clean up
3073 $this->cleanopt();
3074 // set cookie
3075 if (!empty($this->cookie) || !empty($options['cookie'])) {
3076 $this->setopt(array('cookiejar'=>$this->cookie,
3077 'cookiefile'=>$this->cookie
3078 ));
3079 }
3080
220eef0e
PS
3081 // Bypass proxy if required.
3082 if ($this->proxy === null) {
3083 if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3084 $proxy = false;
3085 } else {
3086 $proxy = true;
3087 }
3088 } else {
3089 $proxy = (bool)$this->proxy;
3090 }
3091
3092 // Set proxy.
3093 if ($proxy) {
3094 $options['CURLOPT_PROXY'] = $this->proxy_host;
3095 } else {
3096 unset($this->options['CURLOPT_PROXY']);
bb2c046d 3097 }
220eef0e 3098
bb2c046d 3099 $this->setopt($options);
300fcae3
DC
3100
3101 // Reset before set options.
bb2c046d 3102 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
300fcae3
DC
3103
3104 // Setting the User-Agent based on options provided.
3105 $useragent = '';
3106
3107 if (!empty($options['CURLOPT_USERAGENT'])) {
3108 $useragent = $options['CURLOPT_USERAGENT'];
3109 } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3110 $useragent = $this->options['CURLOPT_USERAGENT'];
3111 } else {
3112 $useragent = 'MoodleBot/1.0';
3113 }
3114
3115 // Set headers.
9936c2a5 3116 if (empty($this->header)) {
bb2c046d 3117 $this->setHeader(array(
300fcae3 3118 'User-Agent: ' . $useragent,
bb2c046d 3119 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3120 'Connection: keep-alive'
3121 ));
300fcae3
DC
3122 } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3123 // Remove old User-Agent if one existed.
3124 // We have to partial search since we don't know what the original User-Agent is.
3125 if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3126 $key = array_keys($match)[0];
3127 unset($this->header[$key]);
3128 }
3129 $this->setHeader(array('User-Agent: ' . $useragent));
bb2c046d 3130 }
3131 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3132
9936c2a5 3133 if ($this->debug) {
bb2c046d 3134 echo '<h1>Options</h1>';
3135 var_dump($this->options);
3136 echo '<h1>Header</h1>';
3137 var_dump($this->header);
3138 }
3139
220eef0e
PS
3140 // Do not allow infinite redirects.
3141 if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3142 $this->options['CURLOPT_MAXREDIRS'] = 0;
3143 } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3144 $this->options['CURLOPT_MAXREDIRS'] = 100;
3145 } else {
3146 $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3147 }
3148
3149 // Make sure we always know if redirects expected.
3150 if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3151 $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3152 }
3153
38a73bf4
FM
3154 // Limit the protocols to HTTP and HTTPS.
3155 if (defined('CURLOPT_PROTOCOLS')) {
3156 $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3157 $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3158 }
3159
91c8cf99 3160 // Set options.
bb2c046d 3161 foreach($this->options as $name => $val) {
220eef0e
PS
3162 if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
3163 // The redirects are emulated elsewhere.
3164 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3165 continue;
3166 }
3167 $name = constant($name);
bb2c046d 3168 curl_setopt($curl, $name, $val);
3169 }
220eef0e 3170
bb2c046d 3171 return $curl;
3172 }
d2b7803e 3173
ba21c9d4 3174 /**
bb2c046d 3175 * Download multiple files in parallel
ba21c9d4 3176 *
3177 * Calls {@link multi()} with specific download headers
3178 *
3179 * <code>
def4a8f5
JH
3180 * $c = new curl();
3181 * $file1 = fopen('a', 'wb');
3182 * $file2 = fopen('b', 'wb');
bb2c046d 3183 * $c->download(array(
def4a8f5
JH
3184 * array('url'=>'http://localhost/', 'file'=>$file1),
3185 * array('url'=>'http://localhost/20/', 'file'=>$file2)
3186 * ));
3187 * fclose($file1);
3188 * fclose($file2);
3189 * </code>
3190 *
3191 * or
3192 *
3193 * <code>
3194 * $c = new curl();
3195 * $c->download(array(
3196 * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3197 * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
bb2c046d 3198 * ));
ba21c9d4 3199 * </code>
3200 *
def4a8f5
JH
3201 * @param array $requests An array of files to request {
3202 * url => url to download the file [required]
3203 * file => file handler, or
3204 * filepath => file path
3205 * }
3206 * If 'file' and 'filepath' parameters are both specified in one request, the
3207 * open file handle in the 'file' parameter will take precedence and 'filepath'
3208 * will be ignored.
3209 *
ba21c9d4 3210 * @param array $options An array of options to set
3211 * @return array An array of results
bb2c046d 3212 */
3213 public function download($requests, $options = array()) {
bb2c046d 3214 $options['RETURNTRANSFER'] = false;
3215 return $this->multi($requests, $options);
3216 }
d2b7803e
DC
3217
3218 /**
9936c2a5 3219 * Multi HTTP Requests
bb2c046d 3220 * This function could run multi-requests in parallel.
ba21c9d4 3221 *
3222 * @param array $requests An array of files to request
3223 * @param array $options An array of options to set
3224 * @return array An array of results
bb2c046d 3225 */
3226 protected function multi($requests, $options = array()) {
3227 $count = count($requests);
3228 $handles = array();
3229 $results = array();
3230 $main = curl_multi_init();
3231 for ($i = 0; $i < $count; $i++) {
def4a8f5
JH
3232 if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3233 // open file
3234 $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3235 $requests[$i]['auto-handle'] = true;
3236 }
9936c2a5 3237 foreach($requests[$i] as $n=>$v) {
def4a8f5 3238 $options[$n] = $v;
bb2c046d 3239 }
def4a8f5 3240 $handles[$i] = curl_init($requests[$i]['url']);
bb2c046d 3241 $this->apply_opt($handles[$i], $options);
3242 curl_multi_add_handle($main, $handles[$i]);
3243 }
3244 $running = 0;
3245 do {
3246 curl_multi_exec($main, $running);
3247 } while($running > 0);
3248 for ($i = 0; $i < $count; $i++) {
ba4082f5 3249 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
bb2c046d 3250 $results[] = true;
3251 } else {
3252 $results[] = curl_multi_getcontent($handles[$i]);
3253 }
3254 curl_multi_remove_handle($main, $handles[$i]);
3255 }
3256 curl_multi_close($main);
def4a8f5
JH
3257
3258 for ($i = 0; $i < $count; $i++) {
3259 if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3260 // close file handler if file is opened in this function
3261 fclose($requests[$i]['file']);
3262 }
3263 }
bb2c046d 3264 return $results;
3265 }
d2b7803e 3266
bb2c046d 3267 /**
3268 * Single HTTP Request
ba21c9d4 3269 *
3270 * @param string $url The URL to request
3271 * @param array $options
3272 * @return bool
bb2c046d 3273 */
9936c2a5 3274 protected function request($url, $options = array()) {
ba72e295
FM
3275 // Set the URL as a curl option.
3276 $this->setopt(array('CURLOPT_URL' => $url));
3277
3278 // Create curl instance.
3279 $curl = curl_init();
220eef0e
PS
3280
3281 // Reset here so that the data is valid when result returned from cache.
3282 $this->info = array();
3283 $this->error = '';
3284 $this->errno = 0;
3285 $this->response = array();
3286 $this->rawresponse = array();
3287 $this->responsefinished = false;
3288
bb2c046d 3289 $this->apply_opt($curl, $options);
3290 if ($this->cache && $ret = $this->cache->get($this->options)) {
3291 return $ret;
bb2c046d 3292 }
3293
220eef0e 3294 $ret = curl_exec($curl);
bb2c046d 3295 $this->info = curl_getinfo($curl);
3296 $this->error = curl_error($curl);
a3c94686 3297 $this->errno = curl_errno($curl);
220eef0e
PS
3298 // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3299
3300 if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
3301 $redirects = 0;
3302
3303 while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3304
3305 if ($this->info['http_code'] == 301) {
3306 // Moved Permanently - repeat the same request on new URL.
3307
3308 } else if ($this->info['http_code'] == 302) {
3309 // Found - the standard redirect - repeat the same request on new URL.
3310
3311 } else if ($this->info['http_code'] == 303) {
3312 // 303 See Other - repeat only if GET, do not bother with POSTs.
3313 if (empty($this->options['CURLOPT_HTTPGET'])) {
3314 break;
3315 }
3316
3317 } else if ($this->info['http_code'] == 307) {
3318 // Temporary Redirect - must repeat using the same request type.
3319
3320 } else if ($this->info['http_code'] == 308) {
3321 // Permanent Redirect - must repeat using the same request type.
3322
3323 } else {
3324 // Some other http code means do not retry!
3325 break;
3326 }
3327
3328 $redirects++;
3329
3330 $redirecturl = null;
3331 if (isset($this->info['redirect_url'])) {
3332 if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3333 $redirecturl = $this->info['redirect_url'];
3334 }
3335 }
3336 if (!$redirecturl) {
3337 foreach ($this->response as $k => $v) {
3338 if (strtolower($k) === 'location') {