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