Dan's fix from MDL-7263
[moodle.git] / lib / filelib.php
blobb5d02b556dfabcf8d347015d89e2bf075aa5c212
1 <?php //$Id$
3 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
5 /**
6 * @return List of information about file types based on extensions.
7 * Associative array of extension (lower-case) to associative array
8 * from 'element name' to data. Current element names are 'type' and 'icon'.
9 * Unknown types should use the 'xxx' entry which includes defaults.
11 function get_mimetypes_array() {
12 return array (
13 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
14 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
15 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
16 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
17 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
18 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
19 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
20 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
21 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
22 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
23 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
24 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
25 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
26 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
27 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
28 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
29 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
30 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
31 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
32 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
33 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
34 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
35 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
36 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
37 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
38 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
39 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
40 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
41 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
42 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
43 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
44 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
45 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
46 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
47 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
48 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
49 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
50 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
51 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
52 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
53 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
54 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
55 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
56 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
57 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
58 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
59 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
60 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
61 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
62 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
63 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
64 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
65 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
66 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
67 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
68 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
70 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
71 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
72 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
73 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odt.gif'),
74 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odt.gif'),
75 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odt.gif'),
76 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odt.gif'),
77 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odt.gif'),
78 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'odt.gif'),
79 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'odt.gif'),
80 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odt.gif'),
81 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odt.gif'),
82 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odt.gif'),
83 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odt.gif'),
85 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
86 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
87 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
88 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
89 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
90 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
91 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
92 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
93 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
94 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
95 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
96 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
97 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
98 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
99 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
100 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
101 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
102 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
103 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
104 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
105 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
106 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
107 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
108 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
109 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
110 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
112 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
113 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
114 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
115 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
116 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
117 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
118 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
119 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
120 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
121 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
123 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
124 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
125 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
126 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
127 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
128 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
129 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
130 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
131 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
132 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
133 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
134 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
135 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
136 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
137 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
141 /**
142 * Obtains information about a filetype based on its extension. Will
143 * use a default if no information is present about that particular
144 * extension.
145 * @param string $element Desired information (usually 'icon'
146 * for icon filename or 'type' for MIME type)
147 * @param string $filename Filename we're looking up
148 * @return string Requested piece of information from array
150 function mimeinfo($element, $filename) {
151 static $mimeinfo;
152 $mimeinfo=get_mimetypes_array();
154 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
155 if (isset($mimeinfo[strtolower($match[1])][$element])) {
156 return $mimeinfo[strtolower($match[1])][$element];
157 } else {
158 return $mimeinfo['xxx'][$element]; // By default
160 } else {
161 return $mimeinfo['xxx'][$element]; // By default
165 /**
166 * Obtains information about a filetype based on the MIME type rather than
167 * the other way around.
168 * @param string $element Desired information (usually 'icon')
169 * @param string $mimetype MIME type we're looking up
170 * @return string Requested piece of information from array
172 function mimeinfo_from_type($element, $mimetype) {
173 static $mimeinfo;
174 $mimeinfo=get_mimetypes_array();
176 foreach($mimeinfo as $values) {
177 if($values['type']==$mimetype) {
178 if(isset($values[$element])) {
179 return $values[$element];
181 break;
184 return $mimeinfo['xxx'][$element]; // Default
188 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
189 * mimetypes.php language file.
190 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
191 * @param bool $capitalise If true, capitalises first character of result
192 * @return string Text description
194 function get_mimetype_description($mimetype,$capitalise=false) {
195 $result=get_string($mimetype,'mimetypes');
196 // Surrounded by square brackets indicates that there isn't a string for that
197 // (maybe there is a better way to find this out?)
198 if(strpos($result,'[')===0) {
199 $result=get_string('document/unknown','mimetypes');
201 if($capitalise) {
202 $result=ucfirst($result);
204 return $result;
207 /**
208 * Handles the sending of file data to the user's browser, including support for
209 * byteranges etc.
210 * @param string $path Path of file on disk (including real filename), or actual content of file as string
211 * @param string $filename Filename to send
212 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
213 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
214 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
215 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
216 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
218 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
219 global $CFG;
221 // Use given MIME type if specified, otherwise guess it using mimeinfo.
222 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
223 // only Firefox saves all files locally before opening when content-disposition: attachment stated
224 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
225 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
226 ($mimetype ? $mimetype : mimeinfo('type', $filename));
227 $lastmodified = $pathisstring ? time() : filemtime($path);
228 $filesize = $pathisstring ? strlen($path) : filesize($path);
230 //IE compatibiltiy HACK!
231 if (ini_get('zlib.output_compression')) {
232 ini_set('zlib.output_compression', 'Off');
235 //try to disable automatic sid rewrite in cookieless mode
236 @ini_set("session.use_trans_sid", "false");
238 //do not put '@' before the next header to detect incorrect moodle configurations,
239 //error should be better than "weird" empty lines for admins/users
240 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
241 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
243 if ($forcedownload) {
244 @header('Content-Disposition: attachment; filename='.$filename);
245 } else {
246 @header('Content-Disposition: inline; filename='.$filename);
249 if ($lifetime > 0) {
250 @header('Cache-Control: max-age='.$lifetime);
251 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
252 @header('Pragma: ');
254 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
256 @header('Accept-Ranges: bytes');
258 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
259 // byteserving stuff - for acrobat reader and download accelerators
260 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
261 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
262 $ranges = false;
263 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
264 foreach ($ranges as $key=>$value) {
265 if ($ranges[$key][1] == '') {
266 //suffix case
267 $ranges[$key][1] = $filesize - $ranges[$key][2];
268 $ranges[$key][2] = $filesize - 1;
269 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
270 //fix range length
271 $ranges[$key][2] = $filesize - 1;
273 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
274 //invalid byte-range ==> ignore header
275 $ranges = false;
276 break;
278 //prepare multipart header
279 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
280 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
282 } else {
283 $ranges = false;
285 if ($ranges) {
286 byteserving_send_file($path, $mimetype, $ranges);
289 } else {
290 /// Do not byteserve (disabled, strings, text and html files).
291 @header('Accept-Ranges: none');
293 } else { // Do not cache files in proxies and browsers
294 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
295 @header('Cache-Control: max-age=10');
296 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
297 @header('Pragma: ');
298 } else { //normal http - prevent caching at all cost
299 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
300 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
301 @header('Pragma: no-cache');
303 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
306 if (empty($filter)) {
307 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
308 //cookieless mode - rewrite links
309 @header('Content-Type: text/html');
310 $path = $pathisstring ? $path : implode('', file($path));
311 $path = sid_ob_rewrite($path);
312 $filesize = strlen($path);
313 $pathisstring = true;
314 } else if ($mimetype == 'text/plain') {
315 @header('Content-Type: Text/plain; charset='.current_charset()); //add encoding
316 } else {
317 @header('Content-Type: '.$mimetype);
319 @header('Content-Length: '.$filesize);
320 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
321 if ($pathisstring) {
322 echo $path;
323 } else {
324 readfile_chunked($path);
326 } else { // Try to put the file through filters
327 global $course; // HACK!
328 if (!empty($course->id)) {
329 $courseid = $course->id;
330 } else {
331 $courseid = SITEID;
333 if ($mimetype == 'text/html') {
334 $options = new object();
335 $options->noclean = true;
336 $options->nocache = true; // temporary workaround for MDL-5136
337 $text = $pathisstring ? $path : implode('', file($path));
338 $output = format_text($text, FORMAT_HTML, $options, $courseid);
339 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
340 //cookieless mode - rewrite links
341 $output = sid_ob_rewrite($output);
344 @header('Content-Length: '.strlen($output));
345 @header('Content-Type: text/html');
346 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
347 echo $output;
348 // only filter text if filter all files is selected
349 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
350 $options->newlines = false;
351 $options->noclean = true;
352 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
353 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $courseid) .'</pre>';
354 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
355 //cookieless mode - rewrite links
356 $output = sid_ob_rewrite($output);
359 @header('Content-Length: '.strlen($output));
360 @header('Content-Type: text/html; charset='.current_charset()); //add encoding
361 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
362 echo $output;
363 } else { // Just send it out raw
364 @header('Content-Length: '.$filesize);
365 @header('Content-Type: '.$mimetype);
366 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
367 if ($pathisstring) {
368 echo $path;
369 }else {
370 readfile_chunked($path);
374 die; //no more chars to output!!!
377 function get_records_csv($file, $table) {
378 global $CFG, $db;
380 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
381 return false;
384 if(!($handle = @fopen($file, 'r'))) {
385 error('get_records_csv failed to open '.$file);
388 $fieldnames = fgetcsv($handle, 4096);
389 if(empty($fieldnames)) {
390 fclose($handle);
391 return false;
394 $columns = array();
396 foreach($metacolumns as $metacolumn) {
397 $ord = array_search($metacolumn->name, $fieldnames);
398 if(is_int($ord)) {
399 $columns[$metacolumn->name] = $ord;
403 $rows = array();
405 while (($data = fgetcsv($handle, 4096)) !== false) {
406 $item = new stdClass;
407 foreach($columns as $name => $ord) {
408 $item->$name = $data[$ord];
410 $rows[] = $item;
413 fclose($handle);
414 return $rows;
417 function put_records_csv($file, $records, $table = NULL) {
418 global $CFG, $db;
420 if (empty($records)) {
421 return true;
424 $metacolumns = NULL;
425 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
426 return false;
429 echo "x";
431 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
432 error('put_records_csv failed to open '.$file);
435 $proto = reset($records);
436 if(is_object($proto)) {
437 $fields_records = array_keys(get_object_vars($proto));
439 else if(is_array($proto)) {
440 $fields_records = array_keys($proto);
442 else {
443 return false;
445 echo "x";
447 if(!empty($metacolumns)) {
448 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
449 $fields = array_intersect($fields_records, $fields_table);
451 else {
452 $fields = $fields_records;
455 fwrite($fp, implode(',', $fields));
456 fwrite($fp, "\r\n");
458 foreach($records as $record) {
459 $array = (array)$record;
460 $values = array();
461 foreach($fields as $field) {
462 if(strpos($array[$field], ',')) {
463 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
465 else {
466 $values[] = $array[$field];
469 fwrite($fp, implode(',', $values)."\r\n");
472 fclose($fp);
473 return true;
477 if (!function_exists('file_get_contents')) {
478 function file_get_contents($file) {
479 $file = file($file);
480 return !$file ? false : implode('', $file);
486 * Recursively delete the file or folder with path $location. That is,
487 * if it is a file delete it. If it is a folder, delete all its content
488 * then delete it. If $location does not exist to start, that is not
489 * considered an error.
491 * @param $location the path to remove.
493 function fulldelete($location) {
494 if (is_dir($location)) {
495 $currdir = opendir($location);
496 while (false !== ($file = readdir($currdir))) {
497 if ($file <> ".." && $file <> ".") {
498 $fullfile = $location."/".$file;
499 if (is_dir($fullfile)) {
500 if (!fulldelete($fullfile)) {
501 return false;
503 } else {
504 if (!unlink($fullfile)) {
505 return false;
510 closedir($currdir);
511 if (! rmdir($location)) {
512 return false;
515 } else if (file_exists($location)) {
516 if (!unlink($location)) {
517 return false;
520 return true;
524 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
526 function readfile_chunked($filename, $retbytes=true) {
527 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
528 $buffer = '';
529 $cnt =0;// $handle = fopen($filename, 'rb');
530 $handle = fopen($filename, 'rb');
531 if ($handle === false) {
532 return false;
535 while (!feof($handle)) {
536 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
537 $buffer = fread($handle, $chunksize);
538 echo $buffer;
539 flush();
540 if ($retbytes) {
541 $cnt += strlen($buffer);
544 $status = fclose($handle);
545 if ($retbytes && $status) {
546 return $cnt; // return num. bytes delivered like readfile() does.
548 return $status;
552 * Send requested byterange of file.
554 function byteserving_send_file($filename, $mimetype, $ranges) {
555 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
556 $handle = fopen($filename, 'rb');
557 if ($handle === false) {
558 die;
560 if (count($ranges) == 1) { //only one range requested
561 $length = $ranges[0][2] - $ranges[0][1] + 1;
562 @header('HTTP/1.1 206 Partial content');
563 @header('Content-Length: '.$length);
564 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
565 @header('Content-Type: '.$mimetype);
566 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
567 $buffer = '';
568 fseek($handle, $ranges[0][1]);
569 while (!feof($handle) && $length > 0) {
570 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
571 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
572 echo $buffer;
573 flush();
574 $length -= strlen($buffer);
576 fclose($handle);
577 die;
578 } else { // multiple ranges requested - not tested much
579 $totallength = 0;
580 foreach($ranges as $range) {
581 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
583 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
584 @header('HTTP/1.1 206 Partial content');
585 @header('Content-Length: '.$totallength);
586 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
587 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
588 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
589 foreach($ranges as $range) {
590 $length = $range[2] - $range[1] + 1;
591 echo $range[0];
592 $buffer = '';
593 fseek($handle, $range[1]);
594 while (!feof($handle) && $length > 0) {
595 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
596 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
597 echo $buffer;
598 flush();
599 $length -= strlen($buffer);
602 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
603 fclose($handle);
604 die;