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