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