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