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