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