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