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