xref: /dokuwiki/inc/io.php (revision 4e2eb11e7d0d0920cf92885367f092e5d808051f)
1ed7b5f09Sandi<?php
2d4f83172SAndreas Gohr
315fae107Sandi/**
415fae107Sandi * File IO functions
515fae107Sandi *
615fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
715fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
815fae107Sandi */
9d4f83172SAndreas Gohr
1024870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
115a8d6e48SMichael Großeuse dokuwiki\HTTP\DokuHTTPClient;
12cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
13198564abSMichael Große
14f3f0262cSandi/**
1553d6ccfeSandi * Removes empty directories
1653d6ccfeSandi *
17cc7d0c94SBen Coburn * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
18cc7d0c94SBen Coburn * Event data:
19cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
20cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
21cc7d0c94SBen Coburn *
22d186898bSAndreas Gohr * @param string $id      - a pageid, the namespace of that id will be tried to deleted
23cd2f903bSMichael Hamann * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
24cd2f903bSMichael Hamann * @return bool - true if at least one namespace was deleted
2542ea7f44SGerrit Uitslag *
2653d6ccfeSandi * @author  Andreas Gohr <andi@splitbrain.org>
27cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
2853d6ccfeSandi */
29d868eb89SAndreas Gohrfunction io_sweepNS($id, $basedir = 'datadir')
30d868eb89SAndreas Gohr{
3153d6ccfeSandi    global $conf;
3224870174SAndreas Gohr    $types = ['datadir' => 'pages', 'mediadir' => 'media'];
3324870174SAndreas Gohr    $ns_type = ($types[$basedir] ?? false);
3453d6ccfeSandi
35d186898bSAndreas Gohr    $delone = false;
36d186898bSAndreas Gohr
3753d6ccfeSandi    //scan all namespaces
3853d6ccfeSandi    while (($id = getNS($id)) !== false) {
39755f1e03SAndreas Gohr        $dir = $conf[$basedir] . '/' . utf8_encodeFN(str_replace(':', '/', $id));
4053d6ccfeSandi
4153d6ccfeSandi        //try to delete dir else return
42cc7d0c94SBen Coburn        if (@rmdir($dir)) {
43cc7d0c94SBen Coburn            if ($ns_type !== false) {
4424870174SAndreas Gohr                $data = [$id, $ns_type];
45d186898bSAndreas Gohr                $delone = true; // we deleted at least one dir
46cbb44eabSAndreas Gohr                Event::createAndTrigger('IO_NAMESPACE_DELETED', $data);
47cc7d0c94SBen Coburn            }
48177d6836SAndreas Gohr        } else {
49d4f83172SAndreas Gohr            return $delone;
50d4f83172SAndreas Gohr        }
51cc7d0c94SBen Coburn    }
52d186898bSAndreas Gohr    return $delone;
53cc7d0c94SBen Coburn}
54cc7d0c94SBen Coburn
55cc7d0c94SBen Coburn/**
56cc7d0c94SBen Coburn * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
57cc7d0c94SBen Coburn *
58cc7d0c94SBen Coburn * Generates the action event which delegates to io_readFile().
59cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
60cc7d0c94SBen Coburn * The file path should not be changed.
61cc7d0c94SBen Coburn *
62cc7d0c94SBen Coburn * Event data:
63cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_readFile as an array.
64cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
65cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
66cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
67cc7d0c94SBen Coburn *
68cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
6942ea7f44SGerrit Uitslag *
7042ea7f44SGerrit Uitslag * @param string   $file filename
7142ea7f44SGerrit Uitslag * @param string   $id page id
7242ea7f44SGerrit Uitslag * @param bool|int $rev revision timestamp
7342ea7f44SGerrit Uitslag * @return string
74cc7d0c94SBen Coburn */
75d868eb89SAndreas Gohrfunction io_readWikiPage($file, $id, $rev = false)
76d868eb89SAndreas Gohr{
77177d6836SAndreas Gohr    if (empty($rev)) {
78d4f83172SAndreas Gohr        $rev = false;
79d4f83172SAndreas Gohr    }
8024870174SAndreas Gohr    $data = [[$file, true], getNS($id), noNS($id), $rev];
81cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
82cc7d0c94SBen Coburn}
83cc7d0c94SBen Coburn
84cc7d0c94SBen Coburn/**
85cc7d0c94SBen Coburn * Callback adapter for io_readFile().
8642ea7f44SGerrit Uitslag *
87cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
8842ea7f44SGerrit Uitslag *
8942ea7f44SGerrit Uitslag * @param array $data event data
9042ea7f44SGerrit Uitslag * @return string
91cc7d0c94SBen Coburn */
92d868eb89SAndreas Gohrfunction _io_readWikiPage_action($data)
93d868eb89SAndreas Gohr{
94cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0]) === 2) {
9524870174SAndreas Gohr        return io_readFile(...$data[0]);
96cc7d0c94SBen Coburn    } else {
97cc7d0c94SBen Coburn        return ''; //callback error
9853d6ccfeSandi    }
9953d6ccfeSandi}
10053d6ccfeSandi
10153d6ccfeSandi/**
10215fae107Sandi * Returns content of $file as cleaned string.
10315fae107Sandi *
10415fae107Sandi * Uses gzip if extension is .gz
10515fae107Sandi *
106ee4c4a1bSAndreas Gohr * If you want to use the returned value in unserialize
107ee4c4a1bSAndreas Gohr * be sure to set $clean to false!
108ee4c4a1bSAndreas Gohr *
10915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
11042ea7f44SGerrit Uitslag *
11142ea7f44SGerrit Uitslag * @param string $file  filename
11242ea7f44SGerrit Uitslag * @param bool   $clean
113d387bf5eSAndreas Gohr * @return string|bool the file contents or false on error
114f3f0262cSandi */
115d868eb89SAndreas Gohrfunction io_readFile($file, $clean = true)
116d868eb89SAndreas Gohr{
117f3f0262cSandi    $ret = '';
11879e79377SAndreas Gohr    if (file_exists($file)) {
119f3f0262cSandi        if (substr($file, -3) == '.gz') {
12013c37900SAndreas Gohr            if (!DOKU_HAS_GZIP) return false;
1212ad45addSAndreas Gohr            $ret = gzfile($file);
12224870174SAndreas Gohr            if (is_array($ret)) $ret = implode('', $ret);
123ff3ed99fSmarcel        } elseif (substr($file, -4) == '.bz2') {
12413c37900SAndreas Gohr            if (!DOKU_HAS_BZIP) return false;
125ff3ed99fSmarcel            $ret = bzfile($file);
126f3f0262cSandi        } else {
12743078d10SAndreas Gohr            $ret = file_get_contents($file);
128f3f0262cSandi        }
129f3f0262cSandi    }
1302ad45addSAndreas Gohr    if ($ret === null) return false;
131d387bf5eSAndreas Gohr    if ($ret !== false && $clean) {
132f3f0262cSandi        return cleanText($ret);
133e34c0709SAndreas Gohr    } else {
134e34c0709SAndreas Gohr        return $ret;
135e34c0709SAndreas Gohr    }
136f3f0262cSandi}
137ff3ed99fSmarcel/**
138ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
13942ea7f44SGerrit Uitslag *
140ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
141d387bf5eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
14242ea7f44SGerrit Uitslag *
14342ea7f44SGerrit Uitslag * @param string $file filename
144cfb71e37SPatrick Brown * @param bool   $array return array of lines
145cfb71e37SPatrick Brown * @return string|array|bool content or false on error
146ff3ed99fSmarcel */
147d868eb89SAndreas Gohrfunction bzfile($file, $array = false)
148d868eb89SAndreas Gohr{
149ff3ed99fSmarcel    $bz = bzopen($file, "r");
150d387bf5eSAndreas Gohr    if ($bz === false) return false;
151d387bf5eSAndreas Gohr
15224870174SAndreas Gohr    if ($array) $lines = [];
153cd2f903bSMichael Hamann    $str = '';
154ff3ed99fSmarcel    while (!feof($bz)) {
155ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
156d387bf5eSAndreas Gohr        $buffer = bzread($bz, 8192);
157d387bf5eSAndreas Gohr        if (($buffer === false) || (bzerrno($bz) !== 0)) {
158d387bf5eSAndreas Gohr            return false;
159d387bf5eSAndreas Gohr        }
16024870174SAndreas Gohr        $str .= $buffer;
161cfb71e37SPatrick Brown        if ($array) {
162cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
163cfb71e37SPatrick Brown            while ($pos !== false) {
164cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos + 1);
165cfb71e37SPatrick Brown                $str = substr($str, $pos + 1);
166cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
167cfb71e37SPatrick Brown            }
168cfb71e37SPatrick Brown        }
169ff3ed99fSmarcel    }
170ff3ed99fSmarcel    bzclose($bz);
171cfb71e37SPatrick Brown    if ($array) {
172cfb71e37SPatrick Brown        if ($str !== '') $lines[] = $str;
173cfb71e37SPatrick Brown        return $lines;
174cfb71e37SPatrick Brown    }
175ff3ed99fSmarcel    return $str;
176ff3ed99fSmarcel}
177ff3ed99fSmarcel
178f3f0262cSandi/**
179cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
180cc7d0c94SBen Coburn *
181cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
182cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
183cc7d0c94SBen Coburn * The file path should not be changed.
184cc7d0c94SBen Coburn * (The append parameter is set to false.)
185cc7d0c94SBen Coburn *
186cc7d0c94SBen Coburn * Event data:
187cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
188cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
189cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
190cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
191cc7d0c94SBen Coburn *
192cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
19342ea7f44SGerrit Uitslag *
19442ea7f44SGerrit Uitslag * @param string $file      filename
19542ea7f44SGerrit Uitslag * @param string $content
19642ea7f44SGerrit Uitslag * @param string $id        page id
19742ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
19842ea7f44SGerrit Uitslag * @return bool
199cc7d0c94SBen Coburn */
200d868eb89SAndreas Gohrfunction io_writeWikiPage($file, $content, $id, $rev = false)
201d868eb89SAndreas Gohr{
202177d6836SAndreas Gohr    if (empty($rev)) {
203d4f83172SAndreas Gohr        $rev = false;
204d4f83172SAndreas Gohr    }
205177d6836SAndreas Gohr    if ($rev === false) {
206*4e2eb11eSGerrit Uitslag        io_createNamespace($id); // create namespaces as needed
207*4e2eb11eSGerrit Uitslag    }
20824870174SAndreas Gohr    $data = [[$file, $content, false], getNS($id), noNS($id), $rev];
209cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
210cc7d0c94SBen Coburn}
211cc7d0c94SBen Coburn
212cc7d0c94SBen Coburn/**
213cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
214cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
21542ea7f44SGerrit Uitslag *
21642ea7f44SGerrit Uitslag * @param array $data event data
21742ea7f44SGerrit Uitslag * @return bool
218cc7d0c94SBen Coburn */
219d868eb89SAndreas Gohrfunction _io_writeWikiPage_action($data)
220d868eb89SAndreas Gohr{
221cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0]) === 3) {
22224870174SAndreas Gohr        $ok = io_saveFile(...$data[0]);
223a4306b74SAndreas Gohr        // for attic files make sure the file has the mtime of the revision
224a4306b74SAndreas Gohr        if ($ok && is_int($data[3]) && $data[3] > 0) {
225a4306b74SAndreas Gohr            @touch($data[0][0], $data[3]);
226a4306b74SAndreas Gohr        }
227a4306b74SAndreas Gohr        return $ok;
228cc7d0c94SBen Coburn    } else {
229cc7d0c94SBen Coburn        return false; //callback error
230cc7d0c94SBen Coburn    }
231cc7d0c94SBen Coburn}
232cc7d0c94SBen Coburn
233cc7d0c94SBen Coburn/**
2341bd6bbdeSPatrick Brown * Internal function to save contents to a file.
2351bd6bbdeSPatrick Brown *
2361bd6bbdeSPatrick Brown * @author  Andreas Gohr <andi@splitbrain.org>
2371bd6bbdeSPatrick Brown *
2381bd6bbdeSPatrick Brown * @param string $file filename path to file
2391bd6bbdeSPatrick Brown * @param string $content
2401bd6bbdeSPatrick Brown * @param bool   $append
2411bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
2421bd6bbdeSPatrick Brown */
243d868eb89SAndreas Gohrfunction _io_saveFile($file, $content, $append)
244d868eb89SAndreas Gohr{
2451bd6bbdeSPatrick Brown    global $conf;
2461bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
2471bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
2481bd6bbdeSPatrick Brown
2491bd6bbdeSPatrick Brown    if (substr($file, -3) == '.gz') {
25013c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
2511bd6bbdeSPatrick Brown        $fh = @gzopen($file, $mode . '9');
2521bd6bbdeSPatrick Brown        if (!$fh) return false;
2531bd6bbdeSPatrick Brown        gzwrite($fh, $content);
2541bd6bbdeSPatrick Brown        gzclose($fh);
2551bd6bbdeSPatrick Brown    } elseif (substr($file, -4) == '.bz2') {
25613c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
2571bd6bbdeSPatrick Brown        if ($append) {
2581bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
2591bd6bbdeSPatrick Brown            if ($bzcontent === false) return false;
2601bd6bbdeSPatrick Brown            $content = $bzcontent . $content;
2611bd6bbdeSPatrick Brown        }
2621bd6bbdeSPatrick Brown        $fh = @bzopen($file, 'w');
2631bd6bbdeSPatrick Brown        if (!$fh) return false;
2641bd6bbdeSPatrick Brown        bzwrite($fh, $content);
2651bd6bbdeSPatrick Brown        bzclose($fh);
2661bd6bbdeSPatrick Brown    } else {
2671bd6bbdeSPatrick Brown        $fh = @fopen($file, $mode);
2681bd6bbdeSPatrick Brown        if (!$fh) return false;
2691bd6bbdeSPatrick Brown        fwrite($fh, $content);
2701bd6bbdeSPatrick Brown        fclose($fh);
2711bd6bbdeSPatrick Brown    }
2721bd6bbdeSPatrick Brown
27324870174SAndreas Gohr    if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
2741bd6bbdeSPatrick Brown    return true;
2751bd6bbdeSPatrick Brown}
2761bd6bbdeSPatrick Brown
2771bd6bbdeSPatrick Brown/**
27815fae107Sandi * Saves $content to $file.
279f3f0262cSandi *
2801380fc45SAndreas Gohr * If the third parameter is set to true the given content
2811380fc45SAndreas Gohr * will be appended.
2821380fc45SAndreas Gohr *
28315fae107Sandi * Uses gzip if extension is .gz
284ff3ed99fSmarcel * and bz2 if extension is .bz2
28515fae107Sandi *
28615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28742ea7f44SGerrit Uitslag *
28842ea7f44SGerrit Uitslag * @param string $file filename path to file
28942ea7f44SGerrit Uitslag * @param string $content
29042ea7f44SGerrit Uitslag * @param bool   $append
29142ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
292f3f0262cSandi */
293d868eb89SAndreas Gohrfunction io_saveFile($file, $content, $append = false)
294d868eb89SAndreas Gohr{
295f3f0262cSandi    io_makeFileDir($file);
29690eb8392Sandi    io_lock($file);
2971bd6bbdeSPatrick Brown    if (!_io_saveFile($file, $content, $append)) {
298f3f0262cSandi        msg("Writing $file failed", -1);
299fb7125eeSAndreas Gohr        io_unlock($file);
300f3f0262cSandi        return false;
301f3f0262cSandi    }
30290eb8392Sandi    io_unlock($file);
303f3f0262cSandi    return true;
304f3f0262cSandi}
305f3f0262cSandi
306f3f0262cSandi/**
3071bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
3081380fc45SAndreas Gohr *
309d93ba631SPatrick Brown * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
310d93ba631SPatrick Brown * A regex that matches any part of the line will remove the entire line in this mode.
311d93ba631SPatrick Brown * Captures in $newline are not available.
3121bd6bbdeSPatrick Brown *
313d93ba631SPatrick Brown * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
314d93ba631SPatrick Brown * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
315d93ba631SPatrick Brown *
316d93ba631SPatrick Brown * Be sure to include the trailing newline in $oldline when replacing entire lines.
317b158d625SSteven Danz *
318b158d625SSteven Danz * Uses gzip if extension is .gz
3191bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
3208b06d178Schris *
321b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
3221bd6bbdeSPatrick Brown * @author Christopher Smith <chris@jalakai.co.uk>
3231bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
32442ea7f44SGerrit Uitslag *
32542ea7f44SGerrit Uitslag * @param string $file     filename
3261bd6bbdeSPatrick Brown * @param string $oldline  exact linematch to remove
3271bd6bbdeSPatrick Brown * @param string $newline  new line to insert
32842ea7f44SGerrit Uitslag * @param bool   $regex    use regexp?
3291bd6bbdeSPatrick Brown * @param int    $maxlines number of occurrences of the line to replace
330b158d625SSteven Danz * @return bool true on success
331b158d625SSteven Danz */
332d868eb89SAndreas Gohrfunction io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines = 0)
333d868eb89SAndreas Gohr{
334dc4a4eb0SPatrick Brown    if ((string)$oldline === '') {
335dc4a4eb0SPatrick Brown        trigger_error('$oldline parameter cannot be empty in io_replaceInFile()', E_USER_WARNING);
336dc4a4eb0SPatrick Brown        return false;
337dc4a4eb0SPatrick Brown    }
338dc4a4eb0SPatrick Brown
33979e79377SAndreas Gohr    if (!file_exists($file)) return true;
3401380fc45SAndreas Gohr
341b158d625SSteven Danz    io_lock($file);
3421380fc45SAndreas Gohr
3431380fc45SAndreas Gohr    // load into array
344b158d625SSteven Danz    if (substr($file, -3) == '.gz') {
34513c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
3461380fc45SAndreas Gohr        $lines = gzfile($file);
347cfb71e37SPatrick Brown    } elseif (substr($file, -4) == '.bz2') {
34813c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
349cfb71e37SPatrick Brown        $lines = bzfile($file, true);
350b158d625SSteven Danz    } else {
3511380fc45SAndreas Gohr        $lines = file($file);
352b158d625SSteven Danz    }
353b158d625SSteven Danz
3549a734b7aSChristopher Smith    // make non-regexes into regexes
3553dfe7d64SChristopher Smith    $pattern = $regex ? $oldline : '/^' . preg_quote($oldline, '/') . '$/';
3569a734b7aSChristopher Smith    $replace = $regex ? $newline : addcslashes($newline, '\$');
3579a734b7aSChristopher Smith
3589a734b7aSChristopher Smith    // remove matching lines
3596c000204SPatrick Brown    if ($maxlines > 0) {
3606c000204SPatrick Brown        $count = 0;
3619a734b7aSChristopher Smith        $matched = 0;
362a93ad676SAndreas Gohr        foreach ($lines as $i => $line) {
363a93ad676SAndreas Gohr            if ($count >= $maxlines) break;
3649a734b7aSChristopher Smith            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
3659a734b7aSChristopher Smith            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
3669a734b7aSChristopher Smith            if ($matched) $count++;
3676c000204SPatrick Brown        }
368e12c5ac7SChristopher Smith    } elseif ($maxlines == 0) {
369e12c5ac7SChristopher Smith        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
370e12c5ac7SChristopher Smith        if ((string)$newline !== '') {
3711bd6bbdeSPatrick Brown            $lines[] = $newline;
3721bd6bbdeSPatrick Brown        }
373e12c5ac7SChristopher Smith    } else {
374e12c5ac7SChristopher Smith        $lines = preg_replace($pattern, $replace, $lines);
375e12c5ac7SChristopher Smith    }
3761bd6bbdeSPatrick Brown
3771380fc45SAndreas Gohr    if (count($lines)) {
37824870174SAndreas Gohr        if (!_io_saveFile($file, implode('', $lines), false)) {
379b158d625SSteven Danz            msg("Removing content from $file failed", -1);
380fb7125eeSAndreas Gohr            io_unlock($file);
381b158d625SSteven Danz            return false;
382b158d625SSteven Danz        }
383b158d625SSteven Danz    } else {
384b158d625SSteven Danz        @unlink($file);
385b158d625SSteven Danz    }
386b158d625SSteven Danz
387b158d625SSteven Danz    io_unlock($file);
388b158d625SSteven Danz    return true;
389b158d625SSteven Danz}
390b158d625SSteven Danz
391b158d625SSteven Danz/**
3921bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
3931bd6bbdeSPatrick Brown *
3941bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
3951bd6bbdeSPatrick Brown *
3961bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
3971bd6bbdeSPatrick Brown *
3981bd6bbdeSPatrick Brown * @param string $file    filename
3991bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
4001bd6bbdeSPatrick Brown * @param bool   $regex   use regexp?
4011bd6bbdeSPatrick Brown * @return bool true on success
4021bd6bbdeSPatrick Brown */
403d868eb89SAndreas Gohrfunction io_deleteFromFile($file, $badline, $regex = false)
404d868eb89SAndreas Gohr{
4051bd6bbdeSPatrick Brown    return io_replaceInFile($file, $badline, null, $regex, 0);
4061bd6bbdeSPatrick Brown}
4071bd6bbdeSPatrick Brown
4081bd6bbdeSPatrick Brown/**
40990eb8392Sandi * Tries to lock a file
41090eb8392Sandi *
41190eb8392Sandi * Locking is only done for io_savefile and uses directories
41290eb8392Sandi * inside $conf['lockdir']
41390eb8392Sandi *
41490eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
41590eb8392Sandi * the lock is assumed to be stale and the function goes on
41690eb8392Sandi *
41790eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
41842ea7f44SGerrit Uitslag *
41942ea7f44SGerrit Uitslag * @param string $file filename
42090eb8392Sandi */
421d868eb89SAndreas Gohrfunction io_lock($file)
422d868eb89SAndreas Gohr{
42390eb8392Sandi    global $conf;
42490eb8392Sandi
42590eb8392Sandi    $lockDir = $conf['lockdir'] . '/' . md5($file);
42690eb8392Sandi    @ignore_user_abort(1);
42790eb8392Sandi
42890eb8392Sandi    $timeStart = time();
42990eb8392Sandi    do {
43090eb8392Sandi        //waited longer than 3 seconds? -> stale lock
43190eb8392Sandi        if ((time() - $timeStart) > 3) break;
432bd539124SAndreas Gohr        $locked = @mkdir($lockDir);
43377b98903SAndreas Gohr        if ($locked) {
43423420346SDamien Regad            if ($conf['dperm']) chmod($lockDir, $conf['dperm']);
43577b98903SAndreas Gohr            break;
43677b98903SAndreas Gohr        }
43777b98903SAndreas Gohr        usleep(50);
43890eb8392Sandi    } while ($locked === false);
43990eb8392Sandi}
44090eb8392Sandi
44190eb8392Sandi/**
44290eb8392Sandi * Unlocks a file
44390eb8392Sandi *
44490eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
44542ea7f44SGerrit Uitslag *
44642ea7f44SGerrit Uitslag * @param string $file filename
44790eb8392Sandi */
448d868eb89SAndreas Gohrfunction io_unlock($file)
449d868eb89SAndreas Gohr{
45090eb8392Sandi    global $conf;
45190eb8392Sandi
45290eb8392Sandi    $lockDir = $conf['lockdir'] . '/' . md5($file);
45390eb8392Sandi    @rmdir($lockDir);
45490eb8392Sandi    @ignore_user_abort(0);
45590eb8392Sandi}
45690eb8392Sandi
45790eb8392Sandi/**
458cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
459cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
460cc7d0c94SBen Coburn *
461cc7d0c94SBen Coburn * Event data:
462cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
463cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
464cc7d0c94SBen Coburn *
465cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
46642ea7f44SGerrit Uitslag *
46742ea7f44SGerrit Uitslag * @param string $id page id
46842ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
469cc7d0c94SBen Coburn */
470d868eb89SAndreas Gohrfunction io_createNamespace($id, $ns_type = 'pages')
471d868eb89SAndreas Gohr{
472cc7d0c94SBen Coburn    // verify ns_type
47324870174SAndreas Gohr    $types = ['pages' => 'wikiFN', 'media' => 'mediaFN'];
474cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
475cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
476cc7d0c94SBen Coburn        return;
477cc7d0c94SBen Coburn    }
478cc7d0c94SBen Coburn    // make event list
47924870174SAndreas Gohr    $missing = [];
480cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
481cc7d0c94SBen Coburn    $ns = $id;
482cc7d0c94SBen Coburn    $tmp = dirname($file = call_user_func($types[$ns_type], $ns));
48379e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
484cc7d0c94SBen Coburn        array_pop($ns_stack);
485cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
486177d6836SAndreas Gohr        if (strlen($ns) == 0) {
487d4f83172SAndreas Gohr            break;
488d4f83172SAndreas Gohr        }
489cc7d0c94SBen Coburn        $missing[] = $ns;
490cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
491cc7d0c94SBen Coburn    }
492cc7d0c94SBen Coburn    // make directories
493cc7d0c94SBen Coburn    io_makeFileDir($file);
494cc7d0c94SBen Coburn    // send the events
495cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
496cc7d0c94SBen Coburn    foreach ($missing as $ns) {
49724870174SAndreas Gohr        $data = [$ns, $ns_type];
498cbb44eabSAndreas Gohr        Event::createAndTrigger('IO_NAMESPACE_CREATED', $data);
499cc7d0c94SBen Coburn    }
500cc7d0c94SBen Coburn}
501cc7d0c94SBen Coburn
502cc7d0c94SBen Coburn/**
503f3f0262cSandi * Create the directory needed for the given file
50415fae107Sandi *
50515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
50642ea7f44SGerrit Uitslag *
50742ea7f44SGerrit Uitslag * @param string $file file name
508f3f0262cSandi */
509d868eb89SAndreas Gohrfunction io_makeFileDir($file)
510d868eb89SAndreas Gohr{
511f3f0262cSandi    $dir = dirname($file);
5120d8850c4SAndreas Gohr    if (!@is_dir($dir)) {
513f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed", -1);
514f3f0262cSandi    }
515f3f0262cSandi}
516f3f0262cSandi
517f3f0262cSandi/**
518f3f0262cSandi * Creates a directory hierachy.
519f3f0262cSandi *
52059752844SAnders Sandblad * @link    http://php.net/manual/en/function.mkdir.php
521f3f0262cSandi * @author  <saint@corenova.com>
5223dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
52342ea7f44SGerrit Uitslag *
52442ea7f44SGerrit Uitslag * @param string $target filename
52542ea7f44SGerrit Uitslag * @return bool|int|string
526f3f0262cSandi */
527d868eb89SAndreas Gohrfunction io_mkdir_p($target)
528d868eb89SAndreas Gohr{
5293dc3a5f1Sandi    global $conf;
5300d8850c4SAndreas Gohr    if (@is_dir($target) || empty($target)) return 1; // best case check first
53179e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
5323dc3a5f1Sandi    //recursion
5333dc3a5f1Sandi    if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))) {
534bd539124SAndreas Gohr        $ret = @mkdir($target); // crawl back up & create dir tree
535443e135dSChristopher Smith        if ($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
53644881d27STroels Liebe Bentsen        return $ret;
5373dc3a5f1Sandi    }
538f3f0262cSandi    return 0;
539f3f0262cSandi}
540f3f0262cSandi
541f3f0262cSandi/**
5424d47e8e3SAndreas Gohr * Recursively delete a directory
5434d47e8e3SAndreas Gohr *
5444d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5454d47e8e3SAndreas Gohr * @param string $path
5464d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
5474d47e8e3SAndreas Gohr * @return bool
5484d47e8e3SAndreas Gohr */
549d868eb89SAndreas Gohrfunction io_rmdir($path, $removefiles = false)
550d868eb89SAndreas Gohr{
5514d47e8e3SAndreas Gohr    if (!is_string($path) || $path == "") return false;
552d8cf4dd4SAndreas Gohr    if (!file_exists($path)) return true; // it's already gone or was never there, count as success
5534d47e8e3SAndreas Gohr
5544d47e8e3SAndreas Gohr    if (is_dir($path) && !is_link($path)) {
55524870174SAndreas Gohr        $dirs  = [];
55624870174SAndreas Gohr        $files = [];
5574d47e8e3SAndreas Gohr        if (!$dh = @opendir($path)) return false;
5588426a3eeSAndreas Gohr        while (false !== ($f = readdir($dh))) {
5594d47e8e3SAndreas Gohr            if ($f == '..' || $f == '.') continue;
5604d47e8e3SAndreas Gohr
5614d47e8e3SAndreas Gohr            // collect dirs and files first
5624d47e8e3SAndreas Gohr            if (is_dir("$path/$f") && !is_link("$path/$f")) {
5634d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5644d47e8e3SAndreas Gohr            } elseif ($removefiles) {
5654d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5664d47e8e3SAndreas Gohr            } else {
5674d47e8e3SAndreas Gohr                return false; // abort when non empty
5684d47e8e3SAndreas Gohr            }
5694d47e8e3SAndreas Gohr        }
5704d47e8e3SAndreas Gohr        closedir($dh);
5714d47e8e3SAndreas Gohr        // now traverse into  directories first
5724d47e8e3SAndreas Gohr        foreach ($dirs as $dir) {
5734d47e8e3SAndreas Gohr            if (!io_rmdir($dir, $removefiles)) return false; // abort on any error
5744d47e8e3SAndreas Gohr        }
5754d47e8e3SAndreas Gohr        // now delete files
5764d47e8e3SAndreas Gohr        foreach ($files as $file) {
5774d47e8e3SAndreas Gohr            if (!@unlink($file)) return false; //abort on any error
5784d47e8e3SAndreas Gohr        }
5794d47e8e3SAndreas Gohr        // remove self
5804d47e8e3SAndreas Gohr        return @rmdir($path);
5814d47e8e3SAndreas Gohr    } elseif ($removefiles) {
5824d47e8e3SAndreas Gohr        return @unlink($path);
5834d47e8e3SAndreas Gohr    }
5844d47e8e3SAndreas Gohr    return false;
5854d47e8e3SAndreas Gohr}
5864d47e8e3SAndreas Gohr
5874d47e8e3SAndreas Gohr/**
588de862555SMichael Klier * Creates a unique temporary directory and returns
589de862555SMichael Klier * its path.
590de862555SMichael Klier *
591de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
59242ea7f44SGerrit Uitslag *
59342ea7f44SGerrit Uitslag * @return false|string path to new directory or false
594de862555SMichael Klier */
595d868eb89SAndreas Gohrfunction io_mktmpdir()
596d868eb89SAndreas Gohr{
597de862555SMichael Klier    global $conf;
598de862555SMichael Klier
599da1e1077SChris Smith    $base = $conf['tmpdir'];
60024870174SAndreas Gohr    $dir  = md5(uniqid(random_int(0, mt_getrandmax()), true));
601287f35bdSAndreas Gohr    $tmpdir = $base . '/' . $dir;
602de862555SMichael Klier
603de862555SMichael Klier    if (io_mkdir_p($tmpdir)) {
604de862555SMichael Klier        return($tmpdir);
605de862555SMichael Klier    } else {
606de862555SMichael Klier        return false;
607de862555SMichael Klier    }
608de862555SMichael Klier}
609de862555SMichael Klier
610de862555SMichael Klier/**
61173ccfcb9Schris * downloads a file from the net and saves it
61273ccfcb9Schris *
61373ccfcb9Schris * if $useAttachment is false,
61473ccfcb9Schris * - $file is the full filename to save the file, incl. path
61573ccfcb9Schris * - if successful will return true, false otherwise
616db959ae3SAndreas Gohr *
61773ccfcb9Schris * if $useAttachment is true,
61873ccfcb9Schris * - $file is the directory where the file should be saved
61973ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
620b625487dSandi *
621b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
62273ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
62342ea7f44SGerrit Uitslag *
62442ea7f44SGerrit Uitslag * @param string $url           url to download
62542ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
62664159a61SAndreas Gohr * @param bool   $useAttachment true: try to use name of download, uses otherwise $defaultName
62764159a61SAndreas Gohr *                              false: uses $file as path to file
62842ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
62942ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
63042ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
631b625487dSandi */
632d868eb89SAndreas Gohrfunction io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2_097_152)
633d868eb89SAndreas Gohr{
634ac9115b0STroels Liebe Bentsen    global $conf;
6359b307a83SAndreas Gohr    $http = new DokuHTTPClient();
636847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6379b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
638a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6399b307a83SAndreas Gohr
6409b307a83SAndreas Gohr    $data = $http->get($url);
6419b307a83SAndreas Gohr    if (!$data) return false;
6429b307a83SAndreas Gohr
64373ccfcb9Schris    $name = '';
644cd2f903bSMichael Hamann    if ($useAttachment) {
64573ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
64673ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
64724870174SAndreas Gohr            $match = [];
6487d34963bSAndreas Gohr            if (
6497d34963bSAndreas Gohr                is_string($content_disposition) &&
6507d34963bSAndreas Gohr                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)
6517d34963bSAndreas Gohr            ) {
65224870174SAndreas Gohr                $name = PhpString::basename($match[1]);
65373ccfcb9Schris            }
65473ccfcb9Schris        }
65573ccfcb9Schris
65673ccfcb9Schris        if (!$name) {
65773ccfcb9Schris            if (!$defaultName) return false;
65873ccfcb9Schris            $name = $defaultName;
65973ccfcb9Schris        }
66073ccfcb9Schris
66124870174SAndreas Gohr        $file .= $name;
66273ccfcb9Schris    }
66373ccfcb9Schris
66479e79377SAndreas Gohr    $fileexists = file_exists($file);
6659b307a83SAndreas Gohr    $fp = @fopen($file, "w");
666b625487dSandi    if (!$fp) return false;
6679b307a83SAndreas Gohr    fwrite($fp, $data);
668b625487dSandi    fclose($fp);
66924870174SAndreas Gohr    if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
67073ccfcb9Schris    if ($useAttachment) return $name;
671b625487dSandi    return true;
672b625487dSandi}
673b625487dSandi
674b625487dSandi/**
675ac9115b0STroels Liebe Bentsen * Windows compatible rename
676bf5e5a5bSAndreas Gohr *
677bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
678bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
67942ea7f44SGerrit Uitslag *
68042ea7f44SGerrit Uitslag * @param string $from
68142ea7f44SGerrit Uitslag * @param string $to
68242ea7f44SGerrit Uitslag * @return bool succes or fail
683bf5e5a5bSAndreas Gohr */
684d868eb89SAndreas Gohrfunction io_rename($from, $to)
685d868eb89SAndreas Gohr{
686ac9115b0STroels Liebe Bentsen    global $conf;
687bf5e5a5bSAndreas Gohr    if (!@rename($from, $to)) {
688bf5e5a5bSAndreas Gohr        if (@copy($from, $to)) {
6898e0b019fSAndreas Gohr            if ($conf['fperm']) chmod($to, $conf['fperm']);
690bf5e5a5bSAndreas Gohr            @unlink($from);
691bf5e5a5bSAndreas Gohr            return true;
692bf5e5a5bSAndreas Gohr        }
693bf5e5a5bSAndreas Gohr        return false;
694bf5e5a5bSAndreas Gohr    }
695bf5e5a5bSAndreas Gohr    return true;
696bf5e5a5bSAndreas Gohr}
697bf5e5a5bSAndreas Gohr
698420edfd6STom N Harris/**
699420edfd6STom N Harris * Runs an external command with input and output pipes.
700420edfd6STom N Harris * Returns the exit code from the process.
701420edfd6STom N Harris *
702420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
70342ea7f44SGerrit Uitslag *
70442ea7f44SGerrit Uitslag * @param string $cmd
70542ea7f44SGerrit Uitslag * @param string $input  input pipe
70642ea7f44SGerrit Uitslag * @param string $output output pipe
70742ea7f44SGerrit Uitslag * @return int exit code from process
708420edfd6STom N Harris */
709d868eb89SAndreas Gohrfunction io_exec($cmd, $input, &$output)
710d868eb89SAndreas Gohr{
71124870174SAndreas Gohr    $descspec = [
71224870174SAndreas Gohr        0 => ["pipe", "r"],
71324870174SAndreas Gohr        1 => ["pipe", "w"],
71424870174SAndreas Gohr        2 => ["pipe", "w"]
71524870174SAndreas Gohr    ];
7166c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7176c528220STom N Harris    if (!$ph) return -1;
7186c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7196c528220STom N Harris    fwrite($pipes[0], $input);
7206c528220STom N Harris    fclose($pipes[0]);
7216c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7226c528220STom N Harris    fclose($pipes[1]);
7236c528220STom N Harris    return proc_close($ph);
724f3f0262cSandi}
725f3f0262cSandi
7267421c3ccSAndreas Gohr/**
7277421c3ccSAndreas Gohr * Search a file for matching lines
7287421c3ccSAndreas Gohr *
7297421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7307421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7317421c3ccSAndreas Gohr * at once.
7327421c3ccSAndreas Gohr *
7337421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7347421c3ccSAndreas Gohr * @param  string $file    The file to search
7357421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
7367421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
737cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
738cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
7397421c3ccSAndreas Gohr */
740d868eb89SAndreas Gohrfunction io_grep($file, $pattern, $max = 0, $backref = false)
741d868eb89SAndreas Gohr{
7427421c3ccSAndreas Gohr    $fh = @fopen($file, 'r');
7437421c3ccSAndreas Gohr    if (!$fh) return false;
74424870174SAndreas Gohr    $matches = [];
7457421c3ccSAndreas Gohr
7467421c3ccSAndreas Gohr    $cnt  = 0;
7477421c3ccSAndreas Gohr    $line = '';
7487421c3ccSAndreas Gohr    while (!feof($fh)) {
7497421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7507421c3ccSAndreas Gohr        if (substr($line, -1) != "\n") continue;
7517421c3ccSAndreas Gohr
7527421c3ccSAndreas Gohr        // check if line matches
7537421c3ccSAndreas Gohr        if (preg_match($pattern, $line, $match)) {
7547421c3ccSAndreas Gohr            if ($backref) {
7557421c3ccSAndreas Gohr                $matches[] = $match;
7567421c3ccSAndreas Gohr            } else {
7577421c3ccSAndreas Gohr                $matches[] = $line;
7587421c3ccSAndreas Gohr            }
7597421c3ccSAndreas Gohr            $cnt++;
7607421c3ccSAndreas Gohr        }
7617421c3ccSAndreas Gohr        if ($max && $max == $cnt) break;
7627421c3ccSAndreas Gohr        $line = '';
7637421c3ccSAndreas Gohr    }
7647421c3ccSAndreas Gohr    fclose($fh);
7657421c3ccSAndreas Gohr    return $matches;
7667421c3ccSAndreas Gohr}
7677421c3ccSAndreas Gohr
768f549be3dSGerrit Uitslag
769f549be3dSGerrit Uitslag/**
770f549be3dSGerrit Uitslag * Get size of contents of a file, for a compressed file the uncompressed size
771f549be3dSGerrit Uitslag * Warning: reading uncompressed size of content of bz-files requires uncompressing
772f549be3dSGerrit Uitslag *
773f549be3dSGerrit Uitslag * @author  Gerrit Uitslag <klapinklapin@gmail.com>
774f549be3dSGerrit Uitslag *
775f549be3dSGerrit Uitslag * @param string $file filename path to file
776f549be3dSGerrit Uitslag * @return int size of file
777f549be3dSGerrit Uitslag */
778d868eb89SAndreas Gohrfunction io_getSizeFile($file)
779d868eb89SAndreas Gohr{
780f549be3dSGerrit Uitslag    if (!file_exists($file)) return 0;
781f549be3dSGerrit Uitslag
782f549be3dSGerrit Uitslag    if (substr($file, -3) == '.gz') {
783f549be3dSGerrit Uitslag        $fp = @fopen($file, "rb");
784f549be3dSGerrit Uitslag        if ($fp === false) return 0;
785f549be3dSGerrit Uitslag        fseek($fp, -4, SEEK_END);
786f549be3dSGerrit Uitslag        $buffer = fread($fp, 4);
787f549be3dSGerrit Uitslag        fclose($fp);
788f549be3dSGerrit Uitslag        $array = unpack("V", $buffer);
789f549be3dSGerrit Uitslag        $uncompressedsize = end($array);
790f549be3dSGerrit Uitslag    } elseif (substr($file, -4) == '.bz2') {
791f549be3dSGerrit Uitslag        if (!DOKU_HAS_BZIP) return 0;
792f549be3dSGerrit Uitslag        $bz = bzopen($file, "r");
793f549be3dSGerrit Uitslag        if ($bz === false) return 0;
794f549be3dSGerrit Uitslag        $uncompressedsize = 0;
795f549be3dSGerrit Uitslag        while (!feof($bz)) {
796f549be3dSGerrit Uitslag            //8192 seems to be the maximum buffersize?
797f549be3dSGerrit Uitslag            $buffer = bzread($bz, 8192);
798f549be3dSGerrit Uitslag            if (($buffer === false) || (bzerrno($bz) !== 0)) {
799f549be3dSGerrit Uitslag                return 0;
800f549be3dSGerrit Uitslag            }
801f549be3dSGerrit Uitslag            $uncompressedsize += strlen($buffer);
802f549be3dSGerrit Uitslag        }
803f549be3dSGerrit Uitslag    } else {
804f549be3dSGerrit Uitslag        $uncompressedsize = filesize($file);
805f549be3dSGerrit Uitslag    }
806f549be3dSGerrit Uitslag
807f549be3dSGerrit Uitslag    return $uncompressedsize;
808f549be3dSGerrit Uitslag}
809