xref: /dokuwiki/inc/io.php (revision 2fb31c4fed0ff12d61c4239c5fe25d3d2005f183)
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
70c826df86SAndreas 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)) {
1206c16a3a9Sfiwswe        if (str_ends_with($file, '.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            }
1266c16a3a9Sfiwswe        } elseif (str_ends_with($file, '.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
203c826df86SAndreas 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
2586c16a3a9Sfiwswe    if (str_ends_with($file, '.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);
2646c16a3a9Sfiwswe    } elseif (str_ends_with($file, '.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
3556c16a3a9Sfiwswe    if (str_ends_with($file, '.gz')) {
35613c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
3571380fc45SAndreas Gohr        $lines = gzfile($file);
3586c16a3a9Sfiwswe    } elseif (str_ends_with($file, '.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{
418*2fb31c4fSAndreas Gohr    return io_replaceInFile($file, $badline, '', $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)) {
528c347b097Ssplitbrain        if (!io_mkdir_p($dir)) {
529c347b097Ssplitbrain            msg("Creating directory $dir failed", -1);
530c347b097Ssplitbrain        }
531f3f0262cSandi    }
532f3f0262cSandi}
533f3f0262cSandi
534f3f0262cSandi/**
535f3f0262cSandi * Creates a directory hierachy.
536f3f0262cSandi *
537aa659bbaSGerrit Uitslag * @param string $target filename
538679f3774SGerrit Uitslag * @return bool
539aa659bbaSGerrit Uitslag *
54059752844SAnders Sandblad * @link    http://php.net/manual/en/function.mkdir.php
541f3f0262cSandi * @author  <saint@corenova.com>
5423dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
543f3f0262cSandi */
544d868eb89SAndreas Gohrfunction io_mkdir_p($target)
545d868eb89SAndreas Gohr{
5463dc3a5f1Sandi    global $conf;
547679f3774SGerrit Uitslag    if (@is_dir($target) || empty($target)) return true; // best case check first
548679f3774SGerrit Uitslag    if (file_exists($target) && !is_dir($target)) return false;
5493dc3a5f1Sandi    //recursion
5503dc3a5f1Sandi    if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))) {
551bd539124SAndreas Gohr        $ret = @mkdir($target); // crawl back up & create dir tree
552aa659bbaSGerrit Uitslag        if ($ret && !empty($conf['dperm'])) {
553aa659bbaSGerrit Uitslag            chmod($target, $conf['dperm']);
554aa659bbaSGerrit Uitslag        }
55544881d27STroels Liebe Bentsen        return $ret;
5563dc3a5f1Sandi    }
557679f3774SGerrit Uitslag    return false;
558f3f0262cSandi}
559f3f0262cSandi
560f3f0262cSandi/**
5614d47e8e3SAndreas Gohr * Recursively delete a directory
5624d47e8e3SAndreas Gohr *
5634d47e8e3SAndreas Gohr * @param string $path
5644d47e8e3SAndreas Gohr * @param bool $removefiles defaults to false which will delete empty directories only
5654d47e8e3SAndreas Gohr * @return bool
566aa659bbaSGerrit Uitslag *
567aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
5684d47e8e3SAndreas Gohr */
569d868eb89SAndreas Gohrfunction io_rmdir($path, $removefiles = false)
570d868eb89SAndreas Gohr{
5714d47e8e3SAndreas Gohr    if (!is_string($path) || $path == "") return false;
572d8cf4dd4SAndreas Gohr    if (!file_exists($path)) return true; // it's already gone or was never there, count as success
5734d47e8e3SAndreas Gohr
5744d47e8e3SAndreas Gohr    if (is_dir($path) && !is_link($path)) {
57524870174SAndreas Gohr        $dirs = [];
57624870174SAndreas Gohr        $files = [];
5774d47e8e3SAndreas Gohr        if (!$dh = @opendir($path)) return false;
5788426a3eeSAndreas Gohr        while (false !== ($f = readdir($dh))) {
5794d47e8e3SAndreas Gohr            if ($f == '..' || $f == '.') continue;
5804d47e8e3SAndreas Gohr
5814d47e8e3SAndreas Gohr            // collect dirs and files first
5824d47e8e3SAndreas Gohr            if (is_dir("$path/$f") && !is_link("$path/$f")) {
5834d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5844d47e8e3SAndreas Gohr            } elseif ($removefiles) {
5854d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5864d47e8e3SAndreas Gohr            } else {
5874d47e8e3SAndreas Gohr                return false; // abort when non empty
5884d47e8e3SAndreas Gohr            }
5894d47e8e3SAndreas Gohr        }
5904d47e8e3SAndreas Gohr        closedir($dh);
5914d47e8e3SAndreas Gohr        // now traverse into  directories first
5924d47e8e3SAndreas Gohr        foreach ($dirs as $dir) {
5934d47e8e3SAndreas Gohr            if (!io_rmdir($dir, $removefiles)) return false; // abort on any error
5944d47e8e3SAndreas Gohr        }
5954d47e8e3SAndreas Gohr        // now delete files
5964d47e8e3SAndreas Gohr        foreach ($files as $file) {
5974d47e8e3SAndreas Gohr            if (!@unlink($file)) return false; //abort on any error
5984d47e8e3SAndreas Gohr        }
5994d47e8e3SAndreas Gohr        // remove self
6004d47e8e3SAndreas Gohr        return @rmdir($path);
6014d47e8e3SAndreas Gohr    } elseif ($removefiles) {
6024d47e8e3SAndreas Gohr        return @unlink($path);
6034d47e8e3SAndreas Gohr    }
6044d47e8e3SAndreas Gohr    return false;
6054d47e8e3SAndreas Gohr}
6064d47e8e3SAndreas Gohr
6074d47e8e3SAndreas Gohr/**
608de862555SMichael Klier * Creates a unique temporary directory and returns
609de862555SMichael Klier * its path.
610de862555SMichael Klier *
61142ea7f44SGerrit Uitslag * @return false|string path to new directory or false
612aa659bbaSGerrit Uitslag * @throws Exception
613aa659bbaSGerrit Uitslag *
614aa659bbaSGerrit Uitslag * @author Michael Klier <chi@chimeric.de>
615de862555SMichael Klier */
616d868eb89SAndreas Gohrfunction io_mktmpdir()
617d868eb89SAndreas Gohr{
618de862555SMichael Klier    global $conf;
619de862555SMichael Klier
620da1e1077SChris Smith    $base = $conf['tmpdir'];
62124870174SAndreas Gohr    $dir = md5(uniqid(random_int(0, mt_getrandmax()), true));
622287f35bdSAndreas Gohr    $tmpdir = $base . '/' . $dir;
623de862555SMichael Klier
624de862555SMichael Klier    if (io_mkdir_p($tmpdir)) {
625aa659bbaSGerrit Uitslag        return $tmpdir;
626de862555SMichael Klier    } else {
627de862555SMichael Klier        return false;
628de862555SMichael Klier    }
629de862555SMichael Klier}
630de862555SMichael Klier
631de862555SMichael Klier/**
63273ccfcb9Schris * downloads a file from the net and saves it
63373ccfcb9Schris *
63473ccfcb9Schris * if $useAttachment is false,
63573ccfcb9Schris * - $file is the full filename to save the file, incl. path
63673ccfcb9Schris * - if successful will return true, false otherwise
637db959ae3SAndreas Gohr *
63873ccfcb9Schris * if $useAttachment is true,
63973ccfcb9Schris * - $file is the directory where the file should be saved
64073ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
641b625487dSandi *
64242ea7f44SGerrit Uitslag * @param string $url url to download
64342ea7f44SGerrit Uitslag * @param string $file path to file or directory where to save
64464159a61SAndreas Gohr * @param bool $useAttachment true: try to use name of download, uses otherwise $defaultName
64564159a61SAndreas Gohr *                            false: uses $file as path to file
64642ea7f44SGerrit Uitslag * @param string $defaultName fallback for if using $useAttachment
64742ea7f44SGerrit Uitslag * @param int $maxSize maximum file size
64842ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
649aa659bbaSGerrit Uitslag *
650aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
651aa659bbaSGerrit Uitslag * @author Chris Smith <chris@jalakai.co.uk>
652b625487dSandi */
653d868eb89SAndreas Gohrfunction io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2_097_152)
654d868eb89SAndreas Gohr{
655ac9115b0STroels Liebe Bentsen    global $conf;
6569b307a83SAndreas Gohr    $http = new DokuHTTPClient();
657847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6589b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
659a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6609b307a83SAndreas Gohr
6619b307a83SAndreas Gohr    $data = $http->get($url);
6629b307a83SAndreas Gohr    if (!$data) return false;
6639b307a83SAndreas Gohr
66473ccfcb9Schris    $name = '';
665cd2f903bSMichael Hamann    if ($useAttachment) {
66673ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
66773ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
66824870174SAndreas Gohr            $match = [];
6697d34963bSAndreas Gohr            if (
6707d34963bSAndreas Gohr                is_string($content_disposition) &&
6717d34963bSAndreas Gohr                preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)
6727d34963bSAndreas Gohr            ) {
67324870174SAndreas Gohr                $name = PhpString::basename($match[1]);
67473ccfcb9Schris            }
67573ccfcb9Schris        }
67673ccfcb9Schris
67773ccfcb9Schris        if (!$name) {
67873ccfcb9Schris            if (!$defaultName) return false;
67973ccfcb9Schris            $name = $defaultName;
68073ccfcb9Schris        }
68173ccfcb9Schris
68224870174SAndreas Gohr        $file .= $name;
68373ccfcb9Schris    }
68473ccfcb9Schris
68579e79377SAndreas Gohr    $fileexists = file_exists($file);
6869b307a83SAndreas Gohr    $fp = @fopen($file, "w");
687b625487dSandi    if (!$fp) return false;
6889b307a83SAndreas Gohr    fwrite($fp, $data);
689b625487dSandi    fclose($fp);
690aa659bbaSGerrit Uitslag    if (!$fileexists && $conf['fperm']) {
691aa659bbaSGerrit Uitslag        chmod($file, $conf['fperm']);
692aa659bbaSGerrit Uitslag    }
69373ccfcb9Schris    if ($useAttachment) return $name;
694b625487dSandi    return true;
695b625487dSandi}
696b625487dSandi
697b625487dSandi/**
698ac9115b0STroels Liebe Bentsen * Windows compatible rename
699bf5e5a5bSAndreas Gohr *
700bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
701bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
70242ea7f44SGerrit Uitslag *
70342ea7f44SGerrit Uitslag * @param string $from
70442ea7f44SGerrit Uitslag * @param string $to
70542ea7f44SGerrit Uitslag * @return bool succes or fail
706bf5e5a5bSAndreas Gohr */
707d868eb89SAndreas Gohrfunction io_rename($from, $to)
708d868eb89SAndreas Gohr{
709ac9115b0STroels Liebe Bentsen    global $conf;
710bf5e5a5bSAndreas Gohr    if (!@rename($from, $to)) {
711bf5e5a5bSAndreas Gohr        if (@copy($from, $to)) {
712aa659bbaSGerrit Uitslag            if ($conf['fperm']) {
713aa659bbaSGerrit Uitslag                chmod($to, $conf['fperm']);
714aa659bbaSGerrit Uitslag            }
715bf5e5a5bSAndreas Gohr            @unlink($from);
716bf5e5a5bSAndreas Gohr            return true;
717bf5e5a5bSAndreas Gohr        }
718bf5e5a5bSAndreas Gohr        return false;
719bf5e5a5bSAndreas Gohr    }
720bf5e5a5bSAndreas Gohr    return true;
721bf5e5a5bSAndreas Gohr}
722bf5e5a5bSAndreas Gohr
723420edfd6STom N Harris/**
724420edfd6STom N Harris * Runs an external command with input and output pipes.
725420edfd6STom N Harris * Returns the exit code from the process.
726420edfd6STom N Harris *
72742ea7f44SGerrit Uitslag * @param string $cmd
72842ea7f44SGerrit Uitslag * @param string $input input pipe
72942ea7f44SGerrit Uitslag * @param string $output output pipe
73042ea7f44SGerrit Uitslag * @return int exit code from process
731aa659bbaSGerrit Uitslag *
732aa659bbaSGerrit Uitslag * @author Tom N Harris <tnharris@whoopdedo.org>
733420edfd6STom N Harris */
734d868eb89SAndreas Gohrfunction io_exec($cmd, $input, &$output)
735d868eb89SAndreas Gohr{
73624870174SAndreas Gohr    $descspec = [
73724870174SAndreas Gohr        0 => ["pipe", "r"],
73824870174SAndreas Gohr        1 => ["pipe", "w"],
73924870174SAndreas Gohr        2 => ["pipe", "w"]
74024870174SAndreas Gohr    ];
7416c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7426c528220STom N Harris    if (!$ph) return -1;
7436c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7446c528220STom N Harris    fwrite($pipes[0], $input);
7456c528220STom N Harris    fclose($pipes[0]);
7466c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7476c528220STom N Harris    fclose($pipes[1]);
7486c528220STom N Harris    return proc_close($ph);
749f3f0262cSandi}
750f3f0262cSandi
7517421c3ccSAndreas Gohr/**
7527421c3ccSAndreas Gohr * Search a file for matching lines
7537421c3ccSAndreas Gohr *
7547421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7557421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7567421c3ccSAndreas Gohr * at once.
7577421c3ccSAndreas Gohr *
7587421c3ccSAndreas Gohr * @param string $file The file to search
7597421c3ccSAndreas Gohr * @param string $pattern PCRE pattern
7607421c3ccSAndreas Gohr * @param int $max How many lines to return (0 for all)
761cd2f903bSMichael Hamann * @param bool $backref When true returns array with backreferences instead of lines
762cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
763aa659bbaSGerrit Uitslag *
764aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
7657421c3ccSAndreas Gohr */
766d868eb89SAndreas Gohrfunction io_grep($file, $pattern, $max = 0, $backref = false)
767d868eb89SAndreas Gohr{
7687421c3ccSAndreas Gohr    $fh = @fopen($file, 'r');
7697421c3ccSAndreas Gohr    if (!$fh) return false;
77024870174SAndreas Gohr    $matches = [];
7717421c3ccSAndreas Gohr
7727421c3ccSAndreas Gohr    $cnt = 0;
7737421c3ccSAndreas Gohr    $line = '';
7747421c3ccSAndreas Gohr    while (!feof($fh)) {
7757421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7766c16a3a9Sfiwswe        if (!str_ends_with($line, "\n")) continue;
7777421c3ccSAndreas Gohr
7787421c3ccSAndreas Gohr        // check if line matches
7797421c3ccSAndreas Gohr        if (preg_match($pattern, $line, $match)) {
7807421c3ccSAndreas Gohr            if ($backref) {
7817421c3ccSAndreas Gohr                $matches[] = $match;
7827421c3ccSAndreas Gohr            } else {
7837421c3ccSAndreas Gohr                $matches[] = $line;
7847421c3ccSAndreas Gohr            }
7857421c3ccSAndreas Gohr            $cnt++;
7867421c3ccSAndreas Gohr        }
7877421c3ccSAndreas Gohr        if ($max && $max == $cnt) break;
7887421c3ccSAndreas Gohr        $line = '';
7897421c3ccSAndreas Gohr    }
7907421c3ccSAndreas Gohr    fclose($fh);
7917421c3ccSAndreas Gohr    return $matches;
7927421c3ccSAndreas Gohr}
7937421c3ccSAndreas Gohr
794f549be3dSGerrit Uitslag
795f549be3dSGerrit Uitslag/**
796f549be3dSGerrit Uitslag * Get size of contents of a file, for a compressed file the uncompressed size
797f549be3dSGerrit Uitslag * Warning: reading uncompressed size of content of bz-files requires uncompressing
798f549be3dSGerrit Uitslag *
799f549be3dSGerrit Uitslag * @param string $file filename path to file
800f549be3dSGerrit Uitslag * @return int size of file
801aa659bbaSGerrit Uitslag *
802aa659bbaSGerrit Uitslag * @author  Gerrit Uitslag <klapinklapin@gmail.com>
803f549be3dSGerrit Uitslag */
804d868eb89SAndreas Gohrfunction io_getSizeFile($file)
805d868eb89SAndreas Gohr{
806f549be3dSGerrit Uitslag    if (!file_exists($file)) return 0;
807f549be3dSGerrit Uitslag
8086c16a3a9Sfiwswe    if (str_ends_with($file, '.gz')) {
809f549be3dSGerrit Uitslag        $fp = @fopen($file, "rb");
810f549be3dSGerrit Uitslag        if ($fp === false) return 0;
811f549be3dSGerrit Uitslag        fseek($fp, -4, SEEK_END);
812f549be3dSGerrit Uitslag        $buffer = fread($fp, 4);
813f549be3dSGerrit Uitslag        fclose($fp);
814f549be3dSGerrit Uitslag        $array = unpack("V", $buffer);
815f549be3dSGerrit Uitslag        $uncompressedsize = end($array);
8166c16a3a9Sfiwswe    } elseif (str_ends_with($file, '.bz2')) {
817f549be3dSGerrit Uitslag        if (!DOKU_HAS_BZIP) return 0;
818f549be3dSGerrit Uitslag        $bz = bzopen($file, "r");
819f549be3dSGerrit Uitslag        if ($bz === false) return 0;
820f549be3dSGerrit Uitslag        $uncompressedsize = 0;
821f549be3dSGerrit Uitslag        while (!feof($bz)) {
822f549be3dSGerrit Uitslag            //8192 seems to be the maximum buffersize?
823f549be3dSGerrit Uitslag            $buffer = bzread($bz, 8192);
824f549be3dSGerrit Uitslag            if (($buffer === false) || (bzerrno($bz) !== 0)) {
825f549be3dSGerrit Uitslag                return 0;
826f549be3dSGerrit Uitslag            }
827f549be3dSGerrit Uitslag            $uncompressedsize += strlen($buffer);
828f549be3dSGerrit Uitslag        }
829f549be3dSGerrit Uitslag    } else {
830f549be3dSGerrit Uitslag        $uncompressedsize = filesize($file);
831f549be3dSGerrit Uitslag    }
832f549be3dSGerrit Uitslag
833f549be3dSGerrit Uitslag    return $uncompressedsize;
834f549be3dSGerrit Uitslag}
835