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