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