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