MDL-9137 Fixing errors in the overview report
[moodle-pu.git] / lib / filelib.php
blob55154261cd26440f0874bd056ae1f8b590b355ff
1 <?php //$Id$
3 require_once($CFG->libdir.'/libcurlemu/libcurlemu.inc.php'); // might be moved to setup.php later
5 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
7 /**
8 * Fetches content of file from Internet (using proxy if defined).
10 * @return mixed false if request failed or content of the file as string if ok.
12 function 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);
23 if(!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
24 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
27 $result = curl_exec($ch);
28 curl_close($ch);
29 return $result;
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.
38 function get_mimetypes_array() {
39 return array (
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'),
48 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
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'),
52 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
53 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
54 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
55 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
56 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
57 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
58 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
59 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
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'),
66 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
67 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
68 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
69 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
70 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
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'),
74 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
75 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
76 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
77 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
78 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
79 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
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'),
83 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
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'),
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'),
92 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
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'),
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'),
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'),
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'),
132 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
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'),
140 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
141 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
142 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
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'),
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'),
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'),
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'),
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')
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
188 function mimeinfo($element, $filename) {
189 static $mimeinfo;
190 $mimeinfo=get_mimetypes_array();
192 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
193 if (isset($mimeinfo[strtolower($match[1])][$element])) {
194 return $mimeinfo[strtolower($match[1])][$element];
195 } else {
196 return $mimeinfo['xxx'][$element]; // By default
198 } else {
199 return $mimeinfo['xxx'][$element]; // By default
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
210 function mimeinfo_from_type($element, $mimetype) {
211 static $mimeinfo;
212 $mimeinfo=get_mimetypes_array();
214 foreach($mimeinfo as $values) {
215 if($values['type']==$mimetype) {
216 if(isset($values[$element])) {
217 return $values[$element];
219 break;
222 return $mimeinfo['xxx'][$element]; // Default
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
232 function 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');
239 if($capitalise) {
240 $result=ucfirst($result);
242 return $result;
245 /**
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
256 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
257 global $CFG, $COURSE;
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));
265 $lastmodified = $pathisstring ? time() : filemtime($path);
266 $filesize = $pathisstring ? strlen($path) : filesize($path);
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
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) {
276 $mimetype = 'application/x-forcedownload';
277 $forcedownload = true;
278 $lifetime = 0;
279 } else {
280 $lifetime = 1; // >0 needed for byteserving
284 //IE compatibiltiy HACK!
285 if (ini_get('zlib.output_compression')) {
286 ini_set('zlib.output_compression', 'Off');
289 //try to disable automatic sid rewrite in cookieless mode
290 @ini_set("session.use_trans_sid", "false");
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');
297 if ($forcedownload) {
298 @header('Content-Disposition: attachment; filename='.$filename);
299 } else {
300 @header('Content-Disposition: inline; filename='.$filename);
303 if ($lifetime > 0) {
304 @header('Cache-Control: max-age='.$lifetime);
305 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
306 @header('Pragma: ');
308 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
310 @header('Accept-Ranges: bytes');
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;
327 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
328 //invalid byte-range ==> ignore header
329 $ranges = false;
330 break;
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";
336 } else {
337 $ranges = false;
339 if ($ranges) {
340 byteserving_send_file($path, $mimetype, $ranges);
343 } else {
344 /// Do not byteserve (disabled, strings, text and html files).
345 @header('Accept-Ranges: none');
347 } else { // Do not cache files in proxies and browsers
348 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
349 @header('Cache-Control: max-age=10');
350 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
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');
354 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
355 @header('Pragma: no-cache');
357 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
360 if (empty($filter)) {
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') {
369 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
370 } else {
371 @header('Content-Type: '.$mimetype);
373 @header('Content-Length: '.$filesize);
374 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
375 if ($pathisstring) {
376 echo $path;
377 } else {
378 readfile_chunked($path);
380 } else { // Try to put the file through filters
381 if ($mimetype == 'text/html') {
382 $options = new object();
383 $options->noclean = true;
384 $options->nocache = true; // temporary workaround for MDL-5136
385 $text = $pathisstring ? $path : implode('', file($path));
386 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
387 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
388 //cookieless mode - rewrite links
389 $output = sid_ob_rewrite($output);
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
395 echo $output;
396 // only filter text if filter all files is selected
397 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
398 $options = new object();
399 $options->newlines = false;
400 $options->noclean = true;
401 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
402 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
403 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
404 //cookieless mode - rewrite links
405 $output = sid_ob_rewrite($output);
408 @header('Content-Length: '.strlen($output));
409 @header('Content-Type: text/html; charset=utf-8'); //add encoding
410 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
411 echo $output;
412 } else { // Just send it out raw
413 @header('Content-Length: '.$filesize);
414 @header('Content-Type: '.$mimetype);
415 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
416 if ($pathisstring) {
417 echo $path;
418 }else {
419 readfile_chunked($path);
423 die; //no more chars to output!!!
426 function get_records_csv($file, $table) {
427 global $CFG, $db;
429 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
430 return false;
433 if(!($handle = @fopen($file, 'r'))) {
434 error('get_records_csv failed to open '.$file);
437 $fieldnames = fgetcsv($handle, 4096);
438 if(empty($fieldnames)) {
439 fclose($handle);
440 return false;
443 $columns = array();
445 foreach($metacolumns as $metacolumn) {
446 $ord = array_search($metacolumn->name, $fieldnames);
447 if(is_int($ord)) {
448 $columns[$metacolumn->name] = $ord;
452 $rows = array();
454 while (($data = fgetcsv($handle, 4096)) !== false) {
455 $item = new stdClass;
456 foreach($columns as $name => $ord) {
457 $item->$name = $data[$ord];
459 $rows[] = $item;
462 fclose($handle);
463 return $rows;
466 function put_records_csv($file, $records, $table = NULL) {
467 global $CFG, $db;
469 if (empty($records)) {
470 return true;
473 $metacolumns = NULL;
474 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
475 return false;
478 echo "x";
480 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
481 error('put_records_csv failed to open '.$file);
484 $proto = reset($records);
485 if(is_object($proto)) {
486 $fields_records = array_keys(get_object_vars($proto));
488 else if(is_array($proto)) {
489 $fields_records = array_keys($proto);
491 else {
492 return false;
494 echo "x";
496 if(!empty($metacolumns)) {
497 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
498 $fields = array_intersect($fields_records, $fields_table);
500 else {
501 $fields = $fields_records;
504 fwrite($fp, implode(',', $fields));
505 fwrite($fp, "\r\n");
507 foreach($records as $record) {
508 $array = (array)$record;
509 $values = array();
510 foreach($fields as $field) {
511 if(strpos($array[$field], ',')) {
512 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
514 else {
515 $values[] = $array[$field];
518 fwrite($fp, implode(',', $values)."\r\n");
521 fclose($fp);
522 return true;
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.
532 * @param $location the path to remove.
534 function fulldelete($location) {
535 if (is_dir($location)) {
536 $currdir = opendir($location);
537 while (false !== ($file = readdir($currdir))) {
538 if ($file <> ".." && $file <> ".") {
539 $fullfile = $location."/".$file;
540 if (is_dir($fullfile)) {
541 if (!fulldelete($fullfile)) {
542 return false;
544 } else {
545 if (!unlink($fullfile)) {
546 return false;
551 closedir($currdir);
552 if (! rmdir($location)) {
553 return false;
556 } else if (file_exists($location)) {
557 if (!unlink($location)) {
558 return false;
561 return true;
565 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
567 function readfile_chunked($filename, $retbytes=true) {
568 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
569 $buffer = '';
570 $cnt =0;// $handle = fopen($filename, 'rb');
571 $handle = fopen($filename, 'rb');
572 if ($handle === false) {
573 return false;
576 while (!feof($handle)) {
577 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
578 $buffer = fread($handle, $chunksize);
579 echo $buffer;
580 flush();
581 if ($retbytes) {
582 $cnt += strlen($buffer);
585 $status = fclose($handle);
586 if ($retbytes && $status) {
587 return $cnt; // return num. bytes delivered like readfile() does.
589 return $status;
593 * Send requested byterange of file.
595 function 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;
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) {
611 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
612 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
613 echo $buffer;
614 flush();
615 $length -= strlen($buffer);
617 fclose($handle);
618 die;
619 } else { // multiple ranges requested - not tested much
620 $totallength = 0;
621 foreach($ranges as $range) {
622 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
624 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
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) {
636 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
637 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
638 echo $buffer;
639 flush();
640 $length -= strlen($buffer);
643 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
644 fclose($handle);
645 die;