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