xref: /dokuwiki/inc/io.php (revision 7d34963b3e75ea04c63ec066a6b7a692e123cb53)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * File IO functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
824870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
95a8d6e48SMichael Großeuse dokuwiki\HTTP\DokuHTTPClient;
10cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
11198564abSMichael Große
12f3f0262cSandi/**
1353d6ccfeSandi * Removes empty directories
1453d6ccfeSandi *
15cc7d0c94SBen Coburn * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
16cc7d0c94SBen Coburn * Event data:
17cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
18cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
19cc7d0c94SBen Coburn *
20d186898bSAndreas Gohr * @param string $id      - a pageid, the namespace of that id will be tried to deleted
21cd2f903bSMichael Hamann * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
22cd2f903bSMichael Hamann * @return bool - true if at least one namespace was deleted
2342ea7f44SGerrit Uitslag *
2453d6ccfeSandi * @author  Andreas Gohr <andi@splitbrain.org>
25cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
2653d6ccfeSandi */
27d868eb89SAndreas Gohrfunction io_sweepNS($id, $basedir = 'datadir')
28d868eb89SAndreas Gohr{
2953d6ccfeSandi    global $conf;
3024870174SAndreas Gohr    $types = ['datadir'=>'pages', 'mediadir'=>'media'];
3124870174SAndreas Gohr    $ns_type = ($types[$basedir] ?? false);
3253d6ccfeSandi
33d186898bSAndreas Gohr    $delone = false;
34d186898bSAndreas Gohr
3553d6ccfeSandi    //scan all namespaces
3653d6ccfeSandi    while (($id = getNS($id)) !== false) {
37755f1e03SAndreas Gohr        $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':', '/', $id));
3853d6ccfeSandi
3953d6ccfeSandi        //try to delete dir else return
40cc7d0c94SBen Coburn        if (@rmdir($dir)) {
41cc7d0c94SBen Coburn            if ($ns_type!==false) {
4224870174SAndreas Gohr                $data = [$id, $ns_type];
43d186898bSAndreas Gohr                $delone = true; // we deleted at least one dir
44cbb44eabSAndreas Gohr                Event::createAndTrigger('IO_NAMESPACE_DELETED', $data);
45cc7d0c94SBen Coburn            }
46177d6836SAndreas Gohr        } else {
47177d6836SAndreas Gohrreturn $delone; }
48cc7d0c94SBen Coburn    }
49d186898bSAndreas Gohr    return $delone;
50cc7d0c94SBen Coburn}
51cc7d0c94SBen Coburn
52cc7d0c94SBen Coburn/**
53cc7d0c94SBen Coburn * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
54cc7d0c94SBen Coburn *
55cc7d0c94SBen Coburn * Generates the action event which delegates to io_readFile().
56cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
57cc7d0c94SBen Coburn * The file path should not be changed.
58cc7d0c94SBen Coburn *
59cc7d0c94SBen Coburn * Event data:
60cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_readFile as an array.
61cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
62cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
63cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
64cc7d0c94SBen Coburn *
65cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
6642ea7f44SGerrit Uitslag *
6742ea7f44SGerrit Uitslag * @param string   $file filename
6842ea7f44SGerrit Uitslag * @param string   $id page id
6942ea7f44SGerrit Uitslag * @param bool|int $rev revision timestamp
7042ea7f44SGerrit Uitslag * @return string
71cc7d0c94SBen Coburn */
72d868eb89SAndreas Gohrfunction io_readWikiPage($file, $id, $rev = false)
73d868eb89SAndreas Gohr{
74177d6836SAndreas Gohr    if (empty($rev)) {
75177d6836SAndreas Gohr$rev = false; }
7624870174SAndreas Gohr    $data = [[$file, true], getNS($id), noNS($id), $rev];
77cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
78cc7d0c94SBen Coburn}
79cc7d0c94SBen Coburn
80cc7d0c94SBen Coburn/**
81cc7d0c94SBen Coburn * Callback adapter for io_readFile().
8242ea7f44SGerrit Uitslag *
83cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
8442ea7f44SGerrit Uitslag *
8542ea7f44SGerrit Uitslag * @param array $data event data
8642ea7f44SGerrit Uitslag * @return string
87cc7d0c94SBen Coburn */
88d868eb89SAndreas Gohrfunction _io_readWikiPage_action($data)
89d868eb89SAndreas Gohr{
90cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
9124870174SAndreas Gohr        return io_readFile(...$data[0]);
92cc7d0c94SBen Coburn    } else {
93cc7d0c94SBen Coburn        return ''; //callback error
9453d6ccfeSandi    }
9553d6ccfeSandi}
9653d6ccfeSandi
9753d6ccfeSandi/**
9815fae107Sandi * Returns content of $file as cleaned string.
9915fae107Sandi *
10015fae107Sandi * Uses gzip if extension is .gz
10115fae107Sandi *
102ee4c4a1bSAndreas Gohr * If you want to use the returned value in unserialize
103ee4c4a1bSAndreas Gohr * be sure to set $clean to false!
104ee4c4a1bSAndreas Gohr *
10515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
10642ea7f44SGerrit Uitslag *
10742ea7f44SGerrit Uitslag * @param string $file  filename
10842ea7f44SGerrit Uitslag * @param bool   $clean
109d387bf5eSAndreas Gohr * @return string|bool the file contents or false on error
110f3f0262cSandi */
111d868eb89SAndreas Gohrfunction io_readFile($file, $clean = true)
112d868eb89SAndreas Gohr{
113f3f0262cSandi    $ret = '';
11479e79377SAndreas Gohr    if (file_exists($file)) {
115f3f0262cSandi        if (substr($file, -3) == '.gz') {
11613c37900SAndreas Gohr            if (!DOKU_HAS_GZIP) return false;
1172ad45addSAndreas Gohr            $ret = gzfile($file);
11824870174SAndreas Gohr            if (is_array($ret)) $ret = implode('', $ret);
119ff3ed99fSmarcel        } elseif (substr($file, -4) == '.bz2') {
12013c37900SAndreas Gohr            if (!DOKU_HAS_BZIP) return false;
121ff3ed99fSmarcel            $ret = bzfile($file);
122f3f0262cSandi        } else {
12343078d10SAndreas Gohr            $ret = file_get_contents($file);
124f3f0262cSandi        }
125f3f0262cSandi    }
1262ad45addSAndreas Gohr    if ($ret === null) return false;
127d387bf5eSAndreas Gohr    if ($ret !== false && $clean) {
128f3f0262cSandi        return cleanText($ret);
129e34c0709SAndreas Gohr    } else {
130e34c0709SAndreas Gohr        return $ret;
131e34c0709SAndreas Gohr    }
132f3f0262cSandi}
133ff3ed99fSmarcel/**
134ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
13542ea7f44SGerrit Uitslag *
136ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
137d387bf5eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
13842ea7f44SGerrit Uitslag *
13942ea7f44SGerrit Uitslag * @param string $file filename
140cfb71e37SPatrick Brown * @param bool   $array return array of lines
141cfb71e37SPatrick Brown * @return string|array|bool content or false on error
142ff3ed99fSmarcel */
143d868eb89SAndreas Gohrfunction bzfile($file, $array = false)
144d868eb89SAndreas Gohr{
145ff3ed99fSmarcel    $bz = bzopen($file, "r");
146d387bf5eSAndreas Gohr    if ($bz === false) return false;
147d387bf5eSAndreas Gohr
14824870174SAndreas Gohr    if ($array) $lines = [];
149cd2f903bSMichael Hamann    $str = '';
150ff3ed99fSmarcel    while (!feof($bz)) {
151ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
152d387bf5eSAndreas Gohr        $buffer = bzread($bz, 8192);
153d387bf5eSAndreas Gohr        if (($buffer === false) || (bzerrno($bz) !== 0)) {
154d387bf5eSAndreas Gohr            return false;
155d387bf5eSAndreas Gohr        }
15624870174SAndreas Gohr        $str .= $buffer;
157cfb71e37SPatrick Brown        if ($array) {
158cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
159cfb71e37SPatrick Brown            while ($pos !== false) {
160cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos+1);
161cfb71e37SPatrick Brown                $str = substr($str, $pos+1);
162cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
163cfb71e37SPatrick Brown            }
164cfb71e37SPatrick Brown        }
165ff3ed99fSmarcel    }
166ff3ed99fSmarcel    bzclose($bz);
167cfb71e37SPatrick Brown    if ($array) {
168cfb71e37SPatrick Brown        if ($str !== '') $lines[] = $str;
169cfb71e37SPatrick Brown        return $lines;
170cfb71e37SPatrick Brown    }
171ff3ed99fSmarcel    return $str;
172ff3ed99fSmarcel}
173ff3ed99fSmarcel
174f3f0262cSandi/**
175cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
176cc7d0c94SBen Coburn *
177cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
178cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
179cc7d0c94SBen Coburn * The file path should not be changed.
180cc7d0c94SBen Coburn * (The append parameter is set to false.)
181cc7d0c94SBen Coburn *
182cc7d0c94SBen Coburn * Event data:
183cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
184cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
185cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
186cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
187cc7d0c94SBen Coburn *
188cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
18942ea7f44SGerrit Uitslag *
19042ea7f44SGerrit Uitslag * @param string $file      filename
19142ea7f44SGerrit Uitslag * @param string $content
19242ea7f44SGerrit Uitslag * @param string $id        page id
19342ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
19442ea7f44SGerrit Uitslag * @return bool
195cc7d0c94SBen Coburn */
196d868eb89SAndreas Gohrfunction io_writeWikiPage($file, $content, $id, $rev = false)
197d868eb89SAndreas Gohr{
198177d6836SAndreas Gohr    if (empty($rev)) {
199177d6836SAndreas Gohr$rev = false; }
200177d6836SAndreas Gohr    if ($rev===false) {
201177d6836SAndreas Gohrio_createNamespace($id); } // create namespaces as needed
20224870174SAndreas Gohr    $data = [[$file, $content, false], getNS($id), noNS($id), $rev];
203cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
204cc7d0c94SBen Coburn}
205cc7d0c94SBen Coburn
206cc7d0c94SBen Coburn/**
207cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
208cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
20942ea7f44SGerrit Uitslag *
21042ea7f44SGerrit Uitslag * @param array $data event data
21142ea7f44SGerrit Uitslag * @return bool
212cc7d0c94SBen Coburn */
213d868eb89SAndreas Gohrfunction _io_writeWikiPage_action($data)
214d868eb89SAndreas Gohr{
215cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
21624870174SAndreas Gohr        $ok = io_saveFile(...$data[0]);
217a4306b74SAndreas Gohr        // for attic files make sure the file has the mtime of the revision
218a4306b74SAndreas Gohr        if ($ok && is_int($data[3]) && $data[3] > 0) {
219a4306b74SAndreas Gohr            @touch($data[0][0], $data[3]);
220a4306b74SAndreas Gohr        }
221a4306b74SAndreas Gohr        return $ok;
222cc7d0c94SBen Coburn    } else {
223cc7d0c94SBen Coburn        return false; //callback error
224cc7d0c94SBen Coburn    }
225cc7d0c94SBen Coburn}
226cc7d0c94SBen Coburn
227cc7d0c94SBen Coburn/**
2281bd6bbdeSPatrick Brown * Internal function to save contents to a file.
2291bd6bbdeSPatrick Brown *
2301bd6bbdeSPatrick Brown * @author  Andreas Gohr <andi@splitbrain.org>
2311bd6bbdeSPatrick Brown *
2321bd6bbdeSPatrick Brown * @param string $file filename path to file
2331bd6bbdeSPatrick Brown * @param string $content
2341bd6bbdeSPatrick Brown * @param bool   $append
2351bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
2361bd6bbdeSPatrick Brown */
237d868eb89SAndreas Gohrfunction _io_saveFile($file, $content, $append)
238d868eb89SAndreas Gohr{
2391bd6bbdeSPatrick Brown    global $conf;
2401bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
2411bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
2421bd6bbdeSPatrick Brown
2431bd6bbdeSPatrick Brown    if (substr($file, -3) == '.gz') {
24413c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
2451bd6bbdeSPatrick Brown        $fh = @gzopen($file, $mode.'9');
2461bd6bbdeSPatrick Brown        if (!$fh) return false;
2471bd6bbdeSPatrick Brown        gzwrite($fh, $content);
2481bd6bbdeSPatrick Brown        gzclose($fh);
2491bd6bbdeSPatrick Brown    } elseif (substr($file, -4) == '.bz2') {
25013c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
2511bd6bbdeSPatrick Brown        if ($append) {
2521bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
2531bd6bbdeSPatrick Brown            if ($bzcontent === false) return false;
2541bd6bbdeSPatrick Brown            $content = $bzcontent.$content;
2551bd6bbdeSPatrick Brown        }
2561bd6bbdeSPatrick Brown        $fh = @bzopen($file, 'w');
2571bd6bbdeSPatrick Brown        if (!$fh) return false;
2581bd6bbdeSPatrick Brown        bzwrite($fh, $content);
2591bd6bbdeSPatrick Brown        bzclose($fh);
2601bd6bbdeSPatrick Brown    } else {
2611bd6bbdeSPatrick Brown        $fh = @fopen($file, $mode);
2621bd6bbdeSPatrick Brown        if (!$fh) return false;
2631bd6bbdeSPatrick Brown        fwrite($fh, $content);
2641bd6bbdeSPatrick Brown        fclose($fh);
2651bd6bbdeSPatrick Brown    }
2661bd6bbdeSPatrick Brown
26724870174SAndreas Gohr    if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
2681bd6bbdeSPatrick Brown    return true;
2691bd6bbdeSPatrick Brown}
2701bd6bbdeSPatrick Brown
2711bd6bbdeSPatrick Brown/**
27215fae107Sandi * Saves $content to $file.
273f3f0262cSandi *
2741380fc45SAndreas Gohr * If the third parameter is set to true the given content
2751380fc45SAndreas Gohr * will be appended.
2761380fc45SAndreas Gohr *
27715fae107Sandi * Uses gzip if extension is .gz
278ff3ed99fSmarcel * and bz2 if extension is .bz2
27915fae107Sandi *
28015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28142ea7f44SGerrit Uitslag *
28242ea7f44SGerrit Uitslag * @param string $file filename path to file
28342ea7f44SGerrit Uitslag * @param string $content
28442ea7f44SGerrit Uitslag * @param bool   $append
28542ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
286f3f0262cSandi */
287d868eb89SAndreas Gohrfunction io_saveFile($file, $content, $append = false)
288d868eb89SAndreas Gohr{
289f3f0262cSandi    io_makeFileDir($file);
29090eb8392Sandi    io_lock($file);
2911bd6bbdeSPatrick Brown    if (!_io_saveFile($file, $content, $append)) {
292f3f0262cSandi        msg("Writing $file failed", -1);
293fb7125eeSAndreas Gohr        io_unlock($file);
294f3f0262cSandi        return false;
295f3f0262cSandi    }
29690eb8392Sandi    io_unlock($file);
297f3f0262cSandi    return true;
298f3f0262cSandi}
299f3f0262cSandi
300f3f0262cSandi/**
3011bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
3021380fc45SAndreas Gohr *
303d93ba631SPatrick Brown * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
304d93ba631SPatrick Brown * A regex that matches any part of the line will remove the entire line in this mode.
305d93ba631SPatrick Brown * Captures in $newline are not available.
3061bd6bbdeSPatrick Brown *
307d93ba631SPatrick Brown * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
308d93ba631SPatrick Brown * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
309d93ba631SPatrick Brown *
310d93ba631SPatrick Brown * Be sure to include the trailing newline in $oldline when replacing entire lines.
311b158d625SSteven Danz *
312b158d625SSteven Danz * Uses gzip if extension is .gz
3131bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
3148b06d178Schris *
315b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
3161bd6bbdeSPatrick Brown * @author Christopher Smith <chris@jalakai.co.uk>
3171bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
31842ea7f44SGerrit Uitslag *
31942ea7f44SGerrit Uitslag * @param string $file     filename
3201bd6bbdeSPatrick Brown * @param string $oldline  exact linematch to remove
3211bd6bbdeSPatrick Brown * @param string $newline  new line to insert
32242ea7f44SGerrit Uitslag * @param bool   $regex    use regexp?
3231bd6bbdeSPatrick Brown * @param int    $maxlines number of occurrences of the line to replace
324b158d625SSteven Danz * @return bool true on success
325b158d625SSteven Danz */
326d868eb89SAndreas Gohrfunction io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines = 0)
327d868eb89SAndreas Gohr{
328dc4a4eb0SPatrick Brown    if ((string)$oldline === '') {
329dc4a4eb0SPatrick Brown        trigger_error('$oldline parameter cannot be empty in io_replaceInFile()', E_USER_WARNING);
330dc4a4eb0SPatrick Brown        return false;
331dc4a4eb0SPatrick Brown    }
332dc4a4eb0SPatrick Brown
33379e79377SAndreas Gohr    if (!file_exists($file)) return true;
3341380fc45SAndreas Gohr
335b158d625SSteven Danz    io_lock($file);
3361380fc45SAndreas Gohr
3371380fc45SAndreas Gohr    // load into array
338b158d625SSteven Danz    if (substr($file, -3) == '.gz') {
33913c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
3401380fc45SAndreas Gohr        $lines = gzfile($file);
341cfb71e37SPatrick Brown    } elseif (substr($file, -4) == '.bz2') {
34213c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
343cfb71e37SPatrick Brown        $lines = bzfile($file, true);
344b158d625SSteven Danz    } else {
3451380fc45SAndreas Gohr        $lines = file($file);
346b158d625SSteven Danz    }
347b158d625SSteven Danz
3489a734b7aSChristopher Smith    // make non-regexes into regexes
3493dfe7d64SChristopher Smith    $pattern = $regex ? $oldline : '/^'.preg_quote($oldline, '/').'$/';
3509a734b7aSChristopher Smith    $replace = $regex ? $newline : addcslashes($newline, '\$');
3519a734b7aSChristopher Smith
3529a734b7aSChristopher Smith    // remove matching lines
3536c000204SPatrick Brown    if ($maxlines > 0) {
3546c000204SPatrick Brown        $count = 0;
3559a734b7aSChristopher Smith        $matched = 0;
356a93ad676SAndreas Gohr        foreach ($lines as $i => $line) {
357a93ad676SAndreas Gohr            if ($count >= $maxlines) break;
3589a734b7aSChristopher Smith            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
3599a734b7aSChristopher Smith            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
3609a734b7aSChristopher Smith            if ($matched) $count++;
3616c000204SPatrick Brown        }
362e12c5ac7SChristopher Smith    } elseif ($maxlines == 0) {
363e12c5ac7SChristopher Smith        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
364e12c5ac7SChristopher Smith        if ((string)$newline !== '') {
3651bd6bbdeSPatrick Brown            $lines[] = $newline;
3661bd6bbdeSPatrick Brown        }
367e12c5ac7SChristopher Smith    } else {
368e12c5ac7SChristopher Smith        $lines = preg_replace($pattern, $replace, $lines);
369e12c5ac7SChristopher Smith    }
3701bd6bbdeSPatrick Brown
3711380fc45SAndreas Gohr    if (count($lines)) {
37224870174SAndreas Gohr        if (!_io_saveFile($file, implode('', $lines), false)) {
373b158d625SSteven Danz            msg("Removing content from $file failed", -1);
374fb7125eeSAndreas Gohr            io_unlock($file);
375b158d625SSteven Danz            return false;
376b158d625SSteven Danz        }
377b158d625SSteven Danz    } else {
378b158d625SSteven Danz        @unlink($file);
379b158d625SSteven Danz    }
380b158d625SSteven Danz
381b158d625SSteven Danz    io_unlock($file);
382b158d625SSteven Danz    return true;
383b158d625SSteven Danz}
384b158d625SSteven Danz
385b158d625SSteven Danz/**
3861bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
3871bd6bbdeSPatrick Brown *
3881bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
3891bd6bbdeSPatrick Brown *
3901bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
3911bd6bbdeSPatrick Brown *
3921bd6bbdeSPatrick Brown * @param string $file    filename
3931bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
3941bd6bbdeSPatrick Brown * @param bool   $regex   use regexp?
3951bd6bbdeSPatrick Brown * @return bool true on success
3961bd6bbdeSPatrick Brown */
397d868eb89SAndreas Gohrfunction io_deleteFromFile($file, $badline, $regex = false)
398d868eb89SAndreas Gohr{
3991bd6bbdeSPatrick Brown    return io_replaceInFile($file, $badline, null, $regex, 0);
4001bd6bbdeSPatrick Brown}
4011bd6bbdeSPatrick Brown
4021bd6bbdeSPatrick Brown/**
40390eb8392Sandi * Tries to lock a file
40490eb8392Sandi *
40590eb8392Sandi * Locking is only done for io_savefile and uses directories
40690eb8392Sandi * inside $conf['lockdir']
40790eb8392Sandi *
40890eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
40990eb8392Sandi * the lock is assumed to be stale and the function goes on
41090eb8392Sandi *
41190eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
41242ea7f44SGerrit Uitslag *
41342ea7f44SGerrit Uitslag * @param string $file filename
41490eb8392Sandi */
415d868eb89SAndreas Gohrfunction io_lock($file)
416d868eb89SAndreas Gohr{
41790eb8392Sandi    global $conf;
41890eb8392Sandi
41990eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
42090eb8392Sandi    @ignore_user_abort(1);
42190eb8392Sandi
42290eb8392Sandi    $timeStart = time();
42390eb8392Sandi    do {
42490eb8392Sandi        //waited longer than 3 seconds? -> stale lock
42590eb8392Sandi        if ((time() - $timeStart) > 3) break;
426bd539124SAndreas Gohr        $locked = @mkdir($lockDir);
42777b98903SAndreas Gohr        if ($locked) {
42823420346SDamien Regad            if ($conf['dperm']) chmod($lockDir, $conf['dperm']);
42977b98903SAndreas Gohr            break;
43077b98903SAndreas Gohr        }
43177b98903SAndreas Gohr        usleep(50);
43290eb8392Sandi    } while ($locked === false);
43390eb8392Sandi}
43490eb8392Sandi
43590eb8392Sandi/**
43690eb8392Sandi * Unlocks a file
43790eb8392Sandi *
43890eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
43942ea7f44SGerrit Uitslag *
44042ea7f44SGerrit Uitslag * @param string $file filename
44190eb8392Sandi */
442d868eb89SAndreas Gohrfunction io_unlock($file)
443d868eb89SAndreas Gohr{
44490eb8392Sandi    global $conf;
44590eb8392Sandi
44690eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
44790eb8392Sandi    @rmdir($lockDir);
44890eb8392Sandi    @ignore_user_abort(0);
44990eb8392Sandi}
45090eb8392Sandi
45190eb8392Sandi/**
452cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
453cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
454cc7d0c94SBen Coburn *
455cc7d0c94SBen Coburn * Event data:
456cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
457cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
458cc7d0c94SBen Coburn *
459cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
46042ea7f44SGerrit Uitslag *
46142ea7f44SGerrit Uitslag * @param string $id page id
46242ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
463cc7d0c94SBen Coburn */
464d868eb89SAndreas Gohrfunction io_createNamespace($id, $ns_type = 'pages')
465d868eb89SAndreas Gohr{
466cc7d0c94SBen Coburn    // verify ns_type
46724870174SAndreas Gohr    $types = ['pages'=>'wikiFN', 'media'=>'mediaFN'];
468cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
469cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
470cc7d0c94SBen Coburn        return;
471cc7d0c94SBen Coburn    }
472cc7d0c94SBen Coburn    // make event list
47324870174SAndreas Gohr    $missing = [];
474cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
475cc7d0c94SBen Coburn    $ns = $id;
476cc7d0c94SBen Coburn    $tmp = dirname($file = call_user_func($types[$ns_type], $ns));
47779e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
478cc7d0c94SBen Coburn        array_pop($ns_stack);
479cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
480177d6836SAndreas Gohr        if (strlen($ns)==0) {
481177d6836SAndreas Gohrbreak; }
482cc7d0c94SBen Coburn        $missing[] = $ns;
483cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
484cc7d0c94SBen Coburn    }
485cc7d0c94SBen Coburn    // make directories
486cc7d0c94SBen Coburn    io_makeFileDir($file);
487cc7d0c94SBen Coburn    // send the events
488cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
489cc7d0c94SBen Coburn    foreach ($missing as $ns) {
49024870174SAndreas Gohr        $data = [$ns, $ns_type];
491cbb44eabSAndreas Gohr        Event::createAndTrigger('IO_NAMESPACE_CREATED', $data);
492cc7d0c94SBen Coburn    }
493cc7d0c94SBen Coburn}
494cc7d0c94SBen Coburn
495cc7d0c94SBen Coburn/**
496f3f0262cSandi * Create the directory needed for the given file
49715fae107Sandi *
49815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
49942ea7f44SGerrit Uitslag *
50042ea7f44SGerrit Uitslag * @param string $file file name
501f3f0262cSandi */
502d868eb89SAndreas Gohrfunction io_makeFileDir($file)
503d868eb89SAndreas Gohr{
504f3f0262cSandi    $dir = dirname($file);
5050d8850c4SAndreas Gohr    if (!@is_dir($dir)) {
506f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed", -1);
507f3f0262cSandi    }
508f3f0262cSandi}
509f3f0262cSandi
510f3f0262cSandi/**
511f3f0262cSandi * Creates a directory hierachy.
512f3f0262cSandi *
51359752844SAnders Sandblad * @link    http://php.net/manual/en/function.mkdir.php
514f3f0262cSandi * @author  <saint@corenova.com>
5153dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
51642ea7f44SGerrit Uitslag *
51742ea7f44SGerrit Uitslag * @param string $target filename
51842ea7f44SGerrit Uitslag * @return bool|int|string
519f3f0262cSandi */
520d868eb89SAndreas Gohrfunction io_mkdir_p($target)
521d868eb89SAndreas Gohr{
5223dc3a5f1Sandi    global $conf;
5230d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
52479e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
5253dc3a5f1Sandi    //recursion
5263dc3a5f1Sandi    if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))) {
527bd539124SAndreas Gohr        $ret = @mkdir($target); // crawl back up & create dir tree
528443e135dSChristopher Smith        if ($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
52944881d27STroels Liebe Bentsen        return $ret;
5303dc3a5f1Sandi    }
531f3f0262cSandi    return 0;
532f3f0262cSandi}
533f3f0262cSandi
534f3f0262cSandi/**
5354d47e8e3SAndreas Gohr * Recursively delete a directory
5364d47e8e3SAndreas Gohr *
5374d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5384d47e8e3SAndreas Gohr * @param string $path
5394d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
5404d47e8e3SAndreas Gohr * @return bool
5414d47e8e3SAndreas Gohr */
542d868eb89SAndreas Gohrfunction io_rmdir($path, $removefiles = false)
543d868eb89SAndreas Gohr{
5444d47e8e3SAndreas Gohr    if (!is_string($path) || $path == "") return false;
545d8cf4dd4SAndreas Gohr    if (!file_exists($path)) return true; // it's already gone or was never there, count as success
5464d47e8e3SAndreas Gohr
5474d47e8e3SAndreas Gohr    if (is_dir($path) && !is_link($path)) {
54824870174SAndreas Gohr        $dirs  = [];
54924870174SAndreas Gohr        $files = [];
5504d47e8e3SAndreas Gohr        if (!$dh = @opendir($path)) return false;
5518426a3eeSAndreas Gohr        while (false !== ($f = readdir($dh))) {
5524d47e8e3SAndreas Gohr            if ($f == '..' || $f == '.') continue;
5534d47e8e3SAndreas Gohr
5544d47e8e3SAndreas Gohr            // collect dirs and files first
5554d47e8e3SAndreas Gohr            if (is_dir("$path/$f") && !is_link("$path/$f")) {
5564d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5574d47e8e3SAndreas Gohr            } elseif ($removefiles) {
5584d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5594d47e8e3SAndreas Gohr            } else {
5604d47e8e3SAndreas Gohr                return false; // abort when non empty
5614d47e8e3SAndreas Gohr            }
5624d47e8e3SAndreas Gohr        }
5634d47e8e3SAndreas Gohr        closedir($dh);
5644d47e8e3SAndreas Gohr        // now traverse into  directories first
5654d47e8e3SAndreas Gohr        foreach ($dirs as $dir) {
5664d47e8e3SAndreas Gohr            if (!io_rmdir($dir, $removefiles)) return false; // abort on any error
5674d47e8e3SAndreas Gohr        }
5684d47e8e3SAndreas Gohr        // now delete files
5694d47e8e3SAndreas Gohr        foreach ($files as $file) {
5704d47e8e3SAndreas Gohr            if (!@unlink($file)) return false; //abort on any error
5714d47e8e3SAndreas Gohr        }
5724d47e8e3SAndreas Gohr        // remove self
5734d47e8e3SAndreas Gohr        return @rmdir($path);
5744d47e8e3SAndreas Gohr    } elseif ($removefiles) {
5754d47e8e3SAndreas Gohr        return @unlink($path);
5764d47e8e3SAndreas Gohr    }
5774d47e8e3SAndreas Gohr    return false;
5784d47e8e3SAndreas Gohr}
5794d47e8e3SAndreas Gohr
5804d47e8e3SAndreas Gohr/**
581de862555SMichael Klier * Creates a unique temporary directory and returns
582de862555SMichael Klier * its path.
583de862555SMichael Klier *
584de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
58542ea7f44SGerrit Uitslag *
58642ea7f44SGerrit Uitslag * @return false|string path to new directory or false
587de862555SMichael Klier */
588d868eb89SAndreas Gohrfunction io_mktmpdir()
589d868eb89SAndreas Gohr{
590de862555SMichael Klier    global $conf;
591de862555SMichael Klier
592da1e1077SChris Smith    $base = $conf['tmpdir'];
59324870174SAndreas Gohr    $dir  = md5(uniqid(random_int(0, mt_getrandmax()), true));
594287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
595de862555SMichael Klier
596de862555SMichael Klier    if (io_mkdir_p($tmpdir)) {
597de862555SMichael Klier        return($tmpdir);
598de862555SMichael Klier    } else {
599de862555SMichael Klier        return false;
600de862555SMichael Klier    }
601de862555SMichael Klier}
602de862555SMichael Klier
603de862555SMichael Klier/**
60473ccfcb9Schris * downloads a file from the net and saves it
60573ccfcb9Schris *
60673ccfcb9Schris * if $useAttachment is false,
60773ccfcb9Schris * - $file is the full filename to save the file, incl. path
60873ccfcb9Schris * - if successful will return true, false otherwise
609db959ae3SAndreas Gohr *
61073ccfcb9Schris * if $useAttachment is true,
61173ccfcb9Schris * - $file is the directory where the file should be saved
61273ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
613b625487dSandi *
614b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
61573ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
61642ea7f44SGerrit Uitslag *
61742ea7f44SGerrit Uitslag * @param string $url           url to download
61842ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
61964159a61SAndreas Gohr * @param bool   $useAttachment true: try to use name of download, uses otherwise $defaultName
62064159a61SAndreas Gohr *                              false: uses $file as path to file
62142ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
62242ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
62342ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
624b625487dSandi */
625d868eb89SAndreas Gohrfunction io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2_097_152)
626d868eb89SAndreas Gohr{
627ac9115b0STroels Liebe Bentsen    global $conf;
6289b307a83SAndreas Gohr    $http = new DokuHTTPClient();
629847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6309b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
631a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6329b307a83SAndreas Gohr
6339b307a83SAndreas Gohr    $data = $http->get($url);
6349b307a83SAndreas Gohr    if (!$data) return false;
6359b307a83SAndreas Gohr
63673ccfcb9Schris    $name = '';
637cd2f903bSMichael Hamann    if ($useAttachment) {
63873ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
63973ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
64024870174SAndreas Gohr            $match=[];
641*7d34963bSAndreas Gohr            if (
642*7d34963bSAndreas Gohr                is_string($content_disposition) &&
643*7d34963bSAndreas Gohr                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)
644*7d34963bSAndreas Gohr            ) {
64524870174SAndreas Gohr                $name = PhpString::basename($match[1]);
64673ccfcb9Schris            }
64773ccfcb9Schris        }
64873ccfcb9Schris
64973ccfcb9Schris        if (!$name) {
65073ccfcb9Schris            if (!$defaultName) return false;
65173ccfcb9Schris            $name = $defaultName;
65273ccfcb9Schris        }
65373ccfcb9Schris
65424870174SAndreas Gohr        $file .= $name;
65573ccfcb9Schris    }
65673ccfcb9Schris
65779e79377SAndreas Gohr    $fileexists = file_exists($file);
6589b307a83SAndreas Gohr    $fp = @fopen($file, "w");
659b625487dSandi    if (!$fp) return false;
6609b307a83SAndreas Gohr    fwrite($fp, $data);
661b625487dSandi    fclose($fp);
66224870174SAndreas Gohr    if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
66373ccfcb9Schris    if ($useAttachment) return $name;
664b625487dSandi    return true;
665b625487dSandi}
666b625487dSandi
667b625487dSandi/**
668ac9115b0STroels Liebe Bentsen * Windows compatible rename
669bf5e5a5bSAndreas Gohr *
670bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
671bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
67242ea7f44SGerrit Uitslag *
67342ea7f44SGerrit Uitslag * @param string $from
67442ea7f44SGerrit Uitslag * @param string $to
67542ea7f44SGerrit Uitslag * @return bool succes or fail
676bf5e5a5bSAndreas Gohr */
677d868eb89SAndreas Gohrfunction io_rename($from, $to)
678d868eb89SAndreas Gohr{
679ac9115b0STroels Liebe Bentsen    global $conf;
680bf5e5a5bSAndreas Gohr    if (!@rename($from, $to)) {
681bf5e5a5bSAndreas Gohr        if (@copy($from, $to)) {
6828e0b019fSAndreas Gohr            if ($conf['fperm']) chmod($to, $conf['fperm']);
683bf5e5a5bSAndreas Gohr            @unlink($from);
684bf5e5a5bSAndreas Gohr            return true;
685bf5e5a5bSAndreas Gohr        }
686bf5e5a5bSAndreas Gohr        return false;
687bf5e5a5bSAndreas Gohr    }
688bf5e5a5bSAndreas Gohr    return true;
689bf5e5a5bSAndreas Gohr}
690bf5e5a5bSAndreas Gohr
691420edfd6STom N Harris/**
692420edfd6STom N Harris * Runs an external command with input and output pipes.
693420edfd6STom N Harris * Returns the exit code from the process.
694420edfd6STom N Harris *
695420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
69642ea7f44SGerrit Uitslag *
69742ea7f44SGerrit Uitslag * @param string $cmd
69842ea7f44SGerrit Uitslag * @param string $input  input pipe
69942ea7f44SGerrit Uitslag * @param string $output output pipe
70042ea7f44SGerrit Uitslag * @return int exit code from process
701420edfd6STom N Harris */
702d868eb89SAndreas Gohrfunction io_exec($cmd, $input, &$output)
703d868eb89SAndreas Gohr{
70424870174SAndreas Gohr    $descspec = [
70524870174SAndreas Gohr        0=>["pipe", "r"],
70624870174SAndreas Gohr        1=>["pipe", "w"],
70724870174SAndreas Gohr        2=>["pipe", "w"]
70824870174SAndreas Gohr    ];
7096c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7106c528220STom N Harris    if (!$ph) return -1;
7116c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7126c528220STom N Harris    fwrite($pipes[0], $input);
7136c528220STom N Harris    fclose($pipes[0]);
7146c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7156c528220STom N Harris    fclose($pipes[1]);
7166c528220STom N Harris    return proc_close($ph);
717f3f0262cSandi}
718f3f0262cSandi
7197421c3ccSAndreas Gohr/**
7207421c3ccSAndreas Gohr * Search a file for matching lines
7217421c3ccSAndreas Gohr *
7227421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7237421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7247421c3ccSAndreas Gohr * at once.
7257421c3ccSAndreas Gohr *
7267421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7277421c3ccSAndreas Gohr * @param  string $file    The file to search
7287421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
7297421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
730cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
731cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
7327421c3ccSAndreas Gohr */
733d868eb89SAndreas Gohrfunction io_grep($file, $pattern, $max = 0, $backref = false)
734d868eb89SAndreas Gohr{
7357421c3ccSAndreas Gohr    $fh = @fopen($file, 'r');
7367421c3ccSAndreas Gohr    if (!$fh) return false;
73724870174SAndreas Gohr    $matches = [];
7387421c3ccSAndreas Gohr
7397421c3ccSAndreas Gohr    $cnt  = 0;
7407421c3ccSAndreas Gohr    $line = '';
7417421c3ccSAndreas Gohr    while (!feof($fh)) {
7427421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7437421c3ccSAndreas Gohr        if (substr($line, -1) != "\n") continue;
7447421c3ccSAndreas Gohr
7457421c3ccSAndreas Gohr        // check if line matches
7467421c3ccSAndreas Gohr        if (preg_match($pattern, $line, $match)) {
7477421c3ccSAndreas Gohr            if ($backref) {
7487421c3ccSAndreas Gohr                $matches[] = $match;
7497421c3ccSAndreas Gohr            } else {
7507421c3ccSAndreas Gohr                $matches[] = $line;
7517421c3ccSAndreas Gohr            }
7527421c3ccSAndreas Gohr            $cnt++;
7537421c3ccSAndreas Gohr        }
7547421c3ccSAndreas Gohr        if ($max && $max == $cnt) break;
7557421c3ccSAndreas Gohr        $line = '';
7567421c3ccSAndreas Gohr    }
7577421c3ccSAndreas Gohr    fclose($fh);
7587421c3ccSAndreas Gohr    return $matches;
7597421c3ccSAndreas Gohr}
7607421c3ccSAndreas Gohr
761f549be3dSGerrit Uitslag
762f549be3dSGerrit Uitslag/**
763f549be3dSGerrit Uitslag * Get size of contents of a file, for a compressed file the uncompressed size
764f549be3dSGerrit Uitslag * Warning: reading uncompressed size of content of bz-files requires uncompressing
765f549be3dSGerrit Uitslag *
766f549be3dSGerrit Uitslag * @author  Gerrit Uitslag <klapinklapin@gmail.com>
767f549be3dSGerrit Uitslag *
768f549be3dSGerrit Uitslag * @param string $file filename path to file
769f549be3dSGerrit Uitslag * @return int size of file
770f549be3dSGerrit Uitslag */
771d868eb89SAndreas Gohrfunction io_getSizeFile($file)
772d868eb89SAndreas Gohr{
773f549be3dSGerrit Uitslag    if (!file_exists($file)) return 0;
774f549be3dSGerrit Uitslag
775f549be3dSGerrit Uitslag    if (substr($file, -3) == '.gz') {
776f549be3dSGerrit Uitslag        $fp = @fopen($file, "rb");
777f549be3dSGerrit Uitslag        if ($fp === false) return 0;
778f549be3dSGerrit Uitslag        fseek($fp, -4, SEEK_END);
779f549be3dSGerrit Uitslag        $buffer = fread($fp, 4);
780f549be3dSGerrit Uitslag        fclose($fp);
781f549be3dSGerrit Uitslag        $array = unpack("V", $buffer);
782f549be3dSGerrit Uitslag        $uncompressedsize = end($array);
783f549be3dSGerrit Uitslag    } elseif (substr($file, -4) == '.bz2') {
784f549be3dSGerrit Uitslag        if (!DOKU_HAS_BZIP) return 0;
785f549be3dSGerrit Uitslag        $bz = bzopen($file, "r");
786f549be3dSGerrit Uitslag        if ($bz === false) return 0;
787f549be3dSGerrit Uitslag        $uncompressedsize = 0;
788f549be3dSGerrit Uitslag        while (!feof($bz)) {
789f549be3dSGerrit Uitslag            //8192 seems to be the maximum buffersize?
790f549be3dSGerrit Uitslag            $buffer = bzread($bz, 8192);
791f549be3dSGerrit Uitslag            if (($buffer === false) || (bzerrno($bz) !== 0)) {
792f549be3dSGerrit Uitslag                return 0;
793f549be3dSGerrit Uitslag            }
794f549be3dSGerrit Uitslag            $uncompressedsize += strlen($buffer);
795f549be3dSGerrit Uitslag        }
796f549be3dSGerrit Uitslag    } else {
797f549be3dSGerrit Uitslag        $uncompressedsize = filesize($file);
798f549be3dSGerrit Uitslag    }
799f549be3dSGerrit Uitslag
800f549be3dSGerrit Uitslag    return $uncompressedsize;
801f549be3dSGerrit Uitslag }
802