xref: /dokuwiki/inc/io.php (revision a93ad6769c3a8fd93efce37c8d67fb6dfc85f4d5)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * File IO functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
815fae107Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10f3f0262cSandi
11f3f0262cSandi/**
1253d6ccfeSandi * Removes empty directories
1353d6ccfeSandi *
14cc7d0c94SBen Coburn * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
15cc7d0c94SBen Coburn * Event data:
16cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
17cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
18cc7d0c94SBen Coburn *
1953d6ccfeSandi * @todo use safemode hack
20d186898bSAndreas Gohr * @param string $id      - a pageid, the namespace of that id will be tried to deleted
21cd2f903bSMichael Hamann * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
22cd2f903bSMichael Hamann * @return bool - true if at least one namespace was deleted
2342ea7f44SGerrit Uitslag *
2453d6ccfeSandi * @author  Andreas Gohr <andi@splitbrain.org>
25cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
2653d6ccfeSandi */
27755f1e03SAndreas Gohrfunction io_sweepNS($id,$basedir='datadir'){
2853d6ccfeSandi    global $conf;
29cc7d0c94SBen Coburn    $types = array ('datadir'=>'pages', 'mediadir'=>'media');
30cc7d0c94SBen Coburn    $ns_type = (isset($types[$basedir])?$types[$basedir]:false);
3153d6ccfeSandi
32d186898bSAndreas Gohr    $delone = false;
33d186898bSAndreas Gohr
3453d6ccfeSandi    //scan all namespaces
3553d6ccfeSandi    while(($id = getNS($id)) !== false){
36755f1e03SAndreas Gohr        $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':','/',$id));
3753d6ccfeSandi
3853d6ccfeSandi        //try to delete dir else return
39cc7d0c94SBen Coburn        if(@rmdir($dir)) {
40cc7d0c94SBen Coburn            if ($ns_type!==false) {
41cc7d0c94SBen Coburn                $data = array($id, $ns_type);
42d186898bSAndreas Gohr                $delone = true; // we deleted at least one dir
43cc7d0c94SBen Coburn                trigger_event('IO_NAMESPACE_DELETED', $data);
44cc7d0c94SBen Coburn            }
45d186898bSAndreas Gohr        } else { return $delone; }
46cc7d0c94SBen Coburn    }
47d186898bSAndreas Gohr    return $delone;
48cc7d0c94SBen Coburn}
49cc7d0c94SBen Coburn
50cc7d0c94SBen Coburn/**
51cc7d0c94SBen Coburn * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
52cc7d0c94SBen Coburn *
53cc7d0c94SBen Coburn * Generates the action event which delegates to io_readFile().
54cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
55cc7d0c94SBen Coburn * The file path should not be changed.
56cc7d0c94SBen Coburn *
57cc7d0c94SBen Coburn * Event data:
58cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_readFile as an array.
59cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
60cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
61cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
62cc7d0c94SBen Coburn *
63cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
6442ea7f44SGerrit Uitslag *
6542ea7f44SGerrit Uitslag * @param string   $file filename
6642ea7f44SGerrit Uitslag * @param string   $id page id
6742ea7f44SGerrit Uitslag * @param bool|int $rev revision timestamp
6842ea7f44SGerrit Uitslag * @return string
69cc7d0c94SBen Coburn */
70cc7d0c94SBen Coburnfunction io_readWikiPage($file, $id, $rev=false) {
71cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
727651b376SAndreas Gohr    $data = array(array($file, true), getNS($id), noNS($id), $rev);
73cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
74cc7d0c94SBen Coburn}
75cc7d0c94SBen Coburn
76cc7d0c94SBen Coburn/**
77cc7d0c94SBen Coburn * Callback adapter for io_readFile().
7842ea7f44SGerrit Uitslag *
79cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
8042ea7f44SGerrit Uitslag *
8142ea7f44SGerrit Uitslag * @param array $data event data
8242ea7f44SGerrit Uitslag * @return string
83cc7d0c94SBen Coburn */
84cc7d0c94SBen Coburnfunction _io_readWikiPage_action($data) {
85cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
86cc7d0c94SBen Coburn        return call_user_func_array('io_readFile', $data[0]);
87cc7d0c94SBen Coburn    } else {
88cc7d0c94SBen Coburn        return ''; //callback error
8953d6ccfeSandi    }
9053d6ccfeSandi}
9153d6ccfeSandi
9253d6ccfeSandi/**
9315fae107Sandi * Returns content of $file as cleaned string.
9415fae107Sandi *
9515fae107Sandi * Uses gzip if extension is .gz
9615fae107Sandi *
97ee4c4a1bSAndreas Gohr * If you want to use the returned value in unserialize
98ee4c4a1bSAndreas Gohr * be sure to set $clean to false!
99ee4c4a1bSAndreas Gohr *
10015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
10142ea7f44SGerrit Uitslag *
10242ea7f44SGerrit Uitslag * @param string $file  filename
10342ea7f44SGerrit Uitslag * @param bool   $clean
104d387bf5eSAndreas Gohr * @return string|bool the file contents or false on error
105f3f0262cSandi */
106e34c0709SAndreas Gohrfunction io_readFile($file,$clean=true){
107f3f0262cSandi    $ret = '';
10879e79377SAndreas Gohr    if(file_exists($file)){
109f3f0262cSandi        if(substr($file,-3) == '.gz'){
11013c37900SAndreas Gohr            if(!DOKU_HAS_GZIP) return false;
1112ad45addSAndreas Gohr            $ret = gzfile($file);
1122ad45addSAndreas Gohr            if(is_array($ret)) $ret = join('', $ret);
113ff3ed99fSmarcel        }else if(substr($file,-4) == '.bz2'){
11413c37900SAndreas Gohr            if(!DOKU_HAS_BZIP) return false;
115ff3ed99fSmarcel            $ret = bzfile($file);
116f3f0262cSandi        }else{
11743078d10SAndreas Gohr            $ret = file_get_contents($file);
118f3f0262cSandi        }
119f3f0262cSandi    }
1202ad45addSAndreas Gohr    if($ret === null) return false;
121d387bf5eSAndreas Gohr    if($ret !== false && $clean){
122f3f0262cSandi        return cleanText($ret);
123e34c0709SAndreas Gohr    }else{
124e34c0709SAndreas Gohr        return $ret;
125e34c0709SAndreas Gohr    }
126f3f0262cSandi}
127ff3ed99fSmarcel/**
128ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
12942ea7f44SGerrit Uitslag *
130ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
131d387bf5eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
13242ea7f44SGerrit Uitslag *
13342ea7f44SGerrit Uitslag * @param string $file filename
134cfb71e37SPatrick Brown * @param bool   $array return array of lines
135cfb71e37SPatrick Brown * @return string|array|bool content or false on error
136ff3ed99fSmarcel */
137cfb71e37SPatrick Brownfunction bzfile($file, $array=false) {
138ff3ed99fSmarcel    $bz = bzopen($file,"r");
139d387bf5eSAndreas Gohr    if($bz === false) return false;
140d387bf5eSAndreas Gohr
141cfb71e37SPatrick Brown    if($array) $lines = array();
142cd2f903bSMichael Hamann    $str = '';
143ff3ed99fSmarcel    while (!feof($bz)) {
144ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
145d387bf5eSAndreas Gohr        $buffer = bzread($bz,8192);
146d387bf5eSAndreas Gohr        if(($buffer === false) || (bzerrno($bz) !== 0)) {
147d387bf5eSAndreas Gohr            return false;
148d387bf5eSAndreas Gohr        }
149d387bf5eSAndreas Gohr        $str = $str . $buffer;
150cfb71e37SPatrick Brown        if($array) {
151cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
152cfb71e37SPatrick Brown            while($pos !== false) {
153cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos+1);
154cfb71e37SPatrick Brown                $str = substr($str, $pos+1);
155cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
156cfb71e37SPatrick Brown            }
157cfb71e37SPatrick Brown        }
158ff3ed99fSmarcel    }
159ff3ed99fSmarcel    bzclose($bz);
160cfb71e37SPatrick Brown    if($array) {
161cfb71e37SPatrick Brown        if($str !== '') $lines[] = $str;
162cfb71e37SPatrick Brown        return $lines;
163cfb71e37SPatrick Brown    }
164ff3ed99fSmarcel    return $str;
165ff3ed99fSmarcel}
166ff3ed99fSmarcel
167f3f0262cSandi/**
168cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
169cc7d0c94SBen Coburn *
170cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
171cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
172cc7d0c94SBen Coburn * The file path should not be changed.
173cc7d0c94SBen Coburn * (The append parameter is set to false.)
174cc7d0c94SBen Coburn *
175cc7d0c94SBen Coburn * Event data:
176cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
177cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
178cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
179cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
180cc7d0c94SBen Coburn *
181cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
18242ea7f44SGerrit Uitslag *
18342ea7f44SGerrit Uitslag * @param string $file      filename
18442ea7f44SGerrit Uitslag * @param string $content
18542ea7f44SGerrit Uitslag * @param string $id        page id
18642ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
18742ea7f44SGerrit Uitslag * @return bool
188cc7d0c94SBen Coburn */
189cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
190cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
191cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
192cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
193cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
194cc7d0c94SBen Coburn}
195cc7d0c94SBen Coburn
196cc7d0c94SBen Coburn/**
197cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
198cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
19942ea7f44SGerrit Uitslag *
20042ea7f44SGerrit Uitslag * @param array $data event data
20142ea7f44SGerrit Uitslag * @return bool
202cc7d0c94SBen Coburn */
203cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
204cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
205a4306b74SAndreas Gohr        $ok = call_user_func_array('io_saveFile', $data[0]);
206a4306b74SAndreas Gohr        // for attic files make sure the file has the mtime of the revision
207a4306b74SAndreas Gohr        if($ok && is_int($data[3]) && $data[3] > 0) {
208a4306b74SAndreas Gohr            @touch($data[0][0], $data[3]);
209a4306b74SAndreas Gohr        }
210a4306b74SAndreas Gohr        return $ok;
211cc7d0c94SBen Coburn    } else {
212cc7d0c94SBen Coburn        return false; //callback error
213cc7d0c94SBen Coburn    }
214cc7d0c94SBen Coburn}
215cc7d0c94SBen Coburn
216cc7d0c94SBen Coburn/**
2171bd6bbdeSPatrick Brown * Internal function to save contents to a file.
2181bd6bbdeSPatrick Brown *
2191bd6bbdeSPatrick Brown * @author  Andreas Gohr <andi@splitbrain.org>
2201bd6bbdeSPatrick Brown *
2211bd6bbdeSPatrick Brown * @param string $file filename path to file
2221bd6bbdeSPatrick Brown * @param string $content
2231bd6bbdeSPatrick Brown * @param bool   $append
2241bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
2251bd6bbdeSPatrick Brown */
2261bd6bbdeSPatrick Brownfunction _io_saveFile($file, $content, $append) {
2271bd6bbdeSPatrick Brown    global $conf;
2281bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
2291bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
2301bd6bbdeSPatrick Brown
2311bd6bbdeSPatrick Brown    if(substr($file,-3) == '.gz'){
23213c37900SAndreas Gohr        if(!DOKU_HAS_GZIP) return false;
2331bd6bbdeSPatrick Brown        $fh = @gzopen($file,$mode.'9');
2341bd6bbdeSPatrick Brown        if(!$fh) return false;
2351bd6bbdeSPatrick Brown        gzwrite($fh, $content);
2361bd6bbdeSPatrick Brown        gzclose($fh);
2371bd6bbdeSPatrick Brown    }else if(substr($file,-4) == '.bz2'){
23813c37900SAndreas Gohr        if(!DOKU_HAS_BZIP) return false;
2391bd6bbdeSPatrick Brown        if($append) {
2401bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
2411bd6bbdeSPatrick Brown            if($bzcontent === false) return false;
2421bd6bbdeSPatrick Brown            $content = $bzcontent.$content;
2431bd6bbdeSPatrick Brown        }
2441bd6bbdeSPatrick Brown        $fh = @bzopen($file,'w');
2451bd6bbdeSPatrick Brown        if(!$fh) return false;
2461bd6bbdeSPatrick Brown        bzwrite($fh, $content);
2471bd6bbdeSPatrick Brown        bzclose($fh);
2481bd6bbdeSPatrick Brown    }else{
2491bd6bbdeSPatrick Brown        $fh = @fopen($file,$mode);
2501bd6bbdeSPatrick Brown        if(!$fh) return false;
2511bd6bbdeSPatrick Brown        fwrite($fh, $content);
2521bd6bbdeSPatrick Brown        fclose($fh);
2531bd6bbdeSPatrick Brown    }
2541bd6bbdeSPatrick Brown
2551bd6bbdeSPatrick Brown    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
2561bd6bbdeSPatrick Brown    return true;
2571bd6bbdeSPatrick Brown}
2581bd6bbdeSPatrick Brown
2591bd6bbdeSPatrick Brown/**
26015fae107Sandi * Saves $content to $file.
261f3f0262cSandi *
2621380fc45SAndreas Gohr * If the third parameter is set to true the given content
2631380fc45SAndreas Gohr * will be appended.
2641380fc45SAndreas Gohr *
26515fae107Sandi * Uses gzip if extension is .gz
266ff3ed99fSmarcel * and bz2 if extension is .bz2
26715fae107Sandi *
26815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
26942ea7f44SGerrit Uitslag *
27042ea7f44SGerrit Uitslag * @param string $file filename path to file
27142ea7f44SGerrit Uitslag * @param string $content
27242ea7f44SGerrit Uitslag * @param bool   $append
27342ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
274f3f0262cSandi */
2751380fc45SAndreas Gohrfunction io_saveFile($file, $content, $append=false) {
276f3f0262cSandi    io_makeFileDir($file);
27790eb8392Sandi    io_lock($file);
2781bd6bbdeSPatrick Brown    if(!_io_saveFile($file, $content, $append)) {
279f3f0262cSandi        msg("Writing $file failed",-1);
280fb7125eeSAndreas Gohr        io_unlock($file);
281f3f0262cSandi        return false;
282f3f0262cSandi    }
28390eb8392Sandi    io_unlock($file);
284f3f0262cSandi    return true;
285f3f0262cSandi}
286f3f0262cSandi
287f3f0262cSandi/**
2881bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
2891380fc45SAndreas Gohr *
290d93ba631SPatrick Brown * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
291d93ba631SPatrick Brown * A regex that matches any part of the line will remove the entire line in this mode.
292d93ba631SPatrick Brown * Captures in $newline are not available.
2931bd6bbdeSPatrick Brown *
294d93ba631SPatrick Brown * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
295d93ba631SPatrick Brown * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
296d93ba631SPatrick Brown *
297d93ba631SPatrick Brown * Be sure to include the trailing newline in $oldline when replacing entire lines.
298b158d625SSteven Danz *
299b158d625SSteven Danz * Uses gzip if extension is .gz
3001bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
3018b06d178Schris *
302b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
3031bd6bbdeSPatrick Brown * @author Christopher Smith <chris@jalakai.co.uk>
3041bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
30542ea7f44SGerrit Uitslag *
30642ea7f44SGerrit Uitslag * @param string $file     filename
3071bd6bbdeSPatrick Brown * @param string $oldline  exact linematch to remove
3081bd6bbdeSPatrick Brown * @param string $newline  new line to insert
30942ea7f44SGerrit Uitslag * @param bool   $regex    use regexp?
3101bd6bbdeSPatrick Brown * @param int    $maxlines number of occurrences of the line to replace
311b158d625SSteven Danz * @return bool true on success
312b158d625SSteven Danz */
3131bd6bbdeSPatrick Brownfunction io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0) {
314dc4a4eb0SPatrick Brown    if ((string)$oldline === '') {
315dc4a4eb0SPatrick Brown        trigger_error('$oldline parameter cannot be empty in io_replaceInFile()', E_USER_WARNING);
316dc4a4eb0SPatrick Brown        return false;
317dc4a4eb0SPatrick Brown    }
318dc4a4eb0SPatrick Brown
31979e79377SAndreas Gohr    if (!file_exists($file)) return true;
3201380fc45SAndreas Gohr
321b158d625SSteven Danz    io_lock($file);
3221380fc45SAndreas Gohr
3231380fc45SAndreas Gohr    // load into array
324b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
32513c37900SAndreas Gohr        if(!DOKU_HAS_GZIP) return false;
3261380fc45SAndreas Gohr        $lines = gzfile($file);
327cfb71e37SPatrick Brown    }else if(substr($file,-4) == '.bz2'){
32813c37900SAndreas Gohr        if(!DOKU_HAS_BZIP) return false;
329cfb71e37SPatrick Brown        $lines = bzfile($file, true);
330b158d625SSteven Danz    }else{
3311380fc45SAndreas Gohr        $lines = file($file);
332b158d625SSteven Danz    }
333b158d625SSteven Danz
3349a734b7aSChristopher Smith    // make non-regexes into regexes
3353dfe7d64SChristopher Smith    $pattern = $regex ? $oldline : '/^'.preg_quote($oldline,'/').'$/';
3369a734b7aSChristopher Smith    $replace = $regex ? $newline : addcslashes($newline, '\$');
3379a734b7aSChristopher Smith
3389a734b7aSChristopher Smith    // remove matching lines
3396c000204SPatrick Brown    if ($maxlines > 0) {
3406c000204SPatrick Brown        $count = 0;
3419a734b7aSChristopher Smith        $matched = 0;
342*a93ad676SAndreas Gohr        foreach($lines as $i => $line) {
343*a93ad676SAndreas Gohr            if($count >= $maxlines) break;
3449a734b7aSChristopher Smith            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
3459a734b7aSChristopher Smith            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
3469a734b7aSChristopher Smith            if ($matched) $count++;
3476c000204SPatrick Brown        }
348e12c5ac7SChristopher Smith    } else if ($maxlines == 0) {
349e12c5ac7SChristopher Smith        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
350b158d625SSteven Danz
351e12c5ac7SChristopher Smith        if ((string)$newline !== ''){
3521bd6bbdeSPatrick Brown            $lines[] = $newline;
3531bd6bbdeSPatrick Brown        }
354e12c5ac7SChristopher Smith    } else {
355e12c5ac7SChristopher Smith        $lines = preg_replace($pattern, $replace, $lines);
356e12c5ac7SChristopher Smith    }
3571bd6bbdeSPatrick Brown
3581380fc45SAndreas Gohr    if(count($lines)){
3591bd6bbdeSPatrick Brown        if(!_io_saveFile($file, join('',$lines), false)) {
360b158d625SSteven Danz            msg("Removing content from $file failed",-1);
361fb7125eeSAndreas Gohr            io_unlock($file);
362b158d625SSteven Danz            return false;
363b158d625SSteven Danz        }
364b158d625SSteven Danz    }else{
365b158d625SSteven Danz        @unlink($file);
366b158d625SSteven Danz    }
367b158d625SSteven Danz
368b158d625SSteven Danz    io_unlock($file);
369b158d625SSteven Danz    return true;
370b158d625SSteven Danz}
371b158d625SSteven Danz
372b158d625SSteven Danz/**
3731bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
3741bd6bbdeSPatrick Brown *
3751bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
3761bd6bbdeSPatrick Brown *
3771bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
3781bd6bbdeSPatrick Brown *
3791bd6bbdeSPatrick Brown * @param string $file    filename
3801bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
3811bd6bbdeSPatrick Brown * @param bool   $regex   use regexp?
3821bd6bbdeSPatrick Brown * @return bool true on success
3831bd6bbdeSPatrick Brown */
3841bd6bbdeSPatrick Brownfunction io_deleteFromFile($file,$badline,$regex=false){
3851bd6bbdeSPatrick Brown    return io_replaceInFile($file,$badline,null,$regex,0);
3861bd6bbdeSPatrick Brown}
3871bd6bbdeSPatrick Brown
3881bd6bbdeSPatrick Brown/**
38990eb8392Sandi * Tries to lock a file
39090eb8392Sandi *
39190eb8392Sandi * Locking is only done for io_savefile and uses directories
39290eb8392Sandi * inside $conf['lockdir']
39390eb8392Sandi *
39490eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
39590eb8392Sandi * the lock is assumed to be stale and the function goes on
39690eb8392Sandi *
39790eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
39842ea7f44SGerrit Uitslag *
39942ea7f44SGerrit Uitslag * @param string $file filename
40090eb8392Sandi */
40190eb8392Sandifunction io_lock($file){
40290eb8392Sandi    global $conf;
40390eb8392Sandi    // no locking if safemode hack
40490eb8392Sandi    if($conf['safemodehack']) return;
40590eb8392Sandi
40690eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
40790eb8392Sandi    @ignore_user_abort(1);
40890eb8392Sandi
40990eb8392Sandi    $timeStart = time();
41090eb8392Sandi    do {
41190eb8392Sandi        //waited longer than 3 seconds? -> stale lock
41290eb8392Sandi        if ((time() - $timeStart) > 3) break;
41344881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
41477b98903SAndreas Gohr        if($locked){
415bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
41677b98903SAndreas Gohr            break;
41777b98903SAndreas Gohr        }
41877b98903SAndreas Gohr        usleep(50);
41990eb8392Sandi    } while ($locked === false);
42090eb8392Sandi}
42190eb8392Sandi
42290eb8392Sandi/**
42390eb8392Sandi * Unlocks a file
42490eb8392Sandi *
42590eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
42642ea7f44SGerrit Uitslag *
42742ea7f44SGerrit Uitslag * @param string $file filename
42890eb8392Sandi */
42990eb8392Sandifunction io_unlock($file){
43090eb8392Sandi    global $conf;
43190eb8392Sandi    // no locking if safemode hack
43290eb8392Sandi    if($conf['safemodehack']) return;
43390eb8392Sandi
43490eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
43590eb8392Sandi    @rmdir($lockDir);
43690eb8392Sandi    @ignore_user_abort(0);
43790eb8392Sandi}
43890eb8392Sandi
43990eb8392Sandi/**
440cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
441cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
442cc7d0c94SBen Coburn *
443cc7d0c94SBen Coburn * Event data:
444cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
445cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
446cc7d0c94SBen Coburn *
447cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
44842ea7f44SGerrit Uitslag *
44942ea7f44SGerrit Uitslag * @param string $id page id
45042ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
451cc7d0c94SBen Coburn */
452cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
453cc7d0c94SBen Coburn    // verify ns_type
454cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
455cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
456cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
457cc7d0c94SBen Coburn        return;
458cc7d0c94SBen Coburn    }
459cc7d0c94SBen Coburn    // make event list
460cc7d0c94SBen Coburn    $missing = array();
461cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
462cc7d0c94SBen Coburn    $ns = $id;
463cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
46479e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
465cc7d0c94SBen Coburn        array_pop($ns_stack);
466cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
467cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
468cc7d0c94SBen Coburn        $missing[] = $ns;
469cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
470cc7d0c94SBen Coburn    }
471cc7d0c94SBen Coburn    // make directories
472cc7d0c94SBen Coburn    io_makeFileDir($file);
473cc7d0c94SBen Coburn    // send the events
474cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
475cc7d0c94SBen Coburn    foreach ($missing as $ns) {
476cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
477cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
478cc7d0c94SBen Coburn    }
479cc7d0c94SBen Coburn}
480cc7d0c94SBen Coburn
481cc7d0c94SBen Coburn/**
482f3f0262cSandi * Create the directory needed for the given file
48315fae107Sandi *
48415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
48542ea7f44SGerrit Uitslag *
48642ea7f44SGerrit Uitslag * @param string $file file name
487f3f0262cSandi */
488f3f0262cSandifunction io_makeFileDir($file){
489f3f0262cSandi    $dir = dirname($file);
4900d8850c4SAndreas Gohr    if(!@is_dir($dir)){
491f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
492f3f0262cSandi    }
493f3f0262cSandi}
494f3f0262cSandi
495f3f0262cSandi/**
496f3f0262cSandi * Creates a directory hierachy.
497f3f0262cSandi *
49859752844SAnders Sandblad * @link    http://php.net/manual/en/function.mkdir.php
499f3f0262cSandi * @author  <saint@corenova.com>
5003dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
50142ea7f44SGerrit Uitslag *
50242ea7f44SGerrit Uitslag * @param string $target filename
50342ea7f44SGerrit Uitslag * @return bool|int|string
504f3f0262cSandi */
505f3f0262cSandifunction io_mkdir_p($target){
5063dc3a5f1Sandi    global $conf;
5070d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
50879e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
5093dc3a5f1Sandi    //recursion
5103dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
5113dc3a5f1Sandi        if($conf['safemodehack']){
51200976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
513034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
5143dc3a5f1Sandi        }else{
51544881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
516443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
51744881d27STroels Liebe Bentsen            return $ret;
5183dc3a5f1Sandi        }
5193dc3a5f1Sandi    }
520f3f0262cSandi    return 0;
521f3f0262cSandi}
522f3f0262cSandi
523f3f0262cSandi/**
5244d47e8e3SAndreas Gohr * Recursively delete a directory
5254d47e8e3SAndreas Gohr *
5264d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5274d47e8e3SAndreas Gohr * @param string $path
5284d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
5294d47e8e3SAndreas Gohr * @return bool
5304d47e8e3SAndreas Gohr */
5314d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
5324d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
533d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
5344d47e8e3SAndreas Gohr
5354d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
5364d47e8e3SAndreas Gohr        $dirs  = array();
5374d47e8e3SAndreas Gohr        $files = array();
5384d47e8e3SAndreas Gohr
5394d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
5408426a3eeSAndreas Gohr        while(false !== ($f = readdir($dh))) {
5414d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
5424d47e8e3SAndreas Gohr
5434d47e8e3SAndreas Gohr            // collect dirs and files first
5444d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
5454d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5464d47e8e3SAndreas Gohr            } else if($removefiles) {
5474d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5484d47e8e3SAndreas Gohr            } else {
5494d47e8e3SAndreas Gohr                return false; // abort when non empty
5504d47e8e3SAndreas Gohr            }
5514d47e8e3SAndreas Gohr
5524d47e8e3SAndreas Gohr        }
5534d47e8e3SAndreas Gohr        closedir($dh);
5544d47e8e3SAndreas Gohr
5554d47e8e3SAndreas Gohr        // now traverse into  directories first
5564d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
5574d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
5584d47e8e3SAndreas Gohr        }
5594d47e8e3SAndreas Gohr
5604d47e8e3SAndreas Gohr        // now delete files
5614d47e8e3SAndreas Gohr        foreach($files as $file) {
5624d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
5634d47e8e3SAndreas Gohr        }
5644d47e8e3SAndreas Gohr
5654d47e8e3SAndreas Gohr        // remove self
5664d47e8e3SAndreas Gohr        return @rmdir($path);
5674d47e8e3SAndreas Gohr    } else if($removefiles) {
5684d47e8e3SAndreas Gohr        return @unlink($path);
5694d47e8e3SAndreas Gohr    }
5704d47e8e3SAndreas Gohr    return false;
5714d47e8e3SAndreas Gohr}
5724d47e8e3SAndreas Gohr
5734d47e8e3SAndreas Gohr/**
5743dc3a5f1Sandi * Creates a directory using FTP
5753dc3a5f1Sandi *
5763dc3a5f1Sandi * This is used when the safemode workaround is enabled
5773dc3a5f1Sandi *
5783dc3a5f1Sandi * @author <andi@splitbrain.org>
57942ea7f44SGerrit Uitslag *
58042ea7f44SGerrit Uitslag * @param string $dir name of the new directory
58142ea7f44SGerrit Uitslag * @return false|string
5823dc3a5f1Sandi */
5833dc3a5f1Sandifunction io_mkdir_ftp($dir){
5843dc3a5f1Sandi    global $conf;
5853dc3a5f1Sandi
5863dc3a5f1Sandi    if(!function_exists('ftp_connect')){
5873dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
5883dc3a5f1Sandi        return false;
5893dc3a5f1Sandi    }
5903dc3a5f1Sandi
5913dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
5923dc3a5f1Sandi    if(!$conn){
5933dc3a5f1Sandi        msg("FTP connection failed",-1);
5943dc3a5f1Sandi        return false;
5953dc3a5f1Sandi    }
5963dc3a5f1Sandi
5973994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
5983dc3a5f1Sandi        msg("FTP login failed",-1);
5993dc3a5f1Sandi        return false;
6003dc3a5f1Sandi    }
6013dc3a5f1Sandi
6023dc3a5f1Sandi    //create directory
603034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
6041ca31cfeSAndreas Gohr    //set permissions
6051ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
6063dc3a5f1Sandi
607034138e2SRainer Weinhold    @ftp_close($conn);
6083dc3a5f1Sandi    return $ok;
6093dc3a5f1Sandi}
6103dc3a5f1Sandi
6113dc3a5f1Sandi/**
612de862555SMichael Klier * Creates a unique temporary directory and returns
613de862555SMichael Klier * its path.
614de862555SMichael Klier *
615de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
61642ea7f44SGerrit Uitslag *
61742ea7f44SGerrit Uitslag * @return false|string path to new directory or false
618de862555SMichael Klier */
619de862555SMichael Klierfunction io_mktmpdir() {
620de862555SMichael Klier    global $conf;
621de862555SMichael Klier
622da1e1077SChris Smith    $base = $conf['tmpdir'];
623da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
624287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
625de862555SMichael Klier
626de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
627de862555SMichael Klier        return($tmpdir);
628de862555SMichael Klier    } else {
629de862555SMichael Klier        return false;
630de862555SMichael Klier    }
631de862555SMichael Klier}
632de862555SMichael Klier
633de862555SMichael Klier/**
63473ccfcb9Schris * downloads a file from the net and saves it
63573ccfcb9Schris *
63673ccfcb9Schris * if $useAttachment is false,
63773ccfcb9Schris * - $file is the full filename to save the file, incl. path
63873ccfcb9Schris * - if successful will return true, false otherwise
639db959ae3SAndreas Gohr *
64073ccfcb9Schris * if $useAttachment is true,
64173ccfcb9Schris * - $file is the directory where the file should be saved
64273ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
643b625487dSandi *
644b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
64573ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
64642ea7f44SGerrit Uitslag *
64742ea7f44SGerrit Uitslag * @param string $url           url to download
64842ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
64942ea7f44SGerrit Uitslag * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
65042ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
65142ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
65242ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
653b625487dSandi */
654847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
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'];
668ce070a9fSchris            $match=array();
66973ccfcb9Schris            if (is_string($content_disposition) &&
670ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
67173ccfcb9Schris
6723009a773SAndreas Gohr                $name = utf8_basename($match[1]);
67373ccfcb9Schris            }
67473ccfcb9Schris
67573ccfcb9Schris        }
67673ccfcb9Schris
67773ccfcb9Schris        if (!$name) {
67873ccfcb9Schris            if (!$defaultName) return false;
67973ccfcb9Schris            $name = $defaultName;
68073ccfcb9Schris        }
68173ccfcb9Schris
68273ccfcb9Schris        $file = $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);
6901ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
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 */
705bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
706ac9115b0STroels Liebe Bentsen    global $conf;
707bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
708bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
7098e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
710bf5e5a5bSAndreas Gohr            @unlink($from);
711bf5e5a5bSAndreas Gohr            return true;
712bf5e5a5bSAndreas Gohr        }
713bf5e5a5bSAndreas Gohr        return false;
714bf5e5a5bSAndreas Gohr    }
715bf5e5a5bSAndreas Gohr    return true;
716bf5e5a5bSAndreas Gohr}
717bf5e5a5bSAndreas Gohr
718420edfd6STom N Harris/**
719420edfd6STom N Harris * Runs an external command with input and output pipes.
720420edfd6STom N Harris * Returns the exit code from the process.
721420edfd6STom N Harris *
722420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
72342ea7f44SGerrit Uitslag *
72442ea7f44SGerrit Uitslag * @param string $cmd
72542ea7f44SGerrit Uitslag * @param string $input  input pipe
72642ea7f44SGerrit Uitslag * @param string $output output pipe
72742ea7f44SGerrit Uitslag * @return int exit code from process
728420edfd6STom N Harris */
729420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
7306c528220STom N Harris    $descspec = array(
7316c528220STom N Harris            0=>array("pipe","r"),
7326c528220STom N Harris            1=>array("pipe","w"),
7336c528220STom N Harris            2=>array("pipe","w"));
7346c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7356c528220STom N Harris    if(!$ph) return -1;
7366c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7376c528220STom N Harris    fwrite($pipes[0], $input);
7386c528220STom N Harris    fclose($pipes[0]);
7396c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7406c528220STom N Harris    fclose($pipes[1]);
7416c528220STom N Harris    return proc_close($ph);
742f3f0262cSandi}
743f3f0262cSandi
7447421c3ccSAndreas Gohr/**
7457421c3ccSAndreas Gohr * Search a file for matching lines
7467421c3ccSAndreas Gohr *
7477421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7487421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7497421c3ccSAndreas Gohr * at once.
7507421c3ccSAndreas Gohr *
7517421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7527421c3ccSAndreas Gohr * @param  string $file    The file to search
7537421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
7547421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
755cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
756cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
7577421c3ccSAndreas Gohr */
7587421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
7597421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
7607421c3ccSAndreas Gohr    if(!$fh) return false;
7617421c3ccSAndreas Gohr    $matches = array();
7627421c3ccSAndreas Gohr
7637421c3ccSAndreas Gohr    $cnt  = 0;
7647421c3ccSAndreas Gohr    $line = '';
7657421c3ccSAndreas Gohr    while (!feof($fh)) {
7667421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7677421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
7687421c3ccSAndreas Gohr
7697421c3ccSAndreas Gohr        // check if line matches
7707421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
7717421c3ccSAndreas Gohr            if($backref){
7727421c3ccSAndreas Gohr                $matches[] = $match;
7737421c3ccSAndreas Gohr            }else{
7747421c3ccSAndreas Gohr                $matches[] = $line;
7757421c3ccSAndreas Gohr            }
7767421c3ccSAndreas Gohr            $cnt++;
7777421c3ccSAndreas Gohr        }
7787421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
7797421c3ccSAndreas Gohr        $line = '';
7807421c3ccSAndreas Gohr    }
7817421c3ccSAndreas Gohr    fclose($fh);
7827421c3ccSAndreas Gohr    return $matches;
7837421c3ccSAndreas Gohr}
7847421c3ccSAndreas Gohr
785f549be3dSGerrit Uitslag
786f549be3dSGerrit Uitslag/**
787f549be3dSGerrit Uitslag * Get size of contents of a file, for a compressed file the uncompressed size
788f549be3dSGerrit Uitslag * Warning: reading uncompressed size of content of bz-files requires uncompressing
789f549be3dSGerrit Uitslag *
790f549be3dSGerrit Uitslag * @author  Gerrit Uitslag <klapinklapin@gmail.com>
791f549be3dSGerrit Uitslag *
792f549be3dSGerrit Uitslag * @param string $file filename path to file
793f549be3dSGerrit Uitslag * @return int size of file
794f549be3dSGerrit Uitslag */
795f549be3dSGerrit Uitslagfunction io_getSizeFile($file) {
796f549be3dSGerrit Uitslag    if (!file_exists($file)) return 0;
797f549be3dSGerrit Uitslag
798f549be3dSGerrit Uitslag    if(substr($file,-3) == '.gz'){
799f549be3dSGerrit Uitslag        $fp = @fopen($file, "rb");
800f549be3dSGerrit Uitslag        if($fp === false) return 0;
801f549be3dSGerrit Uitslag
802f549be3dSGerrit Uitslag        fseek($fp, -4, SEEK_END);
803f549be3dSGerrit Uitslag        $buffer = fread($fp, 4);
804f549be3dSGerrit Uitslag        fclose($fp);
805f549be3dSGerrit Uitslag        $array = unpack("V", $buffer);
806f549be3dSGerrit Uitslag        $uncompressedsize = end($array);
807f549be3dSGerrit Uitslag    }else if(substr($file,-4) == '.bz2'){
808f549be3dSGerrit Uitslag        if(!DOKU_HAS_BZIP) return 0;
809f549be3dSGerrit Uitslag
810f549be3dSGerrit Uitslag        $bz = bzopen($file,"r");
811f549be3dSGerrit Uitslag        if($bz === false) return 0;
812f549be3dSGerrit Uitslag
813f549be3dSGerrit Uitslag        $uncompressedsize = 0;
814f549be3dSGerrit Uitslag        while (!feof($bz)) {
815f549be3dSGerrit Uitslag            //8192 seems to be the maximum buffersize?
816f549be3dSGerrit Uitslag            $buffer = bzread($bz,8192);
817f549be3dSGerrit Uitslag            if(($buffer === false) || (bzerrno($bz) !== 0)) {
818f549be3dSGerrit Uitslag                return 0;
819f549be3dSGerrit Uitslag            }
820f549be3dSGerrit Uitslag            $uncompressedsize += strlen($buffer);
821f549be3dSGerrit Uitslag        }
822f549be3dSGerrit Uitslag    }else{
823f549be3dSGerrit Uitslag        $uncompressedsize = filesize($file);
824f549be3dSGerrit Uitslag    }
825f549be3dSGerrit Uitslag
826f549be3dSGerrit Uitslag    return $uncompressedsize;
827f549be3dSGerrit Uitslag }
828