xref: /dokuwiki/inc/io.php (revision 109ebc86261a0180ea28685cc90702b1c701198e)
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
10*109ebc86SAndreas Gohruse dokuwiki\Logger;
1124870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
125a8d6e48SMichael Großeuse dokuwiki\HTTP\DokuHTTPClient;
13cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
14198564abSMichael Große
15f3f0262cSandi/**
1653d6ccfeSandi * Removes empty directories
1753d6ccfeSandi *
18cc7d0c94SBen Coburn * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
19cc7d0c94SBen Coburn * Event data:
20cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
21cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
22cc7d0c94SBen Coburn *
23d186898bSAndreas Gohr * @param string $id - a pageid, the namespace of that id will be tried to deleted
24cd2f903bSMichael Hamann * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
25cd2f903bSMichael Hamann * @return bool - true if at least one namespace was deleted
2642ea7f44SGerrit Uitslag *
2753d6ccfeSandi * @author  Andreas Gohr <andi@splitbrain.org>
28cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
2953d6ccfeSandi */
30d868eb89SAndreas Gohrfunction io_sweepNS($id, $basedir = 'datadir')
31d868eb89SAndreas Gohr{
3253d6ccfeSandi    global $conf;
3324870174SAndreas Gohr    $types = ['datadir' => 'pages', 'mediadir' => 'media'];
3424870174SAndreas Gohr    $ns_type = ($types[$basedir] ?? false);
3553d6ccfeSandi
36d186898bSAndreas Gohr    $delone = false;
37d186898bSAndreas Gohr
3853d6ccfeSandi    //scan all namespaces
3953d6ccfeSandi    while (($id = getNS($id)) !== false) {
40755f1e03SAndreas Gohr        $dir = $conf[$basedir] . '/' . utf8_encodeFN(str_replace(':', '/', $id));
4153d6ccfeSandi
4253d6ccfeSandi        //try to delete dir else return
43cc7d0c94SBen Coburn        if (@rmdir($dir)) {
44cc7d0c94SBen Coburn            if ($ns_type !== false) {
4524870174SAndreas Gohr                $data = [$id, $ns_type];
46d186898bSAndreas Gohr                $delone = true; // we deleted at least one dir
47cbb44eabSAndreas Gohr                Event::createAndTrigger('IO_NAMESPACE_DELETED', $data);
48cc7d0c94SBen Coburn            }
49177d6836SAndreas Gohr        } else {
50d4f83172SAndreas Gohr            return $delone;
51d4f83172SAndreas Gohr        }
52cc7d0c94SBen Coburn    }
53d186898bSAndreas Gohr    return $delone;
54cc7d0c94SBen Coburn}
55cc7d0c94SBen Coburn
56cc7d0c94SBen Coburn/**
57cc7d0c94SBen Coburn * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
58cc7d0c94SBen Coburn *
59cc7d0c94SBen Coburn * Generates the action event which delegates to io_readFile().
60cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
61cc7d0c94SBen Coburn * The file path should not be changed.
62cc7d0c94SBen Coburn *
63cc7d0c94SBen Coburn * Event data:
64cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_readFile as an array.
65cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
66cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
67cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
68cc7d0c94SBen Coburn *
6942ea7f44SGerrit Uitslag * @param string $file filename
7042ea7f44SGerrit Uitslag * @param string $id page id
71c826df86SAndreas Gohr * @param bool|int|string $rev revision timestamp
7242ea7f44SGerrit Uitslag * @return string
73aa659bbaSGerrit Uitslag *
74aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
75cc7d0c94SBen Coburn */
76d868eb89SAndreas Gohrfunction io_readWikiPage($file, $id, $rev = false)
77d868eb89SAndreas Gohr{
78177d6836SAndreas Gohr    if (empty($rev)) {
79d4f83172SAndreas Gohr        $rev = false;
80d4f83172SAndreas Gohr    }
8124870174SAndreas Gohr    $data = [[$file, true], getNS($id), noNS($id), $rev];
82cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
83cc7d0c94SBen Coburn}
84cc7d0c94SBen Coburn
85cc7d0c94SBen Coburn/**
86cc7d0c94SBen Coburn * Callback adapter for io_readFile().
8742ea7f44SGerrit Uitslag *
8842ea7f44SGerrit Uitslag * @param array $data event data
8942ea7f44SGerrit Uitslag * @return string
90aa659bbaSGerrit Uitslag *
91aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
92cc7d0c94SBen Coburn */
93d868eb89SAndreas Gohrfunction _io_readWikiPage_action($data)
94d868eb89SAndreas Gohr{
95cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0]) === 2) {
9624870174SAndreas Gohr        return io_readFile(...$data[0]);
97cc7d0c94SBen Coburn    } else {
98cc7d0c94SBen Coburn        return ''; //callback error
9953d6ccfeSandi    }
10053d6ccfeSandi}
10153d6ccfeSandi
10253d6ccfeSandi/**
10315fae107Sandi * Returns content of $file as cleaned string.
10415fae107Sandi *
10515fae107Sandi * Uses gzip if extension is .gz
10615fae107Sandi *
107ee4c4a1bSAndreas Gohr * If you want to use the returned value in unserialize
108ee4c4a1bSAndreas Gohr * be sure to set $clean to false!
109ee4c4a1bSAndreas Gohr *
11042ea7f44SGerrit Uitslag *
11142ea7f44SGerrit Uitslag * @param string $file filename
11242ea7f44SGerrit Uitslag * @param bool $clean
113d387bf5eSAndreas Gohr * @return string|bool the file contents or false on error
114aa659bbaSGerrit Uitslag *
115aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
116f3f0262cSandi */
117d868eb89SAndreas Gohrfunction io_readFile($file, $clean = true)
118d868eb89SAndreas Gohr{
119f3f0262cSandi    $ret = '';
12079e79377SAndreas Gohr    if (file_exists($file)) {
1216c16a3a9Sfiwswe        if (str_ends_with($file, '.gz')) {
12213c37900SAndreas Gohr            if (!DOKU_HAS_GZIP) return false;
1232ad45addSAndreas Gohr            $ret = gzfile($file);
124aa659bbaSGerrit Uitslag            if (is_array($ret)) {
125aa659bbaSGerrit Uitslag                $ret = implode('', $ret);
126aa659bbaSGerrit Uitslag            }
1276c16a3a9Sfiwswe        } elseif (str_ends_with($file, '.bz2')) {
12813c37900SAndreas Gohr            if (!DOKU_HAS_BZIP) return false;
129ff3ed99fSmarcel            $ret = bzfile($file);
130f3f0262cSandi        } else {
13143078d10SAndreas Gohr            $ret = file_get_contents($file);
132f3f0262cSandi        }
133f3f0262cSandi    }
1342ad45addSAndreas Gohr    if ($ret === null) return false;
135d387bf5eSAndreas Gohr    if ($ret !== false && $clean) {
136f3f0262cSandi        return cleanText($ret);
137e34c0709SAndreas Gohr    } else {
138e34c0709SAndreas Gohr        return $ret;
139e34c0709SAndreas Gohr    }
140f3f0262cSandi}
141aa659bbaSGerrit Uitslag
142ff3ed99fSmarcel/**
143ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
14442ea7f44SGerrit Uitslag *
14542ea7f44SGerrit Uitslag * @param string $file filename
146cfb71e37SPatrick Brown * @param bool $array return array of lines
147cfb71e37SPatrick Brown * @return string|array|bool content or false on error
148aa659bbaSGerrit Uitslag *
149aa659bbaSGerrit Uitslag * @author marcel senf <marcel@rucksackreinigung.de>
150aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
151ff3ed99fSmarcel */
152d868eb89SAndreas Gohrfunction bzfile($file, $array = false)
153d868eb89SAndreas Gohr{
154ff3ed99fSmarcel    $bz = bzopen($file, "r");
155d387bf5eSAndreas Gohr    if ($bz === false) return false;
156d387bf5eSAndreas Gohr
157aa659bbaSGerrit Uitslag    if ($array) {
158aa659bbaSGerrit Uitslag        $lines = [];
159aa659bbaSGerrit Uitslag    }
160cd2f903bSMichael Hamann    $str = '';
161ff3ed99fSmarcel    while (!feof($bz)) {
162ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
163d387bf5eSAndreas Gohr        $buffer = bzread($bz, 8192);
164d387bf5eSAndreas Gohr        if (($buffer === false) || (bzerrno($bz) !== 0)) {
165d387bf5eSAndreas Gohr            return false;
166d387bf5eSAndreas Gohr        }
16724870174SAndreas Gohr        $str .= $buffer;
168cfb71e37SPatrick Brown        if ($array) {
169cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
170cfb71e37SPatrick Brown            while ($pos !== false) {
171cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos + 1);
172cfb71e37SPatrick Brown                $str = substr($str, $pos + 1);
173cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
174cfb71e37SPatrick Brown            }
175cfb71e37SPatrick Brown        }
176ff3ed99fSmarcel    }
177ff3ed99fSmarcel    bzclose($bz);
178cfb71e37SPatrick Brown    if ($array) {
179aa659bbaSGerrit Uitslag        if ($str !== '') {
180aa659bbaSGerrit Uitslag            $lines[] = $str;
181aa659bbaSGerrit Uitslag        }
182cfb71e37SPatrick Brown        return $lines;
183cfb71e37SPatrick Brown    }
184ff3ed99fSmarcel    return $str;
185ff3ed99fSmarcel}
186ff3ed99fSmarcel
187f3f0262cSandi/**
188cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
189cc7d0c94SBen Coburn *
190cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
191cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
192cc7d0c94SBen Coburn * The file path should not be changed.
193cc7d0c94SBen Coburn * (The append parameter is set to false.)
194cc7d0c94SBen Coburn *
195cc7d0c94SBen Coburn * Event data:
196cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
197cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
198cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
199cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
200cc7d0c94SBen Coburn *
20142ea7f44SGerrit Uitslag * @param string $file filename
20242ea7f44SGerrit Uitslag * @param string $content
20342ea7f44SGerrit Uitslag * @param string $id page id
204c826df86SAndreas Gohr * @param int|bool|string $rev timestamp of revision
20542ea7f44SGerrit Uitslag * @return bool
206aa659bbaSGerrit Uitslag *
207aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
208cc7d0c94SBen Coburn */
209d868eb89SAndreas Gohrfunction io_writeWikiPage($file, $content, $id, $rev = false)
210d868eb89SAndreas Gohr{
211177d6836SAndreas Gohr    if (empty($rev)) {
212d4f83172SAndreas Gohr        $rev = false;
213d4f83172SAndreas Gohr    }
214177d6836SAndreas Gohr    if ($rev === false) {
2154e2eb11eSGerrit Uitslag        io_createNamespace($id); // create namespaces as needed
2164e2eb11eSGerrit Uitslag    }
21724870174SAndreas Gohr    $data = [[$file, $content, false], getNS($id), noNS($id), $rev];
218cbb44eabSAndreas Gohr    return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
219cc7d0c94SBen Coburn}
220cc7d0c94SBen Coburn
221cc7d0c94SBen Coburn/**
222cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
22342ea7f44SGerrit Uitslag *
22442ea7f44SGerrit Uitslag * @param array $data event data
22542ea7f44SGerrit Uitslag * @return bool
226aa659bbaSGerrit Uitslag *
227aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
228cc7d0c94SBen Coburn */
229d868eb89SAndreas Gohrfunction _io_writeWikiPage_action($data)
230d868eb89SAndreas Gohr{
231cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0]) === 3) {
23224870174SAndreas Gohr        $ok = io_saveFile(...$data[0]);
233a4306b74SAndreas Gohr        // for attic files make sure the file has the mtime of the revision
234a4306b74SAndreas Gohr        if ($ok && is_int($data[3]) && $data[3] > 0) {
235a4306b74SAndreas Gohr            @touch($data[0][0], $data[3]);
236a4306b74SAndreas Gohr        }
237a4306b74SAndreas Gohr        return $ok;
238cc7d0c94SBen Coburn    } else {
239cc7d0c94SBen Coburn        return false; //callback error
240cc7d0c94SBen Coburn    }
241cc7d0c94SBen Coburn}
242cc7d0c94SBen Coburn
243cc7d0c94SBen Coburn/**
2441bd6bbdeSPatrick Brown * Internal function to save contents to a file.
2451bd6bbdeSPatrick Brown *
2461bd6bbdeSPatrick Brown * @param string $file filename path to file
2471bd6bbdeSPatrick Brown * @param string $content
2481bd6bbdeSPatrick Brown * @param bool $append
2491bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
250aa659bbaSGerrit Uitslag *
251aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
2521bd6bbdeSPatrick Brown */
253d868eb89SAndreas Gohrfunction _io_saveFile($file, $content, $append)
254d868eb89SAndreas Gohr{
2551bd6bbdeSPatrick Brown    global $conf;
2561bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
2571bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
2581bd6bbdeSPatrick Brown
2596c16a3a9Sfiwswe    if (str_ends_with($file, '.gz')) {
26013c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
2611bd6bbdeSPatrick Brown        $fh = @gzopen($file, $mode . '9');
2621bd6bbdeSPatrick Brown        if (!$fh) return false;
2631bd6bbdeSPatrick Brown        gzwrite($fh, $content);
2641bd6bbdeSPatrick Brown        gzclose($fh);
2656c16a3a9Sfiwswe    } elseif (str_ends_with($file, '.bz2')) {
26613c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
2671bd6bbdeSPatrick Brown        if ($append) {
2681bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
2691bd6bbdeSPatrick Brown            if ($bzcontent === false) return false;
2701bd6bbdeSPatrick Brown            $content = $bzcontent . $content;
2711bd6bbdeSPatrick Brown        }
2721bd6bbdeSPatrick Brown        $fh = @bzopen($file, 'w');
2731bd6bbdeSPatrick Brown        if (!$fh) return false;
2741bd6bbdeSPatrick Brown        bzwrite($fh, $content);
2751bd6bbdeSPatrick Brown        bzclose($fh);
2761bd6bbdeSPatrick Brown    } else {
2771bd6bbdeSPatrick Brown        $fh = @fopen($file, $mode);
2781bd6bbdeSPatrick Brown        if (!$fh) return false;
2791bd6bbdeSPatrick Brown        fwrite($fh, $content);
2801bd6bbdeSPatrick Brown        fclose($fh);
2811bd6bbdeSPatrick Brown    }
2821bd6bbdeSPatrick Brown
283aa659bbaSGerrit Uitslag    if (!$fileexists && $conf['fperm']) {
284aa659bbaSGerrit Uitslag        chmod($file, $conf['fperm']);
285aa659bbaSGerrit Uitslag    }
2861bd6bbdeSPatrick Brown    return true;
2871bd6bbdeSPatrick Brown}
2881bd6bbdeSPatrick Brown
2891bd6bbdeSPatrick Brown/**
29015fae107Sandi * Saves $content to $file.
291f3f0262cSandi *
2921380fc45SAndreas Gohr * If the third parameter is set to true the given content
2931380fc45SAndreas Gohr * will be appended.
2941380fc45SAndreas Gohr *
29515fae107Sandi * Uses gzip if extension is .gz
296ff3ed99fSmarcel * and bz2 if extension is .bz2
29715fae107Sandi *
29842ea7f44SGerrit Uitslag * @param string $file filename path to file
29942ea7f44SGerrit Uitslag * @param string $content
30042ea7f44SGerrit Uitslag * @param bool $append
30142ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
302aa659bbaSGerrit Uitslag *
303aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
304f3f0262cSandi */
305d868eb89SAndreas Gohrfunction io_saveFile($file, $content, $append = false)
306d868eb89SAndreas Gohr{
307f3f0262cSandi    io_makeFileDir($file);
30890eb8392Sandi    io_lock($file);
3091bd6bbdeSPatrick Brown    if (!_io_saveFile($file, $content, $append)) {
310f3f0262cSandi        msg("Writing $file failed", -1);
311fb7125eeSAndreas Gohr        io_unlock($file);
312f3f0262cSandi        return false;
313f3f0262cSandi    }
31490eb8392Sandi    io_unlock($file);
315f3f0262cSandi    return true;
316f3f0262cSandi}
317f3f0262cSandi
318f3f0262cSandi/**
3191bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
3201380fc45SAndreas Gohr *
321d93ba631SPatrick Brown * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
322d93ba631SPatrick Brown * A regex that matches any part of the line will remove the entire line in this mode.
323d93ba631SPatrick Brown * Captures in $newline are not available.
3241bd6bbdeSPatrick Brown *
325d93ba631SPatrick Brown * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
326d93ba631SPatrick Brown * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
327d93ba631SPatrick Brown *
328d93ba631SPatrick Brown * Be sure to include the trailing newline in $oldline when replacing entire lines.
329b158d625SSteven Danz *
330b158d625SSteven Danz * Uses gzip if extension is .gz
3311bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
3328b06d178Schris *
33342ea7f44SGerrit Uitslag * @param string $file filename
3341bd6bbdeSPatrick Brown * @param string $oldline exact linematch to remove
3351bd6bbdeSPatrick Brown * @param string $newline new line to insert
33642ea7f44SGerrit Uitslag * @param bool $regex use regexp?
3371bd6bbdeSPatrick Brown * @param int $maxlines number of occurrences of the line to replace
338b158d625SSteven Danz * @return bool true on success
339aa659bbaSGerrit Uitslag *
340aa659bbaSGerrit Uitslag * @author Steven Danz <steven-danz@kc.rr.com>
341aa659bbaSGerrit Uitslag * @author Christopher Smith <chris@jalakai.co.uk>
342aa659bbaSGerrit Uitslag * @author Patrick Brown <ptbrown@whoopdedo.org>
343b158d625SSteven Danz */
344d868eb89SAndreas Gohrfunction io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines = 0)
345d868eb89SAndreas Gohr{
346dc4a4eb0SPatrick Brown    if ((string)$oldline === '') {
347*109ebc86SAndreas Gohr        Logger::error('io_replaceInFile() $oldline parameter cannot be empty');
348dc4a4eb0SPatrick Brown        return false;
349dc4a4eb0SPatrick Brown    }
350dc4a4eb0SPatrick Brown
35179e79377SAndreas Gohr    if (!file_exists($file)) return true;
3521380fc45SAndreas Gohr
353b158d625SSteven Danz    io_lock($file);
3541380fc45SAndreas Gohr
3551380fc45SAndreas Gohr    // load into array
3566c16a3a9Sfiwswe    if (str_ends_with($file, '.gz')) {
35713c37900SAndreas Gohr        if (!DOKU_HAS_GZIP) return false;
3581380fc45SAndreas Gohr        $lines = gzfile($file);
3596c16a3a9Sfiwswe    } elseif (str_ends_with($file, '.bz2')) {
36013c37900SAndreas Gohr        if (!DOKU_HAS_BZIP) return false;
361cfb71e37SPatrick Brown        $lines = bzfile($file, true);
362b158d625SSteven Danz    } else {
3631380fc45SAndreas Gohr        $lines = file($file);
364b158d625SSteven Danz    }
365b158d625SSteven Danz
3669a734b7aSChristopher Smith    // make non-regexes into regexes
3673dfe7d64SChristopher Smith    $pattern = $regex ? $oldline : '/^' . preg_quote($oldline, '/') . '$/';
3689a734b7aSChristopher Smith    $replace = $regex ? $newline : addcslashes($newline, '\$');
3699a734b7aSChristopher Smith
3709a734b7aSChristopher Smith    // remove matching lines
3716c000204SPatrick Brown    if ($maxlines > 0) {
3726c000204SPatrick Brown        $count = 0;
3739a734b7aSChristopher Smith        $matched = 0;
374a93ad676SAndreas Gohr        foreach ($lines as $i => $line) {
375a93ad676SAndreas Gohr            if ($count >= $maxlines) break;
3769a734b7aSChristopher Smith            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
3779a734b7aSChristopher Smith            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
378aa659bbaSGerrit Uitslag            if ($matched) {
379aa659bbaSGerrit Uitslag                $count++;
380aa659bbaSGerrit Uitslag            }
3816c000204SPatrick Brown        }
382e12c5ac7SChristopher Smith    } elseif ($maxlines == 0) {
383e12c5ac7SChristopher Smith        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
384e12c5ac7SChristopher Smith        if ((string)$newline !== '') {
3851bd6bbdeSPatrick Brown            $lines[] = $newline;
3861bd6bbdeSPatrick Brown        }
387e12c5ac7SChristopher Smith    } else {
388e12c5ac7SChristopher Smith        $lines = preg_replace($pattern, $replace, $lines);
389e12c5ac7SChristopher Smith    }
3901bd6bbdeSPatrick Brown
3911380fc45SAndreas Gohr    if (count($lines)) {
39224870174SAndreas Gohr        if (!_io_saveFile($file, implode('', $lines), false)) {
393b158d625SSteven Danz            msg("Removing content from $file failed", -1);
394fb7125eeSAndreas Gohr            io_unlock($file);
395b158d625SSteven Danz            return false;
396b158d625SSteven Danz        }
397b158d625SSteven Danz    } else {
398b158d625SSteven Danz        @unlink($file);
399b158d625SSteven Danz    }
400b158d625SSteven Danz
401b158d625SSteven Danz    io_unlock($file);
402b158d625SSteven Danz    return true;
403b158d625SSteven Danz}
404b158d625SSteven Danz
405b158d625SSteven Danz/**
4061bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
4071bd6bbdeSPatrick Brown *
4081bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
4091bd6bbdeSPatrick Brown *
4101bd6bbdeSPatrick Brown * @param string $file filename
4111bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
4121bd6bbdeSPatrick Brown * @param bool $regex use regexp?
4131bd6bbdeSPatrick Brown * @return bool true on success
414aa659bbaSGerrit Uitslag *
415aa659bbaSGerrit Uitslag * @author Patrick Brown <ptbrown@whoopdedo.org>
4161bd6bbdeSPatrick Brown */
417d868eb89SAndreas Gohrfunction io_deleteFromFile($file, $badline, $regex = false)
418d868eb89SAndreas Gohr{
4192fb31c4fSAndreas Gohr    return io_replaceInFile($file, $badline, '', $regex, 0);
4201bd6bbdeSPatrick Brown}
4211bd6bbdeSPatrick Brown
4221bd6bbdeSPatrick Brown/**
42390eb8392Sandi * Tries to lock a file
42490eb8392Sandi *
42590eb8392Sandi * Locking is only done for io_savefile and uses directories
42690eb8392Sandi * inside $conf['lockdir']
42790eb8392Sandi *
42890eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
42990eb8392Sandi * the lock is assumed to be stale and the function goes on
43090eb8392Sandi *
43142ea7f44SGerrit Uitslag * @param string $file filename
432aa659bbaSGerrit Uitslag *
433aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
43490eb8392Sandi */
435d868eb89SAndreas Gohrfunction io_lock($file)
436d868eb89SAndreas Gohr{
43790eb8392Sandi    global $conf;
43890eb8392Sandi
43990eb8392Sandi    $lockDir = $conf['lockdir'] . '/' . md5($file);
44090eb8392Sandi    @ignore_user_abort(1);
44190eb8392Sandi
44290eb8392Sandi    $timeStart = time();
44390eb8392Sandi    do {
44490eb8392Sandi        //waited longer than 3 seconds? -> stale lock
44590eb8392Sandi        if ((time() - $timeStart) > 3) break;
446bd539124SAndreas Gohr        $locked = @mkdir($lockDir);
44777b98903SAndreas Gohr        if ($locked) {
448aa659bbaSGerrit Uitslag            if ($conf['dperm']) {
449aa659bbaSGerrit Uitslag                chmod($lockDir, $conf['dperm']);
450aa659bbaSGerrit Uitslag            }
45177b98903SAndreas Gohr            break;
45277b98903SAndreas Gohr        }
45377b98903SAndreas Gohr        usleep(50);
45490eb8392Sandi    } while ($locked === false);
45590eb8392Sandi}
45690eb8392Sandi
45790eb8392Sandi/**
45890eb8392Sandi * Unlocks a file
45990eb8392Sandi *
46042ea7f44SGerrit Uitslag * @param string $file filename
461aa659bbaSGerrit Uitslag *
462aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
46390eb8392Sandi */
464d868eb89SAndreas Gohrfunction io_unlock($file)
465d868eb89SAndreas Gohr{
46690eb8392Sandi    global $conf;
46790eb8392Sandi
46890eb8392Sandi    $lockDir = $conf['lockdir'] . '/' . md5($file);
46990eb8392Sandi    @rmdir($lockDir);
47090eb8392Sandi    @ignore_user_abort(0);
47190eb8392Sandi}
47290eb8392Sandi
47390eb8392Sandi/**
474cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
475cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
476cc7d0c94SBen Coburn *
477cc7d0c94SBen Coburn * Event data:
478cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
479cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
480cc7d0c94SBen Coburn *
48142ea7f44SGerrit Uitslag * @param string $id page id
48242ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
483aa659bbaSGerrit Uitslag *
484aa659bbaSGerrit Uitslag * @author Ben Coburn <btcoburn@silicodon.net>
485cc7d0c94SBen Coburn */
486d868eb89SAndreas Gohrfunction io_createNamespace($id, $ns_type = 'pages')
487d868eb89SAndreas Gohr{
488cc7d0c94SBen Coburn    // verify ns_type
48924870174SAndreas Gohr    $types = ['pages' => 'wikiFN', 'media' => 'mediaFN'];
490cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
491cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
492cc7d0c94SBen Coburn        return;
493cc7d0c94SBen Coburn    }
494cc7d0c94SBen Coburn    // make event list
49524870174SAndreas Gohr    $missing = [];
496cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
497cc7d0c94SBen Coburn    $ns = $id;
498cc7d0c94SBen Coburn    $tmp = dirname($file = call_user_func($types[$ns_type], $ns));
49979e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
500cc7d0c94SBen Coburn        array_pop($ns_stack);
501cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
502177d6836SAndreas Gohr        if (strlen($ns) == 0) {
503d4f83172SAndreas Gohr            break;
504d4f83172SAndreas Gohr        }
505cc7d0c94SBen Coburn        $missing[] = $ns;
506cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
507cc7d0c94SBen Coburn    }
508cc7d0c94SBen Coburn    // make directories
509cc7d0c94SBen Coburn    io_makeFileDir($file);
510cc7d0c94SBen Coburn    // send the events
511cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
512cc7d0c94SBen Coburn    foreach ($missing as $ns) {
51324870174SAndreas Gohr        $data = [$ns, $ns_type];
514cbb44eabSAndreas Gohr        Event::createAndTrigger('IO_NAMESPACE_CREATED', $data);
515cc7d0c94SBen Coburn    }
516cc7d0c94SBen Coburn}
517cc7d0c94SBen Coburn
518cc7d0c94SBen Coburn/**
519f3f0262cSandi * Create the directory needed for the given file
52015fae107Sandi *
52142ea7f44SGerrit Uitslag * @param string $file file name
522aa659bbaSGerrit Uitslag *
523aa659bbaSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
524f3f0262cSandi */
525d868eb89SAndreas Gohrfunction io_makeFileDir($file)
526d868eb89SAndreas Gohr{
527f3f0262cSandi    $dir = dirname($file);
5280d8850c4SAndreas Gohr    if (!@is_dir($dir)) {
529c347b097Ssplitbrain        if (!io_mkdir_p($dir)) {
530c347b097Ssplitbrain            msg("Creating directory $dir failed", -1);
531c347b097Ssplitbrain        }
532f3f0262cSandi    }
533f3f0262cSandi}
534f3f0262cSandi
535f3f0262cSandi/**
536f3f0262cSandi * Creates a directory hierachy.
537f3f0262cSandi *
538aa659bbaSGerrit Uitslag * @param string $target filename
539679f3774SGerrit Uitslag * @return bool
540aa659bbaSGerrit Uitslag *
54159752844SAnders Sandblad * @link    http://php.net/manual/en/function.mkdir.php
542f3f0262cSandi * @author  <saint@corenova.com>
5433dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
544f3f0262cSandi */
545d868eb89SAndreas Gohrfunction io_mkdir_p($target)
546d868eb89SAndreas Gohr{
5473dc3a5f1Sandi    global $conf;
548679f3774SGerrit Uitslag    if (@is_dir($target) || empty($target)) return true; // best case check first
549679f3774SGerrit Uitslag    if (file_exists($target) && !is_dir($target)) return false;
5503dc3a5f1Sandi    //recursion
5513dc3a5f1Sandi    if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))) {
552bd539124SAndreas Gohr        $ret = @mkdir($target); // crawl back up & create dir tree
553aa659bbaSGerrit Uitslag        if ($ret && !empty($conf['dperm'])) {
554aa659bbaSGerrit Uitslag            chmod($target, $conf['dperm']);
555aa659bbaSGerrit Uitslag        }
55644881d27STroels Liebe Bentsen        return $ret;
5573dc3a5f1Sandi    }
558679f3774SGerrit Uitslag    return false;
559f3f0262cSandi}
560f3f0262cSandi
561f3f0262cSandi/**
5624d47e8e3SAndreas Gohr * Recursively delete a directory
5634d47e8e3SAndreas Gohr *
5644d47e8e3SAndreas Gohr * @param string $path
5654d47e8e3SAndreas Gohr * @param bool $removefiles defaults to false which will delete empty directories only
5664d47e8e3SAndreas Gohr * @return bool
567aa659bbaSGerrit Uitslag *
568aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
5694d47e8e3SAndreas Gohr */
570d868eb89SAndreas Gohrfunction io_rmdir($path, $removefiles = false)
571d868eb89SAndreas Gohr{
5724d47e8e3SAndreas Gohr    if (!is_string($path) || $path == "") return false;
573d8cf4dd4SAndreas Gohr    if (!file_exists($path)) return true; // it's already gone or was never there, count as success
5744d47e8e3SAndreas Gohr
5754d47e8e3SAndreas Gohr    if (is_dir($path) && !is_link($path)) {
57624870174SAndreas Gohr        $dirs = [];
57724870174SAndreas Gohr        $files = [];
5784d47e8e3SAndreas Gohr        if (!$dh = @opendir($path)) return false;
5798426a3eeSAndreas Gohr        while (false !== ($f = readdir($dh))) {
5804d47e8e3SAndreas Gohr            if ($f == '..' || $f == '.') continue;
5814d47e8e3SAndreas Gohr
5824d47e8e3SAndreas Gohr            // collect dirs and files first
5834d47e8e3SAndreas Gohr            if (is_dir("$path/$f") && !is_link("$path/$f")) {
5844d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5854d47e8e3SAndreas Gohr            } elseif ($removefiles) {
5864d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5874d47e8e3SAndreas Gohr            } else {
5884d47e8e3SAndreas Gohr                return false; // abort when non empty
5894d47e8e3SAndreas Gohr            }
5904d47e8e3SAndreas Gohr        }
5914d47e8e3SAndreas Gohr        closedir($dh);
5924d47e8e3SAndreas Gohr        // now traverse into  directories first
5934d47e8e3SAndreas Gohr        foreach ($dirs as $dir) {
5944d47e8e3SAndreas Gohr            if (!io_rmdir($dir, $removefiles)) return false; // abort on any error
5954d47e8e3SAndreas Gohr        }
5964d47e8e3SAndreas Gohr        // now delete files
5974d47e8e3SAndreas Gohr        foreach ($files as $file) {
5984d47e8e3SAndreas Gohr            if (!@unlink($file)) return false; //abort on any error
5994d47e8e3SAndreas Gohr        }
6004d47e8e3SAndreas Gohr        // remove self
6014d47e8e3SAndreas Gohr        return @rmdir($path);
6024d47e8e3SAndreas Gohr    } elseif ($removefiles) {
6034d47e8e3SAndreas Gohr        return @unlink($path);
6044d47e8e3SAndreas Gohr    }
6054d47e8e3SAndreas Gohr    return false;
6064d47e8e3SAndreas Gohr}
6074d47e8e3SAndreas Gohr
6084d47e8e3SAndreas Gohr/**
609de862555SMichael Klier * Creates a unique temporary directory and returns
610de862555SMichael Klier * its path.
611de862555SMichael Klier *
61242ea7f44SGerrit Uitslag * @return false|string path to new directory or false
613aa659bbaSGerrit Uitslag * @throws Exception
614aa659bbaSGerrit Uitslag *
615aa659bbaSGerrit Uitslag * @author Michael Klier <chi@chimeric.de>
616de862555SMichael Klier */
617d868eb89SAndreas Gohrfunction io_mktmpdir()
618d868eb89SAndreas Gohr{
619de862555SMichael Klier    global $conf;
620de862555SMichael Klier
621da1e1077SChris Smith    $base = $conf['tmpdir'];
62224870174SAndreas Gohr    $dir = md5(uniqid(random_int(0, mt_getrandmax()), true));
623287f35bdSAndreas Gohr    $tmpdir = $base . '/' . $dir;
624de862555SMichael Klier
625de862555SMichael Klier    if (io_mkdir_p($tmpdir)) {
626aa659bbaSGerrit Uitslag        return $tmpdir;
627de862555SMichael Klier    } else {
628de862555SMichael Klier        return false;
629de862555SMichael Klier    }
630de862555SMichael Klier}
631de862555SMichael Klier
632de862555SMichael Klier/**
63373ccfcb9Schris * downloads a file from the net and saves it
63473ccfcb9Schris *
63573ccfcb9Schris * if $useAttachment is false,
63673ccfcb9Schris * - $file is the full filename to save the file, incl. path
63773ccfcb9Schris * - if successful will return true, false otherwise
638db959ae3SAndreas Gohr *
63973ccfcb9Schris * if $useAttachment is true,
64073ccfcb9Schris * - $file is the directory where the file should be saved
64173ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
642b625487dSandi *
64342ea7f44SGerrit Uitslag * @param string $url url to download
64442ea7f44SGerrit Uitslag * @param string $file path to file or directory where to save
64564159a61SAndreas Gohr * @param bool $useAttachment true: try to use name of download, uses otherwise $defaultName
64664159a61SAndreas Gohr *                            false: uses $file as path to file
64742ea7f44SGerrit Uitslag * @param string $defaultName fallback for if using $useAttachment
64842ea7f44SGerrit Uitslag * @param int $maxSize maximum file size
64942ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
650aa659bbaSGerrit Uitslag *
651aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
652aa659bbaSGerrit Uitslag * @author Chris Smith <chris@jalakai.co.uk>
653b625487dSandi */
654d868eb89SAndreas Gohrfunction io_download($url, $file, $useAttachment = false, $defaultName = '', $maxSize = 2_097_152)
655d868eb89SAndreas Gohr{
656ac9115b0STroels Liebe Bentsen    global $conf;
6579b307a83SAndreas Gohr    $http = new DokuHTTPClient();
658847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6599b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
660a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6619b307a83SAndreas Gohr
6629b307a83SAndreas Gohr    $data = $http->get($url);
6639b307a83SAndreas Gohr    if (!$data) return false;
6649b307a83SAndreas Gohr
66573ccfcb9Schris    $name = '';
666cd2f903bSMichael Hamann    if ($useAttachment) {
66773ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
66873ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
66924870174SAndreas Gohr            $match = [];
6707d34963bSAndreas Gohr            if (
6717d34963bSAndreas Gohr                is_string($content_disposition) &&
6727d34963bSAndreas Gohr                preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)
6737d34963bSAndreas Gohr            ) {
67424870174SAndreas Gohr                $name = PhpString::basename($match[1]);
67573ccfcb9Schris            }
67673ccfcb9Schris        }
67773ccfcb9Schris
67873ccfcb9Schris        if (!$name) {
67973ccfcb9Schris            if (!$defaultName) return false;
68073ccfcb9Schris            $name = $defaultName;
68173ccfcb9Schris        }
68273ccfcb9Schris
68324870174SAndreas Gohr        $file .= $name;
68473ccfcb9Schris    }
68573ccfcb9Schris
68679e79377SAndreas Gohr    $fileexists = file_exists($file);
6879b307a83SAndreas Gohr    $fp = @fopen($file, "w");
688b625487dSandi    if (!$fp) return false;
6899b307a83SAndreas Gohr    fwrite($fp, $data);
690b625487dSandi    fclose($fp);
691aa659bbaSGerrit Uitslag    if (!$fileexists && $conf['fperm']) {
692aa659bbaSGerrit Uitslag        chmod($file, $conf['fperm']);
693aa659bbaSGerrit Uitslag    }
69473ccfcb9Schris    if ($useAttachment) return $name;
695b625487dSandi    return true;
696b625487dSandi}
697b625487dSandi
698b625487dSandi/**
699ac9115b0STroels Liebe Bentsen * Windows compatible rename
700bf5e5a5bSAndreas Gohr *
701bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
702bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
70342ea7f44SGerrit Uitslag *
70442ea7f44SGerrit Uitslag * @param string $from
70542ea7f44SGerrit Uitslag * @param string $to
70642ea7f44SGerrit Uitslag * @return bool succes or fail
707bf5e5a5bSAndreas Gohr */
708d868eb89SAndreas Gohrfunction io_rename($from, $to)
709d868eb89SAndreas Gohr{
710ac9115b0STroels Liebe Bentsen    global $conf;
711bf5e5a5bSAndreas Gohr    if (!@rename($from, $to)) {
712bf5e5a5bSAndreas Gohr        if (@copy($from, $to)) {
713aa659bbaSGerrit Uitslag            if ($conf['fperm']) {
714aa659bbaSGerrit Uitslag                chmod($to, $conf['fperm']);
715aa659bbaSGerrit Uitslag            }
716bf5e5a5bSAndreas Gohr            @unlink($from);
717bf5e5a5bSAndreas Gohr            return true;
718bf5e5a5bSAndreas Gohr        }
719bf5e5a5bSAndreas Gohr        return false;
720bf5e5a5bSAndreas Gohr    }
721bf5e5a5bSAndreas Gohr    return true;
722bf5e5a5bSAndreas Gohr}
723bf5e5a5bSAndreas Gohr
724420edfd6STom N Harris/**
725420edfd6STom N Harris * Runs an external command with input and output pipes.
726420edfd6STom N Harris * Returns the exit code from the process.
727420edfd6STom N Harris *
72842ea7f44SGerrit Uitslag * @param string $cmd
72942ea7f44SGerrit Uitslag * @param string $input input pipe
73042ea7f44SGerrit Uitslag * @param string $output output pipe
73142ea7f44SGerrit Uitslag * @return int exit code from process
732aa659bbaSGerrit Uitslag *
733aa659bbaSGerrit Uitslag * @author Tom N Harris <tnharris@whoopdedo.org>
734420edfd6STom N Harris */
735d868eb89SAndreas Gohrfunction io_exec($cmd, $input, &$output)
736d868eb89SAndreas Gohr{
73724870174SAndreas Gohr    $descspec = [
73824870174SAndreas Gohr        0 => ["pipe", "r"],
73924870174SAndreas Gohr        1 => ["pipe", "w"],
74024870174SAndreas Gohr        2 => ["pipe", "w"]
74124870174SAndreas Gohr    ];
7426c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7436c528220STom N Harris    if (!$ph) return -1;
7446c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7456c528220STom N Harris    fwrite($pipes[0], $input);
7466c528220STom N Harris    fclose($pipes[0]);
7476c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7486c528220STom N Harris    fclose($pipes[1]);
7496c528220STom N Harris    return proc_close($ph);
750f3f0262cSandi}
751f3f0262cSandi
7527421c3ccSAndreas Gohr/**
7537421c3ccSAndreas Gohr * Search a file for matching lines
7547421c3ccSAndreas Gohr *
7557421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7567421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7577421c3ccSAndreas Gohr * at once.
7587421c3ccSAndreas Gohr *
7597421c3ccSAndreas Gohr * @param string $file The file to search
7607421c3ccSAndreas Gohr * @param string $pattern PCRE pattern
7617421c3ccSAndreas Gohr * @param int $max How many lines to return (0 for all)
762cd2f903bSMichael Hamann * @param bool $backref When true returns array with backreferences instead of lines
763cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
764aa659bbaSGerrit Uitslag *
765aa659bbaSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
7667421c3ccSAndreas Gohr */
767d868eb89SAndreas Gohrfunction io_grep($file, $pattern, $max = 0, $backref = false)
768d868eb89SAndreas Gohr{
7697421c3ccSAndreas Gohr    $fh = @fopen($file, 'r');
7707421c3ccSAndreas Gohr    if (!$fh) return false;
77124870174SAndreas Gohr    $matches = [];
7727421c3ccSAndreas Gohr
7737421c3ccSAndreas Gohr    $cnt = 0;
7747421c3ccSAndreas Gohr    $line = '';
7757421c3ccSAndreas Gohr    while (!feof($fh)) {
7767421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7776c16a3a9Sfiwswe        if (!str_ends_with($line, "\n")) continue;
7787421c3ccSAndreas Gohr
7797421c3ccSAndreas Gohr        // check if line matches
7807421c3ccSAndreas Gohr        if (preg_match($pattern, $line, $match)) {
7817421c3ccSAndreas Gohr            if ($backref) {
7827421c3ccSAndreas Gohr                $matches[] = $match;
7837421c3ccSAndreas Gohr            } else {
7847421c3ccSAndreas Gohr                $matches[] = $line;
7857421c3ccSAndreas Gohr            }
7867421c3ccSAndreas Gohr            $cnt++;
7877421c3ccSAndreas Gohr        }
7887421c3ccSAndreas Gohr        if ($max && $max == $cnt) break;
7897421c3ccSAndreas Gohr        $line = '';
7907421c3ccSAndreas Gohr    }
7917421c3ccSAndreas Gohr    fclose($fh);
7927421c3ccSAndreas Gohr    return $matches;
7937421c3ccSAndreas Gohr}
7947421c3ccSAndreas Gohr
795f549be3dSGerrit Uitslag
796f549be3dSGerrit Uitslag/**
797f549be3dSGerrit Uitslag * Get size of contents of a file, for a compressed file the uncompressed size
798f549be3dSGerrit Uitslag * Warning: reading uncompressed size of content of bz-files requires uncompressing
799f549be3dSGerrit Uitslag *
800f549be3dSGerrit Uitslag * @param string $file filename path to file
801f549be3dSGerrit Uitslag * @return int size of file
802aa659bbaSGerrit Uitslag *
803aa659bbaSGerrit Uitslag * @author  Gerrit Uitslag <klapinklapin@gmail.com>
804f549be3dSGerrit Uitslag */
805d868eb89SAndreas Gohrfunction io_getSizeFile($file)
806d868eb89SAndreas Gohr{
807f549be3dSGerrit Uitslag    if (!file_exists($file)) return 0;
808f549be3dSGerrit Uitslag
8096c16a3a9Sfiwswe    if (str_ends_with($file, '.gz')) {
810f549be3dSGerrit Uitslag        $fp = @fopen($file, "rb");
811f549be3dSGerrit Uitslag        if ($fp === false) return 0;
812f549be3dSGerrit Uitslag        fseek($fp, -4, SEEK_END);
813f549be3dSGerrit Uitslag        $buffer = fread($fp, 4);
814f549be3dSGerrit Uitslag        fclose($fp);
815f549be3dSGerrit Uitslag        $array = unpack("V", $buffer);
816f549be3dSGerrit Uitslag        $uncompressedsize = end($array);
8176c16a3a9Sfiwswe    } elseif (str_ends_with($file, '.bz2')) {
818f549be3dSGerrit Uitslag        if (!DOKU_HAS_BZIP) return 0;
819f549be3dSGerrit Uitslag        $bz = bzopen($file, "r");
820f549be3dSGerrit Uitslag        if ($bz === false) return 0;
821f549be3dSGerrit Uitslag        $uncompressedsize = 0;
822f549be3dSGerrit Uitslag        while (!feof($bz)) {
823f549be3dSGerrit Uitslag            //8192 seems to be the maximum buffersize?
824f549be3dSGerrit Uitslag            $buffer = bzread($bz, 8192);
825f549be3dSGerrit Uitslag            if (($buffer === false) || (bzerrno($bz) !== 0)) {
826f549be3dSGerrit Uitslag                return 0;
827f549be3dSGerrit Uitslag            }
828f549be3dSGerrit Uitslag            $uncompressedsize += strlen($buffer);
829f549be3dSGerrit Uitslag        }
830f549be3dSGerrit Uitslag    } else {
831f549be3dSGerrit Uitslag        $uncompressedsize = filesize($file);
832f549be3dSGerrit Uitslag    }
833f549be3dSGerrit Uitslag
834f549be3dSGerrit Uitslag    return $uncompressedsize;
835f549be3dSGerrit Uitslag}
836