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