MDL-16698 formslib editor element: tweaked maxfiles option
[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'),
13499032 637
a370c895 638 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
13499032 639 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx.gif'),
640 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm.gif'),
641 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx.gif'),
642 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm.gif'),
643
a370c895 644 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
645 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
646 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
647 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
648 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
ee7f231d 649 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
759bc3c8 650 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
a370c895 651 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
652 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
759bc3c8 653 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 654 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
655 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
656 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 657 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 658 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
70ee2841 659 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
a370c895 660 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
1659a998 661 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
a370c895 662 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
08297dcb 663 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
4b270c4c 664 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
08297dcb 665 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
666 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
18bf47ef 667 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 668 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
669 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
670 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
671 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
672 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 673 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
674 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
675 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 676 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 677 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
678 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
679 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
680 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
681 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
682 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
683 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
684 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
685 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
686 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
687 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 688
689 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
690 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
691 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
e10bc440 692 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
693 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
694 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
695 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
696 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
697 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
698 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
699 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
700 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
701 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
702 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
5395334d 703
a370c895 704 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
705 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
706 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
707 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
708 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
709 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
13499032 710
a370c895 711 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
712 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
13499032 713 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx.gif'),
714 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm.gif'),
715 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx.gif'),
716 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm.gif'),
717 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam.gif'),
718 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx.gif'),
719 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm.gif'),
720
a370c895 721 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
722 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
723 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
724 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
a00420fb 725 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 726 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
727 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
728 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
729 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
730 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
731 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
732 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 733 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
4db69ffb 734 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
735 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
a370c895 736 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
737 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
738 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 739
740 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
741 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
742 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
743 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
744 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
745 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
746 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
747 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
748 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
749 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
750
a370c895 751 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
752 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
753 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
754 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
755 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
756 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
757 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
758 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
759 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
760 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
761 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
ee7f231d 762 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
763 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
764 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
13499032 765
a370c895 766 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
13499032 767 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx.gif'),
768 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm.gif'),
769 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx.gif'),
770 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm.gif'),
771 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb.gif'),
772 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam.gif'),
773
a370c895 774 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
775 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
776 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 777 );
172dd12c 778 return $mimearray;
3ce73b14 779}
780
76ca1ff1 781/**
3ce73b14 782 * Obtains information about a filetype based on its extension. Will
783 * use a default if no information is present about that particular
784 * extension.
76ca1ff1 785 * @param string $element Desired information (usually 'icon'
3ce73b14 786 * for icon filename or 'type' for MIME type)
76ca1ff1 787 * @param string $filename Filename we're looking up
3ce73b14 788 * @return string Requested piece of information from array
789 */
790function mimeinfo($element, $filename) {
172dd12c 791 $mimeinfo = get_mimetypes_array();
f1e0649c 792
a370c895 793 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 794 if (isset($mimeinfo[strtolower($match[1])][$element])) {
795 return $mimeinfo[strtolower($match[1])][$element];
796 } else {
a370c895 797 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 798 }
799 } else {
a370c895 800 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 801 }
802}
803
76ca1ff1 804/**
3ce73b14 805 * Obtains information about a filetype based on the MIME type rather than
806 * the other way around.
807 * @param string $element Desired information (usually 'icon')
76ca1ff1 808 * @param string $mimetype MIME type we're looking up
3ce73b14 809 * @return string Requested piece of information from array
810 */
811function mimeinfo_from_type($element, $mimetype) {
172dd12c 812 $mimeinfo = get_mimetypes_array();
76ca1ff1 813
3ce73b14 814 foreach($mimeinfo as $values) {
815 if($values['type']==$mimetype) {
816 if(isset($values[$element])) {
817 return $values[$element];
818 }
819 break;
820 }
821 }
822 return $mimeinfo['xxx'][$element]; // Default
823}
b9709b76 824
42ead7d7 825/**
826 * Get information about a filetype based on the icon file.
827 * @param string $element Desired information (usually 'icon')
828 * @param string $icon Icon file path.
0b46f19e 829 * @param boolean $all return all matching entries (defaults to false - last match)
42ead7d7 830 * @return string Requested piece of information from array
831 */
0b46f19e 832function mimeinfo_from_icon($element, $icon, $all=false) {
172dd12c 833 $mimeinfo = get_mimetypes_array();
42ead7d7 834
835 if (preg_match("/\/(.*)/", $icon, $matches)) {
836 $icon = $matches[1];
837 }
0b46f19e 838 $info = array($mimeinfo['xxx'][$element]); // Default
42ead7d7 839 foreach($mimeinfo as $values) {
840 if($values['icon']==$icon) {
841 if(isset($values[$element])) {
0b46f19e 842 $info[] = $values[$element];
42ead7d7 843 }
844 //No break, for example for 'excel.gif' we don't want 'csv'!
845 }
846 }
0b46f19e 847 if ($all) {
848 return $info;
849 }
850 return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
42ead7d7 851}
852
c0381e22 853/**
76ca1ff1 854 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
855 * mimetypes.php language file.
c0381e22 856 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
857 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 858 * @return string Text description
c0381e22 859 */
860function get_mimetype_description($mimetype,$capitalise=false) {
861 $result=get_string($mimetype,'mimetypes');
862 // Surrounded by square brackets indicates that there isn't a string for that
863 // (maybe there is a better way to find this out?)
864 if(strpos($result,'[')===0) {
865 $result=get_string('document/unknown','mimetypes');
76ca1ff1 866 }
c0381e22 867 if($capitalise) {
868 $result=ucfirst($result);
869 }
870 return $result;
871}
872
9e5fa330 873/**
874 * Reprot file is not found or not accessible
875 * @return does not return, terminates script
876 */
877function send_file_not_found() {
878 global $CFG, $COURSE;
879 header('HTTP/1.0 404 not found');
880 print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
881}
882
c87c428e 883/**
884 * Handles the sending of temporary file to user, download is forced.
885 * File is deleted after abort or succesful sending.
886 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
887 * @param string $filename proposed file name when saving file
888 * @param bool $path is content of file
45c0d224 889 * @return does not return, script terminated
c87c428e 890 */
45c0d224 891function send_temp_file($path, $filename, $pathisstring=false) {
c87c428e 892 global $CFG;
893
894 // close session - not needed anymore
895 @session_write_close();
896
897 if (!$pathisstring) {
898 if (!file_exists($path)) {
899 header('HTTP/1.0 404 not found');
45c0d224 900 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
c87c428e 901 }
902 // executed after normal finish or abort
903 @register_shutdown_function('send_temp_file_finished', $path);
904 }
905
906 //IE compatibiltiy HACK!
907 if (ini_get('zlib.output_compression')) {
908 ini_set('zlib.output_compression', 'Off');
909 }
910
911 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
912 if (check_browser_version('MSIE')) {
913 $filename = urlencode($filename);
914 }
915
916 $filesize = $pathisstring ? strlen($path) : filesize($path);
917
918 @header('Content-Disposition: attachment; filename='.$filename);
919 @header('Content-Length: '.$filesize);
920 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
921 @header('Cache-Control: max-age=10');
922 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
923 @header('Pragma: ');
924 } else { //normal http - prevent caching at all cost
925 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
926 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
927 @header('Pragma: no-cache');
928 }
929 @header('Accept-Ranges: none'); // Do not allow byteserving
930
931 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
932 if ($pathisstring) {
933 echo $path;
934 } else {
29e3d7e2 935 @readfile($path);
c87c428e 936 }
937
938 die; //no more chars to output
939}
940
941/**
942 * Internal callnack function used by send_temp_file()
943 */
944function send_temp_file_finished($path) {
945 if (file_exists($path)) {
946 @unlink($path);
947 }
948}
949
76ca1ff1 950/**
951 * Handles the sending of file data to the user's browser, including support for
952 * byteranges etc.
ba75ad94 953 * @param string $path Path of file on disk (including real filename), or actual content of file as string
954 * @param string $filename Filename to send
955 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
956 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
957 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
958 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
959 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 960 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
961 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 962 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
963 * and should not be reopened.
964 * @return no return or void, script execution stopped unless $dontdie is true
b9709b76 965 */
b379f7d9 966function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
6800d78e 967 global $CFG, $COURSE, $SESSION;
f1e0649c 968
b379f7d9 969 if ($dontdie) {
15325f55 970 ignore_user_abort(true);
b379f7d9 971 }
972
c8a5c6a4 973 // MDL-11789, apply $CFG->filelifetime here
974 if ($lifetime === 'default') {
975 if (!empty($CFG->filelifetime)) {
0cde3ede 976 $lifetime = $CFG->filelifetime;
c8a5c6a4 977 } else {
0cde3ede 978 $lifetime = 86400;
c8a5c6a4 979 }
980 }
981
172dd12c 982 session_write_close(); // unlock session during fileserving
983
ba4e0b05 984 // Use given MIME type if specified, otherwise guess it using mimeinfo.
985 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
986 // only Firefox saves all files locally before opening when content-disposition: attachment stated
987 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 988 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 989 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 990 $lastmodified = $pathisstring ? time() : filemtime($path);
991 $filesize = $pathisstring ? strlen($path) : filesize($path);
992
36bddcf5 993/* - MDL-13949
ee7f231d 994 //Adobe Acrobat Reader XSS prevention
995 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
996 //please note that it prevents opening of pdfs in browser when http referer disabled
997 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 998 if (!empty($_SERVER['HTTP_RANGE'])) {
999 //already byteserving
76ca1ff1 1000 $lifetime = 1; // >0 needed for byteserving
c57d8874 1001 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 1002 $mimetype = 'application/x-forcedownload';
1003 $forcedownload = true;
1004 $lifetime = 0;
1005 } else {
76ca1ff1 1006 $lifetime = 1; // >0 needed for byteserving
ee7f231d 1007 }
b8806ccc 1008 }
36bddcf5 1009*/
f3f7610c 1010
69faecce 1011 //IE compatibiltiy HACK!
4c8c65ec 1012 if (ini_get('zlib.output_compression')) {
69faecce 1013 ini_set('zlib.output_compression', 'Off');
1014 }
1015
4c8c65ec 1016 //try to disable automatic sid rewrite in cookieless mode
8914cb82 1017 @ini_set("session.use_trans_sid", "false");
4c8c65ec 1018
1019 //do not put '@' before the next header to detect incorrect moodle configurations,
1020 //error should be better than "weird" empty lines for admins/users
1021 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1022 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1023
4f047de2 1024 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1025 if (check_browser_version('MSIE')) {
4638009b 1026 $filename = rawurlencode($filename);
4f047de2 1027 }
1028
4c8c65ec 1029 if ($forcedownload) {
4638009b 1030 @header('Content-Disposition: attachment; filename="'.$filename.'"');
4c8c65ec 1031 } else {
4638009b 1032 @header('Content-Disposition: inline; filename="'.$filename.'"');
4c8c65ec 1033 }
1034
f1e0649c 1035 if ($lifetime > 0) {
4c8c65ec 1036 @header('Cache-Control: max-age='.$lifetime);
1037 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 1038 @header('Pragma: ');
4c8c65ec 1039
1040 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1041
1042 @header('Accept-Ranges: bytes');
1043
1044 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1045 // byteserving stuff - for acrobat reader and download accelerators
1046 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1047 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1048 $ranges = false;
1049 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1050 foreach ($ranges as $key=>$value) {
1051 if ($ranges[$key][1] == '') {
1052 //suffix case
1053 $ranges[$key][1] = $filesize - $ranges[$key][2];
1054 $ranges[$key][2] = $filesize - 1;
1055 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1056 //fix range length
1057 $ranges[$key][2] = $filesize - 1;
1058 }
1059 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1060 //invalid byte-range ==> ignore header
1061 $ranges = false;
1062 break;
1063 }
1064 //prepare multipart header
1065 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1066 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1067 }
1068 } else {
1069 $ranges = false;
1070 }
1071 if ($ranges) {
172dd12c 1072 $handle = fopen($filename, 'rb');
1073 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
4c8c65ec 1074 }
1075 }
1076 } else {
1077 /// Do not byteserve (disabled, strings, text and html files).
1078 @header('Accept-Ranges: none');
1079 }
1080 } else { // Do not cache files in proxies and browsers
85e00626 1081 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1082 @header('Cache-Control: max-age=10');
4c8c65ec 1083 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 1084 @header('Pragma: ');
1085 } else { //normal http - prevent caching at all cost
1086 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 1087 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 1088 @header('Pragma: no-cache');
1089 }
4c8c65ec 1090 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 1091 }
f1e0649c 1092
b9709b76 1093 if (empty($filter)) {
4c8c65ec 1094 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
1095 //cookieless mode - rewrite links
1096 @header('Content-Type: text/html');
1097 $path = $pathisstring ? $path : implode('', file($path));
6800d78e 1098 $path = $SESSION->sid_ob_rewrite($path);
4c8c65ec 1099 $filesize = strlen($path);
1100 $pathisstring = true;
1101 } else if ($mimetype == 'text/plain') {
810944af 1102 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 1103 } else {
4c8c65ec 1104 @header('Content-Type: '.$mimetype);
f1e0649c 1105 }
4c8c65ec 1106 @header('Content-Length: '.$filesize);
1107 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1108 if ($pathisstring) {
1109 echo $path;
4c8c65ec 1110 } else {
29e3d7e2 1111 @readfile($path);
f1e0649c 1112 }
1113 } else { // Try to put the file through filters
f1e0649c 1114 if ($mimetype == 'text/html') {
a17c57b5 1115 $options = new object();
f1e0649c 1116 $options->noclean = true;
a17c57b5 1117 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 1118 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 1119
3ace5ee4 1120 $text = file_modify_html_header($text);
60f9e36e 1121 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 1122 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
1123 //cookieless mode - rewrite links
6800d78e 1124 $output = $SESSION->sid_ob_rewrite($output);
4c8c65ec 1125 }
f1e0649c 1126
4c8c65ec 1127 @header('Content-Length: '.strlen($output));
1128 @header('Content-Type: text/html');
1129 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1130 echo $output;
b9709b76 1131 // only filter text if filter all files is selected
1132 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 1133 $options = new object();
f1e0649c 1134 $options->newlines = false;
1135 $options->noclean = true;
1136 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 1137 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 1138 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
1139 //cookieless mode - rewrite links
6800d78e 1140 $output = $SESSION->sid_ob_rewrite($output);
4c8c65ec 1141 }
f1e0649c 1142
4c8c65ec 1143 @header('Content-Length: '.strlen($output));
810944af 1144 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 1145 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1146 echo $output;
1147 } else { // Just send it out raw
4c8c65ec 1148 @header('Content-Length: '.$filesize);
1149 @header('Content-Type: '.$mimetype);
1150 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1151 if ($pathisstring) {
1152 echo $path;
1153 }else {
29e3d7e2 1154 @readfile($path);
f1e0649c 1155 }
1156 }
1157 }
b379f7d9 1158 if ($dontdie) {
1159 return;
1160 }
f1e0649c 1161 die; //no more chars to output!!!
1162}
1163
172dd12c 1164/**
1165 * Handles the sending of file data to the user's browser, including support for
1166 * byteranges etc.
1167 * @param object $stored_file local file object
1168 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1169 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1170 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1171 * @param string $filename Override filename
1172 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 1173 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1174 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 1175 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1176 * and should not be reopened.
1177 * @return no return or void, script execution stopped unless $dontdie is true
172dd12c 1178 */
b379f7d9 1179function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
172dd12c 1180 global $CFG, $COURSE, $SESSION;
1181
b379f7d9 1182 if ($dontdie) {
15325f55 1183 ignore_user_abort(true);
b379f7d9 1184 }
1185
172dd12c 1186 session_write_close(); // unlock session during fileserving
1187
1188 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1189 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1190 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1191 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1192 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1193 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1194 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
1195 $lastmodified = $stored_file->get_timemodified();
1196 $filesize = $stored_file->get_filesize();
1197
1198 //IE compatibiltiy HACK!
1199 if (ini_get('zlib.output_compression')) {
1200 ini_set('zlib.output_compression', 'Off');
1201 }
1202
1203 //try to disable automatic sid rewrite in cookieless mode
1204 @ini_set("session.use_trans_sid", "false");
1205
1206 //do not put '@' before the next header to detect incorrect moodle configurations,
1207 //error should be better than "weird" empty lines for admins/users
1208 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1209 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1210
1211 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1212 if (check_browser_version('MSIE')) {
1213 $filename = rawurlencode($filename);
1214 }
1215
1216 if ($forcedownload) {
1217 @header('Content-Disposition: attachment; filename="'.$filename.'"');
1218 } else {
1219 @header('Content-Disposition: inline; filename="'.$filename.'"');
1220 }
1221
1222 if ($lifetime > 0) {
1223 @header('Cache-Control: max-age='.$lifetime);
1224 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1225 @header('Pragma: ');
1226
1227 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1228
1229 @header('Accept-Ranges: bytes');
1230
1231 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1232 // byteserving stuff - for acrobat reader and download accelerators
1233 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1234 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1235 $ranges = false;
1236 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1237 foreach ($ranges as $key=>$value) {
1238 if ($ranges[$key][1] == '') {
1239 //suffix case
1240 $ranges[$key][1] = $filesize - $ranges[$key][2];
1241 $ranges[$key][2] = $filesize - 1;
1242 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1243 //fix range length
1244 $ranges[$key][2] = $filesize - 1;
1245 }
1246 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1247 //invalid byte-range ==> ignore header
1248 $ranges = false;
1249 break;
1250 }
1251 //prepare multipart header
1252 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1253 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1254 }
1255 } else {
1256 $ranges = false;
1257 }
1258 if ($ranges) {
1259 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1260 }
1261 }
1262 } else {
1263 /// Do not byteserve (disabled, strings, text and html files).
1264 @header('Accept-Ranges: none');
1265 }
1266 } else { // Do not cache files in proxies and browsers
1267 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1268 @header('Cache-Control: max-age=10');
1269 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1270 @header('Pragma: ');
1271 } else { //normal http - prevent caching at all cost
1272 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1273 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1274 @header('Pragma: no-cache');
1275 }
1276 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1277 }
1278
1279 if (empty($filter)) {
1280 $filtered = false;
1281 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
1282 //cookieless mode - rewrite links
1283 @header('Content-Type: text/html');
1284 $text = $stored_file->get_content();
1285 $text = $SESSION->sid_ob_rewrite($text);
1286 $filesize = strlen($text);
1287 $filtered = true;
1288 } else if ($mimetype == 'text/plain') {
1289 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1290 } else {
1291 @header('Content-Type: '.$mimetype);
1292 }
1293 @header('Content-Length: '.$filesize);
1294 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1295 if ($filtered) {
1296 echo $text;
1297 } else {
1298 $stored_file->readfile();
1299 }
1300
1301 } else { // Try to put the file through filters
1302 if ($mimetype == 'text/html') {
1303 $options = new object();
1304 $options->noclean = true;
1305 $options->nocache = true; // temporary workaround for MDL-5136
1306 $text = $stored_file->get_content();
1307 $text = file_modify_html_header($text);
1308 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
1309 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
1310 //cookieless mode - rewrite links
1311 $output = $SESSION->sid_ob_rewrite($output);
1312 }
1313
1314 @header('Content-Length: '.strlen($output));
1315 @header('Content-Type: text/html');
1316 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1317 echo $output;
1318 // only filter text if filter all files is selected
1319 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
1320 $options = new object();
1321 $options->newlines = false;
1322 $options->noclean = true;
1323 $text = $stored_file->get_content();
1324 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
1325 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
1326 //cookieless mode - rewrite links
1327 $output = $SESSION->sid_ob_rewrite($output);
1328 }
1329
1330 @header('Content-Length: '.strlen($output));
1331 @header('Content-Type: text/html; charset=utf-8'); //add encoding
1332 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1333 echo $output;
1334 } else { // Just send it out raw
1335 @header('Content-Length: '.$filesize);
1336 @header('Content-Type: '.$mimetype);
1337 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1338 $stored_file->readfile();
1339 }
1340 }
b379f7d9 1341 if ($dontdie) {
1342 return;
1343 }
172dd12c 1344 die; //no more chars to output!!!
1345}
1346
a43b5308 1347function get_records_csv($file, $table) {
f33e1ed4 1348 global $CFG, $DB;
599f38f9 1349
f33e1ed4 1350 if (!$metacolumns = $DB->get_columns($table)) {
599f38f9 1351 return false;
1352 }
1353
a77b98eb 1354 if(!($handle = @fopen($file, 'r'))) {
5a2a5331 1355 print_error('get_records_csv failed to open '.$file);
599f38f9 1356 }
1357
1358 $fieldnames = fgetcsv($handle, 4096);
1359 if(empty($fieldnames)) {
1360 fclose($handle);
1361 return false;
1362 }
1363
1364 $columns = array();
1365
1366 foreach($metacolumns as $metacolumn) {
1367 $ord = array_search($metacolumn->name, $fieldnames);
1368 if(is_int($ord)) {
1369 $columns[$metacolumn->name] = $ord;
1370 }
1371 }
1372
1373 $rows = array();
1374
1375 while (($data = fgetcsv($handle, 4096)) !== false) {
1376 $item = new stdClass;
1377 foreach($columns as $name => $ord) {
1378 $item->$name = $data[$ord];
1379 }
1380 $rows[] = $item;
1381 }
1382
1383 fclose($handle);
1384 return $rows;
1385}
1386
a77b98eb 1387function put_records_csv($file, $records, $table = NULL) {
f33e1ed4 1388 global $CFG, $DB;
a77b98eb 1389
a1e93da2 1390 if (empty($records)) {
a77b98eb 1391 return true;
1392 }
1393
1394 $metacolumns = NULL;
f33e1ed4 1395 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
a77b98eb 1396 return false;
1397 }
1398
a1e93da2 1399 echo "x";
1400
a77b98eb 1401 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
5a2a5331 1402 print_error('put_records_csv failed to open '.$file);
a77b98eb 1403 }
1404
a43b5308 1405 $proto = reset($records);
1406 if(is_object($proto)) {
1407 $fields_records = array_keys(get_object_vars($proto));
1408 }
1409 else if(is_array($proto)) {
1410 $fields_records = array_keys($proto);
1411 }
1412 else {
1413 return false;
1414 }
a1e93da2 1415 echo "x";
a77b98eb 1416
1417 if(!empty($metacolumns)) {
1418 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
1419 $fields = array_intersect($fields_records, $fields_table);
1420 }
1421 else {
1422 $fields = $fields_records;
1423 }
1424
1425 fwrite($fp, implode(',', $fields));
1426 fwrite($fp, "\r\n");
1427
1428 foreach($records as $record) {
a43b5308 1429 $array = (array)$record;
a77b98eb 1430 $values = array();
1431 foreach($fields as $field) {
a43b5308 1432 if(strpos($array[$field], ',')) {
1433 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 1434 }
1435 else {
a43b5308 1436 $values[] = $array[$field];
a77b98eb 1437 }
1438 }
1439 fwrite($fp, implode(',', $values)."\r\n");
1440 }
1441
1442 fclose($fp);
1443 return true;
1444}
1445
f401cc97 1446
34763a79 1447/**
76ca1ff1 1448 * Recursively delete the file or folder with path $location. That is,
34763a79 1449 * if it is a file delete it. If it is a folder, delete all its content
db3a0b34 1450 * then delete it. If $location does not exist to start, that is not
1451 * considered an error.
76ca1ff1 1452 *
34763a79 1453 * @param $location the path to remove.
1454 */
4c8c65ec 1455function fulldelete($location) {
f401cc97 1456 if (is_dir($location)) {
1457 $currdir = opendir($location);
1458 while (false !== ($file = readdir($currdir))) {
1459 if ($file <> ".." && $file <> ".") {
1460 $fullfile = $location."/".$file;
4c8c65ec 1461 if (is_dir($fullfile)) {
f401cc97 1462 if (!fulldelete($fullfile)) {
1463 return false;
1464 }
1465 } else {
1466 if (!unlink($fullfile)) {
1467 return false;
1468 }
4c8c65ec 1469 }
f401cc97 1470 }
4c8c65ec 1471 }
f401cc97 1472 closedir($currdir);
1473 if (! rmdir($location)) {
1474 return false;
1475 }
1476
34763a79 1477 } else if (file_exists($location)) {
f401cc97 1478 if (!unlink($location)) {
1479 return false;
1480 }
1481 }
1482 return true;
1483}
1484
4c8c65ec 1485/**
1486 * Send requested byterange of file.
1487 */
172dd12c 1488function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
4c8c65ec 1489 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
4c8c65ec 1490 if ($handle === false) {
1491 die;
1492 }
1493 if (count($ranges) == 1) { //only one range requested
1494 $length = $ranges[0][2] - $ranges[0][1] + 1;
1495 @header('HTTP/1.1 206 Partial content');
1496 @header('Content-Length: '.$length);
172dd12c 1497 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
4c8c65ec 1498 @header('Content-Type: '.$mimetype);
1499 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1500 $buffer = '';
1501 fseek($handle, $ranges[0][1]);
1502 while (!feof($handle) && $length > 0) {
68913aec 1503 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 1504 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1505 echo $buffer;
1506 flush();
1507 $length -= strlen($buffer);
1508 }
1509 fclose($handle);
1510 die;
1511 } else { // multiple ranges requested - not tested much
1512 $totallength = 0;
1513 foreach($ranges as $range) {
aba588a7 1514 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 1515 }
aba588a7 1516 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 1517 @header('HTTP/1.1 206 Partial content');
1518 @header('Content-Length: '.$totallength);
1519 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
1520 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
1521 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1522 foreach($ranges as $range) {
1523 $length = $range[2] - $range[1] + 1;
1524 echo $range[0];
1525 $buffer = '';
1526 fseek($handle, $range[1]);
1527 while (!feof($handle) && $length > 0) {
68913aec 1528 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 1529 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1530 echo $buffer;
1531 flush();
1532 $length -= strlen($buffer);
1533 }
1534 }
1535 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
1536 fclose($handle);
1537 die;
1538 }
1539}
f401cc97 1540
3ace5ee4 1541/**
1542 * add includes (js and css) into uploaded files
1543 * before returning them, useful for themes and utf.js includes
1544 * @param string text - text to search and replace
1545 * @return string - text with added head includes
1546 */
1547function file_modify_html_header($text) {
1548 // first look for <head> tag
1549 global $CFG;
76ca1ff1 1550
3ace5ee4 1551 $stylesheetshtml = '';
1552 foreach ($CFG->stylesheets as $stylesheet) {
1553 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 1554 }
1555
3ace5ee4 1556 $filters = explode(",", $CFG->textfilters);
1557 if (in_array('filter/mediaplugin', $filters)) {
76ca1ff1 1558 // this script is needed by most media filter plugins.
7a1f5e93 1559 $ufo = get_require_js_code(array($CFG->wwwroot . '/lib/ufo.js'));
3ace5ee4 1560 } else {
76ca1ff1 1561 $ufo = '';
3ace5ee4 1562 }
76ca1ff1 1563
3ace5ee4 1564 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
1565 if ($matches) {
1566 $replacement = '<head>'.$ufo.$stylesheetshtml;
1567 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 1568 return $text;
3ace5ee4 1569 }
76ca1ff1 1570
3ace5ee4 1571 // if not, look for <html> tag, and stick <head> right after
1572 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
1573 if ($matches) {
1574 // replace <html> tag with <html><head>includes</head>
13534ef7 1575 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 1576 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 1577 return $text;
3ace5ee4 1578 }
76ca1ff1 1579
3ace5ee4 1580 // if not, look for <body> tag, and stick <head> before body
1581 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
1582 if ($matches) {
13534ef7 1583 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 1584 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 1585 return $text;
1586 }
1587
3ace5ee4 1588 // if not, just stick a <head> tag at the beginning
1589 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
1590 return $text;
1591}
1592
bb2c046d 1593/**
1594 * RESTful cURL class
1595 *
1596 * This is a wrapper class for curl, it is quite easy to use:
1597 *
1598 * $c = new curl;
1599 * // enable cache
1600 * $c = new curl(array('cache'=>true));
1601 * // enable cookie
1602 * $c = new curl(array('cookie'=>true));
1603 * // enable proxy
1604 * $c = new curl(array('proxy'=>true));
1605 *
1606 * // HTTP GET Method
1607 * $html = $c->get('http://example.com');
1608 * // HTTP POST Method
1609 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
1610 * // HTTP PUT Method
1611 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
1612 *
1613 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
1614 * @version 0.4 dev
1615 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
1616 */
1617
1618class curl {
1619 public $cache = false;
1620 public $proxy = false;
1621 public $version = '0.4 dev';
1622 public $response = array();
1623 public $header = array();
1624 public $info;
1625 public $error;
1626
1627 private $options;
1628 private $proxy_host = '';
1629 private $proxy_auth = '';
1630 private $proxy_type = '';
1631 private $debug = false;
1632 private $cookie = false;
1633
1634 public function __construct($options = array()){
1635 global $CFG;
1636 if (!function_exists('curl_init')) {
1637 $this->error = 'cURL module must be enabled!';
1638 trigger_error($this->error, E_USER_ERROR);
1639 return false;
1640 }
1641 // the options of curl should be init here.
1642 $this->resetopt();
1643 if (!empty($options['debug'])) {
1644 $this->debug = true;
1645 }
1646 if(!empty($options['cookie'])) {
1647 if($options['cookie'] === true) {
1648 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
1649 } else {
1650 $this->cookie = $options['cookie'];
1651 }
1652 }
1653 if (!empty($options['cache'])) {
1654 if (class_exists('curl_cache')) {
1655 $this->cache = new curl_cache;
1656 }
1657 }
d04ce87f 1658 if (!empty($CFG->proxyhost)) {
1659 if (empty($CFG->proxyport)) {
1660 $this->proxy_host = $CFG->proxyhost;
1661 } else {
1662 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
1663 }
1664 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
1665 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
1666 $this->setopt(array(
1667 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
1668 'proxyuserpwd'=>$this->proxy_auth));
1669 }
1670 if (!empty($CFG->proxytype)) {
1671 if ($CFG->proxytype == 'SOCKS5') {
1672 $this->proxy_type = CURLPROXY_SOCKS5;
bb2c046d 1673 } else {
d04ce87f 1674 $this->proxy_type = CURLPROXY_HTTP;
1675 $this->setopt(array('httpproxytunnel'=>true));
bb2c046d 1676 }
d04ce87f 1677 $this->setopt(array('proxytype'=>$this->proxy_type));
bb2c046d 1678 }
d04ce87f 1679 }
1680 if (!empty($this->proxy_host)) {
1681 $this->proxy = array('proxy'=>$this->proxy_host);
bb2c046d 1682 }
1683 }
1684 public function resetopt(){
1685 $this->options = array();
1686 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
1687 // True to include the header in the output
1688 $this->options['CURLOPT_HEADER'] = 0;
1689 // True to Exclude the body from the output
1690 $this->options['CURLOPT_NOBODY'] = 0;
1691 // TRUE to follow any "Location: " header that the server
1692 // sends as part of the HTTP header (note this is recursive,
1693 // PHP will follow as many "Location: " headers that it is sent,
1694 // unless CURLOPT_MAXREDIRS is set).
1695 $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
1696 $this->options['CURLOPT_MAXREDIRS'] = 10;
1697 $this->options['CURLOPT_ENCODING'] = '';
1698 // TRUE to return the transfer as a string of the return
1699 // value of curl_exec() instead of outputting it out directly.
1700 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
1701 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
1702 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
1703 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
6135bd45 1704 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
bb2c046d 1705 }
1706
1707 /**
1708 * Reset Cookie
1709 *
1710 * @param array $options If array is null, this function will
1711 * reset the options to default value.
1712 *
1713 */
1714 public function resetcookie() {
1715 if (!empty($this->cookie)) {
1716 if (is_file($this->cookie)) {
1717 $fp = fopen($this->cookie, 'w');
1718 if (!empty($fp)) {
1719 fwrite($fp, '');
1720 fclose($fp);
1721 }
1722 }
1723 }
1724 }
1725
1726 /**
1727 * Set curl options
1728 *
1729 * @param array $options If array is null, this function will
1730 * reset the options to default value.
1731 *
1732 */
1733 public function setopt($options = array()) {
1734 if (is_array($options)) {
1735 foreach($options as $name => $val){
1736 if (stripos($name, 'CURLOPT_') === false) {
1737 $name = strtoupper('CURLOPT_'.$name);
1738 }
1739 $this->options[$name] = $val;
1740 }
1741 }
1742 }
1743 /**
1744 * Reset http method
1745 *
1746 */
1747 public function cleanopt(){
1748 unset($this->options['CURLOPT_HTTPGET']);
1749 unset($this->options['CURLOPT_POST']);
1750 unset($this->options['CURLOPT_POSTFIELDS']);
1751 unset($this->options['CURLOPT_PUT']);
1752 unset($this->options['CURLOPT_INFILE']);
1753 unset($this->options['CURLOPT_INFILESIZE']);
1754 unset($this->options['CURLOPT_CUSTOMREQUEST']);
1755 }
1756
1757 /**
1758 * Set HTTP Request Header
1759 *
1760 * @param array $headers
1761 *
1762 */
1763 public function setHeader($header) {
1764 if (is_array($header)){
1765 foreach ($header as $v) {
1766 $this->setHeader($v);
1767 }
1768 } else {
1769 $this->header[] = $header;
1770 }
1771 }
1772 /**
1773 * Set HTTP Response Header
1774 *
1775 */
1776 public function getResponse(){
1777 return $this->response;
1778 }
1779 /**
1780 * private callback function
1781 * Formatting HTTP Response Header
1782 *
1783 */
1784 private function formatHeader($ch, $header)
1785 {
1786 $this->count++;
1787 if (strlen($header) > 2) {
1788 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
1789 $key = rtrim($key, ':');
1790 if (!empty($this->response[$key])) {
1791 if (is_array($this->response[$key])){
1792 $this->response[$key][] = $value;
1793 } else {
1794 $tmp = $this->response[$key];
1795 $this->response[$key] = array();
1796 $this->response[$key][] = $tmp;
1797 $this->response[$key][] = $value;
1798
1799 }
1800 } else {
1801 $this->response[$key] = $value;
1802 }
1803 }
1804 return strlen($header);
1805 }
1806
1807 /**
1808 * Set options for individual curl instance
1809 */
1810 private function apply_opt($curl, $options) {
1811 // Clean up
1812 $this->cleanopt();
1813 // set cookie
1814 if (!empty($this->cookie) || !empty($options['cookie'])) {
1815 $this->setopt(array('cookiejar'=>$this->cookie,
1816 'cookiefile'=>$this->cookie
1817 ));
1818 }
1819
1820 // set proxy
1821 if (!empty($this->proxy) || !empty($options['proxy'])) {
1822 $this->setopt($this->proxy);
1823 }
1824 $this->setopt($options);
1825 // reset before set options
1826 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
1827 // set headers
1828 if (empty($this->header)){
1829 $this->setHeader(array(
1830 'User-Agent: MoodleBot/1.0',
1831 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
1832 'Connection: keep-alive'
1833 ));
1834 }
1835 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
1836
1837 if ($this->debug){
1838 echo '<h1>Options</h1>';
1839 var_dump($this->options);
1840 echo '<h1>Header</h1>';
1841 var_dump($this->header);
1842 }
1843
1844 // set options
1845 foreach($this->options as $name => $val) {
1846 if (is_string($name)) {
1847 $name = constant(strtoupper($name));
1848 }
1849 curl_setopt($curl, $name, $val);
1850 }
1851 return $curl;
1852 }
1853 /*
1854 * Download multiple files in parallel
1855 * $c = new curl;
1856 * $c->download(array(
172dd12c 1857 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
bb2c046d 1858 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
1859 * ));
1860 */
1861 public function download($requests, $options = array()) {
1862 $options['CURLOPT_BINARYTRANSFER'] = 1;
1863 $options['RETURNTRANSFER'] = false;
1864 return $this->multi($requests, $options);
1865 }
1866 /*
1867 * Mulit HTTP Requests
1868 * This function could run multi-requests in parallel.
1869 */
1870 protected function multi($requests, $options = array()) {
1871 $count = count($requests);
1872 $handles = array();
1873 $results = array();
1874 $main = curl_multi_init();
1875 for ($i = 0; $i < $count; $i++) {
1876 $url = $requests[$i];
1877 foreach($url as $n=>$v){
1878 $options[$n] = $url[$n];
1879 }
1880 $handles[$i] = curl_init($url['url']);
1881 $this->apply_opt($handles[$i], $options);
1882 curl_multi_add_handle($main, $handles[$i]);
1883 }
1884 $running = 0;
1885 do {
1886 curl_multi_exec($main, $running);
1887 } while($running > 0);
1888 for ($i = 0; $i < $count; $i++) {
1889 if (!empty($optins['CURLOPT_RETURNTRANSFER'])) {
1890 $results[] = true;
1891 } else {
1892 $results[] = curl_multi_getcontent($handles[$i]);
1893 }
1894 curl_multi_remove_handle($main, $handles[$i]);
1895 }
1896 curl_multi_close($main);
1897 return $results;
1898 }
1899 /**
1900 * Single HTTP Request
1901 */
1902 protected function request($url, $options = array()){
1903 // create curl instance
1904 $curl = curl_init($url);
1905 $options['url'] = $url;
1906 $this->apply_opt($curl, $options);
1907 if ($this->cache && $ret = $this->cache->get($this->options)) {
1908 return $ret;
1909 } else {
6135bd45 1910 $ret = curl_exec($curl);
bb2c046d 1911 if ($this->cache) {
1912 $this->cache->set($this->options, $ret);
1913 }
1914 }
1915
1916 $this->info = curl_getinfo($curl);
1917 $this->error = curl_error($curl);
1918
1919 if ($this->debug){
1920 echo '<h1>Return Data</h1>';
1921 var_dump($ret);
1922 echo '<h1>Info</h1>';
1923 var_dump($this->info);
1924 echo '<h1>Error</h1>';
1925 var_dump($this->error);
1926 }
1927
1928 curl_close($curl);
1929
6135bd45 1930 if (empty($this->error)){
bb2c046d 1931 return $ret;
1932 } else {
6135bd45 1933 throw new moodle_exception($this->error, 'curl');
bb2c046d 1934 }
1935 }
1936
1937 /**
1938 * HTTP HEAD method
1939 */
1940 public function head($url, $options = array()){
1941 $options['CURLOPT_HTTPGET'] = 0;
1942 $options['CURLOPT_HEADER'] = 1;
1943 $options['CURLOPT_NOBODY'] = 1;
1944 return $this->request($url, $options);
1945 }
1946
1947 /**
1948 * HTTP POST method
1949 */
1950 public function post($url, $params = array(), $options = array()){
1951 $options['CURLOPT_POST'] = 1;
5035a8b4 1952 $this->_tmp_file_post_params = array();
1953 foreach ($params as $key => $value) {
1954 if ($value instanceof stored_file) {
1955 $value->add_to_curl_request($this, $key);
1956 } else {
1957 $this->_tmp_file_post_params[$key] = $value;
1958 }
1959 }
1960 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
1961 unset($this->_tmp_file_post_params);
bb2c046d 1962 return $this->request($url, $options);
1963 }
1964
1965 /**
1966 * HTTP GET method
1967 */
1968 public function get($url, $params = array(), $options = array()){
1969 $options['CURLOPT_HTTPGET'] = 1;
1970
1971 if (!empty($params)){
1972 $url .= (stripos($url, '?') !== false) ? '&' : '?';
1973 $url .= http_build_query($params, '', '&');
1974 }
1975 return $this->request($url, $options);
1976 }
1977
1978 /**
1979 * HTTP PUT method
1980 */
1981 public function put($url, $params = array(), $options = array()){
1982 $file = $params['file'];
1983 if (!is_file($file)){
1984 return null;
1985 }
1986 $fp = fopen($file, 'r');
1987 $size = filesize($file);
1988 $options['CURLOPT_PUT'] = 1;
1989 $options['CURLOPT_INFILESIZE'] = $size;
1990 $options['CURLOPT_INFILE'] = $fp;
1991 if (!isset($this->options['CURLOPT_USERPWD'])){
1992 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
1993 }
1994 $ret = $this->request($url, $options);
1995 fclose($fp);
1996 return $ret;
1997 }
1998
1999 /**
2000 * HTTP DELETE method
2001 */
2002 public function delete($url, $param = array(), $options = array()){
2003 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2004 if (!isset($options['CURLOPT_USERPWD'])) {
2005 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2006 }
2007 $ret = $this->request($url, $options);
2008 return $ret;
2009 }
2010 /**
2011 * HTTP TRACE method
2012 */
2013 public function trace($url, $options = array()){
2014 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2015 $ret = $this->request($url, $options);
2016 return $ret;
2017 }
2018 /**
2019 * HTTP OPTIONS method
2020 */
2021 public function options($url, $options = array()){
2022 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2023 $ret = $this->request($url, $options);
2024 return $ret;
2025 }
2026}
2027
2028/**
2029 * This class is used by cURL class, use case:
2030 *
2031 * $CFG->repository_cache_expire = 120;
2032 * $c = new curl(array('cache'=>true));
2033 * $ret = $c->get('http://www.google.com');
2034 *
2035 */
2036class curl_cache {
2037 public $dir = '';
2038 function __construct(){
2039 global $CFG;
c9260130 2040 if (!file_exists($CFG->dataroot.'/cache/repository/')) {
2041 mkdir($CFG->dataroot.'/cache/repository/', 0777, true);
bb2c046d 2042 }
c9260130 2043 if(is_dir($CFG->dataroot.'/cache/repository/')) {
2044 $this->dir = $CFG->dataroot.'/cache/repository/';
bb2c046d 2045 }
d7e122d6 2046 if (empty($CFG->repository_cache_expire)) {
2047 $CFG->repository_cache_expire = 120;
b933a139 2048 }
bb2c046d 2049 }
2050 public function get($param){
aae85978 2051 global $CFG, $USER;
c9260130 2052 $this->cleanup($CFG->repository_cache_expire);
aae85978 2053 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
bb2c046d 2054 if(file_exists($this->dir.$filename)) {
2055 $lasttime = filemtime($this->dir.$filename);
d7e122d6 2056 if(time()-$lasttime > $CFG->repository_cache_expire)
2057 {
bb2c046d 2058 return false;
2059 } else {
2060 $fp = fopen($this->dir.$filename, 'r');
2061 $size = filesize($this->dir.$filename);
2062 $content = fread($fp, $size);
2063 return unserialize($content);
2064 }
2065 }
2066 return false;
2067 }
2068 public function set($param, $val){
aae85978 2069 global $CFG, $USER;
2070 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
bb2c046d 2071 $fp = fopen($this->dir.$filename, 'w');
2072 fwrite($fp, serialize($val));
2073 fclose($fp);
2074 }
2075 public function cleanup($expire){
2076 if($dir = opendir($this->dir)){
2077 while (false !== ($file = readdir($dir))) {
2078 if(!is_dir($file) && $file != '.' && $file != '..') {
2079 $lasttime = @filemtime($this->dir.$file);
2080 if(time() - $lasttime > $expire){
2081 @unlink($this->dir.$file);
2082 }
2083 }
2084 }
2085 }
2086 }
aae85978 2087 /**
2088 * delete current user's cache file
2089 *
2090 * @return null
2091 */
2092 public function refresh(){
2093 global $CFG, $USER;
2094 if($dir = opendir($this->dir)){
2095 while (false !== ($file = readdir($dir))) {
2096 if(!is_dir($file) && $file != '.' && $file != '..') {
2097 if(strpos($file, 'u'.$USER->id.'_')!==false){
2098 @unlink($this->dir.$file);
2099 }
2100 }
2101 }
2102 }
2103 }
bb2c046d 2104}