xref: /dokuwiki/inc/io.php (revision c826df8638a6b5c464282376ead61803e00205ea)
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 *
6842ea7f44SGerrit Uitslag * @param string $file filename
6942ea7f44SGerrit Uitslag * @param string $id page id
70*c826df86SAndreas Gohr * @param bool|int|string $rev revision timestamp
7142ea7f44SGerrit Uitslag * @return string
72aa659bbaSGerrit Uitslag *
73aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
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 *
8742ea7f44SGerrit Uitslag * @param array $data event data
8842ea7f44SGerrit Uitslag * @return string
89aa659bbaSGerrit Uitslag *
90aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
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 *
10942ea7f44SGerrit Uitslag *
11042ea7f44SGerrit Uitslag * @param string $file filename
11142ea7f44SGerrit Uitslag * @param bool $clean
112d387bf5eSAndreas Gohr * @return string|bool the file contents or false on error
113aa659bbaSGerrit Uitslag *
114aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
115f3f0262cSandi */
116d868eb89SAndreas Gohrfunction io_readFile($file, $clean = true)
117d868eb89SAndreas Gohr{
118f3f0262cSandi    $ret = '';
11979e79377SAndreas Gohr    if (file_exists($file)) {
120f3f0262cSandi        if (substr($file, -3) == '.gz') {
12113c37900SAndreas Gohr            if (!DOKU_HAS_GZIP) return false;
1222ad45addSAndreas Gohr            $ret = gzfile($file);
123aa659bbaSGerrit Uitslag            if (is_array($ret)) {
124aa659bbaSGerrit Uitslag                $ret = implode('', $ret);
125aa659bbaSGerrit Uitslag            }
126ff3ed99fSmarcel        } elseif (substr($file, -4) == '.bz2') {
12713c37900SAndreas Gohr            if (!DOKU_HAS_BZIP) return false;
128ff3ed99fSmarcel            $ret = bzfile($file);
129f3f0262cSandi        } else {
13043078d10SAndreas Gohr            $ret = file_get_contents($file);
131f3f0262cSandi        }
132f3f0262cSandi    }
1332ad45addSAndreas Gohr    if ($ret === null) return false;
134d387bf5eSAndreas Gohr    if ($ret !== false && $clean) {
135f3f0262cSandi        return cleanText($ret);
136e34c0709SAndreas Gohr    } else {
137e34c0709SAndreas Gohr        return $ret;
138e34c0709SAndreas Gohr    }
139f3f0262cSandi}
140aa659bbaSGerrit Uitslag
141ff3ed99fSmarcel/**
142ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
14342ea7f44SGerrit Uitslag *
14442ea7f44SGerrit Uitslag * @param string $file filename
145cfb71e37SPatrick Brown * @param bool $array return array of lines
146cfb71e37SPatrick Brown * @return string|array|bool content or false on error
147aa659bbaSGerrit Uitslag *
148aa659bbaSGerrit Uitslag * @author marcel senf <marcel@rucksackreinigung.de>
149aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
150ff3ed99fSmarcel */
151d868eb89SAndreas Gohrfunction bzfile($file, $array = false)
152d868eb89SAndreas Gohr{
153ff3ed99fSmarcel    $bz = bzopen($file, "r");
154d387bf5eSAndreas Gohr    if ($bz === false) return false;
155d387bf5eSAndreas Gohr
156aa659bbaSGerrit Uitslag    if ($array) {
157aa659bbaSGerrit Uitslag        $lines = [];
158aa659bbaSGerrit Uitslag    }
159cd2f903bSMichael Hamann    $str = '';
160ff3ed99fSmarcel    while (!feof($bz)) {
161ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
162d387bf5eSAndreas Gohr        $buffer = bzread($bz, 8192);
163d387bf5eSAndreas Gohr        if (($buffer === false) || (bzerrno($bz) !== 0)) {
164d387bf5eSAndreas Gohr            return false;
165d387bf5eSAndreas Gohr        }
16624870174SAndreas Gohr        $str .= $buffer;
167cfb71e37SPatrick Brown        if ($array) {
168cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
169cfb71e37SPatrick Brown            while ($pos !== false) {
170cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos + 1);
171cfb71e37SPatrick Brown                $str = substr($str, $pos + 1);
172cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
173cfb71e37SPatrick Brown            }
174cfb71e37SPatrick Brown        }
175ff3ed99fSmarcel    }
176ff3ed99fSmarcel    bzclose($bz);
177cfb71e37SPatrick Brown    if ($array) {
178aa659bbaSGerrit Uitslag        if ($str !== '') {
179aa659bbaSGerrit Uitslag            $lines[] = $str;
180aa659bbaSGerrit Uitslag        }
181cfb71e37SPatrick Brown        return $lines;
182cfb71e37SPatrick Brown    }
183ff3ed99fSmarcel    return $str;
184ff3ed99fSmarcel}
185ff3ed99fSmarcel
186f3f0262cSandi/**
187cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
188cc7d0c94SBen Coburn *
189cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
190cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
191cc7d0c94SBen Coburn * The file path should not be changed.
192cc7d0c94SBen Coburn * (The append parameter is set to false.)
193cc7d0c94SBen Coburn *
194cc7d0c94SBen Coburn * Event data:
195cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
196cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
197cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
198cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
199cc7d0c94SBen Coburn *
20042ea7f44SGerrit Uitslag * @param string $file filename
20142ea7f44SGerrit Uitslag * @param string $content
20242ea7f44SGerrit Uitslag * @param string $id page id
203*c826df86SAndreas Gohr * @param int|bool|string $rev timestamp of revision
20442ea7f44SGerrit Uitslag * @return bool
205aa659bbaSGerrit Uitslag *
206aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
207cc7d0c94SBen Coburn */
208d868eb89SAndreas Gohrfunction io_writeWikiPage($file, $content, $id, $rev = false)
209d868eb89SAndreas Gohr{
210177d6836SAndreas Gohr    if (empty($rev)) {
211d4f83172SAndreas Gohr        $rev = false;
212d4f83172SAndreas Gohr    }
213177d6836SAndreas Gohr    if ($rev === false) {
2144e2eb11eSGerrit Uitslag        io_createNamespace($id); // create namespaces as needed
2154e2eb11eSGerrit Uitslag    }
21624870174SAndreas Gohr    $data = [[$file, $content, false], getNS($id), noNS($id), $rev];
217cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
218cc7d0c94SBen Coburn}
219cc7d0c94SBen Coburn
220cc7d0c94SBen Coburn/**
221cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
22242ea7f44SGerrit Uitslag *
22342ea7f44SGerrit Uitslag * @param array $data event data
22442ea7f44SGerrit Uitslag * @return bool
225aa659bbaSGerrit Uitslag *
226aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
227cc7d0c94SBen Coburn */
228d868eb89SAndreas Gohrfunction _io_writeWikiPage_action($data)
229d868eb89SAndreas Gohr{
230cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0]) === 3) {
23124870174SAndreas Gohr        $ok = io_saveFile(...$data[0]);
232a4306b74SAndreas Gohr        // for attic files make sure the file has the mtime of the revision
233a4306b74SAndreas Gohr        if ($ok && is_int($data[3]) && $data[3] > 0) {
234a4306b74SAndreas Gohr            @touch($data[0][0], $data[3]);
235a4306b74SAndreas Gohr        }
236a4306b74SAndreas Gohr        return $ok;
237cc7d0c94SBen Coburn    } else {
238cc7d0c94SBen Coburn        return false; //callback error
239cc7d0c94SBen Coburn    }
240cc7d0c94SBen Coburn}
241cc7d0c94SBen Coburn
242cc7d0c94SBen Coburn/**
2431bd6bbdeSPatrick Brown * Internal function to save contents to a file.
2441bd6bbdeSPatrick Brown *
2451bd6bbdeSPatrick Brown * @param string $file filename path to file
2461bd6bbdeSPatrick Brown * @param string $content
2471bd6bbdeSPatrick Brown * @param bool $append
2481bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
249aa659bbaSGerrit Uitslag *
250aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
2511bd6bbdeSPatrick Brown */
252d868eb89SAndreas Gohrfunction _io_saveFile($file, $content, $append)
253d868eb89SAndreas Gohr{
2541bd6bbdeSPatrick Brown    global $conf;
2551bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
2561bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
2571bd6bbdeSPatrick Brown
2581bd6bbdeSPatrick Brown    if (substr($file, -3) == '.gz') {
25913c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
2601bd6bbdeSPatrick Brown        $fh = @gzopen($file, $mode . '9');
2611bd6bbdeSPatrick Brown        if (!$fh) return false;
2621bd6bbdeSPatrick Brown        gzwrite($fh, $content);
2631bd6bbdeSPatrick Brown        gzclose($fh);
2641bd6bbdeSPatrick Brown    } elseif (substr($file, -4) == '.bz2') {
26513c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
2661bd6bbdeSPatrick Brown        if ($append) {
2671bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
2681bd6bbdeSPatrick Brown            if ($bzcontent === false) return false;
2691bd6bbdeSPatrick Brown            $content = $bzcontent . $content;
2701bd6bbdeSPatrick Brown        }
2711bd6bbdeSPatrick Brown        $fh = @bzopen($file, 'w');
2721bd6bbdeSPatrick Brown        if (!$fh) return false;
2731bd6bbdeSPatrick Brown        bzwrite($fh, $content);
2741bd6bbdeSPatrick Brown        bzclose($fh);
2751bd6bbdeSPatrick Brown    } else {
2761bd6bbdeSPatrick Brown        $fh = @fopen($file, $mode);
2771bd6bbdeSPatrick Brown        if (!$fh) return false;
2781bd6bbdeSPatrick Brown        fwrite($fh, $content);
2791bd6bbdeSPatrick Brown        fclose($fh);
2801bd6bbdeSPatrick Brown    }
2811bd6bbdeSPatrick Brown
282aa659bbaSGerrit Uitslag    if (!$fileexists && $conf['fperm']) {
283aa659bbaSGerrit Uitslag        chmod($file, $conf['fperm']);
284aa659bbaSGerrit Uitslag    }
2851bd6bbdeSPatrick Brown    return true;
2861bd6bbdeSPatrick Brown}
2871bd6bbdeSPatrick Brown
2881bd6bbdeSPatrick Brown/**
28915fae107Sandi * Saves $content to $file.
290f3f0262cSandi *
2911380fc45SAndreas Gohr * If the third parameter is set to true the given content
2921380fc45SAndreas Gohr * will be appended.
2931380fc45SAndreas Gohr *
29415fae107Sandi * Uses gzip if extension is .gz
295ff3ed99fSmarcel * and bz2 if extension is .bz2
29615fae107Sandi *
29742ea7f44SGerrit Uitslag * @param string $file filename path to file
29842ea7f44SGerrit Uitslag * @param string $content
29942ea7f44SGerrit Uitslag * @param bool $append
30042ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
301aa659bbaSGerrit Uitslag *
302aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
303f3f0262cSandi */
304d868eb89SAndreas Gohrfunction io_saveFile($file, $content, $append = false)
305d868eb89SAndreas Gohr{
306f3f0262cSandi    io_makeFileDir($file);
30790eb8392Sandi    io_lock($file);
3081bd6bbdeSPatrick Brown    if (!_io_saveFile($file, $content, $append)) {
309f3f0262cSandi        msg("Writing $file failed", -1);
310fb7125eeSAndreas Gohr        io_unlock($file);
311f3f0262cSandi        return false;
312f3f0262cSandi    }
31390eb8392Sandi    io_unlock($file);
314f3f0262cSandi    return true;
315f3f0262cSandi}
316f3f0262cSandi
317f3f0262cSandi/**
3181bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
3191380fc45SAndreas Gohr *
320d93ba631SPatrick Brown * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
321d93ba631SPatrick Brown * A regex that matches any part of the line will remove the entire line in this mode.
322d93ba631SPatrick Brown * Captures in $newline are not available.
3231bd6bbdeSPatrick Brown *
324d93ba631SPatrick Brown * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
325d93ba631SPatrick Brown * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
326d93ba631SPatrick Brown *
327d93ba631SPatrick Brown * Be sure to include the trailing newline in $oldline when replacing entire lines.
328b158d625SSteven Danz *
329b158d625SSteven Danz * Uses gzip if extension is .gz
3301bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
3318b06d178Schris *
33242ea7f44SGerrit Uitslag * @param string $file filename
3331bd6bbdeSPatrick Brown * @param string $oldline exact linematch to remove
3341bd6bbdeSPatrick Brown * @param string $newline new line to insert
33542ea7f44SGerrit Uitslag * @param bool $regex use regexp?
3361bd6bbdeSPatrick Brown * @param int $maxlines number of occurrences of the line to replace
337b158d625SSteven Danz * @return bool true on success
338aa659bbaSGerrit Uitslag *
339aa659bbaSGerrit Uitslag * @author Steven Danz <steven-danz@kc.rr.com>
340aa659bbaSGerrit Uitslag * @author Christopher Smith <chris@jalakai.co.uk>
341aa659bbaSGerrit Uitslag * @author Patrick Brown <ptbrown@whoopdedo.org>
342b158d625SSteven Danz */
343d868eb89SAndreas Gohrfunction io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines = 0)
344d868eb89SAndreas Gohr{
345dc4a4eb0SPatrick Brown    if ((string)$oldline === '') {
346dc4a4eb0SPatrick Brown        trigger_error('$oldline parameter cannot be empty in io_replaceInFile()', E_USER_WARNING);
347dc4a4eb0SPatrick Brown        return false;
348dc4a4eb0SPatrick Brown    }
349dc4a4eb0SPatrick Brown
35079e79377SAndreas Gohr    if (!file_exists($file)) return true;
3511380fc45SAndreas Gohr
352b158d625SSteven Danz    io_lock($file);
3531380fc45SAndreas Gohr
3541380fc45SAndreas Gohr    // load into array
355b158d625SSteven Danz    if (substr($file, -3) == '.gz') {
35613c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
3571380fc45SAndreas Gohr        $lines = gzfile($file);
358cfb71e37SPatrick Brown    } elseif (substr($file, -4) == '.bz2') {
35913c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
360cfb71e37SPatrick Brown        $lines = bzfile($file, true);
361b158d625SSteven Danz    } else {
3621380fc45SAndreas Gohr        $lines = file($file);
363b158d625SSteven Danz    }
364b158d625SSteven Danz
3659a734b7aSChristopher Smith    // make non-regexes into regexes
3663dfe7d64SChristopher Smith    $pattern = $regex ? $oldline : '/^' . preg_quote($oldline, '/') . '$/';
3679a734b7aSChristopher Smith    $replace = $regex ? $newline : addcslashes($newline, '\$');
3689a734b7aSChristopher Smith
3699a734b7aSChristopher Smith    // remove matching lines
3706c000204SPatrick Brown    if ($maxlines > 0) {
3716c000204SPatrick Brown        $count = 0;
3729a734b7aSChristopher Smith        $matched = 0;
373a93ad676SAndreas Gohr        foreach ($lines as $i => $line) {
374a93ad676SAndreas Gohr            if ($count >= $maxlines) break;
3759a734b7aSChristopher Smith            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
3769a734b7aSChristopher Smith            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
377aa659bbaSGerrit Uitslag            if ($matched) {
378aa659bbaSGerrit Uitslag                $count++;
379aa659bbaSGerrit Uitslag            }
3806c000204SPatrick Brown        }
381e12c5ac7SChristopher Smith    } elseif ($maxlines == 0) {
382e12c5ac7SChristopher Smith        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
383e12c5ac7SChristopher Smith        if ((string)$newline !== '') {
3841bd6bbdeSPatrick Brown            $lines[] = $newline;
3851bd6bbdeSPatrick Brown        }
386e12c5ac7SChristopher Smith    } else {
387e12c5ac7SChristopher Smith        $lines = preg_replace($pattern, $replace, $lines);
388e12c5ac7SChristopher Smith    }
3891bd6bbdeSPatrick Brown
3901380fc45SAndreas Gohr    if (count($lines)) {
39124870174SAndreas Gohr        if (!_io_saveFile($file, implode('', $lines), false)) {
392b158d625SSteven Danz            msg("Removing content from $file failed", -1);
393fb7125eeSAndreas Gohr            io_unlock($file);
394b158d625SSteven Danz            return false;
395b158d625SSteven Danz        }
396b158d625SSteven Danz    } else {
397b158d625SSteven Danz        @unlink($file);
398b158d625SSteven Danz    }
399b158d625SSteven Danz
400b158d625SSteven Danz    io_unlock($file);
401b158d625SSteven Danz    return true;
402b158d625SSteven Danz}
403b158d625SSteven Danz
404b158d625SSteven Danz/**
4051bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
4061bd6bbdeSPatrick Brown *
4071bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
4081bd6bbdeSPatrick Brown *
4091bd6bbdeSPatrick Brown * @param string $file filename
4101bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
4111bd6bbdeSPatrick Brown * @param bool $regex use regexp?
4121bd6bbdeSPatrick Brown * @return bool true on success
413aa659bbaSGerrit Uitslag *
414aa659bbaSGerrit Uitslag * @author Patrick Brown <ptbrown@whoopdedo.org>
4151bd6bbdeSPatrick Brown */
416d868eb89SAndreas Gohrfunction io_deleteFromFile($file, $badline, $regex = false)
417d868eb89SAndreas Gohr{
4181bd6bbdeSPatrick Brown    return io_replaceInFile($file, $badline, null, $regex, 0);
4191bd6bbdeSPatrick Brown}
4201bd6bbdeSPatrick Brown
4211bd6bbdeSPatrick Brown/**
42290eb8392Sandi * Tries to lock a file
42390eb8392Sandi *
42490eb8392Sandi * Locking is only done for io_savefile and uses directories
42590eb8392Sandi * inside $conf['lockdir']
42690eb8392Sandi *
42790eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
42890eb8392Sandi * the lock is assumed to be stale and the function goes on
42990eb8392Sandi *
43042ea7f44SGerrit Uitslag * @param string $file filename
431aa659bbaSGerrit Uitslag *
432aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
43390eb8392Sandi */
434d868eb89SAndreas Gohrfunction io_lock($file)
435d868eb89SAndreas Gohr{
43690eb8392Sandi    global $conf;
43790eb8392Sandi
43890eb8392Sandi    $lockDir = $conf['lockdir'] . '/' . md5($file);
43990eb8392Sandi    @ignore_user_abort(1);
44090eb8392Sandi
44190eb8392Sandi    $timeStart = time();
44290eb8392Sandi    do {
44390eb8392Sandi        //waited longer than 3 seconds? -> stale lock
44490eb8392Sandi        if ((time() - $timeStart) > 3) break;
445bd539124SAndreas Gohr        $locked = @mkdir($lockDir);
44677b98903SAndreas Gohr        if ($locked) {
447aa659bbaSGerrit Uitslag            if ($conf['dperm']) {
448aa659bbaSGerrit Uitslag                chmod($lockDir, $conf['dperm']);
449aa659bbaSGerrit Uitslag            }
45077b98903SAndreas Gohr            break;
45177b98903SAndreas Gohr        }
45277b98903SAndreas Gohr        usleep(50);
45390eb8392Sandi    } while ($locked === false);
45490eb8392Sandi}
45590eb8392Sandi
45690eb8392Sandi/**
45790eb8392Sandi * Unlocks a file
45890eb8392Sandi *
45942ea7f44SGerrit Uitslag * @param string $file filename
460aa659bbaSGerrit Uitslag *
461aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
46290eb8392Sandi */
463d868eb89SAndreas Gohrfunction io_unlock($file)
464d868eb89SAndreas Gohr{
46590eb8392Sandi    global $conf;
46690eb8392Sandi
46790eb8392Sandi    $lockDir = $conf['lockdir'] . '/' . md5($file);
46890eb8392Sandi    @rmdir($lockDir);
46990eb8392Sandi    @ignore_user_abort(0);
47090eb8392Sandi}
47190eb8392Sandi
47290eb8392Sandi/**
473cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
474cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
475cc7d0c94SBen Coburn *
476cc7d0c94SBen Coburn * Event data:
477cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
478cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
479cc7d0c94SBen Coburn *
48042ea7f44SGerrit Uitslag * @param string $id page id
48142ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
482aa659bbaSGerrit Uitslag *
483aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
484cc7d0c94SBen Coburn */
485d868eb89SAndreas Gohrfunction io_createNamespace($id, $ns_type = 'pages')
486d868eb89SAndreas Gohr{
487cc7d0c94SBen Coburn    // verify ns_type
48824870174SAndreas Gohr    $types = ['pages' => 'wikiFN', 'media' => 'mediaFN'];
489cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
490cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
491cc7d0c94SBen Coburn        return;
492cc7d0c94SBen Coburn    }
493cc7d0c94SBen Coburn    // make event list
49424870174SAndreas Gohr    $missing = [];
495cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
496cc7d0c94SBen Coburn    $ns = $id;
497cc7d0c94SBen Coburn    $tmp = dirname($file = call_user_func($types[$ns_type], $ns));
49879e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
499cc7d0c94SBen Coburn        array_pop($ns_stack);
500cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
501177d6836SAndreas Gohr        if (strlen($ns) == 0) {
502d4f83172SAndreas Gohr            break;
503d4f83172SAndreas Gohr        }
504cc7d0c94SBen Coburn        $missing[] = $ns;
505cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
506cc7d0c94SBen Coburn    }
507cc7d0c94SBen Coburn    // make directories
508cc7d0c94SBen Coburn    io_makeFileDir($file);
509cc7d0c94SBen Coburn    // send the events
510cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
511cc7d0c94SBen Coburn    foreach ($missing as $ns) {
51224870174SAndreas Gohr        $data = [$ns, $ns_type];
513cbb44eabSAndreas Gohr        Event::createAndTrigger('IO_NAMESPACE_CREATED', $data);
514cc7d0c94SBen Coburn    }
515cc7d0c94SBen Coburn}
516cc7d0c94SBen Coburn
517cc7d0c94SBen Coburn/**
518f3f0262cSandi * Create the directory needed for the given file
51915fae107Sandi *
52042ea7f44SGerrit Uitslag * @param string $file file name
521aa659bbaSGerrit Uitslag *
522aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
523f3f0262cSandi */
524d868eb89SAndreas Gohrfunction io_makeFileDir($file)
525d868eb89SAndreas Gohr{
526f3f0262cSandi    $dir = dirname($file);
5270d8850c4SAndreas Gohr    if (!@is_dir($dir)) {
528f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed", -1);
529f3f0262cSandi    }
530f3f0262cSandi}
531f3f0262cSandi
532f3f0262cSandi/**
533f3f0262cSandi * Creates a directory hierachy.
534f3f0262cSandi *
535aa659bbaSGerrit Uitslag * @param string $target filename
536679f3774SGerrit Uitslag * @return bool
537aa659bbaSGerrit Uitslag *
53859752844SAnders Sandblad * @link    http://php.net/manual/en/function.mkdir.php
539f3f0262cSandi * @author  <saint@corenova.com>
5403dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
541f3f0262cSandi */
542d868eb89SAndreas Gohrfunction io_mkdir_p($target)
543d868eb89SAndreas Gohr{
5443dc3a5f1Sandi    global $conf;
545679f3774SGerrit Uitslag    if (@is_dir($target) || empty($target)) return true; // best case check first
546679f3774SGerrit Uitslag    if (file_exists($target) && !is_dir($target)) return false;
5473dc3a5f1Sandi    //recursion
5483dc3a5f1Sandi    if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))) {
549bd539124SAndreas Gohr        $ret = @mkdir($target); // crawl back up & create dir tree
550aa659bbaSGerrit Uitslag        if ($ret && !empty($conf['dperm'])) {
551aa659bbaSGerrit Uitslag            chmod($target, $conf['dperm']);
552aa659bbaSGerrit Uitslag        }
55344881d27STroels Liebe Bentsen        return $ret;
5543dc3a5f1Sandi    }
555679f3774SGerrit Uitslag    return false;
556f3f0262cSandi}
557f3f0262cSandi
558f3f0262cSandi/**
5594d47e8e3SAndreas Gohr * Recursively delete a directory
5604d47e8e3SAndreas Gohr *
5614d47e8e3SAndreas Gohr * @param string $path
5624d47e8e3SAndreas Gohr * @param bool $removefiles defaults to false which will delete empty directories only
5634d47e8e3SAndreas Gohr * @return bool
564aa659bbaSGerrit Uitslag *
565aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
5664d47e8e3SAndreas Gohr */
567d868eb89SAndreas Gohrfunction io_rmdir($path, $removefiles = false)
568d868eb89SAndreas Gohr{
5694d47e8e3SAndreas Gohr    if (!is_string($path) || $path == "") return false;
570d8cf4dd4SAndreas Gohr    if (!file_exists($path)) return true; // it's already gone or was never there, count as success
5714d47e8e3SAndreas Gohr
5724d47e8e3SAndreas Gohr    if (is_dir($path) && !is_link($path)) {
57324870174SAndreas Gohr        $dirs = [];
57424870174SAndreas Gohr        $files = [];
5754d47e8e3SAndreas Gohr        if (!$dh = @opendir($path)) return false;
5768426a3eeSAndreas Gohr        while (false !== ($f = readdir($dh))) {
5774d47e8e3SAndreas Gohr            if ($f == '..' || $f == '.') continue;
5784d47e8e3SAndreas Gohr
5794d47e8e3SAndreas Gohr            // collect dirs and files first
5804d47e8e3SAndreas Gohr            if (is_dir("$path/$f") && !is_link("$path/$f")) {
5814d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5824d47e8e3SAndreas Gohr            } elseif ($removefiles) {
5834d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5844d47e8e3SAndreas Gohr            } else {
5854d47e8e3SAndreas Gohr                return false; // abort when non empty
5864d47e8e3SAndreas Gohr            }
5874d47e8e3SAndreas Gohr        }
5884d47e8e3SAndreas Gohr        closedir($dh);
5894d47e8e3SAndreas Gohr        // now traverse into  directories first
5904d47e8e3SAndreas Gohr        foreach ($dirs as $dir) {
5914d47e8e3SAndreas Gohr            if (!io_rmdir($dir, $removefiles)) return false; // abort on any error
5924d47e8e3SAndreas Gohr        }
5934d47e8e3SAndreas Gohr        // now delete files
5944d47e8e3SAndreas Gohr        foreach ($files as $file) {
5954d47e8e3SAndreas Gohr            if (!@unlink($file)) return false; //abort on any error
5964d47e8e3SAndreas Gohr        }
5974d47e8e3SAndreas Gohr        // remove self
5984d47e8e3SAndreas Gohr        return @rmdir($path);
5994d47e8e3SAndreas Gohr    } elseif ($removefiles) {
6004d47e8e3SAndreas Gohr        return @unlink($path);
6014d47e8e3SAndreas Gohr    }
6024d47e8e3SAndreas Gohr    return false;
6034d47e8e3SAndreas Gohr}
6044d47e8e3SAndreas Gohr
6054d47e8e3SAndreas Gohr/**
606de862555SMichael Klier * Creates a unique temporary directory and returns
607de862555SMichael Klier * its path.
608de862555SMichael Klier *
60942ea7f44SGerrit Uitslag * @return false|string path to new directory or false
610aa659bbaSGerrit Uitslag * @throws Exception
611aa659bbaSGerrit Uitslag *
612aa659bbaSGerrit Uitslag * @author Michael Klier <chi@chimeric.de>
613de862555SMichael Klier */
614d868eb89SAndreas Gohrfunction io_mktmpdir()
615d868eb89SAndreas Gohr{
616de862555SMichael Klier    global $conf;
617de862555SMichael Klier
618da1e1077SChris Smith    $base = $conf['tmpdir'];
61924870174SAndreas Gohr    $dir = md5(uniqid(random_int(0, mt_getrandmax()), true));
620287f35bdSAndreas Gohr    $tmpdir = $base . '/' . $dir;
621de862555SMichael Klier
622de862555SMichael Klier    if (io_mkdir_p($tmpdir)) {
623aa659bbaSGerrit Uitslag        return $tmpdir;
624de862555SMichael Klier    } else {
625de862555SMichael Klier        return false;
626de862555SMichael Klier    }
627de862555SMichael Klier}
628de862555SMichael Klier
629de862555SMichael Klier/**
63073ccfcb9Schris * downloads a file from the net and saves it
63173ccfcb9Schris *
63273ccfcb9Schris * if $useAttachment is false,
63373ccfcb9Schris * - $file is the full filename to save the file, incl. path
63473ccfcb9Schris * - if successful will return true, false otherwise
635db959ae3SAndreas Gohr *
63673ccfcb9Schris * if $useAttachment is true,
63773ccfcb9Schris * - $file is the directory where the file should be saved
63873ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
639b625487dSandi *
64042ea7f44SGerrit Uitslag * @param string $url url to download
64142ea7f44SGerrit Uitslag * @param string $file path to file or directory where to save
64264159a61SAndreas Gohr * @param bool $useAttachment true: try to use name of download, uses otherwise $defaultName
64364159a61SAndreas Gohr *                            false: uses $file as path to file
64442ea7f44SGerrit Uitslag * @param string $defaultName fallback for if using $useAttachment
64542ea7f44SGerrit Uitslag * @param int $maxSize maximum file size
64642ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
647aa659bbaSGerrit Uitslag *
648aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
649aa659bbaSGerrit Uitslag * @author Chris Smith <chris@jalakai.co.uk>
650b625487dSandi */
651d868eb89SAndreas Gohrfunction io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2_097_152)
652d868eb89SAndreas Gohr{
653ac9115b0STroels Liebe Bentsen    global $conf;
6549b307a83SAndreas Gohr    $http = new DokuHTTPClient();
655847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6569b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
657a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6589b307a83SAndreas Gohr
6599b307a83SAndreas Gohr    $data = $http->get($url);
6609b307a83SAndreas Gohr    if (!$data) return false;
6619b307a83SAndreas Gohr
66273ccfcb9Schris    $name = '';
663cd2f903bSMichael Hamann    if ($useAttachment) {
66473ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
66573ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
66624870174SAndreas Gohr            $match = [];
6677d34963bSAndreas Gohr            if (
6687d34963bSAndreas Gohr                is_string($content_disposition) &&
6697d34963bSAndreas Gohr                preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)
6707d34963bSAndreas Gohr            ) {
67124870174SAndreas Gohr                $name = PhpString::basename($match[1]);
67273ccfcb9Schris            }
67373ccfcb9Schris        }
67473ccfcb9Schris
67573ccfcb9Schris        if (!$name) {
67673ccfcb9Schris            if (!$defaultName) return false;
67773ccfcb9Schris            $name = $defaultName;
67873ccfcb9Schris        }
67973ccfcb9Schris
68024870174SAndreas Gohr        $file .= $name;
68173ccfcb9Schris    }
68273ccfcb9Schris
68379e79377SAndreas Gohr    $fileexists = file_exists($file);
6849b307a83SAndreas Gohr    $fp = @fopen($file, "w");
685b625487dSandi    if (!$fp) return false;
6869b307a83SAndreas Gohr    fwrite($fp, $data);
687b625487dSandi    fclose($fp);
688aa659bbaSGerrit Uitslag    if (!$fileexists && $conf['fperm']) {
689aa659bbaSGerrit Uitslag        chmod($file, $conf['fperm']);
690aa659bbaSGerrit Uitslag    }
69173ccfcb9Schris    if ($useAttachment) return $name;
692b625487dSandi    return true;
693b625487dSandi}
694b625487dSandi
695b625487dSandi/**
696ac9115b0STroels Liebe Bentsen * Windows compatible rename
697bf5e5a5bSAndreas Gohr *
698bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
699bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
70042ea7f44SGerrit Uitslag *
70142ea7f44SGerrit Uitslag * @param string $from
70242ea7f44SGerrit Uitslag * @param string $to
70342ea7f44SGerrit Uitslag * @return bool succes or fail
704bf5e5a5bSAndreas Gohr */
705d868eb89SAndreas Gohrfunction io_rename($from, $to)
706d868eb89SAndreas Gohr{
707ac9115b0STroels Liebe Bentsen    global $conf;
708bf5e5a5bSAndreas Gohr    if (!@rename($from, $to)) {
709bf5e5a5bSAndreas Gohr        if (@copy($from, $to)) {
710aa659bbaSGerrit Uitslag            if ($conf['fperm']) {
711aa659bbaSGerrit Uitslag                chmod($to, $conf['fperm']);
712aa659bbaSGerrit Uitslag            }
713bf5e5a5bSAndreas Gohr            @unlink($from);
714bf5e5a5bSAndreas Gohr            return true;
715bf5e5a5bSAndreas Gohr        }
716bf5e5a5bSAndreas Gohr        return false;
717bf5e5a5bSAndreas Gohr    }
718bf5e5a5bSAndreas Gohr    return true;
719bf5e5a5bSAndreas Gohr}
720bf5e5a5bSAndreas Gohr
721420edfd6STom N Harris/**
722420edfd6STom N Harris * Runs an external command with input and output pipes.
723420edfd6STom N Harris * Returns the exit code from the process.
724420edfd6STom N Harris *
72542ea7f44SGerrit Uitslag * @param string $cmd
72642ea7f44SGerrit Uitslag * @param string $input input pipe
72742ea7f44SGerrit Uitslag * @param string $output output pipe
72842ea7f44SGerrit Uitslag * @return int exit code from process
729aa659bbaSGerrit Uitslag *
730aa659bbaSGerrit Uitslag * @author Tom N Harris <tnharris@whoopdedo.org>
731420edfd6STom N Harris */
732d868eb89SAndreas Gohrfunction io_exec($cmd, $input, &$output)
733d868eb89SAndreas Gohr{
73424870174SAndreas Gohr    $descspec = [
73524870174SAndreas Gohr        0 => ["pipe", "r"],
73624870174SAndreas Gohr        1 => ["pipe", "w"],
73724870174SAndreas Gohr        2 => ["pipe", "w"]
73824870174SAndreas Gohr    ];
7396c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7406c528220STom N Harris    if (!$ph) return -1;
7416c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7426c528220STom N Harris    fwrite($pipes[0], $input);
7436c528220STom N Harris    fclose($pipes[0]);
7446c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7456c528220STom N Harris    fclose($pipes[1]);
7466c528220STom N Harris    return proc_close($ph);
747f3f0262cSandi}
748f3f0262cSandi
7497421c3ccSAndreas Gohr/**
7507421c3ccSAndreas Gohr * Search a file for matching lines
7517421c3ccSAndreas Gohr *
7527421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7537421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7547421c3ccSAndreas Gohr * at once.
7557421c3ccSAndreas Gohr *
7567421c3ccSAndreas Gohr * @param string $file The file to search
7577421c3ccSAndreas Gohr * @param string $pattern PCRE pattern
7587421c3ccSAndreas Gohr * @param int $max How many lines to return (0 for all)
759cd2f903bSMichael Hamann * @param bool $backref When true returns array with backreferences instead of lines
760cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
761aa659bbaSGerrit Uitslag *
762aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
7637421c3ccSAndreas Gohr */
764d868eb89SAndreas Gohrfunction io_grep($file, $pattern, $max = 0, $backref = false)
765d868eb89SAndreas Gohr{
7667421c3ccSAndreas Gohr    $fh = @fopen($file, 'r');
7677421c3ccSAndreas Gohr    if (!$fh) return false;
76824870174SAndreas Gohr    $matches = [];
7697421c3ccSAndreas Gohr
7707421c3ccSAndreas Gohr    $cnt = 0;
7717421c3ccSAndreas Gohr    $line = '';
7727421c3ccSAndreas Gohr    while (!feof($fh)) {
7737421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7747421c3ccSAndreas Gohr        if (substr($line, -1) != "\n") continue;
7757421c3ccSAndreas Gohr
7767421c3ccSAndreas Gohr        // check if line matches
7777421c3ccSAndreas Gohr        if (preg_match($pattern, $line, $match)) {
7787421c3ccSAndreas Gohr            if ($backref) {
7797421c3ccSAndreas Gohr                $matches[] = $match;
7807421c3ccSAndreas Gohr            } else {
7817421c3ccSAndreas Gohr                $matches[] = $line;
7827421c3ccSAndreas Gohr            }
7837421c3ccSAndreas Gohr            $cnt++;
7847421c3ccSAndreas Gohr        }
7857421c3ccSAndreas Gohr        if ($max && $max == $cnt) break;
7867421c3ccSAndreas Gohr        $line = '';
7877421c3ccSAndreas Gohr    }
7887421c3ccSAndreas Gohr    fclose($fh);
7897421c3ccSAndreas Gohr    return $matches;
7907421c3ccSAndreas Gohr}
7917421c3ccSAndreas Gohr
792f549be3dSGerrit Uitslag
793f549be3dSGerrit Uitslag/**
794f549be3dSGerrit Uitslag * Get size of contents of a file, for a compressed file the uncompressed size
795f549be3dSGerrit Uitslag * Warning: reading uncompressed size of content of bz-files requires uncompressing
796f549be3dSGerrit Uitslag *
797f549be3dSGerrit Uitslag * @param string $file filename path to file
798f549be3dSGerrit Uitslag * @return int size of file
799aa659bbaSGerrit Uitslag *
800aa659bbaSGerrit Uitslag * @author  Gerrit Uitslag <klapinklapin@gmail.com>
801f549be3dSGerrit Uitslag */
802d868eb89SAndreas Gohrfunction io_getSizeFile($file)
803d868eb89SAndreas Gohr{
804f549be3dSGerrit Uitslag    if (!file_exists($file)) return 0;
805f549be3dSGerrit Uitslag
806f549be3dSGerrit Uitslag    if (substr($file, -3) == '.gz') {
807f549be3dSGerrit Uitslag        $fp = @fopen($file, "rb");
808f549be3dSGerrit Uitslag        if ($fp === false) return 0;
809f549be3dSGerrit Uitslag        fseek($fp, -4, SEEK_END);
810f549be3dSGerrit Uitslag        $buffer = fread($fp, 4);
811f549be3dSGerrit Uitslag        fclose($fp);
812f549be3dSGerrit Uitslag        $array = unpack("V", $buffer);
813f549be3dSGerrit Uitslag        $uncompressedsize = end($array);
814f549be3dSGerrit Uitslag    } elseif (substr($file, -4) == '.bz2') {
815f549be3dSGerrit Uitslag        if (!DOKU_HAS_BZIP) return 0;
816f549be3dSGerrit Uitslag        $bz = bzopen($file, "r");
817f549be3dSGerrit Uitslag        if ($bz === false) return 0;
818f549be3dSGerrit Uitslag        $uncompressedsize = 0;
819f549be3dSGerrit Uitslag        while (!feof($bz)) {
820f549be3dSGerrit Uitslag            //8192 seems to be the maximum buffersize?
821f549be3dSGerrit Uitslag            $buffer = bzread($bz, 8192);
822f549be3dSGerrit Uitslag            if (($buffer === false) || (bzerrno($bz) !== 0)) {
823f549be3dSGerrit Uitslag                return 0;
824f549be3dSGerrit Uitslag            }
825f549be3dSGerrit Uitslag            $uncompressedsize += strlen($buffer);
826f549be3dSGerrit Uitslag        }
827f549be3dSGerrit Uitslag    } else {
828f549be3dSGerrit Uitslag        $uncompressedsize = filesize($file);
829f549be3dSGerrit Uitslag    }
830f549be3dSGerrit Uitslag
831f549be3dSGerrit Uitslag    return $uncompressedsize;
832f549be3dSGerrit Uitslag}
833