Fixed small glitch in admin->users->permissions->define roles page, where the manage...
[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));
60f9e36e 386 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 387 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
388 //cookieless mode - rewrite links
389 $output = sid_ob_rewrite($output);
390 }
f1e0649c 391
4c8c65ec 392 @header('Content-Length: '.strlen($output));
393 @header('Content-Type: text/html');
394 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 395 echo $output;
b9709b76 396 // only filter text if filter all files is selected
397 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 398 $options = new object();
f1e0649c 399 $options->newlines = false;
400 $options->noclean = true;
401 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 402 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 403 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
404 //cookieless mode - rewrite links
405 $output = sid_ob_rewrite($output);
406 }
f1e0649c 407
4c8c65ec 408 @header('Content-Length: '.strlen($output));
810944af 409 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 410 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 411 echo $output;
412 } else { // Just send it out raw
4c8c65ec 413 @header('Content-Length: '.$filesize);
414 @header('Content-Type: '.$mimetype);
415 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 416 if ($pathisstring) {
417 echo $path;
418 }else {
69faecce 419 readfile_chunked($path);
f1e0649c 420 }
421 }
422 }
423 die; //no more chars to output!!!
424}
425
a43b5308 426function get_records_csv($file, $table) {
599f38f9 427 global $CFG, $db;
428
429 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
430 return false;
431 }
432
a77b98eb 433 if(!($handle = @fopen($file, 'r'))) {
599f38f9 434 error('get_records_csv failed to open '.$file);
435 }
436
437 $fieldnames = fgetcsv($handle, 4096);
438 if(empty($fieldnames)) {
439 fclose($handle);
440 return false;
441 }
442
443 $columns = array();
444
445 foreach($metacolumns as $metacolumn) {
446 $ord = array_search($metacolumn->name, $fieldnames);
447 if(is_int($ord)) {
448 $columns[$metacolumn->name] = $ord;
449 }
450 }
451
452 $rows = array();
453
454 while (($data = fgetcsv($handle, 4096)) !== false) {
455 $item = new stdClass;
456 foreach($columns as $name => $ord) {
457 $item->$name = $data[$ord];
458 }
459 $rows[] = $item;
460 }
461
462 fclose($handle);
463 return $rows;
464}
465
a77b98eb 466function put_records_csv($file, $records, $table = NULL) {
467 global $CFG, $db;
468
a1e93da2 469 if (empty($records)) {
a77b98eb 470 return true;
471 }
472
473 $metacolumns = NULL;
474 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
475 return false;
476 }
477
a1e93da2 478 echo "x";
479
a77b98eb 480 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
481 error('put_records_csv failed to open '.$file);
482 }
483
a43b5308 484 $proto = reset($records);
485 if(is_object($proto)) {
486 $fields_records = array_keys(get_object_vars($proto));
487 }
488 else if(is_array($proto)) {
489 $fields_records = array_keys($proto);
490 }
491 else {
492 return false;
493 }
a1e93da2 494 echo "x";
a77b98eb 495
496 if(!empty($metacolumns)) {
497 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
498 $fields = array_intersect($fields_records, $fields_table);
499 }
500 else {
501 $fields = $fields_records;
502 }
503
504 fwrite($fp, implode(',', $fields));
505 fwrite($fp, "\r\n");
506
507 foreach($records as $record) {
a43b5308 508 $array = (array)$record;
a77b98eb 509 $values = array();
510 foreach($fields as $field) {
a43b5308 511 if(strpos($array[$field], ',')) {
512 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 513 }
514 else {
a43b5308 515 $values[] = $array[$field];
a77b98eb 516 }
517 }
518 fwrite($fp, implode(',', $values)."\r\n");
519 }
520
521 fclose($fp);
522 return true;
523}
524
f401cc97 525
34763a79 526/**
527 * Recursively delete the file or folder with path $location. That is,
528 * if it is a file delete it. If it is a folder, delete all its content
529 * then delete it. If $location does not exist to start, that is not
530 * considered an error.
531 *
532 * @param $location the path to remove.
533 */
4c8c65ec 534function fulldelete($location) {
f401cc97 535 if (is_dir($location)) {
536 $currdir = opendir($location);
537 while (false !== ($file = readdir($currdir))) {
538 if ($file <> ".." && $file <> ".") {
539 $fullfile = $location."/".$file;
4c8c65ec 540 if (is_dir($fullfile)) {
f401cc97 541 if (!fulldelete($fullfile)) {
542 return false;
543 }
544 } else {
545 if (!unlink($fullfile)) {
546 return false;
547 }
4c8c65ec 548 }
f401cc97 549 }
4c8c65ec 550 }
f401cc97 551 closedir($currdir);
552 if (! rmdir($location)) {
553 return false;
554 }
555
34763a79 556 } else if (file_exists($location)) {
f401cc97 557 if (!unlink($location)) {
558 return false;
559 }
560 }
561 return true;
562}
563
4c8c65ec 564/**
565 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
566 */
567function readfile_chunked($filename, $retbytes=true) {
568 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 569 $buffer = '';
570 $cnt =0;// $handle = fopen($filename, 'rb');
571 $handle = fopen($filename, 'rb');
572 if ($handle === false) {
573 return false;
574 }
20371063 575
69faecce 576 while (!feof($handle)) {
68913aec 577 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 578 $buffer = fread($handle, $chunksize);
579 echo $buffer;
20371063 580 flush();
69faecce 581 if ($retbytes) {
4c8c65ec 582 $cnt += strlen($buffer);
583 }
69faecce 584 }
585 $status = fclose($handle);
586 if ($retbytes && $status) {
587 return $cnt; // return num. bytes delivered like readfile() does.
588 }
589 return $status;
590}
591
4c8c65ec 592/**
593 * Send requested byterange of file.
594 */
595function byteserving_send_file($filename, $mimetype, $ranges) {
596 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
597 $handle = fopen($filename, 'rb');
598 if ($handle === false) {
599 die;
600 }
601 if (count($ranges) == 1) { //only one range requested
602 $length = $ranges[0][2] - $ranges[0][1] + 1;
603 @header('HTTP/1.1 206 Partial content');
604 @header('Content-Length: '.$length);
605 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
606 @header('Content-Type: '.$mimetype);
607 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
608 $buffer = '';
609 fseek($handle, $ranges[0][1]);
610 while (!feof($handle) && $length > 0) {
68913aec 611 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 612 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
613 echo $buffer;
614 flush();
615 $length -= strlen($buffer);
616 }
617 fclose($handle);
618 die;
619 } else { // multiple ranges requested - not tested much
620 $totallength = 0;
621 foreach($ranges as $range) {
aba588a7 622 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 623 }
aba588a7 624 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 625 @header('HTTP/1.1 206 Partial content');
626 @header('Content-Length: '.$totallength);
627 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
628 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
629 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
630 foreach($ranges as $range) {
631 $length = $range[2] - $range[1] + 1;
632 echo $range[0];
633 $buffer = '';
634 fseek($handle, $range[1]);
635 while (!feof($handle) && $length > 0) {
68913aec 636 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 637 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
638 echo $buffer;
639 flush();
640 $length -= strlen($buffer);
641 }
642 }
643 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
644 fclose($handle);
645 die;
646 }
647}
f401cc97 648
a77b98eb 649?>