MDL-4346: limiting the 'defer' clause to one call / fix the missing openpopup() bug...
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
4c8c65ec 3define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
4
74369ab5 5function get_file_url($path, $options=null, $type='coursefile') {
6 global $CFG;
7
b0374a16 8 $path = str_replace('//', '/', $path);
74369ab5 9 $path = trim($path, '/'); // no leading and trailing slashes
10
11 // type of file
12 switch ($type) {
5a254a29 13 case 'questionfile':
14 $url = $CFG->wwwroot."/question/exportfile.php";
15 break;
16 case 'rssfile':
17 $url = $CFG->wwwroot."/rss/file.php";
18 break;
19 case 'user':
20 $url = $CFG->wwwroot."/user/pix.php";
21 break;
22 case 'usergroup':
23 $url = $CFG->wwwroot."/user/pixgroup.php";
24 break;
25 case 'httpscoursefile':
26 $url = $CFG->httpswwwroot."/file.php";
27 break;
28 case 'coursefile':
74369ab5 29 default:
5a254a29 30 $url = $CFG->wwwroot."/file.php";
74369ab5 31 }
32
33 if ($CFG->slasharguments) {
34 $parts = explode('/', $path);
5e19ea32 35 $parts = array_map('rawurlencode', $parts);
74369ab5 36 $path = implode('/', $parts);
5a254a29 37 $ffurl = $url.'/'.$path;
74369ab5 38 $separator = '?';
39 } else {
5a254a29 40 $path = rawurlencode('/'.$path);
41 $ffurl = $url.'?file='.$path;
74369ab5 42 $separator = '&amp;';
43 }
44
45 if ($options) {
46 foreach ($options as $name=>$value) {
47 $ffurl = $ffurl.$separator.$name.'='.$value;
48 $separator = '&amp;';
49 }
50 }
51
52 return $ffurl;
53}
54
8ee88311 55/**
5f8bdc17 56 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
599f06cf 57 * Due to security concerns only downloads from http(s) sources are supported.
58 *
59 * @param string $url file url starting with http(s)://
5ef082df 60 * @param array $headers http headers, null if none. If set, should be an
61 * associative array of header name => value pairs.
6bf55889 62 * @param array $postdata array means use POST request with given parameters
63 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
5ef082df 64 * (if false, just returns content)
65 * @param int $timeout timeout for complete download process including all file transfer
44e02d79 66 * (default 5 minutes)
67 * @param int $connecttimeout timeout for connection to server; this is the timeout that
68 * usually happens if the remote server is completely down (default 20 seconds);
69 * may not work when using proxy
83947a36 70 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
8ee88311 71 * @return mixed false if request failed or content of the file as string if ok.
72 */
83947a36 73function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
e27f0765 74 global $CFG;
75
599f06cf 76 // some extra security
77 $newlines = array("\r", "\n");
78 if (is_array($headers) ) {
79 foreach ($headers as $key => $value) {
80 $headers[$key] = str_replace($newlines, '', $value);
81 }
82 }
83 $url = str_replace($newlines, '', $url);
84 if (!preg_match('|^https?://|i', $url)) {
85 if ($fullresponse) {
86 $response = new object();
87 $response->status = 0;
88 $response->headers = array();
89 $response->response_code = 'Invalid protocol specified in url';
90 $response->results = '';
91 $response->error = 'Invalid protocol specified in url';
92 return $response;
93 } else {
94 return false;
95 }
96 }
97
15c31560 98 // check if proxy (if used) should be bypassed for this url
99 $proxybypass = is_proxybypass( $url );
599f06cf 100
6bf55889 101 if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
5f8bdc17 102 require_once($CFG->libdir.'/snoopy/Snoopy.class.inc');
103 $snoopy = new Snoopy();
6bf55889 104 $snoopy->read_timeout = $timeout;
44e02d79 105 $snoopy->_fp_timeout = $connecttimeout;
15c31560 106 if (!$proxybypass) {
107 $snoopy->proxy_host = $CFG->proxyhost;
108 $snoopy->proxy_port = $CFG->proxyport;
109 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
110 // this will probably fail, but let's try it anyway
111 $snoopy->proxy_user = $CFG->proxyuser;
112 $snoopy->proxy_password = $CFG->proxypassword;
113 }
5f8bdc17 114 }
15c31560 115
6bf55889 116 if (is_array($headers) ) {
117 $client->rawheaders = $headers;
118 }
119
120 if (is_array($postdata)) {
121 $fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
122 } else {
123 $fetch = @$snoopy->fetch($url); // use more specific debug code bellow
124 }
125
126 if ($fetch) {
127 if ($fullresponse) {
128 //fix header line endings
129 foreach ($snoopy->headers as $key=>$unused) {
130 $snoopy->headers[$key] = trim($snoopy->headers[$key]);
131 }
132 $response = new object();
133 $response->status = $snoopy->status;
134 $response->headers = $snoopy->headers;
135 $response->response_code = trim($snoopy->response_code);
136 $response->results = $snoopy->results;
137 $response->error = $snoopy->error;
138 return $response;
139
140 } else if ($snoopy->status != 200) {
5f8bdc17 141 debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code, DEBUG_ALL);
142 return false;
6bf55889 143
5f8bdc17 144 } else {
145 return $snoopy->results;
146 }
147 } else {
6bf55889 148 if ($fullresponse) {
149 $response = new object();
150 $response->status = $snoopy->status;
151 $response->headers = array();
152 $response->response_code = $snoopy->response_code;
153 $response->results = '';
154 $response->error = $snoopy->error;
155 return $response;
156 } else {
157 debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error, DEBUG_ALL);
158 return false;
159 }
160 }
161 }
162
599f06cf 163 // set extra headers
6bf55889 164 if (is_array($headers) ) {
165 $headers2 = array();
166 foreach ($headers as $key => $value) {
6bf55889 167 $headers2[] = "$key: $value";
168 }
169 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
170 }
171
83947a36 172
173 if ($skipcertverify) {
174 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
175 }
176
6bf55889 177 // use POST if requested
178 if (is_array($postdata)) {
179 foreach ($postdata as $k=>$v) {
180 $postdata[$k] = urlencode($k).'='.urlencode($v);
5f8bdc17 181 }
6bf55889 182 $postdata = implode('&', $postdata);
183 curl_setopt($ch, CURLOPT_POST, true);
184 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
5f8bdc17 185 }
186
8ee88311 187 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
6bf55889 188 curl_setopt($ch, CURLOPT_HEADER, true);
44e02d79 189 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
190 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
6bf55889 191 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
599f06cf 192 // TODO: add version test for '7.10.5'
6bf55889 193 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
194 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
195 }
196
15c31560 197 if (!empty($CFG->proxyhost) and !$proxybypass) {
5f8bdc17 198 // SOCKS supported in PHP5 only
199 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
200 if (defined('CURLPROXY_SOCKS5')) {
201 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
202 } else {
5f8bdc17 203 curl_close($ch);
599f06cf 204 if ($fullresponse) {
205 $response = new object();
206 $response->status = '0';
207 $response->headers = array();
208 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
209 $response->results = '';
210 $response->error = 'SOCKS5 proxy is not supported in PHP4';
211 return $response;
212 } else {
213 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
214 return false;
215 }
5f8bdc17 216 }
217 }
218
08ec989f 219 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
220
8ee88311 221 if (empty($CFG->proxyport)) {
e27f0765 222 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
8ee88311 223 } else {
e27f0765 224 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
8ee88311 225 }
5f8bdc17 226
227 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
8ee88311 228 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
5f8bdc17 229 if (defined('CURLOPT_PROXYAUTH')) {
230 // any proxy authentication if PHP 5.1
231 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
232 }
8ee88311 233 }
234 }
6bf55889 235
599f06cf 236 $data = curl_exec($ch);
08ec989f 237
599f06cf 238 // try to detect encoding problems
6bf55889 239 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
240 curl_setopt($ch, CURLOPT_ENCODING, 'none');
599f06cf 241 $data = curl_exec($ch);
6bf55889 242 }
243
08ec989f 244 if (curl_errno($ch)) {
6bf55889 245 $error = curl_error($ch);
246 $error_no = curl_errno($ch);
247 curl_close($ch);
248
249 if ($fullresponse) {
250 $response = new object();
251 if ($error_no == 28) {
252 $response->status = '-100'; // mimic snoopy
253 } else {
254 $response->status = '0';
255 }
256 $response->headers = array();
257 $response->response_code = $error;
258 $response->results = '';
259 $response->error = $error;
260 return $response;
261 } else {
599f06cf 262 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
6bf55889 263 return false;
264 }
5f8bdc17 265
266 } else {
6bf55889 267 $info = curl_getinfo($ch);
268 curl_close($ch);
599f06cf 269
270 if (empty($info['http_code'])) {
271 // for security reasons we support only true http connections (Location: file:// exploit prevention)
272 $response = new object();
273 $response->status = '0';
274 $response->headers = array();
275 $response->response_code = 'Unknown cURL error';
276 $response->results = ''; // do NOT change this!
277 $response->error = 'Unknown cURL error';
278
279 } else {
280 // strip redirect headers and get headers array and content
281 $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
282 $results = array_pop($data);
283 $headers = array_pop($data);
284 $headers = explode("\r\n", trim($headers));
285
286 $response = new object();;
287 $response->status = (string)$info['http_code'];
288 $response->headers = $headers;
289 $response->response_code = $headers[0];
290 $response->results = $results;
291 $response->error = '';
292 }
6bf55889 293
294 if ($fullresponse) {
295 return $response;
296 } else if ($info['http_code'] != 200) {
599f06cf 297 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
6bf55889 298 return false;
299 } else {
300 return $response->results;
5f8bdc17 301 }
08ec989f 302 }
8ee88311 303}
304
3ce73b14 305/**
76ca1ff1 306 * @return List of information about file types based on extensions.
3ce73b14 307 * Associative array of extension (lower-case) to associative array
308 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 309 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 310 */
311function get_mimetypes_array() {
312 return array (
a370c895 313 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
314 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
315 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
316 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
317 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
318 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
319 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
320 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 321 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 322 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
323 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
324 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
18bf47ef 325 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 326 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
18bf47ef 327 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 328 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
76ca1ff1 329 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
6ae5e482 330 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
a370c895 331 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
609d84e3 332 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
a370c895 333 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
68da9722 334 'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
335 'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
336 'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
a370c895 337 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
338 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
339 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
340 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
341 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
ee7f231d 342 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
759bc3c8 343 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
a370c895 344 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
345 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
759bc3c8 346 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 347 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
348 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
349 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 350 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 351 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
70ee2841 352 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
a370c895 353 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
1659a998 354 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
a370c895 355 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
08297dcb 356 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
4b270c4c 357 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
08297dcb 358 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
359 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
18bf47ef 360 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 361 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
362 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
363 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
364 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
365 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 366 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
367 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
368 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 369 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 370 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
371 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
372 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
373 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
374 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
375 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
376 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
377 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
378 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
379 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
380 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 381
382 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
383 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
384 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
e10bc440 385 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
386 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
387 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
388 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
389 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
390 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
391 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
392 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
393 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
394 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
395 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
5395334d 396
a370c895 397 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
398 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
399 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
400 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
401 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
402 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
403 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
404 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
68da9722 405 'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
406 'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
407 'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
408 'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
409 'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
410 'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
411 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
a370c895 412 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
413 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
414 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
415 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
a00420fb 416 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 417 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
418 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
419 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
420 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
421 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
422 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
423 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 424 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
4db69ffb 425 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
426 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
a370c895 427 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
428 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
429 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 430
431 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
432 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
433 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
434 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
435 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
436 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
437 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
438 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
439 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
440 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
441
a370c895 442 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
443 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
444 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
445 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
446 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
447 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
448 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
449 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
450 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
451 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
452 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
ee7f231d 453 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
454 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
455 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
a370c895 456 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
68da9722 457 'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
458 'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
459 'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
460 'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
461 'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
462 'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
a370c895 463 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
464 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
465 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 466 );
3ce73b14 467}
468
76ca1ff1 469/**
3ce73b14 470 * Obtains information about a filetype based on its extension. Will
471 * use a default if no information is present about that particular
472 * extension.
76ca1ff1 473 * @param string $element Desired information (usually 'icon'
3ce73b14 474 * for icon filename or 'type' for MIME type)
76ca1ff1 475 * @param string $filename Filename we're looking up
3ce73b14 476 * @return string Requested piece of information from array
477 */
478function mimeinfo($element, $filename) {
f36cbf1d 479 static $mimeinfo = null;
480 if (is_null($mimeinfo)) {
481 $mimeinfo = get_mimetypes_array();
482 }
f1e0649c 483
a370c895 484 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 485 if (isset($mimeinfo[strtolower($match[1])][$element])) {
486 return $mimeinfo[strtolower($match[1])][$element];
487 } else {
a370c895 488 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 489 }
490 } else {
a370c895 491 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 492 }
493}
494
76ca1ff1 495/**
3ce73b14 496 * Obtains information about a filetype based on the MIME type rather than
497 * the other way around.
498 * @param string $element Desired information (usually 'icon')
76ca1ff1 499 * @param string $mimetype MIME type we're looking up
3ce73b14 500 * @return string Requested piece of information from array
501 */
502function mimeinfo_from_type($element, $mimetype) {
503 static $mimeinfo;
504 $mimeinfo=get_mimetypes_array();
76ca1ff1 505
3ce73b14 506 foreach($mimeinfo as $values) {
507 if($values['type']==$mimetype) {
508 if(isset($values[$element])) {
509 return $values[$element];
510 }
511 break;
512 }
513 }
514 return $mimeinfo['xxx'][$element]; // Default
515}
b9709b76 516
42ead7d7 517/**
518 * Get information about a filetype based on the icon file.
519 * @param string $element Desired information (usually 'icon')
520 * @param string $icon Icon file path.
521 * @return string Requested piece of information from array
522 */
523function mimeinfo_from_icon($element, $icon) {
524 static $mimeinfo;
525 $mimeinfo=get_mimetypes_array();
526
527 if (preg_match("/\/(.*)/", $icon, $matches)) {
528 $icon = $matches[1];
529 }
530 $info = $mimeinfo['xxx'][$element]; // Default
531 foreach($mimeinfo as $values) {
532 if($values['icon']==$icon) {
533 if(isset($values[$element])) {
534 $info = $values[$element];
535 }
536 //No break, for example for 'excel.gif' we don't want 'csv'!
537 }
538 }
539 return $info;
540}
541
c0381e22 542/**
76ca1ff1 543 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
544 * mimetypes.php language file.
c0381e22 545 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
546 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 547 * @return string Text description
c0381e22 548 */
549function get_mimetype_description($mimetype,$capitalise=false) {
550 $result=get_string($mimetype,'mimetypes');
551 // Surrounded by square brackets indicates that there isn't a string for that
552 // (maybe there is a better way to find this out?)
553 if(strpos($result,'[')===0) {
554 $result=get_string('document/unknown','mimetypes');
76ca1ff1 555 }
c0381e22 556 if($capitalise) {
557 $result=ucfirst($result);
558 }
559 return $result;
560}
561
c87c428e 562/**
563 * Handles the sending of temporary file to user, download is forced.
564 * File is deleted after abort or succesful sending.
565 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
566 * @param string $filename proposed file name when saving file
567 * @param bool $path is content of file
568 */
569function send_temp_file($path, $filename, $pathisstring=false) {
570 global $CFG;
571
572 // close session - not needed anymore
573 @session_write_close();
574
575 if (!$pathisstring) {
576 if (!file_exists($path)) {
577 header('HTTP/1.0 404 not found');
578 error(get_string('filenotfound', 'error'), $CFG->wwwroot.'/');
579 }
580 // executed after normal finish or abort
581 @register_shutdown_function('send_temp_file_finished', $path);
582 }
583
584 //IE compatibiltiy HACK!
585 if (ini_get('zlib.output_compression')) {
586 ini_set('zlib.output_compression', 'Off');
587 }
588
589 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
590 if (check_browser_version('MSIE')) {
591 $filename = urlencode($filename);
592 }
593
594 $filesize = $pathisstring ? strlen($path) : filesize($path);
595
596 @header('Content-Disposition: attachment; filename='.$filename);
597 @header('Content-Length: '.$filesize);
598 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
599 @header('Cache-Control: max-age=10');
600 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
601 @header('Pragma: ');
602 } else { //normal http - prevent caching at all cost
603 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
604 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
605 @header('Pragma: no-cache');
606 }
607 @header('Accept-Ranges: none'); // Do not allow byteserving
608
609 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
610 if ($pathisstring) {
611 echo $path;
612 } else {
613 readfile_chunked($path);
614 }
615
616 die; //no more chars to output
617}
618
619/**
620 * Internal callnack function used by send_temp_file()
621 */
622function send_temp_file_finished($path) {
623 if (file_exists($path)) {
624 @unlink($path);
625 }
626}
627
76ca1ff1 628/**
629 * Handles the sending of file data to the user's browser, including support for
630 * byteranges etc.
ba75ad94 631 * @param string $path Path of file on disk (including real filename), or actual content of file as string
632 * @param string $filename Filename to send
633 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
634 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
635 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
636 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
637 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b9709b76 638 */
ba75ad94 639function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
6800d78e 640 global $CFG, $COURSE, $SESSION;
f1e0649c 641
ba4e0b05 642 // Use given MIME type if specified, otherwise guess it using mimeinfo.
643 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
644 // only Firefox saves all files locally before opening when content-disposition: attachment stated
645 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 646 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 647 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 648 $lastmodified = $pathisstring ? time() : filemtime($path);
649 $filesize = $pathisstring ? strlen($path) : filesize($path);
650
36bddcf5 651/* - MDL-13949
ee7f231d 652 //Adobe Acrobat Reader XSS prevention
653 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
654 //please note that it prevents opening of pdfs in browser when http referer disabled
655 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 656 if (!empty($_SERVER['HTTP_RANGE'])) {
657 //already byteserving
76ca1ff1 658 $lifetime = 1; // >0 needed for byteserving
c57d8874 659 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 660 $mimetype = 'application/x-forcedownload';
661 $forcedownload = true;
662 $lifetime = 0;
663 } else {
76ca1ff1 664 $lifetime = 1; // >0 needed for byteserving
ee7f231d 665 }
b8806ccc 666 }
36bddcf5 667*/
f3f7610c 668
69faecce 669 //IE compatibiltiy HACK!
4c8c65ec 670 if (ini_get('zlib.output_compression')) {
69faecce 671 ini_set('zlib.output_compression', 'Off');
672 }
673
4c8c65ec 674 //try to disable automatic sid rewrite in cookieless mode
8914cb82 675 @ini_set("session.use_trans_sid", "false");
4c8c65ec 676
677 //do not put '@' before the next header to detect incorrect moodle configurations,
678 //error should be better than "weird" empty lines for admins/users
679 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
680 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
681
4f047de2 682 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
683 if (check_browser_version('MSIE')) {
4638009b 684 $filename = rawurlencode($filename);
4f047de2 685 }
686
4c8c65ec 687 if ($forcedownload) {
4638009b 688 @header('Content-Disposition: attachment; filename="'.$filename.'"');
4c8c65ec 689 } else {
4638009b 690 @header('Content-Disposition: inline; filename="'.$filename.'"');
4c8c65ec 691 }
692
f1e0649c 693 if ($lifetime > 0) {
4c8c65ec 694 @header('Cache-Control: max-age='.$lifetime);
695 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 696 @header('Pragma: ');
4c8c65ec 697
698 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
699
700 @header('Accept-Ranges: bytes');
701
702 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
703 // byteserving stuff - for acrobat reader and download accelerators
704 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
705 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
706 $ranges = false;
707 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
708 foreach ($ranges as $key=>$value) {
709 if ($ranges[$key][1] == '') {
710 //suffix case
711 $ranges[$key][1] = $filesize - $ranges[$key][2];
712 $ranges[$key][2] = $filesize - 1;
713 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
714 //fix range length
715 $ranges[$key][2] = $filesize - 1;
716 }
717 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
718 //invalid byte-range ==> ignore header
719 $ranges = false;
720 break;
721 }
722 //prepare multipart header
723 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
724 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
725 }
726 } else {
727 $ranges = false;
728 }
729 if ($ranges) {
730 byteserving_send_file($path, $mimetype, $ranges);
731 }
732 }
733 } else {
734 /// Do not byteserve (disabled, strings, text and html files).
735 @header('Accept-Ranges: none');
736 }
737 } else { // Do not cache files in proxies and browsers
85e00626 738 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
739 @header('Cache-Control: max-age=10');
4c8c65ec 740 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 741 @header('Pragma: ');
742 } else { //normal http - prevent caching at all cost
743 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 744 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 745 @header('Pragma: no-cache');
746 }
4c8c65ec 747 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 748 }
f1e0649c 749
b9709b76 750 if (empty($filter)) {
4c8c65ec 751 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
752 //cookieless mode - rewrite links
753 @header('Content-Type: text/html');
754 $path = $pathisstring ? $path : implode('', file($path));
6800d78e 755 $path = $SESSION->sid_ob_rewrite($path);
4c8c65ec 756 $filesize = strlen($path);
757 $pathisstring = true;
758 } else if ($mimetype == 'text/plain') {
810944af 759 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 760 } else {
4c8c65ec 761 @header('Content-Type: '.$mimetype);
f1e0649c 762 }
4c8c65ec 763 @header('Content-Length: '.$filesize);
764 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 765 if ($pathisstring) {
766 echo $path;
4c8c65ec 767 } else {
69faecce 768 readfile_chunked($path);
f1e0649c 769 }
770 } else { // Try to put the file through filters
f1e0649c 771 if ($mimetype == 'text/html') {
a17c57b5 772 $options = new object();
f1e0649c 773 $options->noclean = true;
a17c57b5 774 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 775 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 776
3ace5ee4 777 $text = file_modify_html_header($text);
60f9e36e 778 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 779 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
780 //cookieless mode - rewrite links
6800d78e 781 $output = $SESSION->sid_ob_rewrite($output);
4c8c65ec 782 }
f1e0649c 783
4c8c65ec 784 @header('Content-Length: '.strlen($output));
785 @header('Content-Type: text/html');
786 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 787 echo $output;
b9709b76 788 // only filter text if filter all files is selected
789 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 790 $options = new object();
f1e0649c 791 $options->newlines = false;
792 $options->noclean = true;
793 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 794 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 795 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
796 //cookieless mode - rewrite links
6800d78e 797 $output = $SESSION->sid_ob_rewrite($output);
4c8c65ec 798 }
f1e0649c 799
4c8c65ec 800 @header('Content-Length: '.strlen($output));
810944af 801 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 802 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 803 echo $output;
804 } else { // Just send it out raw
4c8c65ec 805 @header('Content-Length: '.$filesize);
806 @header('Content-Type: '.$mimetype);
807 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 808 if ($pathisstring) {
809 echo $path;
810 }else {
69faecce 811 readfile_chunked($path);
f1e0649c 812 }
813 }
814 }
815 die; //no more chars to output!!!
816}
817
a43b5308 818function get_records_csv($file, $table) {
f33e1ed4 819 global $CFG, $DB;
599f38f9 820
f33e1ed4 821 if (!$metacolumns = $DB->get_columns($table)) {
599f38f9 822 return false;
823 }
824
a77b98eb 825 if(!($handle = @fopen($file, 'r'))) {
5a2a5331 826 print_error('get_records_csv failed to open '.$file);
599f38f9 827 }
828
829 $fieldnames = fgetcsv($handle, 4096);
830 if(empty($fieldnames)) {
831 fclose($handle);
832 return false;
833 }
834
835 $columns = array();
836
837 foreach($metacolumns as $metacolumn) {
838 $ord = array_search($metacolumn->name, $fieldnames);
839 if(is_int($ord)) {
840 $columns[$metacolumn->name] = $ord;
841 }
842 }
843
844 $rows = array();
845
846 while (($data = fgetcsv($handle, 4096)) !== false) {
847 $item = new stdClass;
848 foreach($columns as $name => $ord) {
849 $item->$name = $data[$ord];
850 }
851 $rows[] = $item;
852 }
853
854 fclose($handle);
855 return $rows;
856}
857
a77b98eb 858function put_records_csv($file, $records, $table = NULL) {
f33e1ed4 859 global $CFG, $DB;
a77b98eb 860
a1e93da2 861 if (empty($records)) {
a77b98eb 862 return true;
863 }
864
865 $metacolumns = NULL;
f33e1ed4 866 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
a77b98eb 867 return false;
868 }
869
a1e93da2 870 echo "x";
871
a77b98eb 872 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
5a2a5331 873 print_error('put_records_csv failed to open '.$file);
a77b98eb 874 }
875
a43b5308 876 $proto = reset($records);
877 if(is_object($proto)) {
878 $fields_records = array_keys(get_object_vars($proto));
879 }
880 else if(is_array($proto)) {
881 $fields_records = array_keys($proto);
882 }
883 else {
884 return false;
885 }
a1e93da2 886 echo "x";
a77b98eb 887
888 if(!empty($metacolumns)) {
889 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
890 $fields = array_intersect($fields_records, $fields_table);
891 }
892 else {
893 $fields = $fields_records;
894 }
895
896 fwrite($fp, implode(',', $fields));
897 fwrite($fp, "\r\n");
898
899 foreach($records as $record) {
a43b5308 900 $array = (array)$record;
a77b98eb 901 $values = array();
902 foreach($fields as $field) {
a43b5308 903 if(strpos($array[$field], ',')) {
904 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 905 }
906 else {
a43b5308 907 $values[] = $array[$field];
a77b98eb 908 }
909 }
910 fwrite($fp, implode(',', $values)."\r\n");
911 }
912
913 fclose($fp);
914 return true;
915}
916
f401cc97 917
34763a79 918/**
76ca1ff1 919 * Recursively delete the file or folder with path $location. That is,
34763a79 920 * if it is a file delete it. If it is a folder, delete all its content
76ca1ff1 921 * then delete it. If $location does not exist to start, that is not
922 * considered an error.
923 *
34763a79 924 * @param $location the path to remove.
925 */
4c8c65ec 926function fulldelete($location) {
f401cc97 927 if (is_dir($location)) {
928 $currdir = opendir($location);
929 while (false !== ($file = readdir($currdir))) {
930 if ($file <> ".." && $file <> ".") {
931 $fullfile = $location."/".$file;
4c8c65ec 932 if (is_dir($fullfile)) {
f401cc97 933 if (!fulldelete($fullfile)) {
934 return false;
935 }
936 } else {
937 if (!unlink($fullfile)) {
938 return false;
939 }
4c8c65ec 940 }
f401cc97 941 }
4c8c65ec 942 }
f401cc97 943 closedir($currdir);
944 if (! rmdir($location)) {
945 return false;
946 }
947
34763a79 948 } else if (file_exists($location)) {
f401cc97 949 if (!unlink($location)) {
950 return false;
951 }
952 }
953 return true;
954}
955
4c8c65ec 956/**
957 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
958 */
959function readfile_chunked($filename, $retbytes=true) {
960 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 961 $buffer = '';
76ca1ff1 962 $cnt =0;
69faecce 963 $handle = fopen($filename, 'rb');
964 if ($handle === false) {
965 return false;
966 }
20371063 967
69faecce 968 while (!feof($handle)) {
68913aec 969 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 970 $buffer = fread($handle, $chunksize);
971 echo $buffer;
20371063 972 flush();
69faecce 973 if ($retbytes) {
4c8c65ec 974 $cnt += strlen($buffer);
975 }
69faecce 976 }
977 $status = fclose($handle);
978 if ($retbytes && $status) {
979 return $cnt; // return num. bytes delivered like readfile() does.
980 }
981 return $status;
982}
983
4c8c65ec 984/**
985 * Send requested byterange of file.
986 */
987function byteserving_send_file($filename, $mimetype, $ranges) {
988 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
989 $handle = fopen($filename, 'rb');
990 if ($handle === false) {
991 die;
992 }
993 if (count($ranges) == 1) { //only one range requested
994 $length = $ranges[0][2] - $ranges[0][1] + 1;
995 @header('HTTP/1.1 206 Partial content');
996 @header('Content-Length: '.$length);
997 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
998 @header('Content-Type: '.$mimetype);
999 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1000 $buffer = '';
1001 fseek($handle, $ranges[0][1]);
1002 while (!feof($handle) && $length > 0) {
68913aec 1003 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 1004 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1005 echo $buffer;
1006 flush();
1007 $length -= strlen($buffer);
1008 }
1009 fclose($handle);
1010 die;
1011 } else { // multiple ranges requested - not tested much
1012 $totallength = 0;
1013 foreach($ranges as $range) {
aba588a7 1014 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 1015 }
aba588a7 1016 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 1017 @header('HTTP/1.1 206 Partial content');
1018 @header('Content-Length: '.$totallength);
1019 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
1020 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
1021 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1022 foreach($ranges as $range) {
1023 $length = $range[2] - $range[1] + 1;
1024 echo $range[0];
1025 $buffer = '';
1026 fseek($handle, $range[1]);
1027 while (!feof($handle) && $length > 0) {
68913aec 1028 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 1029 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1030 echo $buffer;
1031 flush();
1032 $length -= strlen($buffer);
1033 }
1034 }
1035 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
1036 fclose($handle);
1037 die;
1038 }
1039}
f401cc97 1040
3ace5ee4 1041/**
1042 * add includes (js and css) into uploaded files
1043 * before returning them, useful for themes and utf.js includes
1044 * @param string text - text to search and replace
1045 * @return string - text with added head includes
1046 */
1047function file_modify_html_header($text) {
1048 // first look for <head> tag
1049 global $CFG;
76ca1ff1 1050
3ace5ee4 1051 $stylesheetshtml = '';
1052 foreach ($CFG->stylesheets as $stylesheet) {
1053 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 1054 }
1055
3ace5ee4 1056 $filters = explode(",", $CFG->textfilters);
1057 if (in_array('filter/mediaplugin', $filters)) {
76ca1ff1 1058 // this script is needed by most media filter plugins.
1059 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
3ace5ee4 1060 } else {
76ca1ff1 1061 $ufo = '';
3ace5ee4 1062 }
76ca1ff1 1063
3ace5ee4 1064 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
1065 if ($matches) {
1066 $replacement = '<head>'.$ufo.$stylesheetshtml;
1067 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 1068 return $text;
3ace5ee4 1069 }
76ca1ff1 1070
3ace5ee4 1071 // if not, look for <html> tag, and stick <head> right after
1072 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
1073 if ($matches) {
1074 // replace <html> tag with <html><head>includes</head>
13534ef7 1075 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 1076 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 1077 return $text;
3ace5ee4 1078 }
76ca1ff1 1079
3ace5ee4 1080 // if not, look for <body> tag, and stick <head> before body
1081 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
1082 if ($matches) {
13534ef7 1083 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 1084 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 1085 return $text;
1086 }
1087
3ace5ee4 1088 // if not, just stick a <head> tag at the beginning
1089 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
1090 return $text;
1091}
1092
a77b98eb 1093?>