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