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