xref: /dokuwiki/inc/io.php (revision 2ad45addfac44b12c095303cf7abe488576b0802)
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'){
110*2ad45addSAndreas Gohr            $ret = gzfile($file);
111*2ad45addSAndreas Gohr            if(is_array($ret)) $ret = join('', $ret);
112ff3ed99fSmarcel        }else if(substr($file,-4) == '.bz2'){
113ff3ed99fSmarcel            $ret = bzfile($file);
114f3f0262cSandi        }else{
11543078d10SAndreas Gohr            $ret = file_get_contents($file);
116f3f0262cSandi        }
117f3f0262cSandi    }
118*2ad45addSAndreas Gohr    if($ret === null) return false;
119d387bf5eSAndreas Gohr    if($ret !== false && $clean){
120f3f0262cSandi        return cleanText($ret);
121e34c0709SAndreas Gohr    }else{
122e34c0709SAndreas Gohr        return $ret;
123e34c0709SAndreas Gohr    }
124f3f0262cSandi}
125ff3ed99fSmarcel/**
126ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
12742ea7f44SGerrit Uitslag *
128ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
129d387bf5eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
13042ea7f44SGerrit Uitslag *
13142ea7f44SGerrit Uitslag * @param string $file filename
132cfb71e37SPatrick Brown * @param bool   $array return array of lines
133cfb71e37SPatrick Brown * @return string|array|bool content or false on error
134ff3ed99fSmarcel */
135cfb71e37SPatrick Brownfunction bzfile($file, $array=false) {
136ff3ed99fSmarcel    $bz = bzopen($file,"r");
137d387bf5eSAndreas Gohr    if($bz === false) return false;
138d387bf5eSAndreas Gohr
139cfb71e37SPatrick Brown    if($array) $lines = array();
140cd2f903bSMichael Hamann    $str = '';
141ff3ed99fSmarcel    while (!feof($bz)) {
142ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
143d387bf5eSAndreas Gohr        $buffer = bzread($bz,8192);
144d387bf5eSAndreas Gohr        if(($buffer === false) || (bzerrno($bz) !== 0)) {
145d387bf5eSAndreas Gohr            return false;
146d387bf5eSAndreas Gohr        }
147d387bf5eSAndreas Gohr        $str = $str . $buffer;
148cfb71e37SPatrick Brown        if($array) {
149cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
150cfb71e37SPatrick Brown            while($pos !== false) {
151cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos+1);
152cfb71e37SPatrick Brown                $str = substr($str, $pos+1);
153cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
154cfb71e37SPatrick Brown            }
155cfb71e37SPatrick Brown        }
156ff3ed99fSmarcel    }
157ff3ed99fSmarcel    bzclose($bz);
158cfb71e37SPatrick Brown    if($array) {
159cfb71e37SPatrick Brown        if($str !== '') $lines[] = $str;
160cfb71e37SPatrick Brown        return $lines;
161cfb71e37SPatrick Brown    }
162ff3ed99fSmarcel    return $str;
163ff3ed99fSmarcel}
164ff3ed99fSmarcel
165f3f0262cSandi/**
166cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
167cc7d0c94SBen Coburn *
168cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
169cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
170cc7d0c94SBen Coburn * The file path should not be changed.
171cc7d0c94SBen Coburn * (The append parameter is set to false.)
172cc7d0c94SBen Coburn *
173cc7d0c94SBen Coburn * Event data:
174cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
175cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
176cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
177cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
178cc7d0c94SBen Coburn *
179cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
18042ea7f44SGerrit Uitslag *
18142ea7f44SGerrit Uitslag * @param string $file      filename
18242ea7f44SGerrit Uitslag * @param string $content
18342ea7f44SGerrit Uitslag * @param string $id        page id
18442ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
18542ea7f44SGerrit Uitslag * @return bool
186cc7d0c94SBen Coburn */
187cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
188cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
189cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
190cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
191cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
192cc7d0c94SBen Coburn}
193cc7d0c94SBen Coburn
194cc7d0c94SBen Coburn/**
195cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
196cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
19742ea7f44SGerrit Uitslag *
19842ea7f44SGerrit Uitslag * @param array $data event data
19942ea7f44SGerrit Uitslag * @return bool
200cc7d0c94SBen Coburn */
201cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
202cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
203cc7d0c94SBen Coburn        return call_user_func_array('io_saveFile', $data[0]);
204cc7d0c94SBen Coburn    } else {
205cc7d0c94SBen Coburn        return false; //callback error
206cc7d0c94SBen Coburn    }
207cc7d0c94SBen Coburn}
208cc7d0c94SBen Coburn
209cc7d0c94SBen Coburn/**
2101bd6bbdeSPatrick Brown * Internal function to save contents to a file.
2111bd6bbdeSPatrick Brown *
2121bd6bbdeSPatrick Brown * @author  Andreas Gohr <andi@splitbrain.org>
2131bd6bbdeSPatrick Brown *
2141bd6bbdeSPatrick Brown * @param string $file filename path to file
2151bd6bbdeSPatrick Brown * @param string $content
2161bd6bbdeSPatrick Brown * @param bool   $append
2171bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
2181bd6bbdeSPatrick Brown */
2191bd6bbdeSPatrick Brownfunction _io_saveFile($file, $content, $append) {
2201bd6bbdeSPatrick Brown    global $conf;
2211bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
2221bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
2231bd6bbdeSPatrick Brown
2241bd6bbdeSPatrick Brown    if(substr($file,-3) == '.gz'){
2251bd6bbdeSPatrick Brown        $fh = @gzopen($file,$mode.'9');
2261bd6bbdeSPatrick Brown        if(!$fh) return false;
2271bd6bbdeSPatrick Brown        gzwrite($fh, $content);
2281bd6bbdeSPatrick Brown        gzclose($fh);
2291bd6bbdeSPatrick Brown    }else if(substr($file,-4) == '.bz2'){
2301bd6bbdeSPatrick Brown        if($append) {
2311bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
2321bd6bbdeSPatrick Brown            if($bzcontent === false) return false;
2331bd6bbdeSPatrick Brown            $content = $bzcontent.$content;
2341bd6bbdeSPatrick Brown        }
2351bd6bbdeSPatrick Brown        $fh = @bzopen($file,'w');
2361bd6bbdeSPatrick Brown        if(!$fh) return false;
2371bd6bbdeSPatrick Brown        bzwrite($fh, $content);
2381bd6bbdeSPatrick Brown        bzclose($fh);
2391bd6bbdeSPatrick Brown    }else{
2401bd6bbdeSPatrick Brown        $fh = @fopen($file,$mode);
2411bd6bbdeSPatrick Brown        if(!$fh) return false;
2421bd6bbdeSPatrick Brown        fwrite($fh, $content);
2431bd6bbdeSPatrick Brown        fclose($fh);
2441bd6bbdeSPatrick Brown    }
2451bd6bbdeSPatrick Brown
2461bd6bbdeSPatrick Brown    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
2471bd6bbdeSPatrick Brown    return true;
2481bd6bbdeSPatrick Brown}
2491bd6bbdeSPatrick Brown
2501bd6bbdeSPatrick Brown/**
25115fae107Sandi * Saves $content to $file.
252f3f0262cSandi *
2531380fc45SAndreas Gohr * If the third parameter is set to true the given content
2541380fc45SAndreas Gohr * will be appended.
2551380fc45SAndreas Gohr *
25615fae107Sandi * Uses gzip if extension is .gz
257ff3ed99fSmarcel * and bz2 if extension is .bz2
25815fae107Sandi *
25915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
26042ea7f44SGerrit Uitslag *
26142ea7f44SGerrit Uitslag * @param string $file filename path to file
26242ea7f44SGerrit Uitslag * @param string $content
26342ea7f44SGerrit Uitslag * @param bool   $append
26442ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
265f3f0262cSandi */
2661380fc45SAndreas Gohrfunction io_saveFile($file, $content, $append=false) {
267f3f0262cSandi    io_makeFileDir($file);
26890eb8392Sandi    io_lock($file);
2691bd6bbdeSPatrick Brown    if(!_io_saveFile($file, $content, $append)) {
270f3f0262cSandi        msg("Writing $file failed",-1);
271fb7125eeSAndreas Gohr        io_unlock($file);
272f3f0262cSandi        return false;
273f3f0262cSandi    }
27490eb8392Sandi    io_unlock($file);
275f3f0262cSandi    return true;
276f3f0262cSandi}
277f3f0262cSandi
278f3f0262cSandi/**
2791bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
2801380fc45SAndreas Gohr *
281d93ba631SPatrick Brown * The default, when $maxlines is 0 is to delete all matching lines then append a single line.
282d93ba631SPatrick Brown * A regex that matches any part of the line will remove the entire line in this mode.
283d93ba631SPatrick Brown * Captures in $newline are not available.
2841bd6bbdeSPatrick Brown *
285d93ba631SPatrick Brown * Otherwise each line is matched and replaced individually, up to the first $maxlines lines
286d93ba631SPatrick Brown * or all lines if $maxlines is -1. If $regex is true then captures can be used in $newline.
287d93ba631SPatrick Brown *
288d93ba631SPatrick Brown * Be sure to include the trailing newline in $oldline when replacing entire lines.
289b158d625SSteven Danz *
290b158d625SSteven Danz * Uses gzip if extension is .gz
2911bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
2928b06d178Schris *
293b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
2941bd6bbdeSPatrick Brown * @author Christopher Smith <chris@jalakai.co.uk>
2951bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
29642ea7f44SGerrit Uitslag *
29742ea7f44SGerrit Uitslag * @param string $file     filename
2981bd6bbdeSPatrick Brown * @param string $oldline  exact linematch to remove
2991bd6bbdeSPatrick Brown * @param string $newline  new line to insert
30042ea7f44SGerrit Uitslag * @param bool   $regex    use regexp?
3011bd6bbdeSPatrick Brown * @param int    $maxlines number of occurrences of the line to replace
302b158d625SSteven Danz * @return bool true on success
303b158d625SSteven Danz */
3041bd6bbdeSPatrick Brownfunction io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0) {
305dc4a4eb0SPatrick Brown    if ((string)$oldline === '') {
306dc4a4eb0SPatrick Brown        trigger_error('$oldline parameter cannot be empty in io_replaceInFile()', E_USER_WARNING);
307dc4a4eb0SPatrick Brown        return false;
308dc4a4eb0SPatrick Brown    }
309dc4a4eb0SPatrick Brown
31079e79377SAndreas Gohr    if (!file_exists($file)) return true;
3111380fc45SAndreas Gohr
312b158d625SSteven Danz    io_lock($file);
3131380fc45SAndreas Gohr
3141380fc45SAndreas Gohr    // load into array
315b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
3161380fc45SAndreas Gohr        $lines = gzfile($file);
317cfb71e37SPatrick Brown    }else if(substr($file,-4) == '.bz2'){
318cfb71e37SPatrick Brown        $lines = bzfile($file, true);
319b158d625SSteven Danz    }else{
3201380fc45SAndreas Gohr        $lines = file($file);
321b158d625SSteven Danz    }
322b158d625SSteven Danz
3239a734b7aSChristopher Smith    // make non-regexes into regexes
3243dfe7d64SChristopher Smith    $pattern = $regex ? $oldline : '/^'.preg_quote($oldline,'/').'$/';
3259a734b7aSChristopher Smith    $replace = $regex ? $newline : addcslashes($newline, '\$');
3269a734b7aSChristopher Smith
3279a734b7aSChristopher Smith    // remove matching lines
3286c000204SPatrick Brown    if ($maxlines > 0) {
3296c000204SPatrick Brown        $count = 0;
3309a734b7aSChristopher Smith        $matched = 0;
3319a734b7aSChristopher Smith        while (($count < $maxlines) && (list($i,$line) = each($lines))) {
3329a734b7aSChristopher Smith            // $matched will be set to 0|1 depending on whether pattern is matched and line replaced
3339a734b7aSChristopher Smith            $lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
3349a734b7aSChristopher Smith            if ($matched) $count++;
3356c000204SPatrick Brown        }
336e12c5ac7SChristopher Smith    } else if ($maxlines == 0) {
337e12c5ac7SChristopher Smith        $lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
338b158d625SSteven Danz
339e12c5ac7SChristopher Smith        if ((string)$newline !== ''){
3401bd6bbdeSPatrick Brown            $lines[] = $newline;
3411bd6bbdeSPatrick Brown        }
342e12c5ac7SChristopher Smith    } else {
343e12c5ac7SChristopher Smith        $lines = preg_replace($pattern, $replace, $lines);
344e12c5ac7SChristopher Smith    }
3451bd6bbdeSPatrick Brown
3461380fc45SAndreas Gohr    if(count($lines)){
3471bd6bbdeSPatrick Brown        if(!_io_saveFile($file, join('',$lines), false)) {
348b158d625SSteven Danz            msg("Removing content from $file failed",-1);
349fb7125eeSAndreas Gohr            io_unlock($file);
350b158d625SSteven Danz            return false;
351b158d625SSteven Danz        }
352b158d625SSteven Danz    }else{
353b158d625SSteven Danz        @unlink($file);
354b158d625SSteven Danz    }
355b158d625SSteven Danz
356b158d625SSteven Danz    io_unlock($file);
357b158d625SSteven Danz    return true;
358b158d625SSteven Danz}
359b158d625SSteven Danz
360b158d625SSteven Danz/**
3611bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
3621bd6bbdeSPatrick Brown *
3631bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
3641bd6bbdeSPatrick Brown *
3651bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
3661bd6bbdeSPatrick Brown *
3671bd6bbdeSPatrick Brown * @param string $file    filename
3681bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
3691bd6bbdeSPatrick Brown * @param bool   $regex   use regexp?
3701bd6bbdeSPatrick Brown * @return bool true on success
3711bd6bbdeSPatrick Brown */
3721bd6bbdeSPatrick Brownfunction io_deleteFromFile($file,$badline,$regex=false){
3731bd6bbdeSPatrick Brown    return io_replaceInFile($file,$badline,null,$regex,0);
3741bd6bbdeSPatrick Brown}
3751bd6bbdeSPatrick Brown
3761bd6bbdeSPatrick Brown/**
37790eb8392Sandi * Tries to lock a file
37890eb8392Sandi *
37990eb8392Sandi * Locking is only done for io_savefile and uses directories
38090eb8392Sandi * inside $conf['lockdir']
38190eb8392Sandi *
38290eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
38390eb8392Sandi * the lock is assumed to be stale and the function goes on
38490eb8392Sandi *
38590eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
38642ea7f44SGerrit Uitslag *
38742ea7f44SGerrit Uitslag * @param string $file filename
38890eb8392Sandi */
38990eb8392Sandifunction io_lock($file){
39090eb8392Sandi    global $conf;
39190eb8392Sandi    // no locking if safemode hack
39290eb8392Sandi    if($conf['safemodehack']) return;
39390eb8392Sandi
39490eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
39590eb8392Sandi    @ignore_user_abort(1);
39690eb8392Sandi
39790eb8392Sandi    $timeStart = time();
39890eb8392Sandi    do {
39990eb8392Sandi        //waited longer than 3 seconds? -> stale lock
40090eb8392Sandi        if ((time() - $timeStart) > 3) break;
40144881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
40277b98903SAndreas Gohr        if($locked){
403bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
40477b98903SAndreas Gohr            break;
40577b98903SAndreas Gohr        }
40677b98903SAndreas Gohr        usleep(50);
40790eb8392Sandi    } while ($locked === false);
40890eb8392Sandi}
40990eb8392Sandi
41090eb8392Sandi/**
41190eb8392Sandi * Unlocks a file
41290eb8392Sandi *
41390eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
41442ea7f44SGerrit Uitslag *
41542ea7f44SGerrit Uitslag * @param string $file filename
41690eb8392Sandi */
41790eb8392Sandifunction io_unlock($file){
41890eb8392Sandi    global $conf;
41990eb8392Sandi    // no locking if safemode hack
42090eb8392Sandi    if($conf['safemodehack']) return;
42190eb8392Sandi
42290eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
42390eb8392Sandi    @rmdir($lockDir);
42490eb8392Sandi    @ignore_user_abort(0);
42590eb8392Sandi}
42690eb8392Sandi
42790eb8392Sandi/**
428cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
429cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
430cc7d0c94SBen Coburn *
431cc7d0c94SBen Coburn * Event data:
432cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
433cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
434cc7d0c94SBen Coburn *
435cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
43642ea7f44SGerrit Uitslag *
43742ea7f44SGerrit Uitslag * @param string $id page id
43842ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
439cc7d0c94SBen Coburn */
440cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
441cc7d0c94SBen Coburn    // verify ns_type
442cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
443cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
444cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
445cc7d0c94SBen Coburn        return;
446cc7d0c94SBen Coburn    }
447cc7d0c94SBen Coburn    // make event list
448cc7d0c94SBen Coburn    $missing = array();
449cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
450cc7d0c94SBen Coburn    $ns = $id;
451cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
45279e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
453cc7d0c94SBen Coburn        array_pop($ns_stack);
454cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
455cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
456cc7d0c94SBen Coburn        $missing[] = $ns;
457cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
458cc7d0c94SBen Coburn    }
459cc7d0c94SBen Coburn    // make directories
460cc7d0c94SBen Coburn    io_makeFileDir($file);
461cc7d0c94SBen Coburn    // send the events
462cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
463cc7d0c94SBen Coburn    foreach ($missing as $ns) {
464cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
465cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
466cc7d0c94SBen Coburn    }
467cc7d0c94SBen Coburn}
468cc7d0c94SBen Coburn
469cc7d0c94SBen Coburn/**
470f3f0262cSandi * Create the directory needed for the given file
47115fae107Sandi *
47215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47342ea7f44SGerrit Uitslag *
47442ea7f44SGerrit Uitslag * @param string $file file name
475f3f0262cSandi */
476f3f0262cSandifunction io_makeFileDir($file){
477f3f0262cSandi    $dir = dirname($file);
4780d8850c4SAndreas Gohr    if(!@is_dir($dir)){
479f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
480f3f0262cSandi    }
481f3f0262cSandi}
482f3f0262cSandi
483f3f0262cSandi/**
484f3f0262cSandi * Creates a directory hierachy.
485f3f0262cSandi *
48615fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
487f3f0262cSandi * @author  <saint@corenova.com>
4883dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
48942ea7f44SGerrit Uitslag *
49042ea7f44SGerrit Uitslag * @param string $target filename
49142ea7f44SGerrit Uitslag * @return bool|int|string
492f3f0262cSandi */
493f3f0262cSandifunction io_mkdir_p($target){
4943dc3a5f1Sandi    global $conf;
4950d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
49679e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
4973dc3a5f1Sandi    //recursion
4983dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
4993dc3a5f1Sandi        if($conf['safemodehack']){
50000976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
501034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
5023dc3a5f1Sandi        }else{
50344881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
504443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
50544881d27STroels Liebe Bentsen            return $ret;
5063dc3a5f1Sandi        }
5073dc3a5f1Sandi    }
508f3f0262cSandi    return 0;
509f3f0262cSandi}
510f3f0262cSandi
511f3f0262cSandi/**
5124d47e8e3SAndreas Gohr * Recursively delete a directory
5134d47e8e3SAndreas Gohr *
5144d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5154d47e8e3SAndreas Gohr * @param string $path
5164d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
5174d47e8e3SAndreas Gohr * @return bool
5184d47e8e3SAndreas Gohr */
5194d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
5204d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
521d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
5224d47e8e3SAndreas Gohr
5234d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
5244d47e8e3SAndreas Gohr        $dirs  = array();
5254d47e8e3SAndreas Gohr        $files = array();
5264d47e8e3SAndreas Gohr
5274d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
5288426a3eeSAndreas Gohr        while(false !== ($f = readdir($dh))) {
5294d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
5304d47e8e3SAndreas Gohr
5314d47e8e3SAndreas Gohr            // collect dirs and files first
5324d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
5334d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5344d47e8e3SAndreas Gohr            } else if($removefiles) {
5354d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5364d47e8e3SAndreas Gohr            } else {
5374d47e8e3SAndreas Gohr                return false; // abort when non empty
5384d47e8e3SAndreas Gohr            }
5394d47e8e3SAndreas Gohr
5404d47e8e3SAndreas Gohr        }
5414d47e8e3SAndreas Gohr        closedir($dh);
5424d47e8e3SAndreas Gohr
5434d47e8e3SAndreas Gohr        // now traverse into  directories first
5444d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
5454d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
5464d47e8e3SAndreas Gohr        }
5474d47e8e3SAndreas Gohr
5484d47e8e3SAndreas Gohr        // now delete files
5494d47e8e3SAndreas Gohr        foreach($files as $file) {
5504d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
5514d47e8e3SAndreas Gohr        }
5524d47e8e3SAndreas Gohr
5534d47e8e3SAndreas Gohr        // remove self
5544d47e8e3SAndreas Gohr        return @rmdir($path);
5554d47e8e3SAndreas Gohr    } else if($removefiles) {
5564d47e8e3SAndreas Gohr        return @unlink($path);
5574d47e8e3SAndreas Gohr    }
5584d47e8e3SAndreas Gohr    return false;
5594d47e8e3SAndreas Gohr}
5604d47e8e3SAndreas Gohr
5614d47e8e3SAndreas Gohr/**
5623dc3a5f1Sandi * Creates a directory using FTP
5633dc3a5f1Sandi *
5643dc3a5f1Sandi * This is used when the safemode workaround is enabled
5653dc3a5f1Sandi *
5663dc3a5f1Sandi * @author <andi@splitbrain.org>
56742ea7f44SGerrit Uitslag *
56842ea7f44SGerrit Uitslag * @param string $dir name of the new directory
56942ea7f44SGerrit Uitslag * @return false|string
5703dc3a5f1Sandi */
5713dc3a5f1Sandifunction io_mkdir_ftp($dir){
5723dc3a5f1Sandi    global $conf;
5733dc3a5f1Sandi
5743dc3a5f1Sandi    if(!function_exists('ftp_connect')){
5753dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
5763dc3a5f1Sandi        return false;
5773dc3a5f1Sandi    }
5783dc3a5f1Sandi
5793dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
5803dc3a5f1Sandi    if(!$conn){
5813dc3a5f1Sandi        msg("FTP connection failed",-1);
5823dc3a5f1Sandi        return false;
5833dc3a5f1Sandi    }
5843dc3a5f1Sandi
5853994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
5863dc3a5f1Sandi        msg("FTP login failed",-1);
5873dc3a5f1Sandi        return false;
5883dc3a5f1Sandi    }
5893dc3a5f1Sandi
5903dc3a5f1Sandi    //create directory
591034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
5921ca31cfeSAndreas Gohr    //set permissions
5931ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
5943dc3a5f1Sandi
595034138e2SRainer Weinhold    @ftp_close($conn);
5963dc3a5f1Sandi    return $ok;
5973dc3a5f1Sandi}
5983dc3a5f1Sandi
5993dc3a5f1Sandi/**
600de862555SMichael Klier * Creates a unique temporary directory and returns
601de862555SMichael Klier * its path.
602de862555SMichael Klier *
603de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
60442ea7f44SGerrit Uitslag *
60542ea7f44SGerrit Uitslag * @return false|string path to new directory or false
606de862555SMichael Klier */
607de862555SMichael Klierfunction io_mktmpdir() {
608de862555SMichael Klier    global $conf;
609de862555SMichael Klier
610da1e1077SChris Smith    $base = $conf['tmpdir'];
611da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
612287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
613de862555SMichael Klier
614de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
615de862555SMichael Klier        return($tmpdir);
616de862555SMichael Klier    } else {
617de862555SMichael Klier        return false;
618de862555SMichael Klier    }
619de862555SMichael Klier}
620de862555SMichael Klier
621de862555SMichael Klier/**
62273ccfcb9Schris * downloads a file from the net and saves it
62373ccfcb9Schris *
62473ccfcb9Schris * if $useAttachment is false,
62573ccfcb9Schris * - $file is the full filename to save the file, incl. path
62673ccfcb9Schris * - if successful will return true, false otherwise
627db959ae3SAndreas Gohr *
62873ccfcb9Schris * if $useAttachment is true,
62973ccfcb9Schris * - $file is the directory where the file should be saved
63073ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
631b625487dSandi *
632b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
63373ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
63442ea7f44SGerrit Uitslag *
63542ea7f44SGerrit Uitslag * @param string $url           url to download
63642ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
63742ea7f44SGerrit Uitslag * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
63842ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
63942ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
64042ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
641b625487dSandi */
642847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
643ac9115b0STroels Liebe Bentsen    global $conf;
6449b307a83SAndreas Gohr    $http = new DokuHTTPClient();
645847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6469b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
647a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6489b307a83SAndreas Gohr
6499b307a83SAndreas Gohr    $data = $http->get($url);
6509b307a83SAndreas Gohr    if(!$data) return false;
6519b307a83SAndreas Gohr
65273ccfcb9Schris    $name = '';
653cd2f903bSMichael Hamann    if ($useAttachment) {
65473ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
65573ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
656ce070a9fSchris            $match=array();
65773ccfcb9Schris            if (is_string($content_disposition) &&
658ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
65973ccfcb9Schris
6603009a773SAndreas Gohr                $name = utf8_basename($match[1]);
66173ccfcb9Schris            }
66273ccfcb9Schris
66373ccfcb9Schris        }
66473ccfcb9Schris
66573ccfcb9Schris        if (!$name) {
66673ccfcb9Schris            if (!$defaultName) return false;
66773ccfcb9Schris            $name = $defaultName;
66873ccfcb9Schris        }
66973ccfcb9Schris
67073ccfcb9Schris        $file = $file.$name;
67173ccfcb9Schris    }
67273ccfcb9Schris
67379e79377SAndreas Gohr    $fileexists = file_exists($file);
6749b307a83SAndreas Gohr    $fp = @fopen($file,"w");
675b625487dSandi    if(!$fp) return false;
6769b307a83SAndreas Gohr    fwrite($fp,$data);
677b625487dSandi    fclose($fp);
6781ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
67973ccfcb9Schris    if ($useAttachment) return $name;
680b625487dSandi    return true;
681b625487dSandi}
682b625487dSandi
683b625487dSandi/**
684ac9115b0STroels Liebe Bentsen * Windows compatible rename
685bf5e5a5bSAndreas Gohr *
686bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
687bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
68842ea7f44SGerrit Uitslag *
68942ea7f44SGerrit Uitslag * @param string $from
69042ea7f44SGerrit Uitslag * @param string $to
69142ea7f44SGerrit Uitslag * @return bool succes or fail
692bf5e5a5bSAndreas Gohr */
693bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
694ac9115b0STroels Liebe Bentsen    global $conf;
695bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
696bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
6978e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
698bf5e5a5bSAndreas Gohr            @unlink($from);
699bf5e5a5bSAndreas Gohr            return true;
700bf5e5a5bSAndreas Gohr        }
701bf5e5a5bSAndreas Gohr        return false;
702bf5e5a5bSAndreas Gohr    }
703bf5e5a5bSAndreas Gohr    return true;
704bf5e5a5bSAndreas Gohr}
705bf5e5a5bSAndreas Gohr
706420edfd6STom N Harris/**
707420edfd6STom N Harris * Runs an external command with input and output pipes.
708420edfd6STom N Harris * Returns the exit code from the process.
709420edfd6STom N Harris *
710420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
71142ea7f44SGerrit Uitslag *
71242ea7f44SGerrit Uitslag * @param string $cmd
71342ea7f44SGerrit Uitslag * @param string $input  input pipe
71442ea7f44SGerrit Uitslag * @param string $output output pipe
71542ea7f44SGerrit Uitslag * @return int exit code from process
716420edfd6STom N Harris */
717420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
7186c528220STom N Harris    $descspec = array(
7196c528220STom N Harris            0=>array("pipe","r"),
7206c528220STom N Harris            1=>array("pipe","w"),
7216c528220STom N Harris            2=>array("pipe","w"));
7226c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7236c528220STom N Harris    if(!$ph) return -1;
7246c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7256c528220STom N Harris    fwrite($pipes[0], $input);
7266c528220STom N Harris    fclose($pipes[0]);
7276c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7286c528220STom N Harris    fclose($pipes[1]);
7296c528220STom N Harris    return proc_close($ph);
730f3f0262cSandi}
731f3f0262cSandi
7327421c3ccSAndreas Gohr/**
7337421c3ccSAndreas Gohr * Search a file for matching lines
7347421c3ccSAndreas Gohr *
7357421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7367421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7377421c3ccSAndreas Gohr * at once.
7387421c3ccSAndreas Gohr *
7397421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7407421c3ccSAndreas Gohr * @param  string $file    The file to search
7417421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
7427421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
743cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
744cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
7457421c3ccSAndreas Gohr */
7467421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
7477421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
7487421c3ccSAndreas Gohr    if(!$fh) return false;
7497421c3ccSAndreas Gohr    $matches = array();
7507421c3ccSAndreas Gohr
7517421c3ccSAndreas Gohr    $cnt  = 0;
7527421c3ccSAndreas Gohr    $line = '';
7537421c3ccSAndreas Gohr    while (!feof($fh)) {
7547421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7557421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
7567421c3ccSAndreas Gohr
7577421c3ccSAndreas Gohr        // check if line matches
7587421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
7597421c3ccSAndreas Gohr            if($backref){
7607421c3ccSAndreas Gohr                $matches[] = $match;
7617421c3ccSAndreas Gohr            }else{
7627421c3ccSAndreas Gohr                $matches[] = $line;
7637421c3ccSAndreas Gohr            }
7647421c3ccSAndreas Gohr            $cnt++;
7657421c3ccSAndreas Gohr        }
7667421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
7677421c3ccSAndreas Gohr        $line = '';
7687421c3ccSAndreas Gohr    }
7697421c3ccSAndreas Gohr    fclose($fh);
7707421c3ccSAndreas Gohr    return $matches;
7717421c3ccSAndreas Gohr}
7727421c3ccSAndreas Gohr
773