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