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