Correct timezones listing when importing olson files ; merged from 19_STABLE
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
4c8c65ec 3define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
4
8ee88311 5/**
5f8bdc17 6 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
7 * @param string $url file url
8ee88311 8 * @return mixed false if request failed or content of the file as string if ok.
9 */
10function download_file_content($url) {
e27f0765 11 global $CFG;
12
5f8bdc17 13 if (!extension_loaded('curl')) {
14 require_once($CFG->libdir.'/snoopy/Snoopy.class.inc');
15 $snoopy = new Snoopy();
16 $snoopy->proxy_host = $CFG->proxyhost;
17 $snoopy->proxy_port = $CFG->proxyport;
18 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
19 // this will probably fail, but let's try it anyway
20 $snoopy->proxy_user = $CFG->proxyuser;
21 $snoopy->proxy_password = $CFG->proxypassword;
22 }
23 if ($snoopy->fetch($url)) {
24 if (strpos($snoopy->response_code, '200') === false) {
25 debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code, DEBUG_ALL);
26 return false;
27 } else {
28 return $snoopy->results;
29 }
30 } else {
31 debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error, DEBUG_ALL);
32 return false;
33 }
34 }
35
8ee88311 36 $ch = curl_init($url);
37 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
38 curl_setopt($ch, CURLOPT_HEADER, false);
39 if (!empty($CFG->proxyhost)) {
5f8bdc17 40 // SOCKS supported in PHP5 only
41 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
42 if (defined('CURLPROXY_SOCKS5')) {
43 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
44 } else {
45 debugging("SOCKS5 proxies are supported only in PHP5 when cURL extension loaded.", DEBUG_ALL);
46 curl_close($ch);
47 return false;
48 }
49 }
50
08ec989f 51 // don't CONNECT for non-https connections
52 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
53
8ee88311 54 if (empty($CFG->proxyport)) {
e27f0765 55 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
8ee88311 56 } else {
e27f0765 57 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
8ee88311 58 }
5f8bdc17 59
60 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
8ee88311 61 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
5f8bdc17 62 if (defined('CURLOPT_PROXYAUTH')) {
63 // any proxy authentication if PHP 5.1
64 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
65 }
8ee88311 66 }
67 }
68 $result = curl_exec($ch);
08ec989f 69
70 if (curl_errno($ch)) {
5f8bdc17 71 debugging("CURL request for \"$url\" failed with: ".curl_error($ch), DEBUG_ALL);
72 $result = false;
73
74 } else {
75 $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
76 if ($code != 200) {
77 $codes = array(
78 100=>'Continue',
79 101=>'Switching Protocols',
80 200=>'OK',
81 201=>'Created',
82 202=>'Accepted',
83 203=>'Non-Authoritative Information',
84 204=>'No Content',
85 205=>'Reset Content',
86 206=>'Partial Content',
87 300=>'Multiple Choices',
88 301=>'Moved Permanently',
ee3501f1 89 302=>'Moved Temporarily',
5f8bdc17 90 303=>'See Other',
91 304=>'Not Modified',
92 305=>'Use Proxy',
93 306=>'(Unused)',
94 307=>'Temporary Redirect',
95 400=>'Bad Request',
96 401=>'Unauthorized',
97 402=>'Payment Required',
98 403=>'Forbidden',
99 404=>'Not Found',
100 405=>'Method Not Allowed',
101 406=>'Not Acceptable',
102 407=>'Proxy Authentication Required',
103 408=>'Request Timeout',
104 409=>'Conflict',
105 410=>'Gone',
106 411=>'Length Required',
107 412=>'Precondition Failed',
108 413=>'Request Entity Too Large',
109 414=>'Request-URI Too Long',
110 415=>'Unsupported Media Type',
111 416=>'Requested Range Not Satisfiable',
112 417=>'Expectation Failed',
113 500=>'Internal Server Error',
114 501=>'Not Implemented',
115 502=>'Bad Gateway',
116 503=>'Service Unavailable',
117 504=>'Gateway Timeout',
118 505=>'HTTP Version Not Supported');
119
120 debugging("CURL request for \"$url\" failed, http response code: ".$code.' '.$codes[$code], DEBUG_ALL);
121 $result = false;
122 }
08ec989f 123 }
124
8ee88311 125 curl_close($ch);
126 return $result;
127}
128
3ce73b14 129/**
76ca1ff1 130 * @return List of information about file types based on extensions.
3ce73b14 131 * Associative array of extension (lower-case) to associative array
132 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 133 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 134 */
135function get_mimetypes_array() {
136 return array (
a370c895 137 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
138 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
139 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
140 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
141 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
142 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
143 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
144 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 145 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 146 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
147 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
148 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
18bf47ef 149 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 150 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
18bf47ef 151 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 152 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
76ca1ff1 153 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
6ae5e482 154 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
a370c895 155 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
609d84e3 156 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
a370c895 157 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
68da9722 158 'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
159 'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
160 'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
a370c895 161 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
162 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
163 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
164 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
165 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
ee7f231d 166 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
759bc3c8 167 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
a370c895 168 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
169 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
759bc3c8 170 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 171 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
172 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
173 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 174 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 175 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
70ee2841 176 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
a370c895 177 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
1659a998 178 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
a370c895 179 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
08297dcb 180 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
181 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
182 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
18bf47ef 183 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 184 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
185 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
186 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
187 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
188 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 189 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
190 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
191 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 192 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 193 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
194 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
195 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
196 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
197 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
198 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
199 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
200 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
201 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
202 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
203 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 204
205 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
206 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
207 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
e10bc440 208 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
209 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
210 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
211 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
212 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
213 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
214 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
215 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
216 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
217 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
218 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
5395334d 219
a370c895 220 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
221 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
222 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
223 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
224 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
225 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
226 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
227 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
68da9722 228 'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
229 'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
230 'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
231 'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
232 'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
233 'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
234 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
a370c895 235 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
236 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
237 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
238 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
a00420fb 239 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 240 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
241 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
242 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
243 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
244 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
245 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
246 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 247 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
4db69ffb 248 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
249 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
a370c895 250 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
251 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
252 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 253
254 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
255 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
256 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
257 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
258 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
259 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
260 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
261 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
262 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
263 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
264
a370c895 265 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
266 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
267 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
268 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
269 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
270 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
271 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
272 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
273 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
274 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
275 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
ee7f231d 276 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
277 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
278 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
a370c895 279 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
68da9722 280 'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
281 'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
282 'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
283 'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
284 'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
285 'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
a370c895 286 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
287 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
288 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 289 );
3ce73b14 290}
291
76ca1ff1 292/**
3ce73b14 293 * Obtains information about a filetype based on its extension. Will
294 * use a default if no information is present about that particular
295 * extension.
76ca1ff1 296 * @param string $element Desired information (usually 'icon'
3ce73b14 297 * for icon filename or 'type' for MIME type)
76ca1ff1 298 * @param string $filename Filename we're looking up
3ce73b14 299 * @return string Requested piece of information from array
300 */
301function mimeinfo($element, $filename) {
302 static $mimeinfo;
303 $mimeinfo=get_mimetypes_array();
f1e0649c 304
a370c895 305 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 306 if (isset($mimeinfo[strtolower($match[1])][$element])) {
307 return $mimeinfo[strtolower($match[1])][$element];
308 } else {
a370c895 309 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 310 }
311 } else {
a370c895 312 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 313 }
314}
315
76ca1ff1 316/**
3ce73b14 317 * Obtains information about a filetype based on the MIME type rather than
318 * the other way around.
319 * @param string $element Desired information (usually 'icon')
76ca1ff1 320 * @param string $mimetype MIME type we're looking up
3ce73b14 321 * @return string Requested piece of information from array
322 */
323function mimeinfo_from_type($element, $mimetype) {
324 static $mimeinfo;
325 $mimeinfo=get_mimetypes_array();
76ca1ff1 326
3ce73b14 327 foreach($mimeinfo as $values) {
328 if($values['type']==$mimetype) {
329 if(isset($values[$element])) {
330 return $values[$element];
331 }
332 break;
333 }
334 }
335 return $mimeinfo['xxx'][$element]; // Default
336}
b9709b76 337
42ead7d7 338/**
339 * Get information about a filetype based on the icon file.
340 * @param string $element Desired information (usually 'icon')
341 * @param string $icon Icon file path.
342 * @return string Requested piece of information from array
343 */
344function mimeinfo_from_icon($element, $icon) {
345 static $mimeinfo;
346 $mimeinfo=get_mimetypes_array();
347
348 if (preg_match("/\/(.*)/", $icon, $matches)) {
349 $icon = $matches[1];
350 }
351 $info = $mimeinfo['xxx'][$element]; // Default
352 foreach($mimeinfo as $values) {
353 if($values['icon']==$icon) {
354 if(isset($values[$element])) {
355 $info = $values[$element];
356 }
357 //No break, for example for 'excel.gif' we don't want 'csv'!
358 }
359 }
360 return $info;
361}
362
c0381e22 363/**
76ca1ff1 364 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
365 * mimetypes.php language file.
c0381e22 366 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
367 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 368 * @return string Text description
c0381e22 369 */
370function get_mimetype_description($mimetype,$capitalise=false) {
371 $result=get_string($mimetype,'mimetypes');
372 // Surrounded by square brackets indicates that there isn't a string for that
373 // (maybe there is a better way to find this out?)
374 if(strpos($result,'[')===0) {
375 $result=get_string('document/unknown','mimetypes');
76ca1ff1 376 }
c0381e22 377 if($capitalise) {
378 $result=ucfirst($result);
379 }
380 return $result;
381}
382
76ca1ff1 383/**
384 * Handles the sending of file data to the user's browser, including support for
385 * byteranges etc.
ba75ad94 386 * @param string $path Path of file on disk (including real filename), or actual content of file as string
387 * @param string $filename Filename to send
388 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
389 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
390 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
391 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
392 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b9709b76 393 */
ba75ad94 394function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
60f9e36e 395 global $CFG, $COURSE;
f1e0649c 396
ba4e0b05 397 // Use given MIME type if specified, otherwise guess it using mimeinfo.
398 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
399 // only Firefox saves all files locally before opening when content-disposition: attachment stated
400 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 401 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 402 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 403 $lastmodified = $pathisstring ? time() : filemtime($path);
404 $filesize = $pathisstring ? strlen($path) : filesize($path);
405
ee7f231d 406 //Adobe Acrobat Reader XSS prevention
407 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
408 //please note that it prevents opening of pdfs in browser when http referer disabled
409 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 410 if (!empty($_SERVER['HTTP_RANGE'])) {
411 //already byteserving
76ca1ff1 412 $lifetime = 1; // >0 needed for byteserving
c57d8874 413 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 414 $mimetype = 'application/x-forcedownload';
415 $forcedownload = true;
416 $lifetime = 0;
417 } else {
76ca1ff1 418 $lifetime = 1; // >0 needed for byteserving
ee7f231d 419 }
b8806ccc 420 }
f3f7610c 421
69faecce 422 //IE compatibiltiy HACK!
4c8c65ec 423 if (ini_get('zlib.output_compression')) {
69faecce 424 ini_set('zlib.output_compression', 'Off');
425 }
426
4c8c65ec 427 //try to disable automatic sid rewrite in cookieless mode
8914cb82 428 @ini_set("session.use_trans_sid", "false");
4c8c65ec 429
430 //do not put '@' before the next header to detect incorrect moodle configurations,
431 //error should be better than "weird" empty lines for admins/users
432 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
433 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
434
4f047de2 435 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
436 if (check_browser_version('MSIE')) {
5f8bdc17 437 $filename = urlencode($filename);
4f047de2 438 }
439
4c8c65ec 440 if ($forcedownload) {
441 @header('Content-Disposition: attachment; filename='.$filename);
442 } else {
443 @header('Content-Disposition: inline; filename='.$filename);
444 }
445
f1e0649c 446 if ($lifetime > 0) {
4c8c65ec 447 @header('Cache-Control: max-age='.$lifetime);
448 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 449 @header('Pragma: ');
4c8c65ec 450
451 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
452
453 @header('Accept-Ranges: bytes');
454
455 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
456 // byteserving stuff - for acrobat reader and download accelerators
457 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
458 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
459 $ranges = false;
460 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
461 foreach ($ranges as $key=>$value) {
462 if ($ranges[$key][1] == '') {
463 //suffix case
464 $ranges[$key][1] = $filesize - $ranges[$key][2];
465 $ranges[$key][2] = $filesize - 1;
466 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
467 //fix range length
468 $ranges[$key][2] = $filesize - 1;
469 }
470 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
471 //invalid byte-range ==> ignore header
472 $ranges = false;
473 break;
474 }
475 //prepare multipart header
476 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
477 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
478 }
479 } else {
480 $ranges = false;
481 }
482 if ($ranges) {
483 byteserving_send_file($path, $mimetype, $ranges);
484 }
485 }
486 } else {
487 /// Do not byteserve (disabled, strings, text and html files).
488 @header('Accept-Ranges: none');
489 }
490 } else { // Do not cache files in proxies and browsers
85e00626 491 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
492 @header('Cache-Control: max-age=10');
4c8c65ec 493 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 494 @header('Pragma: ');
495 } else { //normal http - prevent caching at all cost
496 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 497 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 498 @header('Pragma: no-cache');
499 }
4c8c65ec 500 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 501 }
f1e0649c 502
b9709b76 503 if (empty($filter)) {
4c8c65ec 504 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
505 //cookieless mode - rewrite links
506 @header('Content-Type: text/html');
507 $path = $pathisstring ? $path : implode('', file($path));
508 $path = sid_ob_rewrite($path);
509 $filesize = strlen($path);
510 $pathisstring = true;
511 } else if ($mimetype == 'text/plain') {
810944af 512 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 513 } else {
4c8c65ec 514 @header('Content-Type: '.$mimetype);
f1e0649c 515 }
4c8c65ec 516 @header('Content-Length: '.$filesize);
517 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 518 if ($pathisstring) {
519 echo $path;
4c8c65ec 520 } else {
69faecce 521 readfile_chunked($path);
f1e0649c 522 }
523 } else { // Try to put the file through filters
f1e0649c 524 if ($mimetype == 'text/html') {
a17c57b5 525 $options = new object();
f1e0649c 526 $options->noclean = true;
a17c57b5 527 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 528 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 529
3ace5ee4 530 $text = file_modify_html_header($text);
60f9e36e 531 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 532 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
533 //cookieless mode - rewrite links
534 $output = sid_ob_rewrite($output);
535 }
f1e0649c 536
4c8c65ec 537 @header('Content-Length: '.strlen($output));
538 @header('Content-Type: text/html');
539 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 540 echo $output;
b9709b76 541 // only filter text if filter all files is selected
542 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 543 $options = new object();
f1e0649c 544 $options->newlines = false;
545 $options->noclean = true;
546 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 547 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 548 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
549 //cookieless mode - rewrite links
550 $output = sid_ob_rewrite($output);
551 }
f1e0649c 552
4c8c65ec 553 @header('Content-Length: '.strlen($output));
810944af 554 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 555 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 556 echo $output;
557 } else { // Just send it out raw
4c8c65ec 558 @header('Content-Length: '.$filesize);
559 @header('Content-Type: '.$mimetype);
560 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 561 if ($pathisstring) {
562 echo $path;
563 }else {
69faecce 564 readfile_chunked($path);
f1e0649c 565 }
566 }
567 }
568 die; //no more chars to output!!!
569}
570
a43b5308 571function get_records_csv($file, $table) {
599f38f9 572 global $CFG, $db;
573
574 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
575 return false;
576 }
577
a77b98eb 578 if(!($handle = @fopen($file, 'r'))) {
599f38f9 579 error('get_records_csv failed to open '.$file);
580 }
581
582 $fieldnames = fgetcsv($handle, 4096);
583 if(empty($fieldnames)) {
584 fclose($handle);
585 return false;
586 }
587
588 $columns = array();
589
590 foreach($metacolumns as $metacolumn) {
591 $ord = array_search($metacolumn->name, $fieldnames);
592 if(is_int($ord)) {
593 $columns[$metacolumn->name] = $ord;
594 }
595 }
596
597 $rows = array();
598
599 while (($data = fgetcsv($handle, 4096)) !== false) {
600 $item = new stdClass;
601 foreach($columns as $name => $ord) {
602 $item->$name = $data[$ord];
603 }
604 $rows[] = $item;
605 }
606
607 fclose($handle);
608 return $rows;
609}
610
a77b98eb 611function put_records_csv($file, $records, $table = NULL) {
612 global $CFG, $db;
613
a1e93da2 614 if (empty($records)) {
a77b98eb 615 return true;
616 }
617
618 $metacolumns = NULL;
619 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
620 return false;
621 }
622
a1e93da2 623 echo "x";
624
a77b98eb 625 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
626 error('put_records_csv failed to open '.$file);
627 }
628
a43b5308 629 $proto = reset($records);
630 if(is_object($proto)) {
631 $fields_records = array_keys(get_object_vars($proto));
632 }
633 else if(is_array($proto)) {
634 $fields_records = array_keys($proto);
635 }
636 else {
637 return false;
638 }
a1e93da2 639 echo "x";
a77b98eb 640
641 if(!empty($metacolumns)) {
642 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
643 $fields = array_intersect($fields_records, $fields_table);
644 }
645 else {
646 $fields = $fields_records;
647 }
648
649 fwrite($fp, implode(',', $fields));
650 fwrite($fp, "\r\n");
651
652 foreach($records as $record) {
a43b5308 653 $array = (array)$record;
a77b98eb 654 $values = array();
655 foreach($fields as $field) {
a43b5308 656 if(strpos($array[$field], ',')) {
657 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 658 }
659 else {
a43b5308 660 $values[] = $array[$field];
a77b98eb 661 }
662 }
663 fwrite($fp, implode(',', $values)."\r\n");
664 }
665
666 fclose($fp);
667 return true;
668}
669
f401cc97 670
34763a79 671/**
76ca1ff1 672 * Recursively delete the file or folder with path $location. That is,
34763a79 673 * if it is a file delete it. If it is a folder, delete all its content
76ca1ff1 674 * then delete it. If $location does not exist to start, that is not
675 * considered an error.
676 *
34763a79 677 * @param $location the path to remove.
678 */
4c8c65ec 679function fulldelete($location) {
f401cc97 680 if (is_dir($location)) {
681 $currdir = opendir($location);
682 while (false !== ($file = readdir($currdir))) {
683 if ($file <> ".." && $file <> ".") {
684 $fullfile = $location."/".$file;
4c8c65ec 685 if (is_dir($fullfile)) {
f401cc97 686 if (!fulldelete($fullfile)) {
687 return false;
688 }
689 } else {
690 if (!unlink($fullfile)) {
691 return false;
692 }
4c8c65ec 693 }
f401cc97 694 }
4c8c65ec 695 }
f401cc97 696 closedir($currdir);
697 if (! rmdir($location)) {
698 return false;
699 }
700
34763a79 701 } else if (file_exists($location)) {
f401cc97 702 if (!unlink($location)) {
703 return false;
704 }
705 }
706 return true;
707}
708
4c8c65ec 709/**
710 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
711 */
712function readfile_chunked($filename, $retbytes=true) {
713 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 714 $buffer = '';
76ca1ff1 715 $cnt =0;
69faecce 716 $handle = fopen($filename, 'rb');
717 if ($handle === false) {
718 return false;
719 }
20371063 720
69faecce 721 while (!feof($handle)) {
68913aec 722 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 723 $buffer = fread($handle, $chunksize);
724 echo $buffer;
20371063 725 flush();
69faecce 726 if ($retbytes) {
4c8c65ec 727 $cnt += strlen($buffer);
728 }
69faecce 729 }
730 $status = fclose($handle);
731 if ($retbytes && $status) {
732 return $cnt; // return num. bytes delivered like readfile() does.
733 }
734 return $status;
735}
736
4c8c65ec 737/**
738 * Send requested byterange of file.
739 */
740function byteserving_send_file($filename, $mimetype, $ranges) {
741 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
742 $handle = fopen($filename, 'rb');
743 if ($handle === false) {
744 die;
745 }
746 if (count($ranges) == 1) { //only one range requested
747 $length = $ranges[0][2] - $ranges[0][1] + 1;
748 @header('HTTP/1.1 206 Partial content');
749 @header('Content-Length: '.$length);
750 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
751 @header('Content-Type: '.$mimetype);
752 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
753 $buffer = '';
754 fseek($handle, $ranges[0][1]);
755 while (!feof($handle) && $length > 0) {
68913aec 756 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 757 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
758 echo $buffer;
759 flush();
760 $length -= strlen($buffer);
761 }
762 fclose($handle);
763 die;
764 } else { // multiple ranges requested - not tested much
765 $totallength = 0;
766 foreach($ranges as $range) {
aba588a7 767 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 768 }
aba588a7 769 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 770 @header('HTTP/1.1 206 Partial content');
771 @header('Content-Length: '.$totallength);
772 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
773 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
774 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
775 foreach($ranges as $range) {
776 $length = $range[2] - $range[1] + 1;
777 echo $range[0];
778 $buffer = '';
779 fseek($handle, $range[1]);
780 while (!feof($handle) && $length > 0) {
68913aec 781 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 782 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
783 echo $buffer;
784 flush();
785 $length -= strlen($buffer);
786 }
787 }
788 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
789 fclose($handle);
790 die;
791 }
792}
f401cc97 793
3ace5ee4 794/**
795 * add includes (js and css) into uploaded files
796 * before returning them, useful for themes and utf.js includes
797 * @param string text - text to search and replace
798 * @return string - text with added head includes
799 */
800function file_modify_html_header($text) {
801 // first look for <head> tag
802 global $CFG;
76ca1ff1 803
3ace5ee4 804 $stylesheetshtml = '';
805 foreach ($CFG->stylesheets as $stylesheet) {
806 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 807 }
808
3ace5ee4 809 $filters = explode(",", $CFG->textfilters);
810 if (in_array('filter/mediaplugin', $filters)) {
76ca1ff1 811 // this script is needed by most media filter plugins.
812 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
3ace5ee4 813 } else {
76ca1ff1 814 $ufo = '';
3ace5ee4 815 }
76ca1ff1 816
3ace5ee4 817 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
818 if ($matches) {
819 $replacement = '<head>'.$ufo.$stylesheetshtml;
820 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 821 return $text;
3ace5ee4 822 }
76ca1ff1 823
3ace5ee4 824 // if not, look for <html> tag, and stick <head> right after
825 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
826 if ($matches) {
827 // replace <html> tag with <html><head>includes</head>
13534ef7 828 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 829 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 830 return $text;
3ace5ee4 831 }
76ca1ff1 832
3ace5ee4 833 // if not, look for <body> tag, and stick <head> before body
834 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
835 if ($matches) {
13534ef7 836 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 837 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 838 return $text;
839 }
840
3ace5ee4 841 // if not, just stick a <head> tag at the beginning
842 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
843 return $text;
844}
845
a77b98eb 846?>