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