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