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