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