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