3 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
5 function get_file_url($path, $options=null, $type='coursefile') {
8 $path = trim($path, '/'); // no leading and trailing slashes
14 $url = "$CFG->wwwroot/file.php";
17 if ($CFG->slasharguments
) {
18 $parts = explode('/', $path);
19 $parts = array_map('rawurlencode', $parts);
20 $path = implode('/', $parts);
21 $ffurl = "$CFG->wwwroot/file.php/$path";
24 $path = rawurlencode("/$path");
25 $ffurl = "$CFG->wwwroot/file.php?file=$path";
30 foreach ($options as $name=>$value) {
31 $ffurl = $ffurl.$separator.$name.'='.$value;
40 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
41 * Due to security concerns only downloads from http(s) sources are supported.
43 * @param string $url file url starting with http(s)://
44 * @param array $headers http headers, null if none. If set, should be an
45 * associative array of header name => value pairs.
46 * @param array $postdata array means use POST request with given parameters
47 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
48 * (if false, just returns content)
49 * @param int $timeout timeout for complete download process including all file transfer
51 * @param int $connecttimeout timeout for connection to server; this is the timeout that
52 * usually happens if the remote server is completely down (default 20 seconds);
53 * may not work when using proxy
54 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
55 * @return mixed false if request failed or content of the file as string if ok.
57 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
60 // some extra security
61 $newlines = array("\r", "\n");
62 if (is_array($headers) ) {
63 foreach ($headers as $key => $value) {
64 $headers[$key] = str_replace($newlines, '', $value);
67 $url = str_replace($newlines, '', $url);
68 if (!preg_match('|^https?://|i', $url)) {
70 $response = new object();
71 $response->status
= 0;
72 $response->headers
= array();
73 $response->response_code
= 'Invalid protocol specified in url';
74 $response->results
= '';
75 $response->error
= 'Invalid protocol specified in url';
83 if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
84 require_once($CFG->libdir
.'/snoopy/Snoopy.class.inc');
85 $snoopy = new Snoopy();
86 $snoopy->read_timeout
= $timeout;
87 $snoopy->_fp_timeout
= $connecttimeout;
88 $snoopy->proxy_host
= $CFG->proxyhost
;
89 $snoopy->proxy_port
= $CFG->proxyport
;
90 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
91 // this will probably fail, but let's try it anyway
92 $snoopy->proxy_user
= $CFG->proxyuser
;
93 $snoopy->proxy_password
= $CFG->proxypassword
;
95 if (is_array($headers) ) {
96 $client->rawheaders
= $headers;
99 if (is_array($postdata)) {
100 $fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
102 $fetch = @$snoopy->fetch($url); // use more specific debug code bellow
107 //fix header line endings
108 foreach ($snoopy->headers
as $key=>$unused) {
109 $snoopy->headers
[$key] = trim($snoopy->headers
[$key]);
111 $response = new object();
112 $response->status
= $snoopy->status
;
113 $response->headers
= $snoopy->headers
;
114 $response->response_code
= trim($snoopy->response_code
);
115 $response->results
= $snoopy->results
;
116 $response->error
= $snoopy->error
;
119 } else if ($snoopy->status
!= 200) {
120 debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code
, DEBUG_ALL
);
124 return $snoopy->results
;
128 $response = new object();
129 $response->status
= $snoopy->status
;
130 $response->headers
= array();
131 $response->response_code
= $snoopy->response_code
;
132 $response->results
= '';
133 $response->error
= $snoopy->error
;
136 debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error
, DEBUG_ALL
);
143 if (is_array($headers) ) {
145 foreach ($headers as $key => $value) {
146 $headers2[] = "$key: $value";
148 curl_setopt($ch, CURLOPT_HTTPHEADER
, $headers2);
152 if ($skipcertverify) {
153 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
156 // use POST if requested
157 if (is_array($postdata)) {
158 foreach ($postdata as $k=>$v) {
159 $postdata[$k] = urlencode($k).'='.urlencode($v);
161 $postdata = implode('&', $postdata);
162 curl_setopt($ch, CURLOPT_POST
, true);
163 curl_setopt($ch, CURLOPT_POSTFIELDS
, $postdata);
166 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
167 curl_setopt($ch, CURLOPT_HEADER
, true);
168 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, $connecttimeout);
169 curl_setopt($ch, CURLOPT_TIMEOUT
, $timeout);
170 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
171 // TODO: add version test for '7.10.5'
172 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
173 curl_setopt($ch, CURLOPT_MAXREDIRS
, 5);
176 if (!empty($CFG->proxyhost
)) {
177 // SOCKS supported in PHP5 only
178 if (!empty($CFG->proxytype
) and ($CFG->proxytype
== 'SOCKS5')) {
179 if (defined('CURLPROXY_SOCKS5')) {
180 curl_setopt($ch, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
184 $response = new object();
185 $response->status
= '0';
186 $response->headers
= array();
187 $response->response_code
= 'SOCKS5 proxy is not supported in PHP4';
188 $response->results
= '';
189 $response->error
= 'SOCKS5 proxy is not supported in PHP4';
192 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL
);
198 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, false);
200 if (empty($CFG->proxyport
)) {
201 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
);
203 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
.':'.$CFG->proxyport
);
206 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
207 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
208 if (defined('CURLOPT_PROXYAUTH')) {
209 // any proxy authentication if PHP 5.1
210 curl_setopt($ch, CURLOPT_PROXYAUTH
, CURLAUTH_BASIC | CURLAUTH_NTLM
);
215 $data = curl_exec($ch);
217 // try to detect encoding problems
218 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
219 curl_setopt($ch, CURLOPT_ENCODING
, 'none');
220 $data = curl_exec($ch);
223 if (curl_errno($ch)) {
224 $error = curl_error($ch);
225 $error_no = curl_errno($ch);
229 $response = new object();
230 if ($error_no == 28) {
231 $response->status
= '-100'; // mimic snoopy
233 $response->status
= '0';
235 $response->headers
= array();
236 $response->response_code
= $error;
237 $response->results
= '';
238 $response->error
= $error;
241 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
246 $info = curl_getinfo($ch);
249 if (empty($info['http_code'])) {
250 // for security reasons we support only true http connections (Location: file:// exploit prevention)
251 $response = new object();
252 $response->status
= '0';
253 $response->headers
= array();
254 $response->response_code
= 'Unknown cURL error';
255 $response->results
= ''; // do NOT change this!
256 $response->error
= 'Unknown cURL error';
259 // strip redirect headers and get headers array and content
260 $data = explode("\r\n\r\n", $data, $info['redirect_count'] +
2);
261 $results = array_pop($data);
262 $headers = array_pop($data);
263 $headers = explode("\r\n", trim($headers));
265 $response = new object();;
266 $response->status
= (string)$info['http_code'];
267 $response->headers
= $headers;
268 $response->response_code
= $headers[0];
269 $response->results
= $results;
270 $response->error
= '';
275 } else if ($info['http_code'] != 200) {
276 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
279 return $response->results
;
285 * @return List of information about file types based on extensions.
286 * Associative array of extension (lower-case) to associative array
287 * from 'element name' to data. Current element names are 'type' and 'icon'.
288 * Unknown types should use the 'xxx' entry which includes defaults.
290 function get_mimetypes_array() {
292 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
293 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
294 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
295 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
296 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
297 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
298 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
299 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
300 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
301 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
302 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
303 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
304 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
305 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
306 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
307 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
308 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
309 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
310 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
311 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
312 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
313 'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
314 'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
315 'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
316 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
317 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
318 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
319 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
320 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
321 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
322 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
323 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
324 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
325 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
326 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
327 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
328 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
329 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
330 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
331 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
332 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
333 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
334 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
335 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
336 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
337 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
338 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
339 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
340 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
341 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
342 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
343 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
344 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
345 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
346 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
347 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
348 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
349 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
350 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
351 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
352 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
353 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
354 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
355 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
356 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
357 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
358 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
359 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
361 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
362 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
363 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
364 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
365 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
366 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
367 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
368 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
369 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
370 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
371 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
372 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
373 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
374 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
376 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
377 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
378 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
379 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
380 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
381 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
382 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
383 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
384 'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
385 'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
386 'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
387 'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
388 'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
389 'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
390 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
391 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
392 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
393 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
394 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
395 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
396 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
397 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
398 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
399 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
400 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
401 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
402 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
403 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
404 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
405 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
406 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
407 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
408 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
410 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
411 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
412 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
413 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
414 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
415 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
416 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
417 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
418 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
419 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
421 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
422 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
423 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
424 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
425 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
426 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
427 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
428 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
429 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
430 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
431 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
432 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
433 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
434 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
435 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
436 'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
437 'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
438 'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
439 'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
440 'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
441 'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
442 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
443 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
444 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
449 * Obtains information about a filetype based on its extension. Will
450 * use a default if no information is present about that particular
452 * @param string $element Desired information (usually 'icon'
453 * for icon filename or 'type' for MIME type)
454 * @param string $filename Filename we're looking up
455 * @return string Requested piece of information from array
457 function mimeinfo($element, $filename) {
458 static $mimeinfo = null;
459 if (is_null($mimeinfo)) {
460 $mimeinfo = get_mimetypes_array();
463 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
464 if (isset($mimeinfo[strtolower($match[1])][$element])) {
465 return $mimeinfo[strtolower($match[1])][$element];
467 return $mimeinfo['xxx'][$element]; // By default
470 return $mimeinfo['xxx'][$element]; // By default
475 * Obtains information about a filetype based on the MIME type rather than
476 * the other way around.
477 * @param string $element Desired information (usually 'icon')
478 * @param string $mimetype MIME type we're looking up
479 * @return string Requested piece of information from array
481 function mimeinfo_from_type($element, $mimetype) {
483 $mimeinfo=get_mimetypes_array();
485 foreach($mimeinfo as $values) {
486 if($values['type']==$mimetype) {
487 if(isset($values[$element])) {
488 return $values[$element];
493 return $mimeinfo['xxx'][$element]; // Default
497 * Get information about a filetype based on the icon file.
498 * @param string $element Desired information (usually 'icon')
499 * @param string $icon Icon file path.
500 * @return string Requested piece of information from array
502 function mimeinfo_from_icon($element, $icon) {
504 $mimeinfo=get_mimetypes_array();
506 if (preg_match("/\/(.*)/", $icon, $matches)) {
509 $info = $mimeinfo['xxx'][$element]; // Default
510 foreach($mimeinfo as $values) {
511 if($values['icon']==$icon) {
512 if(isset($values[$element])) {
513 $info = $values[$element];
515 //No break, for example for 'excel.gif' we don't want 'csv'!
522 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
523 * mimetypes.php language file.
524 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
525 * @param bool $capitalise If true, capitalises first character of result
526 * @return string Text description
528 function get_mimetype_description($mimetype,$capitalise=false) {
529 $result=get_string($mimetype,'mimetypes');
530 // Surrounded by square brackets indicates that there isn't a string for that
531 // (maybe there is a better way to find this out?)
532 if(strpos($result,'[')===0) {
533 $result=get_string('document/unknown','mimetypes');
536 $result=ucfirst($result);
542 * Handles the sending of file data to the user's browser, including support for
544 * @param string $path Path of file on disk (including real filename), or actual content of file as string
545 * @param string $filename Filename to send
546 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
547 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
548 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
549 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
550 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
552 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
553 global $CFG, $COURSE;
555 // Use given MIME type if specified, otherwise guess it using mimeinfo.
556 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
557 // only Firefox saves all files locally before opening when content-disposition: attachment stated
558 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
559 $mimetype = ($forcedownload and !$isFF) ?
'application/x-forcedownload' :
560 ($mimetype ?
$mimetype : mimeinfo('type', $filename));
561 $lastmodified = $pathisstring ?
time() : filemtime($path);
562 $filesize = $pathisstring ?
strlen($path) : filesize($path);
565 //Adobe Acrobat Reader XSS prevention
566 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
567 //please note that it prevents opening of pdfs in browser when http referer disabled
568 //or file linked from another site; browser caching of pdfs is now disabled too
569 if (!empty($_SERVER['HTTP_RANGE'])) {
570 //already byteserving
571 $lifetime = 1; // >0 needed for byteserving
572 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
573 $mimetype = 'application/x-forcedownload';
574 $forcedownload = true;
577 $lifetime = 1; // >0 needed for byteserving
582 //IE compatibiltiy HACK!
583 if (ini_get('zlib.output_compression')) {
584 ini_set('zlib.output_compression', 'Off');
587 //try to disable automatic sid rewrite in cookieless mode
588 @ini_set
("session.use_trans_sid", "false");
590 //do not put '@' before the next header to detect incorrect moodle configurations,
591 //error should be better than "weird" empty lines for admins/users
592 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
593 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
595 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
596 if (check_browser_version('MSIE')) {
597 $filename = rawurlencode($filename);
600 if ($forcedownload) {
601 @header
('Content-Disposition: attachment; filename="'.$filename.'"');
603 @header
('Content-Disposition: inline; filename="'.$filename.'"');
607 @header
('Cache-Control: max-age='.$lifetime);
608 @header
('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
611 if (empty($CFG->disablebyteserving
) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
613 @header
('Accept-Ranges: bytes');
615 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
616 // byteserving stuff - for acrobat reader and download accelerators
617 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
618 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
620 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
621 foreach ($ranges as $key=>$value) {
622 if ($ranges[$key][1] == '') {
624 $ranges[$key][1] = $filesize - $ranges[$key][2];
625 $ranges[$key][2] = $filesize - 1;
626 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
628 $ranges[$key][2] = $filesize - 1;
630 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
631 //invalid byte-range ==> ignore header
635 //prepare multipart header
636 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
637 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
643 byteserving_send_file($path, $mimetype, $ranges);
647 /// Do not byteserve (disabled, strings, text and html files).
648 @header
('Accept-Ranges: none');
650 } else { // Do not cache files in proxies and browsers
651 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
652 @header
('Cache-Control: max-age=10');
653 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
655 } else { //normal http - prevent caching at all cost
656 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
657 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
658 @header
('Pragma: no-cache');
660 @header
('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
663 if (empty($filter)) {
664 if ($mimetype == 'text/html' && !empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
665 //cookieless mode - rewrite links
666 @header
('Content-Type: text/html');
667 $path = $pathisstring ?
$path : implode('', file($path));
668 $path = sid_ob_rewrite($path);
669 $filesize = strlen($path);
670 $pathisstring = true;
671 } else if ($mimetype == 'text/plain') {
672 @header
('Content-Type: Text/plain; charset=utf-8'); //add encoding
674 @header
('Content-Type: '.$mimetype);
676 @header
('Content-Length: '.$filesize);
677 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
681 readfile_chunked($path);
683 } else { // Try to put the file through filters
684 if ($mimetype == 'text/html') {
685 $options = new object();
686 $options->noclean
= true;
687 $options->nocache
= true; // temporary workaround for MDL-5136
688 $text = $pathisstring ?
$path : implode('', file($path));
690 $text = file_modify_html_header($text);
691 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
692 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
693 //cookieless mode - rewrite links
694 $output = sid_ob_rewrite($output);
697 @header
('Content-Length: '.strlen($output));
698 @header
('Content-Type: text/html');
699 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
701 // only filter text if filter all files is selected
702 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
703 $options = new object();
704 $options->newlines
= false;
705 $options->noclean
= true;
706 $text = htmlentities($pathisstring ?
$path : implode('', file($path)));
707 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
708 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
709 //cookieless mode - rewrite links
710 $output = sid_ob_rewrite($output);
713 @header
('Content-Length: '.strlen($output));
714 @header
('Content-Type: text/html; charset=utf-8'); //add encoding
715 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
717 } else { // Just send it out raw
718 @header
('Content-Length: '.$filesize);
719 @header
('Content-Type: '.$mimetype);
720 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
724 readfile_chunked($path);
728 die; //no more chars to output!!!
731 function get_records_csv($file, $table) {
734 if (!$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
738 if(!($handle = @fopen
($file, 'r'))) {
739 error('get_records_csv failed to open '.$file);
742 $fieldnames = fgetcsv($handle, 4096);
743 if(empty($fieldnames)) {
750 foreach($metacolumns as $metacolumn) {
751 $ord = array_search($metacolumn->name
, $fieldnames);
753 $columns[$metacolumn->name
] = $ord;
759 while (($data = fgetcsv($handle, 4096)) !== false) {
760 $item = new stdClass
;
761 foreach($columns as $name => $ord) {
762 $item->$name = $data[$ord];
771 function put_records_csv($file, $records, $table = NULL) {
774 if (empty($records)) {
779 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
785 if(!($fp = @fopen
($CFG->dataroot
.'/temp/'.$file, 'w'))) {
786 error('put_records_csv failed to open '.$file);
789 $proto = reset($records);
790 if(is_object($proto)) {
791 $fields_records = array_keys(get_object_vars($proto));
793 else if(is_array($proto)) {
794 $fields_records = array_keys($proto);
801 if(!empty($metacolumns)) {
802 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
803 $fields = array_intersect($fields_records, $fields_table);
806 $fields = $fields_records;
809 fwrite($fp, implode(',', $fields));
812 foreach($records as $record) {
813 $array = (array)$record;
815 foreach($fields as $field) {
816 if(strpos($array[$field], ',')) {
817 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
820 $values[] = $array[$field];
823 fwrite($fp, implode(',', $values)."\r\n");
832 * Recursively delete the file or folder with path $location. That is,
833 * if it is a file delete it. If it is a folder, delete all its content
834 * then delete it. If $location does not exist to start, that is not
835 * considered an error.
837 * @param $location the path to remove.
839 function fulldelete($location) {
840 if (is_dir($location)) {
841 $currdir = opendir($location);
842 while (false !== ($file = readdir($currdir))) {
843 if ($file <> ".." && $file <> ".") {
844 $fullfile = $location."/".$file;
845 if (is_dir($fullfile)) {
846 if (!fulldelete($fullfile)) {
850 if (!unlink($fullfile)) {
857 if (! rmdir($location)) {
861 } else if (file_exists($location)) {
862 if (!unlink($location)) {
870 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
872 function readfile_chunked($filename, $retbytes=true) {
873 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
876 $handle = fopen($filename, 'rb');
877 if ($handle === false) {
881 while (!feof($handle)) {
882 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
883 $buffer = fread($handle, $chunksize);
887 $cnt +
= strlen($buffer);
890 $status = fclose($handle);
891 if ($retbytes && $status) {
892 return $cnt; // return num. bytes delivered like readfile() does.
898 * Send requested byterange of file.
900 function byteserving_send_file($filename, $mimetype, $ranges) {
901 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
902 $handle = fopen($filename, 'rb');
903 if ($handle === false) {
906 if (count($ranges) == 1) { //only one range requested
907 $length = $ranges[0][2] - $ranges[0][1] +
1;
908 @header
('HTTP/1.1 206 Partial content');
909 @header
('Content-Length: '.$length);
910 @header
('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
911 @header
('Content-Type: '.$mimetype);
912 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
914 fseek($handle, $ranges[0][1]);
915 while (!feof($handle) && $length > 0) {
916 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
917 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
920 $length -= strlen($buffer);
924 } else { // multiple ranges requested - not tested much
926 foreach($ranges as $range) {
927 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
929 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
930 @header
('HTTP/1.1 206 Partial content');
931 @header
('Content-Length: '.$totallength);
932 @header
('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
933 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
934 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
935 foreach($ranges as $range) {
936 $length = $range[2] - $range[1] +
1;
939 fseek($handle, $range[1]);
940 while (!feof($handle) && $length > 0) {
941 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
942 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
945 $length -= strlen($buffer);
948 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
955 * add includes (js and css) into uploaded files
956 * before returning them, useful for themes and utf.js includes
957 * @param string text - text to search and replace
958 * @return string - text with added head includes
960 function file_modify_html_header($text) {
961 // first look for <head> tag
964 $stylesheetshtml = '';
965 foreach ($CFG->stylesheets
as $stylesheet) {
966 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
969 $filters = explode(",", $CFG->textfilters
);
970 if (in_array('filter/mediaplugin', $filters)) {
971 // this script is needed by most media filter plugins.
972 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot
.'/lib/ufo.js"></script>'."\n";
977 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
979 $replacement = '<head>'.$ufo.$stylesheetshtml;
980 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
984 // if not, look for <html> tag, and stick <head> right after
985 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
987 // replace <html> tag with <html><head>includes</head>
988 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
989 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
993 // if not, look for <body> tag, and stick <head> before body
994 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
996 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
997 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
1001 // if not, just stick a <head> tag at the beginning
1002 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;