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