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