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