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