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