MDL-19247 Adjusted detection and cleaned up sniff files.
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
edc0c493 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.org //
9// //
10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
26/**
27 * Functions for file handling.
28 *
29 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
30 * @package files
31 */
32
33/** @var string unique string constant. */
34define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
4c8c65ec 35
172dd12c 36require_once("$CFG->libdir/file/file_exceptions.php");
37require_once("$CFG->libdir/file/file_storage.php");
38require_once("$CFG->libdir/file/file_browser.php");
0b0bfa93 39
40require_once("$CFG->libdir/packer/zip_packer.php");
172dd12c 41
509f67e3 42/**
43 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
44 * @param string $path Physical path to a file
45 * @param array $options associative array of GET variables to append to the URL
46 * @param string $type (questionfile|rssfile|user|usergroup|httpscoursefile|coursefile)
47 * @return string URL to file
48 */
74369ab5 49function get_file_url($path, $options=null, $type='coursefile') {
f86eb734 50 global $CFG, $HTTPSPAGEREQUIRED;
74369ab5 51
172dd12c 52 $path = str_replace('//', '/', $path);
74369ab5 53 $path = trim($path, '/'); // no leading and trailing slashes
54
55 // type of file
56 switch ($type) {
5a254a29 57 case 'questionfile':
58 $url = $CFG->wwwroot."/question/exportfile.php";
59 break;
60 case 'rssfile':
61 $url = $CFG->wwwroot."/rss/file.php";
62 break;
63 case 'user':
f86eb734 64 if (!empty($HTTPSPAGEREQUIRED)) {
65 $wwwroot = $CFG->httpswwwroot;
66 }
67 else {
68 $wwwroot = $CFG->wwwroot;
69 }
70 $url = $wwwroot."/user/pix.php";
5a254a29 71 break;
72 case 'usergroup':
11e7b506 73 $url = $CFG->wwwroot."/user/grouppix.php";
5a254a29 74 break;
75 case 'httpscoursefile':
76 $url = $CFG->httpswwwroot."/file.php";
77 break;
78 case 'coursefile':
74369ab5 79 default:
5a254a29 80 $url = $CFG->wwwroot."/file.php";
74369ab5 81 }
82
83 if ($CFG->slasharguments) {
84 $parts = explode('/', $path);
546fef5f 85 foreach ($parts as $key => $part) {
86 /// anchor dash character should not be encoded
87 $subparts = explode('#', $part);
88 $subparts = array_map('rawurlencode', $subparts);
89 $parts[$key] = implode('#', $subparts);
90 }
74369ab5 91 $path = implode('/', $parts);
5a254a29 92 $ffurl = $url.'/'.$path;
74369ab5 93 $separator = '?';
94 } else {
5a254a29 95 $path = rawurlencode('/'.$path);
96 $ffurl = $url.'?file='.$path;
74369ab5 97 $separator = '&amp;';
98 }
99
100 if ($options) {
101 foreach ($options as $name=>$value) {
102 $ffurl = $ffurl.$separator.$name.'='.$value;
103 $separator = '&amp;';
104 }
105 }
106
107 return $ffurl;
108}
109
4eef1399 110
111/**
112 * Encodes file serving url
113 * TODO: decide if we really need this
114 * @param string $urlbase
115 * @param string $path /filearea/itemid/dir/dir/file.exe
116 * @param bool $forcedownload
117 * @param bool $https https url required
118 * @return string encoded file url
119 */
120function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
121 global $CFG;
122
123 if ($CFG->slasharguments) {
124 $parts = explode('/', $path);
125 $parts = array_map('rawurlencode', $parts);
126 $path = implode('/', $parts);
127 $return = $urlbase.$path;
128 if ($forcedownload) {
129 $return .= '?forcedownload=1';
130 }
131 } else {
132 $path = rawurlencode($path);
133 $return = $urlbase.'?file='.$path;
134 if ($forcedownload) {
135 $return .= '&amp;forcedownload=1';
136 }
137 }
138
139 if ($https) {
140 $return = str_replace('http://', 'https://', $return);
141 }
142
143 return $return;
144}
145
c94882ff 146/**
147 * Prepares standardised text field fro editing with Editor formslib element
148 * @param object $data $database entry field
149 * @param string $field name of data field
150 * @param array $options various options
151 * @param object $context context, required for existing data
152 * @param string $filearea file area name
153 * @param int $itemid item id, required if item exists
154 * @return object modified data object
155 */
156function file_prepare_standard_editor($data, $field, array $options, $context=null, $filearea=null, $itemid=null) {
157 $options = (array)$options;
158 if (!isset($options['trusttext'])) {
159 $options['trusttext'] = false;
160 }
161 if (!isset($options['forcehttps'])) {
162 $options['forcehttps'] = false;
163 }
164 if (!isset($options['subdirs'])) {
165 $options['subdirs'] = false;
166 }
989c16ee 167 if (!isset($options['maxfiles'])) {
168 $options['maxfiles'] = 0; // no files by default
169 }
b96ddb7d 170 if (!isset($options['noclean'])) {
171 $options['noclean'] = false;
172 }
c94882ff 173
174 if (empty($data->id) or empty($context)) {
175 $contextid = null;
176 $data->id = null;
177 if (!isset($data->{$field})) {
178 $data->{$field} = '';
179 }
180 if (!isset($data->{$field.'format'})) {
b96ddb7d 181 $data->{$field.'format'} = FORMAT_HTML; // TODO: use better default based on user preferences and browser capabilities
182 }
183 if (!$options['noclean']) {
184 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
c94882ff 185 }
c94882ff 186
187 } else {
188 if ($options['trusttext']) {
b96ddb7d 189 // noclean ignored if trusttext enabled
c94882ff 190 if (!isset($data->{$field.'trust'})) {
191 $data->{$field.'trust'} = 0;
192 }
193 $data = trusttext_pre_edit($data, $field, $context);
194 } else {
b96ddb7d 195 if (!$options['noclean']) {
196 $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
197 }
c94882ff 198 }
199 $contextid = $context->id;
200 }
201
989c16ee 202 if ($options['maxfiles'] != 0) {
203 $draftid_editor = file_get_submitted_draft_itemid($field);
a19a06d0 204 $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $filearea, $data->id, $options, $data->{$field});
989c16ee 205 $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
206 } else {
207 $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 0);
208 }
c94882ff 209
210 return $data;
211}
212
213/**
214 * Prepares editing with File manager formslib element
215 * @param object $data $database entry field
216 * @param string $field name of data field
217 * @param array $options various options
218 * @param object $context context, required for existing data
219 * @param string $filearea file area name
220 * @param int $itemid item id, required if item exists
221 * @return object modified data object
222 */
989c16ee 223function file_postupdate_standard_editor($data, $field, array $options, $context, $filearea=null, $itemid=null) {
c94882ff 224 $options = (array)$options;
225 if (!isset($options['trusttext'])) {
226 $options['trusttext'] = false;
227 }
228 if (!isset($options['forcehttps'])) {
229 $options['forcehttps'] = false;
230 }
231 if (!isset($options['subdirs'])) {
232 $options['subdirs'] = false;
233 }
234 if (!isset($options['maxfiles'])) {
85db95e7 235 $options['maxfiles'] = 0; // no files by default
c94882ff 236 }
237 if (!isset($options['maxbytes'])) {
238 $options['maxbytes'] = 0; // unlimited
239 }
240
241 if ($options['trusttext']) {
242 $data->definitiontrust = trusttext_trusted($context);
243 } else {
244 $data->definitiontrust = 0;
245 }
246
85db95e7 247 $editor = $data->{$field.'_editor'};
c94882ff 248
989c16ee 249 if ($options['maxfiles'] != 0 or is_null($filearea) or is_null($itemid)) {
250 $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
251 } else {
252 $data->{$field} = $editor['text'];
253 }
c94882ff 254 $data->{$field.'format'} = $editor['format'];
255
256 return $data;
257}
258
259/**
260 * Saves text and files modified by Editor formslib element
261 * @param object $data $database entry field
262 * @param string $field name of data field
263 * @param array $options various options
264 * @param object $context context - must already exist
265 * @param string $filearea file area name
266 * @param int $itemid must already exist, usually means data is in db
267 * @return object modified data obejct
268 */
269function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $filearea=null, $itemid=null) {
270 $options = (array)$options;
271 if (!isset($options['subdirs'])) {
272 $options['subdirs'] = false;
273 }
274 if (empty($data->id) or empty($context)) {
275 $data->id = null;
276 $contextid = null;
277 } else {
278 $contextid = $context->id;
279 }
280
85db95e7 281 $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
a19a06d0 282 file_prepare_draft_area($draftid_editor, $contextid, $filearea, $data->id, $options);
85db95e7 283 $data->{$field.'_filemanager'} = $draftid_editor;
c94882ff 284
285 return $data;
286}
287
288/**
289 * Saves files modified by File manager formslib element
290 * @param object $data $database entry field
291 * @param string $field name of data field
292 * @param array $options various options
293 * @param object $context context - must already exist
294 * @param string $filearea file area name
295 * @param int $itemid must already exist, usually means data is in db
296 * @return object modified data obejct
297 */
298function file_postupdate_standard_filemanager($data, $field, array $options, $context, $filearea, $itemid) {
299 $options = (array)$options;
300 if (!isset($options['subdirs'])) {
301 $options['subdirs'] = false;
302 }
303 if (!isset($options['maxfiles'])) {
304 $options['maxfiles'] = -1; // unlimited
305 }
306 if (!isset($options['maxbytes'])) {
307 $options['maxbytes'] = 0; // unlimited
308 }
309
85db95e7 310 if (empty($data->{$field.'_filemanager'})) {
c94882ff 311 $data->$field = '';
312
313 } else {
85db95e7 314 file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $filearea, $data->id, $options);
c94882ff 315 $fs = get_file_storage();
316
317 if ($fs->get_area_files($context->id, $filearea, $itemid)) {
318 $data->$field = '1'; // TODO: this is an ugly hack
319 } else {
320 $data->$field = '';
321 }
322 }
323
324 return $data;
325}
326
8546def3 327/**
509f67e3 328 * @return int a random but available draft itemid that can be used to create a new draft
edc0c493 329 * file area.
8546def3 330 */
edc0c493 331function file_get_unused_draft_itemid() {
8546def3 332 global $DB, $USER;
333
334 if (isguestuser() or !isloggedin()) {
85db95e7 335 // guests and not-logged-in users can not be allowed to upload anything!!!!!!
8546def3 336 print_error('noguest');
337 }
338
339 $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
340 $filearea = 'user_draft';
341
342 $fs = get_file_storage();
343 $draftitemid = rand(1, 999999999);
344 while ($files = $fs->get_area_files($contextid, $filearea, $draftitemid)) {
345 $draftitemid = rand(1, 999999999);
346 }
347
b933a139 348 return $draftitemid;
8546def3 349}
350
7983d682 351/**
edc0c493 352 * Initialise a draft file area from a real one by copying the files. A draft
353 * area will be created if one does not already exist. Normally you should
354 * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
355 * @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.
356 * @param integer $contextid This parameter and the next two identify the file area to copy files from.
357 * @param string $filearea helps indentify the file area.
358 * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
33374f76 359 * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
edc0c493 360 * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
edc0c493 361 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
7983d682 362 */
a19a06d0 363function file_prepare_draft_area(&$draftitemid, $contextid, $filearea, $itemid, array $options=null, $text=null) {
7983d682 364 global $CFG, $USER;
365
a19a06d0 366 $options = (array)$options;
367 if (!isset($options['subdirs'])) {
368 $options['subdirs'] = false;
369 }
33374f76 370 if (!isset($options['forcehttps'])) {
a19a06d0 371 $options['forcehttps'] = false;
372 }
373
8546def3 374 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
b933a139 375 $fs = get_file_storage();
376
377 if (empty($draftitemid)) {
378 // create a new area and copy existing files into
edc0c493 379 $draftitemid = file_get_unused_draft_itemid();
b933a139 380 $file_record = array('contextid'=>$usercontext->id, 'filearea'=>'user_draft', 'itemid'=>$draftitemid);
12fab708 381 if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $filearea, $itemid)) {
b933a139 382 foreach ($files as $file) {
a19a06d0 383 if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
b5b188ce 384 continue;
385 }
b933a139 386 $fs->create_file_from_storedfile($file_record, $file);
387 }
388 }
389 } else {
390 // nothing to do
391 }
392
393 if (is_null($text)) {
394 return null;
395 }
396
edc0c493 397 // relink embedded files - editor can not handle @@PLUGINFILE@@ !
45126617 398 return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user_draft', $draftitemid, $options);
644d506a 399}
400
401/**
edc0c493 402 * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
403 * @param string $text The content that may contain ULRs in need of rewriting.
404 * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
405 * @param integer $contextid This parameter and the next two identify the file area to use.
406 * @param string $filearea helps indentify the file area.
407 * @param integer $itemid helps identify the file area.
33374f76 408 * @param array $options text and file options ('forcehttps'=>false)
edc0c493 409 * @return string the processed text.
644d506a 410 */
33374f76 411function file_rewrite_pluginfile_urls($text, $file, $contextid, $filearea, $itemid, array $options=null) {
644d506a 412 global $CFG;
b933a139 413
33374f76
MH
414 $options = (array)$options;
415 if (!isset($options['forcehttps'])) {
416 $options['forcehttps'] = false;
417 }
418
edc0c493 419 if (!$CFG->slasharguments) {
420 $file = $file . '?file=';
b933a139 421 }
8546def3 422
7d2948bd 423 $baseurl = "$CFG->wwwroot/$file/$contextid/$filearea/";
424
425 if ($itemid !== null) {
426 $baseurl .= "$itemid/";
427 }
edc0c493 428
33374f76 429 if ($options['forcehttps']) {
edc0c493 430 $baseurl = str_replace('http://', 'https://', $baseurl);
b933a139 431 }
432
edc0c493 433 return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
b933a139 434}
435
12fab708 436/**
edc0c493 437 * Returns information about files in a draft area.
438 * @param integer $draftitemid the draft area item id.
439 * @return array with the following entries:
440 * 'filecount' => number of files in the draft area.
441 * (more information will be added as needed).
12fab708 442 */
edc0c493 443function file_get_draft_area_info($draftitemid) {
12fab708 444 global $CFG, $USER;
445
446 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
447 $fs = get_file_storage();
448
edc0c493 449 $results = array();
450
451 // The number of files
12fab708 452 $draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id', false);
4f5521dd 453 $results['filecount'] = count($draftfiles);
12fab708 454
edc0c493 455 return $results;
12fab708 456}
457
3156b8ca 458/**
edc0c493 459 * Returns draft area itemid for a given element.
460 * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
461 * @return inteter the itemid, or 0 if there is not one yet.
3156b8ca 462 */
edc0c493 463function file_get_submitted_draft_itemid($elname) {
464 $param = optional_param($elname, 0, PARAM_INT);
465 if ($param) {
466 confirm_sesskey();
467 }
468 if (is_array($param)) {
469 $param = $param['itemid'];
3156b8ca 470 }
edc0c493 471 return $param;
3156b8ca 472}
473
b933a139 474/**
edc0c493 475 * Saves files from a draft file area to a real one (merging the list of files).
476 * Can rewrite URLs in some content at the same time if desired.
477 * @param int $draftitemid the id of the draft area to use. Normally obtained
478 * from file_get_submitted_draft_itemid('elementname') or similar.
479 * @param integer $contextid This parameter and the next two identify the file area to save to.
a08171c5 480 * @param string $filearea indentifies the file area.
481 * @param integer $itemid helps identifies the file area.
482 * @param array $optionss area options (subdirs=>false, maxfiles=-1, maxbytes=0)
edc0c493 483 * @param string $text some html content that needs to have embedded links rewritten
484 * to the @@PLUGINFILE@@ form for saving in the database.
485 * @param boolean $forcehttps force https urls.
486 * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
b933a139 487 */
a08171c5 488function file_save_draft_area_files($draftitemid, $contextid, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
b933a139 489 global $CFG, $USER;
490
491 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
8546def3 492 $fs = get_file_storage();
b933a139 493
a08171c5 494 $options = (array)$options;
495 if (!isset($options['subdirs'])) {
496 $options['subdirs'] = false;
497 }
498 if (!isset($options['maxfiles'])) {
499 $options['maxfiles'] = -1; // unlimited
500 }
501 if (!isset($options['maxbytes'])) {
502 $options['maxbytes'] = 0; // unlimited
503 }
504
b933a139 505 $draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id');
506 $oldfiles = $fs->get_area_files($contextid, $filearea, $itemid, 'id');
507
508 if (count($draftfiles) < 2) {
509 // means there are no files - one file means root dir only ;-)
510 $fs->delete_area_files($contextid, $filearea, $itemid);
511
512 } else if (count($oldfiles) < 2) {
a08171c5 513 $filecount = 0;
b933a139 514 // there were no files before - one file means root dir only ;-)
8546def3 515 $file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid);
b933a139 516 foreach ($draftfiles as $file) {
a08171c5 517 if (!$options['subdirs']) {
518 if ($file->get_filepath() !== '/' or $file->is_directory()) {
519 continue;
520 }
521 }
522 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
523 // oversized file - should not get here at all
b5b188ce 524 continue;
525 }
a08171c5 526 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
527 // more files - should not get here at all
528 break;
529 }
530 if (!$file->is_directory()) {
531 $filecount++;
532 }
b933a139 533 $fs->create_file_from_storedfile($file_record, $file);
534 }
535
536 } else {
537 // we have to merge old and new files - we want to keep file ids for files that were not changed
538 $file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid);
a08171c5 539
540 $newhashes = array();
b933a139 541 foreach ($draftfiles as $file) {
542 $newhash = sha1($contextid.$filearea.$itemid.$file->get_filepath().$file->get_filename());
a08171c5 543 $newhashes[$newhash] = $file;
544 }
545 $filecount = 0;
546 foreach ($oldfiles as $file) {
547 $oldhash = $file->get_pathnamehash();
548 if (isset($newhashes[$oldhash])) {
b933a139 549 if (!$file->is_directory()) {
a08171c5 550 $filecount++;
b933a139 551 }
a08171c5 552 // unchanged file already there
553 unset($newhashes[$oldhash]);
554 } else {
555 // delete files not needed any more
556 $file->delete();
b933a139 557 }
b933a139 558 }
a08171c5 559
560 // now add new files
561 foreach ($newhashes as $file) {
562 if (!$options['subdirs']) {
563 if ($file->get_filepath() !== '/' or $file->is_directory()) {
564 continue;
565 }
566 }
567 if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
568 // oversized file - should not get here at all
569 continue;
570 }
571 if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
572 // more files - should not get here at all
573 break;
574 }
575 if (!$file->is_directory()) {
576 $filecount++;
577 }
578 $fs->create_file_from_storedfile($file_record, $file);
8546def3 579 }
580 }
581
b933a139 582 // purge the draft area
583 $fs->delete_area_files($usercontext->id, 'user_draft', $draftitemid);
584
8546def3 585 if (is_null($text)) {
586 return null;
587 }
588
edc0c493 589 // relink embedded files if text submitted - no absolute links allowed in database!
7983d682 590 if ($CFG->slasharguments) {
b5b188ce 591 $draftbase = "$CFG->wwwroot/draftfile.php/$usercontext->id/user_draft/$draftitemid/";
7983d682 592 } else {
b5b188ce 593 $draftbase = "$CFG->wwwroot/draftfile.php?file=/$usercontext->id/user_draft/$draftitemid/";
7983d682 594 }
595
b933a139 596 if ($forcehttps) {
7983d682 597 $draftbase = str_replace('http://', 'https://', $draftbase);
598 }
599
644d506a 600 $text = str_ireplace($draftbase, '@@PLUGINFILE@@/', $text);
7983d682 601
7983d682 602 return $text;
603}
604
a83ad946 605/**
606 * Returns description of upload error
607 * @param int $errorcode found in $_FILES['filename.ext']['error']
608 * @return error description string, '' if ok
609 */
610function file_get_upload_error($errorcode) {
a08171c5 611
a83ad946 612 switch ($errorcode) {
613 case 0: // UPLOAD_ERR_OK - no error
614 $errmessage = '';
615 break;
a08171c5 616
a83ad946 617 case 1: // UPLOAD_ERR_INI_SIZE
618 $errmessage = get_string('uploadserverlimit');
619 break;
a08171c5 620
a83ad946 621 case 2: // UPLOAD_ERR_FORM_SIZE
622 $errmessage = get_string('uploadformlimit');
623 break;
a08171c5 624
a83ad946 625 case 3: // UPLOAD_ERR_PARTIAL
626 $errmessage = get_string('uploadpartialfile');
627 break;
a08171c5 628
a83ad946 629 case 4: // UPLOAD_ERR_NO_FILE
630 $errmessage = get_string('uploadnofilefound');
631 break;
a08171c5 632
a83ad946 633 // Note: there is no error with a value of 5
634
635 case 6: // UPLOAD_ERR_NO_TMP_DIR
636 $errmessage = get_string('uploadnotempdir');
637 break;
638
639 case 7: // UPLOAD_ERR_CANT_WRITE
640 $errmessage = get_string('uploadcantwrite');
641 break;
642
643 case 8: // UPLOAD_ERR_EXTENSION
644 $errmessage = get_string('uploadextension');
645 break;
646
647 default:
648 $errmessage = get_string('uploadproblem');
649 }
650
651 return $errmessage;
652}
653
8ee88311 654/**
5f8bdc17 655 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
599f06cf 656 * Due to security concerns only downloads from http(s) sources are supported.
657 *
658 * @param string $url file url starting with http(s)://
5ef082df 659 * @param array $headers http headers, null if none. If set, should be an
660 * associative array of header name => value pairs.
6bf55889 661 * @param array $postdata array means use POST request with given parameters
662 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
5ef082df 663 * (if false, just returns content)
664 * @param int $timeout timeout for complete download process including all file transfer
44e02d79 665 * (default 5 minutes)
666 * @param int $connecttimeout timeout for connection to server; this is the timeout that
667 * usually happens if the remote server is completely down (default 20 seconds);
668 * may not work when using proxy
83947a36 669 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
8ee88311 670 * @return mixed false if request failed or content of the file as string if ok.
671 */
83947a36 672function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
e27f0765 673 global $CFG;
674
599f06cf 675 // some extra security
676 $newlines = array("\r", "\n");
677 if (is_array($headers) ) {
678 foreach ($headers as $key => $value) {
679 $headers[$key] = str_replace($newlines, '', $value);
680 }
681 }
682 $url = str_replace($newlines, '', $url);
683 if (!preg_match('|^https?://|i', $url)) {
684 if ($fullresponse) {
685 $response = new object();
686 $response->status = 0;
687 $response->headers = array();
688 $response->response_code = 'Invalid protocol specified in url';
689 $response->results = '';
690 $response->error = 'Invalid protocol specified in url';
691 return $response;
692 } else {
693 return false;
694 }
695 }
696
bb2c046d 697 // check if proxy (if used) should be bypassed for this url
aa944588 698 $proxybypass = is_proxybypass($url);
699
7fb90df0 700 if (!$ch = curl_init($url)) {
701 debugging('Can not init curl.');
702 return false;
703 }
599f06cf 704
599f06cf 705 // set extra headers
6bf55889 706 if (is_array($headers) ) {
707 $headers2 = array();
708 foreach ($headers as $key => $value) {
6bf55889 709 $headers2[] = "$key: $value";
710 }
711 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
712 }
713
bb2c046d 714
83947a36 715 if ($skipcertverify) {
716 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
717 }
bb2c046d 718
6bf55889 719 // use POST if requested
720 if (is_array($postdata)) {
721 foreach ($postdata as $k=>$v) {
722 $postdata[$k] = urlencode($k).'='.urlencode($v);
5f8bdc17 723 }
6bf55889 724 $postdata = implode('&', $postdata);
725 curl_setopt($ch, CURLOPT_POST, true);
726 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
5f8bdc17 727 }
728
8ee88311 729 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
6bf55889 730 curl_setopt($ch, CURLOPT_HEADER, true);
44e02d79 731 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
732 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
6bf55889 733 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
599f06cf 734 // TODO: add version test for '7.10.5'
6bf55889 735 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
736 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
737 }
738
15c31560 739 if (!empty($CFG->proxyhost) and !$proxybypass) {
5f8bdc17 740 // SOCKS supported in PHP5 only
741 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
742 if (defined('CURLPROXY_SOCKS5')) {
743 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
744 } else {
5f8bdc17 745 curl_close($ch);
599f06cf 746 if ($fullresponse) {
747 $response = new object();
748 $response->status = '0';
749 $response->headers = array();
750 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
751 $response->results = '';
752 $response->error = 'SOCKS5 proxy is not supported in PHP4';
753 return $response;
754 } else {
755 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
756 return false;
757 }
5f8bdc17 758 }
759 }
760
08ec989f 761 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
762
8ee88311 763 if (empty($CFG->proxyport)) {
e27f0765 764 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
8ee88311 765 } else {
e27f0765 766 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
8ee88311 767 }
5f8bdc17 768
769 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
8ee88311 770 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
5f8bdc17 771 if (defined('CURLOPT_PROXYAUTH')) {
772 // any proxy authentication if PHP 5.1
773 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
774 }
8ee88311 775 }
776 }
6bf55889 777
599f06cf 778 $data = curl_exec($ch);
08ec989f 779
599f06cf 780 // try to detect encoding problems
6bf55889 781 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
782 curl_setopt($ch, CURLOPT_ENCODING, 'none');
599f06cf 783 $data = curl_exec($ch);
6bf55889 784 }
785
08ec989f 786 if (curl_errno($ch)) {
6bf55889 787 $error = curl_error($ch);
788 $error_no = curl_errno($ch);
789 curl_close($ch);
790
791 if ($fullresponse) {
792 $response = new object();
793 if ($error_no == 28) {
794 $response->status = '-100'; // mimic snoopy
795 } else {
796 $response->status = '0';
797 }
798 $response->headers = array();
799 $response->response_code = $error;
800 $response->results = '';
801 $response->error = $error;
802 return $response;
803 } else {
599f06cf 804 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
6bf55889 805 return false;
806 }
5f8bdc17 807
808 } else {
6bf55889 809 $info = curl_getinfo($ch);
810 curl_close($ch);
599f06cf 811
812 if (empty($info['http_code'])) {
813 // for security reasons we support only true http connections (Location: file:// exploit prevention)
814 $response = new object();
815 $response->status = '0';
816 $response->headers = array();
817 $response->response_code = 'Unknown cURL error';
818 $response->results = ''; // do NOT change this!
819 $response->error = 'Unknown cURL error';
820
821 } else {
822 // strip redirect headers and get headers array and content
823 $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
824 $results = array_pop($data);
825 $headers = array_pop($data);
826 $headers = explode("\r\n", trim($headers));
827
828 $response = new object();;
829 $response->status = (string)$info['http_code'];
830 $response->headers = $headers;
831 $response->response_code = $headers[0];
832 $response->results = $results;
833 $response->error = '';
834 }
6bf55889 835
836 if ($fullresponse) {
837 return $response;
838 } else if ($info['http_code'] != 200) {
599f06cf 839 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
6bf55889 840 return false;
841 } else {
842 return $response->results;
5f8bdc17 843 }
08ec989f 844 }
8ee88311 845}
846
3ce73b14 847/**
76ca1ff1 848 * @return List of information about file types based on extensions.
3ce73b14 849 * Associative array of extension (lower-case) to associative array
850 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 851 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 852 */
853function get_mimetypes_array() {
172dd12c 854 static $mimearray = array (
a370c895 855 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
856 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
857 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
858 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
859 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
860 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
861 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
862 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 863 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 864 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
865 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
866 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
18bf47ef 867 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 868 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
18bf47ef 869 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 870 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
76ca1ff1 871 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
6ae5e482 872 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
a370c895 873 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
609d84e3 874 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
13499032 875
a370c895 876 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
13499032 877 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx.gif'),
878 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm.gif'),
879 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx.gif'),
880 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm.gif'),
881
a370c895 882 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
883 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
884 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
885 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
886 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
ee7f231d 887 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
759bc3c8 888 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
a370c895 889 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
890 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
759bc3c8 891 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 892 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
893 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
894 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 895 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 896 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
70ee2841 897 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
a370c895 898 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
1659a998 899 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
a370c895 900 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
08297dcb 901 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
4b270c4c 902 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
08297dcb 903 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
904 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
18bf47ef 905 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 906 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
907 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
908 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
909 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
910 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 911 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
912 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
913 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 914 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 915 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
916 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
917 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
918 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
919 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
920 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
921 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
922 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
923 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
924 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
925 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 926
927 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
928 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
929 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
e10bc440 930 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
931 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
932 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
933 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
934 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
935 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
936 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
937 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
938 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
939 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
940 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
5395334d 941
a370c895 942 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
943 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
944 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
945 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
946 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
947 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
13499032 948
a370c895 949 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
950 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
13499032 951 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx.gif'),
952 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm.gif'),
953 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx.gif'),
954 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm.gif'),
955 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam.gif'),
956 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx.gif'),
957 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm.gif'),
958
a370c895 959 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
960 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
7c59f3be 961 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio.gif'),
962 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio.gif'),
a00420fb 963 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
7c59f3be 964 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio.gif'),
a370c895 965 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
966 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
967 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
968 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
969 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
970 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 971 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
4db69ffb 972 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
973 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
a370c895 974 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
975 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
976 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 977
978 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
979 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
980 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
981 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
982 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
983 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
984 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
985 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
986 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
987 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
988
a370c895 989 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
990 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
991 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
992 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
993 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
994 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
995 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
996 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
997 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
998 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
999 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
ee7f231d 1000 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
1001 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
1002 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
13499032 1003
a370c895 1004 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
13499032 1005 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx.gif'),
1006 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm.gif'),
1007 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx.gif'),
1008 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm.gif'),
1009 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb.gif'),
1010 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam.gif'),
1011
a370c895 1012 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
1013 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
1014 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 1015 );
172dd12c 1016 return $mimearray;
3ce73b14 1017}
1018
76ca1ff1 1019/**
3ce73b14 1020 * Obtains information about a filetype based on its extension. Will
1021 * use a default if no information is present about that particular
1022 * extension.
76ca1ff1 1023 * @param string $element Desired information (usually 'icon'
3ce73b14 1024 * for icon filename or 'type' for MIME type)
76ca1ff1 1025 * @param string $filename Filename we're looking up
3ce73b14 1026 * @return string Requested piece of information from array
1027 */
1028function mimeinfo($element, $filename) {
0ef98843 1029 global $CFG;
172dd12c 1030 $mimeinfo = get_mimetypes_array();
f1e0649c 1031
a370c895 1032 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 1033 if (isset($mimeinfo[strtolower($match[1])][$element])) {
1034 return $mimeinfo[strtolower($match[1])][$element];
1035 } else {
72aa74ce 1036 if ($element == 'icon32') {
1037 if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
1038 $filename = substr($mimeinfo[strtolower($match[1])]['icon'], 0, -4);
1039 } else {
1040 $filename = 'unknown';
1041 }
0ef98843 1042 $filename .= '-32.png';
1043 if (file_exists($CFG->dirroot.'/pix/f/'.$filename)) {
1044 return $filename;
1045 } else {
7a34d20d 1046 return 'unknown-32.png';
0ef98843 1047 }
1048 } else {
1049 return $mimeinfo['xxx'][$element]; // By default
1050 }
f1e0649c 1051 }
1052 } else {
7a34d20d 1053 if ($element == 'icon32') {
1054 return 'unknown-32.png';
1055 }
a370c895 1056 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 1057 }
1058}
1059
76ca1ff1 1060/**
3ce73b14 1061 * Obtains information about a filetype based on the MIME type rather than
1062 * the other way around.
1063 * @param string $element Desired information (usually 'icon')
76ca1ff1 1064 * @param string $mimetype MIME type we're looking up
3ce73b14 1065 * @return string Requested piece of information from array
1066 */
1067function mimeinfo_from_type($element, $mimetype) {
172dd12c 1068 $mimeinfo = get_mimetypes_array();
76ca1ff1 1069
3ce73b14 1070 foreach($mimeinfo as $values) {
1071 if($values['type']==$mimetype) {
1072 if(isset($values[$element])) {
1073 return $values[$element];
1074 }
1075 break;
1076 }
1077 }
1078 return $mimeinfo['xxx'][$element]; // Default
1079}
b9709b76 1080
42ead7d7 1081/**
1082 * Get information about a filetype based on the icon file.
1083 * @param string $element Desired information (usually 'icon')
1084 * @param string $icon Icon file path.
0b46f19e 1085 * @param boolean $all return all matching entries (defaults to false - last match)
42ead7d7 1086 * @return string Requested piece of information from array
1087 */
0b46f19e 1088function mimeinfo_from_icon($element, $icon, $all=false) {
172dd12c 1089 $mimeinfo = get_mimetypes_array();
42ead7d7 1090
1091 if (preg_match("/\/(.*)/", $icon, $matches)) {
1092 $icon = $matches[1];
1093 }
0b46f19e 1094 $info = array($mimeinfo['xxx'][$element]); // Default
42ead7d7 1095 foreach($mimeinfo as $values) {
1096 if($values['icon']==$icon) {
1097 if(isset($values[$element])) {
0b46f19e 1098 $info[] = $values[$element];
42ead7d7 1099 }
1100 //No break, for example for 'excel.gif' we don't want 'csv'!
1101 }
1102 }
0b46f19e 1103 if ($all) {
1104 return $info;
1105 }
1106 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
42ead7d7 1107}
1108
c0381e22 1109/**
76ca1ff1 1110 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1111 * mimetypes.php language file.
c0381e22 1112 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
1113 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 1114 * @return string Text description
c0381e22 1115 */
1116function get_mimetype_description($mimetype,$capitalise=false) {
1117 $result=get_string($mimetype,'mimetypes');
1118 // Surrounded by square brackets indicates that there isn't a string for that
1119 // (maybe there is a better way to find this out?)
1120 if(strpos($result,'[')===0) {
1121 $result=get_string('document/unknown','mimetypes');
76ca1ff1 1122 }
c0381e22 1123 if($capitalise) {
1124 $result=ucfirst($result);
1125 }
1126 return $result;
1127}
1128
9e5fa330 1129/**
1130 * Reprot file is not found or not accessible
1131 * @return does not return, terminates script
1132 */
1133function send_file_not_found() {
1134 global $CFG, $COURSE;
1135 header('HTTP/1.0 404 not found');
1136 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
1137}
1138
c87c428e 1139/**
1140 * Handles the sending of temporary file to user, download is forced.
1141 * File is deleted after abort or succesful sending.
1142 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1143 * @param string $filename proposed file name when saving file
1144 * @param bool $path is content of file
45c0d224 1145 * @return does not return, script terminated
c87c428e 1146 */
45c0d224 1147function send_temp_file($path, $filename, $pathisstring=false) {
c87c428e 1148 global $CFG;
1149
1150 // close session - not needed anymore
56949c17 1151 @session_get_instance()->write_close();
c87c428e 1152
1153 if (!$pathisstring) {
1154 if (!file_exists($path)) {
1155 header('HTTP/1.0 404 not found');
45c0d224 1156 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
c87c428e 1157 }
1158 // executed after normal finish or abort
1159 @register_shutdown_function('send_temp_file_finished', $path);
1160 }
1161
1162 //IE compatibiltiy HACK!
1163 if (ini_get('zlib.output_compression')) {
1164 ini_set('zlib.output_compression', 'Off');
1165 }
1166
1167 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1168 if (check_browser_version('MSIE')) {
1169 $filename = urlencode($filename);
1170 }
1171
1172 $filesize = $pathisstring ? strlen($path) : filesize($path);
1173
1174 @header('Content-Disposition: attachment; filename='.$filename);
1175 @header('Content-Length: '.$filesize);
1176 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1177 @header('Cache-Control: max-age=10');
1178 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1179 @header('Pragma: ');
1180 } else { //normal http - prevent caching at all cost
1181 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1182 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1183 @header('Pragma: no-cache');
1184 }
1185 @header('Accept-Ranges: none'); // Do not allow byteserving
1186
1187 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1188 if ($pathisstring) {
1189 echo $path;
1190 } else {
29e3d7e2 1191 @readfile($path);
c87c428e 1192 }
1193
1194 die; //no more chars to output
1195}
1196
1197/**
1198 * Internal callnack function used by send_temp_file()
1199 */
1200function send_temp_file_finished($path) {
1201 if (file_exists($path)) {
1202 @unlink($path);
1203 }
1204}
1205
76ca1ff1 1206/**
1207 * Handles the sending of file data to the user's browser, including support for
1208 * byteranges etc.
ba75ad94 1209 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1210 * @param string $filename Filename to send
1211 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1212 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1213 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1214 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1215 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 1216 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1217 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 1218 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1219 * and should not be reopened.
1220 * @return no return or void, script execution stopped unless $dontdie is true
b9709b76 1221 */
b379f7d9 1222function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
6800d78e 1223 global $CFG, $COURSE, $SESSION;
f1e0649c 1224
b379f7d9 1225 if ($dontdie) {
15325f55 1226 ignore_user_abort(true);
b379f7d9 1227 }
1228
c8a5c6a4 1229 // MDL-11789, apply $CFG->filelifetime here
1230 if ($lifetime === 'default') {
1231 if (!empty($CFG->filelifetime)) {
0cde3ede 1232 $lifetime = $CFG->filelifetime;
c8a5c6a4 1233 } else {
0cde3ede 1234 $lifetime = 86400;
c8a5c6a4 1235 }
1236 }
1237
56949c17 1238 session_get_instance()->write_close(); // unlock session during fileserving
172dd12c 1239
ba4e0b05 1240 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1241 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1242 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1243 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 1244 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 1245 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 1246 $lastmodified = $pathisstring ? time() : filemtime($path);
1247 $filesize = $pathisstring ? strlen($path) : filesize($path);
1248
36bddcf5 1249/* - MDL-13949
ee7f231d 1250 //Adobe Acrobat Reader XSS prevention
1251 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1252 //please note that it prevents opening of pdfs in browser when http referer disabled
1253 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 1254 if (!empty($_SERVER['HTTP_RANGE'])) {
1255 //already byteserving
76ca1ff1 1256 $lifetime = 1; // >0 needed for byteserving
c57d8874 1257 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 1258 $mimetype = 'application/x-forcedownload';
1259 $forcedownload = true;
1260 $lifetime = 0;
1261 } else {
76ca1ff1 1262 $lifetime = 1; // >0 needed for byteserving
ee7f231d 1263 }
b8806ccc 1264 }
36bddcf5 1265*/
f3f7610c 1266
69faecce 1267 //IE compatibiltiy HACK!
4c8c65ec 1268 if (ini_get('zlib.output_compression')) {
69faecce 1269 ini_set('zlib.output_compression', 'Off');
1270 }
1271
4c8c65ec 1272 //try to disable automatic sid rewrite in cookieless mode
8914cb82 1273 @ini_set("session.use_trans_sid", "false");
4c8c65ec 1274
1275 //do not put '@' before the next header to detect incorrect moodle configurations,
1276 //error should be better than "weird" empty lines for admins/users
1277 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1278 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1279
4f047de2 1280 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1281 if (check_browser_version('MSIE')) {
4638009b 1282 $filename = rawurlencode($filename);
4f047de2 1283 }
1284
4c8c65ec 1285 if ($forcedownload) {
4638009b 1286 @header('Content-Disposition: attachment; filename="'.$filename.'"');
4c8c65ec 1287 } else {
4638009b 1288 @header('Content-Disposition: inline; filename="'.$filename.'"');
4c8c65ec 1289 }
1290
f1e0649c 1291 if ($lifetime > 0) {
4c8c65ec 1292 @header('Cache-Control: max-age='.$lifetime);
1293 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 1294 @header('Pragma: ');
4c8c65ec 1295
1296 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1297
1298 @header('Accept-Ranges: bytes');
1299
1300 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1301 // byteserving stuff - for acrobat reader and download accelerators
1302 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1303 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1304 $ranges = false;
1305 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1306 foreach ($ranges as $key=>$value) {
1307 if ($ranges[$key][1] == '') {
1308 //suffix case
1309 $ranges[$key][1] = $filesize - $ranges[$key][2];
1310 $ranges[$key][2] = $filesize - 1;
1311 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1312 //fix range length
1313 $ranges[$key][2] = $filesize - 1;
1314 }
1315 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1316 //invalid byte-range ==> ignore header
1317 $ranges = false;
1318 break;
1319 }
1320 //prepare multipart header
1321 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1322 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1323 }
1324 } else {
1325 $ranges = false;
1326 }
1327 if ($ranges) {
172dd12c 1328 $handle = fopen($filename, 'rb');
1329 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
4c8c65ec 1330 }
1331 }
1332 } else {
1333 /// Do not byteserve (disabled, strings, text and html files).
1334 @header('Accept-Ranges: none');
1335 }
1336 } else { // Do not cache files in proxies and browsers
85e00626 1337 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1338 @header('Cache-Control: max-age=10');
4c8c65ec 1339 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 1340 @header('Pragma: ');
1341 } else { //normal http - prevent caching at all cost
1342 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 1343 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 1344 @header('Pragma: no-cache');
1345 }
4c8c65ec 1346 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 1347 }
f1e0649c 1348
b9709b76 1349 if (empty($filter)) {
0a2092a3 1350 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
4c8c65ec 1351 //cookieless mode - rewrite links
1352 @header('Content-Type: text/html');
1353 $path = $pathisstring ? $path : implode('', file($path));
0ad6b20c 1354 $path = sid_ob_rewrite($path);
4c8c65ec 1355 $filesize = strlen($path);
1356 $pathisstring = true;
1357 } else if ($mimetype == 'text/plain') {
810944af 1358 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 1359 } else {
4c8c65ec 1360 @header('Content-Type: '.$mimetype);
f1e0649c 1361 }
4c8c65ec 1362 @header('Content-Length: '.$filesize);
1363 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1364 if ($pathisstring) {
1365 echo $path;
4c8c65ec 1366 } else {
29e3d7e2 1367 @readfile($path);
f1e0649c 1368 }
1369 } else { // Try to put the file through filters
f1e0649c 1370 if ($mimetype == 'text/html') {
a17c57b5 1371 $options = new object();
f1e0649c 1372 $options->noclean = true;
a17c57b5 1373 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 1374 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 1375
3ace5ee4 1376 $text = file_modify_html_header($text);
60f9e36e 1377 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
0a2092a3 1378 if (!empty($CFG->usesid)) {
4c8c65ec 1379 //cookieless mode - rewrite links
0ad6b20c 1380 $output = sid_ob_rewrite($output);
4c8c65ec 1381 }
f1e0649c 1382
4c8c65ec 1383 @header('Content-Length: '.strlen($output));
1384 @header('Content-Type: text/html');
1385 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1386 echo $output;
b9709b76 1387 // only filter text if filter all files is selected
1388 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 1389 $options = new object();
f1e0649c 1390 $options->newlines = false;
1391 $options->noclean = true;
1392 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 1393 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
0a2092a3 1394 if (!empty($CFG->usesid)) {
4c8c65ec 1395 //cookieless mode - rewrite links
0ad6b20c 1396 $output = sid_ob_rewrite($output);
4c8c65ec 1397 }
f1e0649c 1398
4c8c65ec 1399 @header('Content-Length: '.strlen($output));
810944af 1400 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 1401 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1402 echo $output;
1403 } else { // Just send it out raw
4c8c65ec 1404 @header('Content-Length: '.$filesize);
1405 @header('Content-Type: '.$mimetype);
1406 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1407 if ($pathisstring) {
1408 echo $path;
1409 }else {
29e3d7e2 1410 @readfile($path);
f1e0649c 1411 }
1412 }
1413 }
b379f7d9 1414 if ($dontdie) {
1415 return;
1416 }
f1e0649c 1417 die; //no more chars to output!!!
1418}
1419
172dd12c 1420/**
1421 * Handles the sending of file data to the user's browser, including support for
1422 * byteranges etc.
1423 * @param object $stored_file local file object
1424 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1425 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1426 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1427 * @param string $filename Override filename
1428 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 1429 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1430 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 1431 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1432 * and should not be reopened.
1433 * @return no return or void, script execution stopped unless $dontdie is true
172dd12c 1434 */
b379f7d9 1435function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
172dd12c 1436 global $CFG, $COURSE, $SESSION;
1437
b379f7d9 1438 if ($dontdie) {
15325f55 1439 ignore_user_abort(true);
b379f7d9 1440 }
1441
56949c17 1442 session_get_instance()->write_close(); // unlock session during fileserving
172dd12c 1443
1444 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1445 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1446 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1447 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1448 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1449 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1450 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1451 $lastmodified = $stored_file->get_timemodified();
1452 $filesize = $stored_file->get_filesize();
1453
1454 //IE compatibiltiy HACK!
1455 if (ini_get('zlib.output_compression')) {
1456 ini_set('zlib.output_compression', 'Off');
1457 }
1458
1459 //try to disable automatic sid rewrite in cookieless mode
1460 @ini_set("session.use_trans_sid", "false");
1461
1462 //do not put '@' before the next header to detect incorrect moodle configurations,
1463 //error should be better than "weird" empty lines for admins/users
1464 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1465 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1466
1467 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1468 if (check_browser_version('MSIE')) {
1469 $filename = rawurlencode($filename);
1470 }
1471
1472 if ($forcedownload) {
1473 @header('Content-Disposition: attachment; filename="'.$filename.'"');
1474 } else {
1475 @header('Content-Disposition: inline; filename="'.$filename.'"');
1476 }
1477
1478 if ($lifetime > 0) {
1479 @header('Cache-Control: max-age='.$lifetime);
1480 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1481 @header('Pragma: ');
1482
1483 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1484
1485 @header('Accept-Ranges: bytes');
1486
1487 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1488 // byteserving stuff - for acrobat reader and download accelerators
1489 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1490 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1491 $ranges = false;
1492 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1493 foreach ($ranges as $key=>$value) {
1494 if ($ranges[$key][1] == '') {
1495 //suffix case
1496 $ranges[$key][1] = $filesize - $ranges[$key][2];
1497 $ranges[$key][2] = $filesize - 1;
1498 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1499 //fix range length
1500 $ranges[$key][2] = $filesize - 1;
1501 }
1502 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1503 //invalid byte-range ==> ignore header
1504 $ranges = false;
1505 break;
1506 }
1507 //prepare multipart header
1508 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1509 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1510 }
1511 } else {
1512 $ranges = false;
1513 }
1514 if ($ranges) {
1515 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1516 }
1517 }
1518 } else {
1519 /// Do not byteserve (disabled, strings, text and html files).
1520 @header('Accept-Ranges: none');
1521 }
1522 } else { // Do not cache files in proxies and browsers
1523 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1524 @header('Cache-Control: max-age=10');
1525 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1526 @header('Pragma: ');
1527 } else { //normal http - prevent caching at all cost
1528 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1529 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1530 @header('Pragma: no-cache');
1531 }
1532 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1533 }
1534
1535 if (empty($filter)) {
1536 $filtered = false;
0a2092a3 1537 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
172dd12c 1538 //cookieless mode - rewrite links
1539 @header('Content-Type: text/html');
1540 $text = $stored_file->get_content();
0ad6b20c 1541 $text = sid_ob_rewrite($text);
172dd12c 1542 $filesize = strlen($text);
1543 $filtered = true;
1544 } else if ($mimetype == 'text/plain') {
1545 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1546 } else {
1547 @header('Content-Type: '.$mimetype);
1548 }
1549 @header('Content-Length: '.$filesize);
1550 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1551 if ($filtered) {
1552 echo $text;
1553 } else {
1554 $stored_file->readfile();
1555 }
1556
1557 } else { // Try to put the file through filters
1558 if ($mimetype == 'text/html') {
1559 $options = new object();
1560 $options->noclean = true;
1561 $options->nocache = true; // temporary workaround for MDL-5136
1562 $text = $stored_file->get_content();
1563 $text = file_modify_html_header($text);
1564 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
0a2092a3 1565 if (!empty($CFG->usesid)) {
172dd12c 1566 //cookieless mode - rewrite links
0ad6b20c 1567 $output = sid_ob_rewrite($output);
172dd12c 1568 }
1569
1570 @header('Content-Length: '.strlen($output));
1571 @header('Content-Type: text/html');
1572 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1573 echo $output;
1574 // only filter text if filter all files is selected
1575 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1576 $options = new object();
1577 $options->newlines = false;
1578 $options->noclean = true;
1579 $text = $stored_file->get_content();
1580 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
0a2092a3 1581 if (!empty($CFG->usesid)) {
172dd12c 1582 //cookieless mode - rewrite links
0ad6b20c 1583 $output = sid_ob_rewrite($output);
172dd12c 1584 }
1585
1586 @header('Content-Length: '.strlen($output));
1587 @header('Content-Type: text/html; charset=utf-8'); //add encoding
1588 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1589 echo $output;
1590 } else { // Just send it out raw
1591 @header('Content-Length: '.$filesize);
1592 @header('Content-Type: '.$mimetype);
1593 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1594 $stored_file->readfile();
1595 }
1596 }
b379f7d9 1597 if ($dontdie) {
1598 return;
1599 }
172dd12c 1600 die; //no more chars to output!!!
1601}
1602
a43b5308 1603function get_records_csv($file, $table) {
f33e1ed4 1604 global $CFG, $DB;
599f38f9 1605
f33e1ed4 1606 if (!$metacolumns = $DB->get_columns($table)) {
599f38f9 1607 return false;
1608 }
1609
a77b98eb 1610 if(!($handle = @fopen($file, 'r'))) {
5a2a5331 1611 print_error('get_records_csv failed to open '.$file);
599f38f9 1612 }
1613
1614 $fieldnames = fgetcsv($handle, 4096);
1615 if(empty($fieldnames)) {
1616 fclose($handle);
1617 return false;
1618 }
1619
1620 $columns = array();
1621
1622 foreach($metacolumns as $metacolumn) {
1623 $ord = array_search($metacolumn->name, $fieldnames);
1624 if(is_int($ord)) {
1625 $columns[$metacolumn->name] = $ord;
1626 }
1627 }
1628
1629 $rows = array();
1630
1631 while (($data = fgetcsv($handle, 4096)) !== false) {
1632 $item = new stdClass;
1633 foreach($columns as $name => $ord) {
1634 $item->$name = $data[$ord];
1635 }
1636 $rows[] = $item;
1637 }
1638
1639 fclose($handle);
1640 return $rows;
1641}
1642
a77b98eb 1643function put_records_csv($file, $records, $table = NULL) {
f33e1ed4 1644 global $CFG, $DB;
a77b98eb 1645
a1e93da2 1646 if (empty($records)) {
a77b98eb 1647 return true;
1648 }
1649
1650 $metacolumns = NULL;
f33e1ed4 1651 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
a77b98eb 1652 return false;
1653 }
1654
a1e93da2 1655 echo "x";
1656
a77b98eb 1657 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
5a2a5331 1658 print_error('put_records_csv failed to open '.$file);
a77b98eb 1659 }
1660
a43b5308 1661 $proto = reset($records);
1662 if(is_object($proto)) {
1663 $fields_records = array_keys(get_object_vars($proto));
1664 }
1665 else if(is_array($proto)) {
1666 $fields_records = array_keys($proto);
1667 }
1668 else {
1669 return false;
1670 }
a1e93da2 1671 echo "x";
a77b98eb 1672
1673 if(!empty($metacolumns)) {
1674 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
1675 $fields = array_intersect($fields_records, $fields_table);
1676 }
1677 else {
1678 $fields = $fields_records;
1679 }
1680
1681 fwrite($fp, implode(',', $fields));
1682 fwrite($fp, "\r\n");
1683
1684 foreach($records as $record) {
a43b5308 1685 $array = (array)$record;
a77b98eb 1686 $values = array();
1687 foreach($fields as $field) {
a43b5308 1688 if(strpos($array[$field], ',')) {
1689 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 1690 }
1691 else {
a43b5308 1692 $values[] = $array[$field];
a77b98eb 1693 }
1694 }
1695 fwrite($fp, implode(',', $values)."\r\n");
1696 }
1697
1698 fclose($fp);
1699 return true;
1700}
1701
f401cc97 1702
34763a79 1703/**
76ca1ff1 1704 * Recursively delete the file or folder with path $location. That is,
34763a79 1705 * if it is a file delete it. If it is a folder, delete all its content
db3a0b34 1706 * then delete it. If $location does not exist to start, that is not
1707 * considered an error.
76ca1ff1 1708 *
34763a79 1709 * @param $location the path to remove.
1710 */
4c8c65ec 1711function fulldelete($location) {
f401cc97 1712 if (is_dir($location)) {
1713 $currdir = opendir($location);
1714 while (false !== ($file = readdir($currdir))) {
1715 if ($file <> ".." && $file <> ".") {
1716 $fullfile = $location."/".$file;
4c8c65ec 1717 if (is_dir($fullfile)) {
f401cc97 1718 if (!fulldelete($fullfile)) {
1719 return false;
1720 }
1721 } else {
1722 if (!unlink($fullfile)) {
1723 return false;
1724 }
4c8c65ec 1725 }
f401cc97 1726 }
4c8c65ec 1727 }
f401cc97 1728 closedir($currdir);
1729 if (! rmdir($location)) {
1730 return false;
1731 }
1732
34763a79 1733 } else if (file_exists($location)) {
f401cc97 1734 if (!unlink($location)) {
1735 return false;
1736 }
1737 }
1738 return true;
1739}
1740
4c8c65ec 1741/**
1742 * Send requested byterange of file.
1743 */
172dd12c 1744function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
4c8c65ec 1745 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
4c8c65ec 1746 if ($handle === false) {
1747 die;
1748 }
1749 if (count($ranges) == 1) { //only one range requested
1750 $length = $ranges[0][2] - $ranges[0][1] + 1;
1751 @header('HTTP/1.1 206 Partial content');
1752 @header('Content-Length: '.$length);
172dd12c 1753 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
4c8c65ec 1754 @header('Content-Type: '.$mimetype);
1755 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1756 $buffer = '';
1757 fseek($handle, $ranges[0][1]);
1758 while (!feof($handle) && $length > 0) {
68913aec 1759 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 1760 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1761 echo $buffer;
1762 flush();
1763 $length -= strlen($buffer);
1764 }
1765 fclose($handle);
1766 die;
1767 } else { // multiple ranges requested - not tested much
1768 $totallength = 0;
1769 foreach($ranges as $range) {
aba588a7 1770 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 1771 }
aba588a7 1772 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 1773 @header('HTTP/1.1 206 Partial content');
1774 @header('Content-Length: '.$totallength);
1775 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
1776 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
1777 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1778 foreach($ranges as $range) {
1779 $length = $range[2] - $range[1] + 1;
1780 echo $range[0];
1781 $buffer = '';
1782 fseek($handle, $range[1]);
1783 while (!feof($handle) && $length > 0) {
68913aec 1784 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 1785 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1786 echo $buffer;
1787 flush();
1788 $length -= strlen($buffer);
1789 }
1790 }
1791 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
1792 fclose($handle);
1793 die;
1794 }
1795}
f401cc97 1796
3ace5ee4 1797/**
1798 * add includes (js and css) into uploaded files
1799 * before returning them, useful for themes and utf.js includes
1800 * @param string text - text to search and replace
1801 * @return string - text with added head includes
1802 */
1803function file_modify_html_header($text) {
1804 // first look for <head> tag
1805 global $CFG;
76ca1ff1 1806
3ace5ee4 1807 $stylesheetshtml = '';
1808 foreach ($CFG->stylesheets as $stylesheet) {
1809 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 1810 }
1811
5b8fa09b 1812 $ufo = '';
1813 if (filter_is_enabled('filter/mediaplugin')) {
76ca1ff1 1814 // this script is needed by most media filter plugins.
7a1f5e93 1815 $ufo = get_require_js_code(array($CFG->wwwroot . '/lib/ufo.js'));
3ace5ee4 1816 }
76ca1ff1 1817
3ace5ee4 1818 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
1819 if ($matches) {
1820 $replacement = '<head>'.$ufo.$stylesheetshtml;
1821 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 1822 return $text;
3ace5ee4 1823 }
76ca1ff1 1824
3ace5ee4 1825 // if not, look for <html> tag, and stick <head> right after
1826 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
1827 if ($matches) {
1828 // replace <html> tag with <html><head>includes</head>
13534ef7 1829 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 1830 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 1831 return $text;
3ace5ee4 1832 }
76ca1ff1 1833
3ace5ee4 1834 // if not, look for <body> tag, and stick <head> before body
1835 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
1836 if ($matches) {
13534ef7 1837 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 1838 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 1839 return $text;
1840 }
1841
3ace5ee4 1842 // if not, just stick a <head> tag at the beginning
1843 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
1844 return $text;
1845}
1846
bb2c046d 1847/**
1848 * RESTful cURL class
1849 *
1850 * This is a wrapper class for curl, it is quite easy to use:
1851 *
1852 * $c = new curl;
1853 * // enable cache
1854 * $c = new curl(array('cache'=>true));
1855 * // enable cookie
1856 * $c = new curl(array('cookie'=>true));
1857 * // enable proxy
1858 * $c = new curl(array('proxy'=>true));
1859 *
1860 * // HTTP GET Method
1861 * $html = $c->get('http://example.com');
1862 * // HTTP POST Method
1863 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
1864 * // HTTP PUT Method
1865 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
1866 *
1867 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
1868 * @version 0.4 dev
1869 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
1870 */
1871
1872class curl {
1873 public $cache = false;
1874 public $proxy = false;
1875 public $version = '0.4 dev';
1876 public $response = array();
1877 public $header = array();
1878 public $info;
1879 public $error;
1880
1881 private $options;
1882 private $proxy_host = '';
1883 private $proxy_auth = '';
1884 private $proxy_type = '';
1885 private $debug = false;
1886 private $cookie = false;
1887
1888 public function __construct($options = array()){
1889 global $CFG;
1890 if (!function_exists('curl_init')) {
1891 $this->error = 'cURL module must be enabled!';
1892 trigger_error($this->error, E_USER_ERROR);
1893 return false;
1894 }
1895 // the options of curl should be init here.
1896 $this->resetopt();
1897 if (!empty($options['debug'])) {
1898 $this->debug = true;
1899 }
1900 if(!empty($options['cookie'])) {
1901 if($options['cookie'] === true) {
1902 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
1903 } else {
1904 $this->cookie = $options['cookie'];
1905 }
1906 }
1907 if (!empty($options['cache'])) {
1908 if (class_exists('curl_cache')) {
5430f05b 1909 if (!empty($options['module_cache'])) {
1910 $this->cache = new curl_cache($options['module_cache']);
1911 } else {
1912 $this->cache = new curl_cache('misc');
1913 }
bb2c046d 1914 }
1915 }
d04ce87f 1916 if (!empty($CFG->proxyhost)) {
1917 if (empty($CFG->proxyport)) {
1918 $this->proxy_host = $CFG->proxyhost;
1919 } else {
1920 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
1921 }
1922 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1923 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
1924 $this->setopt(array(
1925 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
1926 'proxyuserpwd'=>$this->proxy_auth));
1927 }
1928 if (!empty($CFG->proxytype)) {
1929 if ($CFG->proxytype == 'SOCKS5') {
1930 $this->proxy_type = CURLPROXY_SOCKS5;
bb2c046d 1931 } else {
d04ce87f 1932 $this->proxy_type = CURLPROXY_HTTP;
f6d3e2c4 1933 $this->setopt(array('httpproxytunnel'=>false));
bb2c046d 1934 }
d04ce87f 1935 $this->setopt(array('proxytype'=>$this->proxy_type));
bb2c046d 1936 }
d04ce87f 1937 }
1938 if (!empty($this->proxy_host)) {
1939 $this->proxy = array('proxy'=>$this->proxy_host);
bb2c046d 1940 }
1941 }
1942 public function resetopt(){
1943 $this->options = array();
1944 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
1945 // True to include the header in the output
1946 $this->options['CURLOPT_HEADER'] = 0;
1947 // True to Exclude the body from the output
1948 $this->options['CURLOPT_NOBODY'] = 0;
1949 // TRUE to follow any "Location: " header that the server
1950 // sends as part of the HTTP header (note this is recursive,
1951 // PHP will follow as many "Location: " headers that it is sent,
1952 // unless CURLOPT_MAXREDIRS is set).
1953 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
1954 $this->options['CURLOPT_MAXREDIRS'] = 10;
1955 $this->options['CURLOPT_ENCODING'] = '';
1956 // TRUE to return the transfer as a string of the return
1957 // value of curl_exec() instead of outputting it out directly.
1958 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
1959 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
1960 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
1961 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
6135bd45 1962 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
bb2c046d 1963 }
1964
1965 /**
1966 * Reset Cookie
1967 *
1968 * @param array $options If array is null, this function will
1969 * reset the options to default value.
1970 *
1971 */
1972 public function resetcookie() {
1973 if (!empty($this->cookie)) {
1974 if (is_file($this->cookie)) {
1975 $fp = fopen($this->cookie, 'w');
1976 if (!empty($fp)) {
1977 fwrite($fp, '');
1978 fclose($fp);
1979 }
1980 }
1981 }
1982 }
1983
1984 /**
1985 * Set curl options
1986 *
1987 * @param array $options If array is null, this function will
1988 * reset the options to default value.
1989 *
1990 */
1991 public function setopt($options = array()) {
1992 if (is_array($options)) {
1993 foreach($options as $name => $val){
1994 if (stripos($name, 'CURLOPT_') === false) {
1995 $name = strtoupper('CURLOPT_'.$name);
1996 }
1997 $this->options[$name] = $val;
1998 }
1999 }
2000 }
2001 /**
2002 * Reset http method
2003 *
2004 */
2005 public function cleanopt(){
2006 unset($this->options['CURLOPT_HTTPGET']);
2007 unset($this->options['CURLOPT_POST']);
2008 unset($this->options['CURLOPT_POSTFIELDS']);
2009 unset($this->options['CURLOPT_PUT']);
2010 unset($this->options['CURLOPT_INFILE']);
2011 unset($this->options['CURLOPT_INFILESIZE']);
2012 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2013 }
2014
2015 /**
2016 * Set HTTP Request Header
2017 *
2018 * @param array $headers
2019 *
2020 */
2021 public function setHeader($header) {
2022 if (is_array($header)){
2023 foreach ($header as $v) {
2024 $this->setHeader($v);
2025 }
2026 } else {
2027 $this->header[] = $header;
2028 }
2029 }
2030 /**
2031 * Set HTTP Response Header
2032 *
2033 */
2034 public function getResponse(){
2035 return $this->response;
2036 }
2037 /**
2038 * private callback function
2039 * Formatting HTTP Response Header
2040 *
2041 */
2042 private function formatHeader($ch, $header)
2043 {
2044 $this->count++;
2045 if (strlen($header) > 2) {
2046 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2047 $key = rtrim($key, ':');
2048 if (!empty($this->response[$key])) {
2049 if (is_array($this->response[$key])){
2050 $this->response[$key][] = $value;
2051 } else {
2052 $tmp = $this->response[$key];
2053 $this->response[$key] = array();
2054 $this->response[$key][] = $tmp;
2055 $this->response[$key][] = $value;
2056
2057 }
2058 } else {
2059 $this->response[$key] = $value;
2060 }
2061 }
2062 return strlen($header);
2063 }
2064
2065 /**
2066 * Set options for individual curl instance
2067 */
2068 private function apply_opt($curl, $options) {
2069 // Clean up
2070 $this->cleanopt();
2071 // set cookie
2072 if (!empty($this->cookie) || !empty($options['cookie'])) {
2073 $this->setopt(array('cookiejar'=>$this->cookie,
2074 'cookiefile'=>$this->cookie
2075 ));
2076 }
2077
2078 // set proxy
2079 if (!empty($this->proxy) || !empty($options['proxy'])) {
2080 $this->setopt($this->proxy);
2081 }
2082 $this->setopt($options);
2083 // reset before set options
2084 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2085 // set headers
2086 if (empty($this->header)){
2087 $this->setHeader(array(
2088 'User-Agent: MoodleBot/1.0',
2089 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2090 'Connection: keep-alive'
2091 ));
2092 }
2093 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2094
2095 if ($this->debug){
2096 echo '<h1>Options</h1>';
2097 var_dump($this->options);
2098 echo '<h1>Header</h1>';
2099 var_dump($this->header);
2100 }
2101
2102 // set options
2103 foreach($this->options as $name => $val) {
2104 if (is_string($name)) {
2105 $name = constant(strtoupper($name));
2106 }
2107 curl_setopt($curl, $name, $val);
2108 }
2109 return $curl;
2110 }
2111 /*
2112 * Download multiple files in parallel
2113 * $c = new curl;
2114 * $c->download(array(
172dd12c 2115 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
bb2c046d 2116 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2117 * ));
2118 */
2119 public function download($requests, $options = array()) {
2120 $options['CURLOPT_BINARYTRANSFER'] = 1;
2121 $options['RETURNTRANSFER'] = false;
2122 return $this->multi($requests, $options);
2123 }
2124 /*
2125 * Mulit HTTP Requests
2126 * This function could run multi-requests in parallel.
2127 */
2128 protected function multi($requests, $options = array()) {
2129 $count = count($requests);
2130 $handles = array();
2131 $results = array();
2132 $main = curl_multi_init();
2133 for ($i = 0; $i < $count; $i++) {
2134 $url = $requests[$i];
2135 foreach($url as $n=>$v){
2136 $options[$n] = $url[$n];
2137 }
2138 $handles[$i] = curl_init($url['url']);
2139 $this->apply_opt($handles[$i], $options);
2140 curl_multi_add_handle($main, $handles[$i]);
2141 }
2142 $running = 0;
2143 do {
2144 curl_multi_exec($main, $running);
2145 } while($running > 0);
2146 for ($i = 0; $i < $count; $i++) {
2147 if (!empty($optins['CURLOPT_RETURNTRANSFER'])) {
2148 $results[] = true;
2149 } else {
2150 $results[] = curl_multi_getcontent($handles[$i]);
2151 }
2152 curl_multi_remove_handle($main, $handles[$i]);
2153 }
2154 curl_multi_close($main);
2155 return $results;
2156 }
2157 /**
2158 * Single HTTP Request
2159 */
2160 protected function request($url, $options = array()){
2161 // create curl instance
2162 $curl = curl_init($url);
2163 $options['url'] = $url;
2164 $this->apply_opt($curl, $options);
2165 if ($this->cache && $ret = $this->cache->get($this->options)) {
2166 return $ret;
2167 } else {
6135bd45 2168 $ret = curl_exec($curl);
bb2c046d 2169 if ($this->cache) {
2170 $this->cache->set($this->options, $ret);
2171 }
2172 }
2173
2174 $this->info = curl_getinfo($curl);
2175 $this->error = curl_error($curl);
2176
2177 if ($this->debug){
2178 echo '<h1>Return Data</h1>';
2179 var_dump($ret);
2180 echo '<h1>Info</h1>';
2181 var_dump($this->info);
2182 echo '<h1>Error</h1>';
2183 var_dump($this->error);
2184 }
2185
2186 curl_close($curl);
2187
6135bd45 2188 if (empty($this->error)){
bb2c046d 2189 return $ret;
2190 } else {
6135bd45 2191 throw new moodle_exception($this->error, 'curl');
bb2c046d 2192 }
2193 }
2194
2195 /**
2196 * HTTP HEAD method
2197 */
2198 public function head($url, $options = array()){
2199 $options['CURLOPT_HTTPGET'] = 0;
2200 $options['CURLOPT_HEADER'] = 1;
2201 $options['CURLOPT_NOBODY'] = 1;
2202 return $this->request($url, $options);
2203 }
2204
2205 /**
2206 * HTTP POST method
2207 */
28c58294 2208 public function post($url, $params = '', $options = array()){
bb2c046d 2209 $options['CURLOPT_POST'] = 1;
28c58294 2210 if (is_array($params)) {
2211 $this->_tmp_file_post_params = array();
2212 foreach ($params as $key => $value) {
2213 if ($value instanceof stored_file) {
2214 $value->add_to_curl_request($this, $key);
2215 } else {
2216 $this->_tmp_file_post_params[$key] = $value;
2217 }
5035a8b4 2218 }
28c58294 2219 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2220 unset($this->_tmp_file_post_params);
2221 } else {
2222 // $params is the raw post data
2223 $options['CURLOPT_POSTFIELDS'] = $params;
5035a8b4 2224 }
bb2c046d 2225 return $this->request($url, $options);
2226 }
2227
2228 /**
2229 * HTTP GET method
2230 */
2231 public function get($url, $params = array(), $options = array()){
2232 $options['CURLOPT_HTTPGET'] = 1;
2233
2234 if (!empty($params)){
2235 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2236 $url .= http_build_query($params, '', '&');
2237 }
2238 return $this->request($url, $options);
2239 }
2240
2241 /**
2242 * HTTP PUT method
2243 */
2244 public function put($url, $params = array(), $options = array()){
2245 $file = $params['file'];
2246 if (!is_file($file)){
2247 return null;
2248 }
2249 $fp = fopen($file, 'r');
2250 $size = filesize($file);
2251 $options['CURLOPT_PUT'] = 1;
2252 $options['CURLOPT_INFILESIZE'] = $size;
2253 $options['CURLOPT_INFILE'] = $fp;
2254 if (!isset($this->options['CURLOPT_USERPWD'])){
2255 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2256 }
2257 $ret = $this->request($url, $options);
2258 fclose($fp);
2259 return $ret;
2260 }
2261
2262 /**
2263 * HTTP DELETE method
2264 */
2265 public function delete($url, $param = array(), $options = array()){
2266 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2267 if (!isset($options['CURLOPT_USERPWD'])) {
2268 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2269 }
2270 $ret = $this->request($url, $options);
2271 return $ret;
2272 }
2273 /**
2274 * HTTP TRACE method
2275 */
2276 public function trace($url, $options = array()){
2277 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2278 $ret = $this->request($url, $options);
2279 return $ret;
2280 }
2281 /**
2282 * HTTP OPTIONS method
2283 */
2284 public function options($url, $options = array()){
2285 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2286 $ret = $this->request($url, $options);
2287 return $ret;
2288 }
2289}
2290
2291/**
2292 * This class is used by cURL class, use case:
2293 *
5430f05b 2294 * $CFG->repositorycacheexpire = 120;
2295 * $CFG->curlcache = 120;
2296 *
2297 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
bb2c046d 2298 * $ret = $c->get('http://www.google.com');
2299 *
2300 */
2301class curl_cache {
2302 public $dir = '';
5430f05b 2303 /**
2304 *
2305 * @global $CFG
2306 * @param string @module, which module is using curl_cache
2307 *
2308 */
37051e58 2309 function __construct($module = 'repository'){
bb2c046d 2310 global $CFG;
5430f05b 2311 if (!empty($module)) {
2312 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2313 } else {
2314 $this->dir = $CFG->dataroot.'/cache/misc/';
bb2c046d 2315 }
5430f05b 2316 if (!file_exists($this->dir)) {
2317 mkdir($this->dir, 0700, true);
bb2c046d 2318 }
5430f05b 2319 if ($module == 'repository') {
2320 if (empty($CFG->repositorycacheexpire)) {
2321 $CFG->repositorycacheexpire = 120;
2322 }
2323 $this->ttl = $CFG->repositorycacheexpire;
2324 } else {
2325 if (empty($CFG->curlcache)) {
2326 $CFG->curlcache = 120;
2327 }
2328 $this->ttl = $CFG->curlcache;
b933a139 2329 }
bb2c046d 2330 }
a08171c5 2331
509f67e3 2332 /**
2333 * TODO Document
2334 */
bb2c046d 2335 public function get($param){
aae85978 2336 global $CFG, $USER;
5430f05b 2337 $this->cleanup($this->ttl);
aae85978 2338 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
bb2c046d 2339 if(file_exists($this->dir.$filename)) {
2340 $lasttime = filemtime($this->dir.$filename);
5430f05b 2341 if(time()-$lasttime > $this->ttl)
d7e122d6 2342 {
bb2c046d 2343 return false;
2344 } else {
2345 $fp = fopen($this->dir.$filename, 'r');
2346 $size = filesize($this->dir.$filename);
2347 $content = fread($fp, $size);
2348 return unserialize($content);
2349 }
2350 }
2351 return false;
2352 }
a08171c5 2353
509f67e3 2354 /**
2355 * TODO Document
2356 */
bb2c046d 2357 public function set($param, $val){
aae85978 2358 global $CFG, $USER;
2359 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
bb2c046d 2360 $fp = fopen($this->dir.$filename, 'w');
2361 fwrite($fp, serialize($val));
2362 fclose($fp);
2363 }
a08171c5 2364
509f67e3 2365 /**
2366 * TODO Document
2367 */
bb2c046d 2368 public function cleanup($expire){
2369 if($dir = opendir($this->dir)){
2370 while (false !== ($file = readdir($dir))) {
2371 if(!is_dir($file) && $file != '.' && $file != '..') {
2372 $lasttime = @filemtime($this->dir.$file);
2373 if(time() - $lasttime > $expire){
2374 @unlink($this->dir.$file);
2375 }
2376 }
2377 }
2378 }
2379 }
aae85978 2380 /**
2381 * delete current user's cache file
2382 *
2383 * @return null
2384 */
2385 public function refresh(){
2386 global $CFG, $USER;
2387 if($dir = opendir($this->dir)){
2388 while (false !== ($file = readdir($dir))) {
2389 if(!is_dir($file) && $file != '.' && $file != '..') {
2390 if(strpos($file, 'u'.$USER->id.'_')!==false){
2391 @unlink($this->dir.$file);
2392 }
2393 }
2394 }
2395 }
2396 }
bb2c046d 2397}
509f67e3 2398
2399/**
2400 * TODO Document
2401 */
014c1ca0 2402class file_type_to_ext {
2403 public function __construct($file = '') {
2404 global $CFG;
2405 if (empty($file)) {
2406 $this->file = $CFG->libdir.'/file/file_types.mm';
2407 } else {
2408 $this->file = $file;
2409 }
2410 $this->tree = array();
2411 $this->result = array();
2412 }
a08171c5 2413
509f67e3 2414 /**
2415 * TODO Document
2416 */
014c1ca0 2417 private function _browse_nodes($parent, $types) {
2418 $key = (string)$parent['TEXT'];
2419 if(isset($parent->node)) {
2420 $this->tree[$key] = array();
2421 if (in_array((string)$parent['TEXT'], $types)) {
2422 $this->_select_nodes($parent, $this->result);
2423 } else {
2424 foreach($parent->node as $v){
2425 $this->_browse_nodes($v, $types);
2426 }
2427 }
2428 } else {
2429 $this->tree[] = $key;
2430 }
2431 }
a08171c5 2432
509f67e3 2433 /**
2434 * TODO Document
2435 */
014c1ca0 2436 private function _select_nodes($parent){
2437 if(isset($parent->node)) {
2438 foreach($parent->node as $v){
2439 $this->_select_nodes($v, $this->result);
2440 }
2441 } else {
2442 $this->result[] = (string)$parent['TEXT'];
2443 }
2444 }
2445
a08171c5 2446
509f67e3 2447 /**
2448 * TODO Document
2449 */
014c1ca0 2450 public function get_file_ext($types) {
2451 $this->result = array();
fc11edbf 2452 if ((is_array($types) && in_array('*', $types)) ||
b933b378 2453 $types == '*' || empty($types)) {
2454 return array('*');
014c1ca0 2455 }
2456 foreach ($types as $key=>$value){
2457 if (strpos($value, '.') !== false) {
2458 $this->result[] = $value;
2459 unset($types[$key]);
2460 }
2461 }
2462 if (file_exists($this->file)) {
2463 $xml = simplexml_load_file($this->file);
2464 foreach($xml->node->node as $v){
2465 if (in_array((string)$v['TEXT'], $types)) {
2466 $this->_select_nodes($v);
2467 } else {
2468 $this->_browse_nodes($v, $types);
2469 }
2470 }
2471 } else {
2472 exit('Failed to open test.xml.');
2473 }
2474 return $this->result;
2475 }
2476}