xref: /dokuwiki/inc/io.php (revision ba8f83490b45737d4cf33484c72b3aaa21e8894d)
1<?php
2/**
3 * File IO functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8use dokuwiki\Utf8\PhpString;
9use dokuwiki\HTTP\DokuHTTPClient;
10use dokuwiki\Extension\Event;
11
12/**
13 * Removes empty directories
14 *
15 * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
16 * Event data:
17 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
18 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
19 *
20 * @param string $id      - a pageid, the namespace of that id will be tried to deleted
21 * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
22 * @return bool - true if at least one namespace was deleted
23 *
24 * @author  Andreas Gohr <andi@splitbrain.org>
25 * @author Ben Coburn <btcoburn@silicodon.net>
26 */
27function io_sweepNS($id, $basedir = 'datadir')
28{
29    global $conf;
30    $types = ['datadir'=>'pages', 'mediadir'=>'media'];
31    $ns_type = ($types[$basedir] ?? false);
32
33    $delone = false;
34
35    //scan all namespaces
36    while(($id = getNS($id)) !== false){
37        $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':', '/', $id));
38
39        //try to delete dir else return
40        if(@rmdir($dir)) {
41            if ($ns_type!==false) {
42                $data = [$id, $ns_type];
43                $delone = true; // we deleted at least one dir
44                Event::createAndTrigger('IO_NAMESPACE_DELETED', $data);
45            }
46        } else { return $delone; }
47    }
48    return $delone;
49}
50
51/**
52 * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
53 *
54 * Generates the action event which delegates to io_readFile().
55 * Action plugins are allowed to modify the page content in transit.
56 * The file path should not be changed.
57 *
58 * Event data:
59 * $data[0]    The raw arguments for io_readFile as an array.
60 * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
61 * $data[2]    page_name: The wiki page name.
62 * $data[3]    rev: The page revision, false for current wiki pages.
63 *
64 * @author Ben Coburn <btcoburn@silicodon.net>
65 *
66 * @param string   $file filename
67 * @param string   $id page id
68 * @param bool|int $rev revision timestamp
69 * @return string
70 */
71function io_readWikiPage($file, $id, $rev = false)
72{
73    if (empty($rev)) { $rev = false; }
74    $data = [[$file, true], getNS($id), noNS($id), $rev];
75    return Event::createAndTrigger('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
76}
77
78/**
79 * Callback adapter for io_readFile().
80 *
81 * @author Ben Coburn <btcoburn@silicodon.net>
82 *
83 * @param array $data event data
84 * @return string
85 */
86function _io_readWikiPage_action($data)
87{
88    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
89        return io_readFile(...$data[0]);
90    } else {
91        return ''; //callback error
92    }
93}
94
95/**
96 * Returns content of $file as cleaned string.
97 *
98 * Uses gzip if extension is .gz
99 *
100 * If you want to use the returned value in unserialize
101 * be sure to set $clean to false!
102 *
103 * @author  Andreas Gohr <andi@splitbrain.org>
104 *
105 * @param string $file  filename
106 * @param bool   $clean
107 * @return string|bool the file contents or false on error
108 */
109function io_readFile($file, $clean = true)
110{
111    $ret = '';
112    if(file_exists($file)){
113        if (substr($file, -3) == '.gz') {
114            if(!DOKU_HAS_GZIP) return false;
115            $ret = gzfile($file);
116            if(is_array($ret)) $ret = implode('', $ret);
117        } elseif (substr($file, -4) == '.bz2') {
118            if(!DOKU_HAS_BZIP) return false;
119            $ret = bzfile($file);
120        } else{
121            $ret = file_get_contents($file);
122        }
123    }
124    if($ret === null) return false;
125    if($ret !== false && $clean){
126        return cleanText($ret);
127    }else{
128        return $ret;
129    }
130}
131/**
132 * Returns the content of a .bz2 compressed file as string
133 *
134 * @author marcel senf <marcel@rucksackreinigung.de>
135 * @author  Andreas Gohr <andi@splitbrain.org>
136 *
137 * @param string $file filename
138 * @param bool   $array return array of lines
139 * @return string|array|bool content or false on error
140 */
141function bzfile($file, $array = false)
142{
143    $bz = bzopen($file, "r");
144    if($bz === false) return false;
145
146    if($array) $lines = [];
147    $str = '';
148    while (!feof($bz)) {
149        //8192 seems to be the maximum buffersize?
150        $buffer = bzread($bz, 8192);
151        if(($buffer === false) || (bzerrno($bz) !== 0)) {
152            return false;
153        }
154        $str .= $buffer;
155        if($array) {
156            $pos = strpos($str, "\n");
157            while($pos !== false) {
158                $lines[] = substr($str, 0, $pos+1);
159                $str = substr($str, $pos+1);
160                $pos = strpos($str, "\n");
161            }
162        }
163    }
164    bzclose($bz);
165    if($array) {
166        if($str !== '') $lines[] = $str;
167        return $lines;
168    }
169    return $str;
170}
171
172/**
173 * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
174 *
175 * This generates an action event and delegates to io_saveFile().
176 * Action plugins are allowed to modify the page content in transit.
177 * The file path should not be changed.
178 * (The append parameter is set to false.)
179 *
180 * Event data:
181 * $data[0]    The raw arguments for io_saveFile as an array.
182 * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
183 * $data[2]    page_name: The wiki page name.
184 * $data[3]    rev: The page revision, false for current wiki pages.
185 *
186 * @author Ben Coburn <btcoburn@silicodon.net>
187 *
188 * @param string $file      filename
189 * @param string $content
190 * @param string $id        page id
191 * @param int|bool $rev timestamp of revision
192 * @return bool
193 */
194function io_writeWikiPage($file, $content, $id, $rev = false)
195{
196    if (empty($rev)) { $rev = false; }
197    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
198    $data = [[$file, $content, false], getNS($id), noNS($id), $rev];
199    return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
200}
201
202/**
203 * Callback adapter for io_saveFile().
204 * @author Ben Coburn <btcoburn@silicodon.net>
205 *
206 * @param array $data event data
207 * @return bool
208 */
209function _io_writeWikiPage_action($data)
210{
211    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
212        $ok = io_saveFile(...$data[0]);
213        // for attic files make sure the file has the mtime of the revision
214        if($ok && is_int($data[3]) && $data[3] > 0) {
215            @touch($data[0][0], $data[3]);
216        }
217        return $ok;
218    } else {
219        return false; //callback error
220    }
221}
222
223/**
224 * Internal function to save contents to a file.
225 *
226 * @author  Andreas Gohr <andi@splitbrain.org>
227 *
228 * @param string $file filename path to file
229 * @param string $content
230 * @param bool   $append
231 * @return bool true on success, otherwise false
232 */
233function _io_saveFile($file, $content, $append)
234{
235    global $conf;
236    $mode = ($append) ? 'ab' : 'wb';
237    $fileexists = file_exists($file);
238
239    if (substr($file, -3) == '.gz') {
240        if(!DOKU_HAS_GZIP) return false;
241        $fh = @gzopen($file, $mode.'9');
242        if(!$fh) return false;
243        gzwrite($fh, $content);
244        gzclose($fh);
245    } elseif (substr($file, -4) == '.bz2') {
246        if(!DOKU_HAS_BZIP) return false;
247        if($append) {
248            $bzcontent = bzfile($file);
249            if($bzcontent === false) return false;
250            $content = $bzcontent.$content;
251        }
252        $fh = @bzopen($file, 'w');
253        if(!$fh) return false;
254        bzwrite($fh, $content);
255        bzclose($fh);
256    } else{
257        $fh = @fopen($file, $mode);
258        if(!$fh) return false;
259        fwrite($fh, $content);
260        fclose($fh);
261    }
262
263    if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
264    return true;
265}
266
267/**
268 * Saves $content to $file.
269 *
270 * If the third parameter is set to true the given content
271 * will be appended.
272 *
273 * Uses gzip if extension is .gz
274 * and bz2 if extension is .bz2
275 *
276 * @author  Andreas Gohr <andi@splitbrain.org>
277 *
278 * @param string $file filename path to file
279 * @param string $content
280 * @param bool   $append
281 * @return bool true on success, otherwise false
282 */
283function io_saveFile($file, $content, $append = false)
284{
285    io_makeFileDir($file);
286    io_lock($file);
287    if(!_io_saveFile($file, $content, $append)) {
288        msg("Writing $file failed", -1);
289        io_unlock($file);
290        return false;
291    }
292    io_unlock($file);
293    return true;
294}
295
296/**
297 * Replace one or more occurrences of a line in a file.
298 *
299 * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
300 * A regex that matches any part of the line will remove the entire line in this mode.
301 * Captures in $newline are not available.
302 *
303 * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
304 * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
305 *
306 * Be sure to include the trailing newline in $oldline when replacing entire lines.
307 *
308 * Uses gzip if extension is .gz
309 * and bz2 if extension is .bz2
310 *
311 * @author Steven Danz <steven-danz@kc.rr.com>
312 * @author Christopher Smith <chris@jalakai.co.uk>
313 * @author Patrick Brown <ptbrown@whoopdedo.org>
314 *
315 * @param string $file     filename
316 * @param string $oldline  exact linematch to remove
317 * @param string $newline  new line to insert
318 * @param bool   $regex    use regexp?
319 * @param int    $maxlines number of occurrences of the line to replace
320 * @return bool true on success
321 */
322function io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines = 0)
323{
324    if ((string)$oldline === '') {
325        trigger_error('$oldline parameter cannot be empty in io_replaceInFile()', E_USER_WARNING);
326        return false;
327    }
328
329    if (!file_exists($file)) return true;
330
331    io_lock($file);
332
333    // load into array
334    if (substr($file, -3) == '.gz') {
335        if(!DOKU_HAS_GZIP) return false;
336        $lines = gzfile($file);
337    } elseif (substr($file, -4) == '.bz2') {
338        if(!DOKU_HAS_BZIP) return false;
339        $lines = bzfile($file, true);
340    } else{
341        $lines = file($file);
342    }
343
344    // make non-regexes into regexes
345    $pattern = $regex ? $oldline : '/^'.preg_quote($oldline, '/').'$/';
346    $replace = $regex ? $newline : addcslashes($newline, '\$');
347
348    // remove matching lines
349    if ($maxlines > 0) {
350        $count = 0;
351        $matched = 0;
352        foreach($lines as $i => $line) {
353            if($count >= $maxlines) break;
354            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
355            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
356            if ($matched) $count++;
357        }
358    } elseif ($maxlines == 0) {
359        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
360        if ((string)$newline !== ''){
361            $lines[] = $newline;
362        }
363    } else {
364        $lines = preg_replace($pattern, $replace, $lines);
365    }
366
367    if(count($lines)){
368        if(!_io_saveFile($file, implode('', $lines), false)) {
369            msg("Removing content from $file failed", -1);
370            io_unlock($file);
371            return false;
372        }
373    }else{
374        @unlink($file);
375    }
376
377    io_unlock($file);
378    return true;
379}
380
381/**
382 * Delete lines that match $badline from $file.
383 *
384 * Be sure to include the trailing newline in $badline
385 *
386 * @author Patrick Brown <ptbrown@whoopdedo.org>
387 *
388 * @param string $file    filename
389 * @param string $badline exact linematch to remove
390 * @param bool   $regex   use regexp?
391 * @return bool true on success
392 */
393function io_deleteFromFile($file, $badline, $regex = false)
394{
395    return io_replaceInFile($file, $badline, null, $regex, 0);
396}
397
398/**
399 * Tries to lock a file
400 *
401 * Locking is only done for io_savefile and uses directories
402 * inside $conf['lockdir']
403 *
404 * It waits maximal 3 seconds for the lock, after this time
405 * the lock is assumed to be stale and the function goes on
406 *
407 * @author Andreas Gohr <andi@splitbrain.org>
408 *
409 * @param string $file filename
410 */
411function io_lock($file)
412{
413    global $conf;
414
415    $lockDir = $conf['lockdir'].'/'.md5($file);
416    @ignore_user_abort(1);
417
418    $timeStart = time();
419    do {
420        //waited longer than 3 seconds? -> stale lock
421        if ((time() - $timeStart) > 3) break;
422        $locked = @mkdir($lockDir);
423        if($locked){
424            if($conf['dperm']) chmod($lockDir, $conf['dperm']);
425            break;
426        }
427        usleep(50);
428    } while ($locked === false);
429}
430
431/**
432 * Unlocks a file
433 *
434 * @author Andreas Gohr <andi@splitbrain.org>
435 *
436 * @param string $file filename
437 */
438function io_unlock($file)
439{
440    global $conf;
441
442    $lockDir = $conf['lockdir'].'/'.md5($file);
443    @rmdir($lockDir);
444    @ignore_user_abort(0);
445}
446
447/**
448 * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
449 * in the order of directory creation. (Parent directories first.)
450 *
451 * Event data:
452 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
453 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
454 *
455 * @author Ben Coburn <btcoburn@silicodon.net>
456 *
457 * @param string $id page id
458 * @param string $ns_type 'pages' or 'media'
459 */
460function io_createNamespace($id, $ns_type = 'pages')
461{
462    // verify ns_type
463    $types = ['pages'=>'wikiFN', 'media'=>'mediaFN'];
464    if (!isset($types[$ns_type])) {
465        trigger_error('Bad $ns_type parameter for io_createNamespace().');
466        return;
467    }
468    // make event list
469    $missing = [];
470    $ns_stack = explode(':', $id);
471    $ns = $id;
472    $tmp = dirname($file = call_user_func($types[$ns_type], $ns));
473    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
474        array_pop($ns_stack);
475        $ns = implode(':', $ns_stack);
476        if (strlen($ns)==0) { break; }
477        $missing[] = $ns;
478        $tmp = dirname(call_user_func($types[$ns_type], $ns));
479    }
480    // make directories
481    io_makeFileDir($file);
482    // send the events
483    $missing = array_reverse($missing); // inside out
484    foreach ($missing as $ns) {
485        $data = [$ns, $ns_type];
486        Event::createAndTrigger('IO_NAMESPACE_CREATED', $data);
487    }
488}
489
490/**
491 * Create the directory needed for the given file
492 *
493 * @author  Andreas Gohr <andi@splitbrain.org>
494 *
495 * @param string $file file name
496 */
497function io_makeFileDir($file)
498{
499    $dir = dirname($file);
500    if(!@is_dir($dir)){
501        io_mkdir_p($dir) || msg("Creating directory $dir failed", -1);
502    }
503}
504
505/**
506 * Creates a directory hierachy.
507 *
508 * @link    http://php.net/manual/en/function.mkdir.php
509 * @author  <saint@corenova.com>
510 * @author  Andreas Gohr <andi@splitbrain.org>
511 *
512 * @param string $target filename
513 * @return bool|int|string
514 */
515function io_mkdir_p($target)
516{
517    global $conf;
518    if (@is_dir($target)||empty($target)) return 1; // best case check first
519    if (file_exists($target) && !is_dir($target)) return 0;
520    //recursion
521    if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))){
522        $ret = @mkdir($target); // crawl back up & create dir tree
523        if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
524        return $ret;
525    }
526    return 0;
527}
528
529/**
530 * Recursively delete a directory
531 *
532 * @author Andreas Gohr <andi@splitbrain.org>
533 * @param string $path
534 * @param bool   $removefiles defaults to false which will delete empty directories only
535 * @return bool
536 */
537function io_rmdir($path, $removefiles = false)
538{
539    if(!is_string($path) || $path == "") return false;
540    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
541
542    if (is_dir($path) && !is_link($path)) {
543        $dirs  = [];
544        $files = [];
545        if(!$dh = @opendir($path)) return false;
546        while(false !== ($f = readdir($dh))) {
547            if($f == '..' || $f == '.') continue;
548
549            // collect dirs and files first
550            if (is_dir("$path/$f") && !is_link("$path/$f")) {
551                $dirs[] = "$path/$f";
552            } elseif ($removefiles) {
553                $files[] = "$path/$f";
554            } else {
555                return false; // abort when non empty
556            }
557
558        }
559        closedir($dh);
560        // now traverse into  directories first
561        foreach($dirs as $dir) {
562            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
563        }
564        // now delete files
565        foreach($files as $file) {
566            if(!@unlink($file)) return false; //abort on any error
567        }
568        // remove self
569        return @rmdir($path);
570    } elseif ($removefiles) {
571        return @unlink($path);
572    }
573    return false;
574}
575
576/**
577 * Creates a unique temporary directory and returns
578 * its path.
579 *
580 * @author Michael Klier <chi@chimeric.de>
581 *
582 * @return false|string path to new directory or false
583 */
584function io_mktmpdir()
585{
586    global $conf;
587
588    $base = $conf['tmpdir'];
589    $dir  = md5(uniqid(random_int(0, mt_getrandmax()), true));
590    $tmpdir = $base.'/'.$dir;
591
592    if(io_mkdir_p($tmpdir)) {
593        return($tmpdir);
594    } else {
595        return false;
596    }
597}
598
599/**
600 * downloads a file from the net and saves it
601 *
602 * if $useAttachment is false,
603 * - $file is the full filename to save the file, incl. path
604 * - if successful will return true, false otherwise
605 *
606 * if $useAttachment is true,
607 * - $file is the directory where the file should be saved
608 * - if successful will return the name used for the saved file, false otherwise
609 *
610 * @author Andreas Gohr <andi@splitbrain.org>
611 * @author Chris Smith <chris@jalakai.co.uk>
612 *
613 * @param string $url           url to download
614 * @param string $file          path to file or directory where to save
615 * @param bool   $useAttachment true: try to use name of download, uses otherwise $defaultName
616 *                              false: uses $file as path to file
617 * @param string $defaultName   fallback for if using $useAttachment
618 * @param int    $maxSize       maximum file size
619 * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
620 */
621function io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2_097_152)
622{
623    global $conf;
624    $http = new DokuHTTPClient();
625    $http->max_bodysize = $maxSize;
626    $http->timeout = 25; //max. 25 sec
627    $http->keep_alive = false; // we do single ops here, no need for keep-alive
628
629    $data = $http->get($url);
630    if(!$data) return false;
631
632    $name = '';
633    if ($useAttachment) {
634        if (isset($http->resp_headers['content-disposition'])) {
635            $content_disposition = $http->resp_headers['content-disposition'];
636            $match=[];
637            if (is_string($content_disposition) &&
638                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
639
640                $name = PhpString::basename($match[1]);
641            }
642
643        }
644
645        if (!$name) {
646            if (!$defaultName) return false;
647            $name = $defaultName;
648        }
649
650        $file .= $name;
651    }
652
653    $fileexists = file_exists($file);
654    $fp = @fopen($file, "w");
655    if(!$fp) return false;
656    fwrite($fp, $data);
657    fclose($fp);
658    if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
659    if ($useAttachment) return $name;
660    return true;
661}
662
663/**
664 * Windows compatible rename
665 *
666 * rename() can not overwrite existing files on Windows
667 * this function will use copy/unlink instead
668 *
669 * @param string $from
670 * @param string $to
671 * @return bool succes or fail
672 */
673function io_rename($from, $to)
674{
675    global $conf;
676    if(!@rename($from, $to)){
677        if(@copy($from, $to)){
678            if($conf['fperm']) chmod($to, $conf['fperm']);
679            @unlink($from);
680            return true;
681        }
682        return false;
683    }
684    return true;
685}
686
687/**
688 * Runs an external command with input and output pipes.
689 * Returns the exit code from the process.
690 *
691 * @author Tom N Harris <tnharris@whoopdedo.org>
692 *
693 * @param string $cmd
694 * @param string $input  input pipe
695 * @param string $output output pipe
696 * @return int exit code from process
697 */
698function io_exec($cmd, $input, &$output)
699{
700    $descspec = [
701        0=>["pipe", "r"],
702        1=>["pipe", "w"],
703        2=>["pipe", "w"]
704    ];
705    $ph = proc_open($cmd, $descspec, $pipes);
706    if(!$ph) return -1;
707    fclose($pipes[2]); // ignore stderr
708    fwrite($pipes[0], $input);
709    fclose($pipes[0]);
710    $output = stream_get_contents($pipes[1]);
711    fclose($pipes[1]);
712    return proc_close($ph);
713}
714
715/**
716 * Search a file for matching lines
717 *
718 * This is probably not faster than file()+preg_grep() but less
719 * memory intensive because not the whole file needs to be loaded
720 * at once.
721 *
722 * @author Andreas Gohr <andi@splitbrain.org>
723 * @param  string $file    The file to search
724 * @param  string $pattern PCRE pattern
725 * @param  int    $max     How many lines to return (0 for all)
726 * @param  bool   $backref When true returns array with backreferences instead of lines
727 * @return array matching lines or backref, false on error
728 */
729function io_grep($file, $pattern, $max = 0, $backref = false)
730{
731    $fh = @fopen($file, 'r');
732    if(!$fh) return false;
733    $matches = [];
734
735    $cnt  = 0;
736    $line = '';
737    while (!feof($fh)) {
738        $line .= fgets($fh, 4096);  // read full line
739        if(substr($line, -1) != "\n") continue;
740
741        // check if line matches
742        if(preg_match($pattern, $line, $match)){
743            if($backref){
744                $matches[] = $match;
745            }else{
746                $matches[] = $line;
747            }
748            $cnt++;
749        }
750        if($max && $max == $cnt) break;
751        $line = '';
752    }
753    fclose($fh);
754    return $matches;
755}
756
757
758/**
759 * Get size of contents of a file, for a compressed file the uncompressed size
760 * Warning: reading uncompressed size of content of bz-files requires uncompressing
761 *
762 * @author  Gerrit Uitslag <klapinklapin@gmail.com>
763 *
764 * @param string $file filename path to file
765 * @return int size of file
766 */
767function io_getSizeFile($file)
768{
769    if (!file_exists($file)) return 0;
770
771    if (substr($file, -3) == '.gz') {
772        $fp = @fopen($file, "rb");
773        if($fp === false) return 0;
774        fseek($fp, -4, SEEK_END);
775        $buffer = fread($fp, 4);
776        fclose($fp);
777        $array = unpack("V", $buffer);
778        $uncompressedsize = end($array);
779    } elseif (substr($file, -4) == '.bz2') {
780        if(!DOKU_HAS_BZIP) return 0;
781        $bz = bzopen($file, "r");
782        if($bz === false) return 0;
783        $uncompressedsize = 0;
784        while (!feof($bz)) {
785            //8192 seems to be the maximum buffersize?
786            $buffer = bzread($bz, 8192);
787            if(($buffer === false) || (bzerrno($bz) !== 0)) {
788                return 0;
789            }
790            $uncompressedsize += strlen($buffer);
791        }
792    } else{
793        $uncompressedsize = filesize($file);
794    }
795
796    return $uncompressedsize;
797 }
798