xref: /dokuwiki/inc/io.php (revision 1bd6bbdebc26f9cd916f8f287cd2cabc07bee8d1)
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'){
110f3f0262cSandi            $ret = join('',gzfile($file));
111ff3ed99fSmarcel        }else if(substr($file,-4) == '.bz2'){
112ff3ed99fSmarcel            $ret = bzfile($file);
113f3f0262cSandi        }else{
11443078d10SAndreas Gohr            $ret = file_get_contents($file);
115f3f0262cSandi        }
116f3f0262cSandi    }
117d387bf5eSAndreas Gohr    if($ret !== false && $clean){
118f3f0262cSandi        return cleanText($ret);
119e34c0709SAndreas Gohr    }else{
120e34c0709SAndreas Gohr        return $ret;
121e34c0709SAndreas Gohr    }
122f3f0262cSandi}
123ff3ed99fSmarcel/**
124ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
12542ea7f44SGerrit Uitslag *
126ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
127d387bf5eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
12842ea7f44SGerrit Uitslag *
12942ea7f44SGerrit Uitslag * @param string $file filename
130cfb71e37SPatrick Brown * @param bool   $array return array of lines
131cfb71e37SPatrick Brown * @return string|array|bool content or false on error
132ff3ed99fSmarcel */
133cfb71e37SPatrick Brownfunction bzfile($file, $array=false) {
134ff3ed99fSmarcel    $bz = bzopen($file,"r");
135d387bf5eSAndreas Gohr    if($bz === false) return false;
136d387bf5eSAndreas Gohr
137cfb71e37SPatrick Brown    if($array) $lines = array();
138cd2f903bSMichael Hamann    $str = '';
139ff3ed99fSmarcel    while (!feof($bz)) {
140ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
141d387bf5eSAndreas Gohr        $buffer = bzread($bz,8192);
142d387bf5eSAndreas Gohr        if(($buffer === false) || (bzerrno($bz) !== 0)) {
143d387bf5eSAndreas Gohr            return false;
144d387bf5eSAndreas Gohr        }
145d387bf5eSAndreas Gohr        $str = $str . $buffer;
146cfb71e37SPatrick Brown        if($array) {
147cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
148cfb71e37SPatrick Brown            while($pos !== false) {
149cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos+1);
150cfb71e37SPatrick Brown                $str = substr($str, $pos+1);
151cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
152cfb71e37SPatrick Brown            }
153cfb71e37SPatrick Brown        }
154ff3ed99fSmarcel    }
155ff3ed99fSmarcel    bzclose($bz);
156cfb71e37SPatrick Brown    if($array) {
157cfb71e37SPatrick Brown        if($str !== '') $lines[] = $str;
158cfb71e37SPatrick Brown        return $lines;
159cfb71e37SPatrick Brown    }
160ff3ed99fSmarcel    return $str;
161ff3ed99fSmarcel}
162ff3ed99fSmarcel
163f3f0262cSandi/**
164cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
165cc7d0c94SBen Coburn *
166cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
167cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
168cc7d0c94SBen Coburn * The file path should not be changed.
169cc7d0c94SBen Coburn * (The append parameter is set to false.)
170cc7d0c94SBen Coburn *
171cc7d0c94SBen Coburn * Event data:
172cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
173cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
174cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
175cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
176cc7d0c94SBen Coburn *
177cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
17842ea7f44SGerrit Uitslag *
17942ea7f44SGerrit Uitslag * @param string $file      filename
18042ea7f44SGerrit Uitslag * @param string $content
18142ea7f44SGerrit Uitslag * @param string $id        page id
18242ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
18342ea7f44SGerrit Uitslag * @return bool
184cc7d0c94SBen Coburn */
185cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
186cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
187cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
188cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
189cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
190cc7d0c94SBen Coburn}
191cc7d0c94SBen Coburn
192cc7d0c94SBen Coburn/**
193cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
194cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
19542ea7f44SGerrit Uitslag *
19642ea7f44SGerrit Uitslag * @param array $data event data
19742ea7f44SGerrit Uitslag * @return bool
198cc7d0c94SBen Coburn */
199cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
200cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
201cc7d0c94SBen Coburn        return call_user_func_array('io_saveFile', $data[0]);
202cc7d0c94SBen Coburn    } else {
203cc7d0c94SBen Coburn        return false; //callback error
204cc7d0c94SBen Coburn    }
205cc7d0c94SBen Coburn}
206cc7d0c94SBen Coburn
207cc7d0c94SBen Coburn/**
208*1bd6bbdeSPatrick Brown * Internal function to save contents to a file.
209*1bd6bbdeSPatrick Brown *
210*1bd6bbdeSPatrick Brown * @author  Andreas Gohr <andi@splitbrain.org>
211*1bd6bbdeSPatrick Brown *
212*1bd6bbdeSPatrick Brown * @param string $file filename path to file
213*1bd6bbdeSPatrick Brown * @param string $content
214*1bd6bbdeSPatrick Brown * @param bool   $append
215*1bd6bbdeSPatrick Brown * @return bool true on success, otherwise false
216*1bd6bbdeSPatrick Brown */
217*1bd6bbdeSPatrick Brownfunction _io_saveFile($file, $content, $append) {
218*1bd6bbdeSPatrick Brown    global $conf;
219*1bd6bbdeSPatrick Brown    $mode = ($append) ? 'ab' : 'wb';
220*1bd6bbdeSPatrick Brown    $fileexists = file_exists($file);
221*1bd6bbdeSPatrick Brown
222*1bd6bbdeSPatrick Brown    if(substr($file,-3) == '.gz'){
223*1bd6bbdeSPatrick Brown        $fh = @gzopen($file,$mode.'9');
224*1bd6bbdeSPatrick Brown        if(!$fh) return false;
225*1bd6bbdeSPatrick Brown        gzwrite($fh, $content);
226*1bd6bbdeSPatrick Brown        gzclose($fh);
227*1bd6bbdeSPatrick Brown    }else if(substr($file,-4) == '.bz2'){
228*1bd6bbdeSPatrick Brown        if($append) {
229*1bd6bbdeSPatrick Brown            $bzcontent = bzfile($file);
230*1bd6bbdeSPatrick Brown            if($bzcontent === false) return false;
231*1bd6bbdeSPatrick Brown            $content = $bzcontent.$content;
232*1bd6bbdeSPatrick Brown        }
233*1bd6bbdeSPatrick Brown        $fh = @bzopen($file,'w');
234*1bd6bbdeSPatrick Brown        if(!$fh) return false;
235*1bd6bbdeSPatrick Brown        bzwrite($fh, $content);
236*1bd6bbdeSPatrick Brown        bzclose($fh);
237*1bd6bbdeSPatrick Brown    }else{
238*1bd6bbdeSPatrick Brown        $fh = @fopen($file,$mode);
239*1bd6bbdeSPatrick Brown        if(!$fh) return false;
240*1bd6bbdeSPatrick Brown        fwrite($fh, $content);
241*1bd6bbdeSPatrick Brown        fclose($fh);
242*1bd6bbdeSPatrick Brown    }
243*1bd6bbdeSPatrick Brown
244*1bd6bbdeSPatrick Brown    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
245*1bd6bbdeSPatrick Brown    return true;
246*1bd6bbdeSPatrick Brown}
247*1bd6bbdeSPatrick Brown
248*1bd6bbdeSPatrick Brown/**
24915fae107Sandi * Saves $content to $file.
250f3f0262cSandi *
2511380fc45SAndreas Gohr * If the third parameter is set to true the given content
2521380fc45SAndreas Gohr * will be appended.
2531380fc45SAndreas Gohr *
25415fae107Sandi * Uses gzip if extension is .gz
255ff3ed99fSmarcel * and bz2 if extension is .bz2
25615fae107Sandi *
25715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
25842ea7f44SGerrit Uitslag *
25942ea7f44SGerrit Uitslag * @param string $file filename path to file
26042ea7f44SGerrit Uitslag * @param string $content
26142ea7f44SGerrit Uitslag * @param bool   $append
26242ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
263f3f0262cSandi */
2641380fc45SAndreas Gohrfunction io_saveFile($file, $content, $append=false) {
265f3f0262cSandi    io_makeFileDir($file);
26690eb8392Sandi    io_lock($file);
267*1bd6bbdeSPatrick Brown    if(!_io_saveFile($file, $content, $append)) {
268f3f0262cSandi        msg("Writing $file failed",-1);
269fb7125eeSAndreas Gohr        io_unlock($file);
270f3f0262cSandi        return false;
271f3f0262cSandi    }
27290eb8392Sandi    io_unlock($file);
273f3f0262cSandi    return true;
274f3f0262cSandi}
275f3f0262cSandi
276f3f0262cSandi/**
277*1bd6bbdeSPatrick Brown * Replace one or more occurrences of a line in a file.
2781380fc45SAndreas Gohr *
279*1bd6bbdeSPatrick Brown * The default, when $maxlines is 0 is to delete all matches then append a single line.
280*1bd6bbdeSPatrick Brown * If $maxlines is -1, then every $oldline will be replaced with $newline, and $regex is true
281*1bd6bbdeSPatrick Brown * then preg captures are used. If $maxlines is greater than 0 then the first $maxlines
282*1bd6bbdeSPatrick Brown * matches are replaced with $newline.
283*1bd6bbdeSPatrick Brown *
284*1bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $oldline
285b158d625SSteven Danz *
286b158d625SSteven Danz * Uses gzip if extension is .gz
287*1bd6bbdeSPatrick Brown * and bz2 if extension is .bz2
2888b06d178Schris *
289b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
290*1bd6bbdeSPatrick Brown * @author Christopher Smith <chris@jalakai.co.uk>
291*1bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
29242ea7f44SGerrit Uitslag *
29342ea7f44SGerrit Uitslag * @param string $file     filename
294*1bd6bbdeSPatrick Brown * @param string $oldline  exact linematch to remove
295*1bd6bbdeSPatrick Brown * @param string $newline  new line to insert
29642ea7f44SGerrit Uitslag * @param bool   $regex    use regexp?
297*1bd6bbdeSPatrick Brown * @param int    $maxlines number of occurrences of the line to replace
298b158d625SSteven Danz * @return bool true on success
299b158d625SSteven Danz */
300*1bd6bbdeSPatrick Brownfunction io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0) {
30179e79377SAndreas Gohr    if (!file_exists($file)) return true;
3021380fc45SAndreas Gohr
303b158d625SSteven Danz    io_lock($file);
3041380fc45SAndreas Gohr
3051380fc45SAndreas Gohr    // load into array
306b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
3071380fc45SAndreas Gohr        $lines = gzfile($file);
308cfb71e37SPatrick Brown    }else if(substr($file,-4) == '.bz2'){
309cfb71e37SPatrick Brown        $lines = bzfile($file, true);
310b158d625SSteven Danz    }else{
3111380fc45SAndreas Gohr        $lines = file($file);
312b158d625SSteven Danz    }
313b158d625SSteven Danz
3141380fc45SAndreas Gohr    // remove all matching lines
3158b06d178Schris    if ($regex) {
316*1bd6bbdeSPatrick Brown        if($maxlines == 0) {
317*1bd6bbdeSPatrick Brown            $lines = preg_grep($oldline, $lines, PREG_GREP_INVERT);
3188b06d178Schris        } else {
319*1bd6bbdeSPatrick Brown            $lines = preg_replace($oldline, $newline, $lines, $maxlines);
320*1bd6bbdeSPatrick Brown        }
321*1bd6bbdeSPatrick Brown    } else {
322*1bd6bbdeSPatrick Brown        $count = 0;
323*1bd6bbdeSPatrick Brown        $replaceline = $maxlines == 0 ? '' : $newline;
324*1bd6bbdeSPatrick Brown        $pos = array_search($oldline,$lines); //return null or false if not found
3251380fc45SAndreas Gohr        while(is_int($pos)){
326*1bd6bbdeSPatrick Brown            $lines[$pos] = $replaceline;
327*1bd6bbdeSPatrick Brown            if($maxlines > 0 && ++$count >= $maxlines) break;
328*1bd6bbdeSPatrick Brown            $pos = array_search($oldline,$lines);
329b158d625SSteven Danz        }
3308b06d178Schris    }
331b158d625SSteven Danz
332*1bd6bbdeSPatrick Brown    if($maxlines == 0 && ((string)$newline) !== '') {
333*1bd6bbdeSPatrick Brown        $lines[] = $newline;
334*1bd6bbdeSPatrick Brown    }
335*1bd6bbdeSPatrick Brown
3361380fc45SAndreas Gohr    if(count($lines)){
337*1bd6bbdeSPatrick Brown        if(!_io_saveFile($file, join('',$lines), false)) {
338b158d625SSteven Danz            msg("Removing content from $file failed",-1);
339fb7125eeSAndreas Gohr            io_unlock($file);
340b158d625SSteven Danz            return false;
341b158d625SSteven Danz        }
342b158d625SSteven Danz    }else{
343b158d625SSteven Danz        @unlink($file);
344b158d625SSteven Danz    }
345b158d625SSteven Danz
346b158d625SSteven Danz    io_unlock($file);
347b158d625SSteven Danz    return true;
348b158d625SSteven Danz}
349b158d625SSteven Danz
350b158d625SSteven Danz/**
351*1bd6bbdeSPatrick Brown * Delete lines that match $badline from $file.
352*1bd6bbdeSPatrick Brown *
353*1bd6bbdeSPatrick Brown * Be sure to include the trailing newline in $badline
354*1bd6bbdeSPatrick Brown *
355*1bd6bbdeSPatrick Brown * @author Patrick Brown <ptbrown@whoopdedo.org>
356*1bd6bbdeSPatrick Brown *
357*1bd6bbdeSPatrick Brown * @param string $file    filename
358*1bd6bbdeSPatrick Brown * @param string $badline exact linematch to remove
359*1bd6bbdeSPatrick Brown * @param bool   $regex   use regexp?
360*1bd6bbdeSPatrick Brown * @return bool true on success
361*1bd6bbdeSPatrick Brown */
362*1bd6bbdeSPatrick Brownfunction io_deleteFromFile($file,$badline,$regex=false){
363*1bd6bbdeSPatrick Brown    return io_replaceInFile($file,$badline,null,$regex,0);
364*1bd6bbdeSPatrick Brown}
365*1bd6bbdeSPatrick Brown
366*1bd6bbdeSPatrick Brown/**
36790eb8392Sandi * Tries to lock a file
36890eb8392Sandi *
36990eb8392Sandi * Locking is only done for io_savefile and uses directories
37090eb8392Sandi * inside $conf['lockdir']
37190eb8392Sandi *
37290eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
37390eb8392Sandi * the lock is assumed to be stale and the function goes on
37490eb8392Sandi *
37590eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
37642ea7f44SGerrit Uitslag *
37742ea7f44SGerrit Uitslag * @param string $file filename
37890eb8392Sandi */
37990eb8392Sandifunction io_lock($file){
38090eb8392Sandi    global $conf;
38190eb8392Sandi    // no locking if safemode hack
38290eb8392Sandi    if($conf['safemodehack']) return;
38390eb8392Sandi
38490eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
38590eb8392Sandi    @ignore_user_abort(1);
38690eb8392Sandi
38790eb8392Sandi    $timeStart = time();
38890eb8392Sandi    do {
38990eb8392Sandi        //waited longer than 3 seconds? -> stale lock
39090eb8392Sandi        if ((time() - $timeStart) > 3) break;
39144881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
39277b98903SAndreas Gohr        if($locked){
393bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
39477b98903SAndreas Gohr            break;
39577b98903SAndreas Gohr        }
39677b98903SAndreas Gohr        usleep(50);
39790eb8392Sandi    } while ($locked === false);
39890eb8392Sandi}
39990eb8392Sandi
40090eb8392Sandi/**
40190eb8392Sandi * Unlocks a file
40290eb8392Sandi *
40390eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
40442ea7f44SGerrit Uitslag *
40542ea7f44SGerrit Uitslag * @param string $file filename
40690eb8392Sandi */
40790eb8392Sandifunction io_unlock($file){
40890eb8392Sandi    global $conf;
40990eb8392Sandi    // no locking if safemode hack
41090eb8392Sandi    if($conf['safemodehack']) return;
41190eb8392Sandi
41290eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
41390eb8392Sandi    @rmdir($lockDir);
41490eb8392Sandi    @ignore_user_abort(0);
41590eb8392Sandi}
41690eb8392Sandi
41790eb8392Sandi/**
418cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
419cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
420cc7d0c94SBen Coburn *
421cc7d0c94SBen Coburn * Event data:
422cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
423cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
424cc7d0c94SBen Coburn *
425cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
42642ea7f44SGerrit Uitslag *
42742ea7f44SGerrit Uitslag * @param string $id page id
42842ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
429cc7d0c94SBen Coburn */
430cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
431cc7d0c94SBen Coburn    // verify ns_type
432cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
433cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
434cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
435cc7d0c94SBen Coburn        return;
436cc7d0c94SBen Coburn    }
437cc7d0c94SBen Coburn    // make event list
438cc7d0c94SBen Coburn    $missing = array();
439cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
440cc7d0c94SBen Coburn    $ns = $id;
441cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
44279e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
443cc7d0c94SBen Coburn        array_pop($ns_stack);
444cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
445cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
446cc7d0c94SBen Coburn        $missing[] = $ns;
447cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
448cc7d0c94SBen Coburn    }
449cc7d0c94SBen Coburn    // make directories
450cc7d0c94SBen Coburn    io_makeFileDir($file);
451cc7d0c94SBen Coburn    // send the events
452cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
453cc7d0c94SBen Coburn    foreach ($missing as $ns) {
454cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
455cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
456cc7d0c94SBen Coburn    }
457cc7d0c94SBen Coburn}
458cc7d0c94SBen Coburn
459cc7d0c94SBen Coburn/**
460f3f0262cSandi * Create the directory needed for the given file
46115fae107Sandi *
46215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
46342ea7f44SGerrit Uitslag *
46442ea7f44SGerrit Uitslag * @param string $file file name
465f3f0262cSandi */
466f3f0262cSandifunction io_makeFileDir($file){
467f3f0262cSandi    $dir = dirname($file);
4680d8850c4SAndreas Gohr    if(!@is_dir($dir)){
469f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
470f3f0262cSandi    }
471f3f0262cSandi}
472f3f0262cSandi
473f3f0262cSandi/**
474f3f0262cSandi * Creates a directory hierachy.
475f3f0262cSandi *
47615fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
477f3f0262cSandi * @author  <saint@corenova.com>
4783dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47942ea7f44SGerrit Uitslag *
48042ea7f44SGerrit Uitslag * @param string $target filename
48142ea7f44SGerrit Uitslag * @return bool|int|string
482f3f0262cSandi */
483f3f0262cSandifunction io_mkdir_p($target){
4843dc3a5f1Sandi    global $conf;
4850d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
48679e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
4873dc3a5f1Sandi    //recursion
4883dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
4893dc3a5f1Sandi        if($conf['safemodehack']){
49000976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
491034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
4923dc3a5f1Sandi        }else{
49344881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
494443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
49544881d27STroels Liebe Bentsen            return $ret;
4963dc3a5f1Sandi        }
4973dc3a5f1Sandi    }
498f3f0262cSandi    return 0;
499f3f0262cSandi}
500f3f0262cSandi
501f3f0262cSandi/**
5024d47e8e3SAndreas Gohr * Recursively delete a directory
5034d47e8e3SAndreas Gohr *
5044d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5054d47e8e3SAndreas Gohr * @param string $path
5064d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
5074d47e8e3SAndreas Gohr * @return bool
5084d47e8e3SAndreas Gohr */
5094d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
5104d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
511d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
5124d47e8e3SAndreas Gohr
5134d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
5144d47e8e3SAndreas Gohr        $dirs  = array();
5154d47e8e3SAndreas Gohr        $files = array();
5164d47e8e3SAndreas Gohr
5174d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
5188426a3eeSAndreas Gohr        while(false !== ($f = readdir($dh))) {
5194d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
5204d47e8e3SAndreas Gohr
5214d47e8e3SAndreas Gohr            // collect dirs and files first
5224d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
5234d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5244d47e8e3SAndreas Gohr            } else if($removefiles) {
5254d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5264d47e8e3SAndreas Gohr            } else {
5274d47e8e3SAndreas Gohr                return false; // abort when non empty
5284d47e8e3SAndreas Gohr            }
5294d47e8e3SAndreas Gohr
5304d47e8e3SAndreas Gohr        }
5314d47e8e3SAndreas Gohr        closedir($dh);
5324d47e8e3SAndreas Gohr
5334d47e8e3SAndreas Gohr        // now traverse into  directories first
5344d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
5354d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
5364d47e8e3SAndreas Gohr        }
5374d47e8e3SAndreas Gohr
5384d47e8e3SAndreas Gohr        // now delete files
5394d47e8e3SAndreas Gohr        foreach($files as $file) {
5404d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
5414d47e8e3SAndreas Gohr        }
5424d47e8e3SAndreas Gohr
5434d47e8e3SAndreas Gohr        // remove self
5444d47e8e3SAndreas Gohr        return @rmdir($path);
5454d47e8e3SAndreas Gohr    } else if($removefiles) {
5464d47e8e3SAndreas Gohr        return @unlink($path);
5474d47e8e3SAndreas Gohr    }
5484d47e8e3SAndreas Gohr    return false;
5494d47e8e3SAndreas Gohr}
5504d47e8e3SAndreas Gohr
5514d47e8e3SAndreas Gohr/**
5523dc3a5f1Sandi * Creates a directory using FTP
5533dc3a5f1Sandi *
5543dc3a5f1Sandi * This is used when the safemode workaround is enabled
5553dc3a5f1Sandi *
5563dc3a5f1Sandi * @author <andi@splitbrain.org>
55742ea7f44SGerrit Uitslag *
55842ea7f44SGerrit Uitslag * @param string $dir name of the new directory
55942ea7f44SGerrit Uitslag * @return false|string
5603dc3a5f1Sandi */
5613dc3a5f1Sandifunction io_mkdir_ftp($dir){
5623dc3a5f1Sandi    global $conf;
5633dc3a5f1Sandi
5643dc3a5f1Sandi    if(!function_exists('ftp_connect')){
5653dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
5663dc3a5f1Sandi        return false;
5673dc3a5f1Sandi    }
5683dc3a5f1Sandi
5693dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
5703dc3a5f1Sandi    if(!$conn){
5713dc3a5f1Sandi        msg("FTP connection failed",-1);
5723dc3a5f1Sandi        return false;
5733dc3a5f1Sandi    }
5743dc3a5f1Sandi
5753994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
5763dc3a5f1Sandi        msg("FTP login failed",-1);
5773dc3a5f1Sandi        return false;
5783dc3a5f1Sandi    }
5793dc3a5f1Sandi
5803dc3a5f1Sandi    //create directory
581034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
5821ca31cfeSAndreas Gohr    //set permissions
5831ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
5843dc3a5f1Sandi
585034138e2SRainer Weinhold    @ftp_close($conn);
5863dc3a5f1Sandi    return $ok;
5873dc3a5f1Sandi}
5883dc3a5f1Sandi
5893dc3a5f1Sandi/**
590de862555SMichael Klier * Creates a unique temporary directory and returns
591de862555SMichael Klier * its path.
592de862555SMichael Klier *
593de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
59442ea7f44SGerrit Uitslag *
59542ea7f44SGerrit Uitslag * @return false|string path to new directory or false
596de862555SMichael Klier */
597de862555SMichael Klierfunction io_mktmpdir() {
598de862555SMichael Klier    global $conf;
599de862555SMichael Klier
600da1e1077SChris Smith    $base = $conf['tmpdir'];
601da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
602287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
603de862555SMichael Klier
604de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
605de862555SMichael Klier        return($tmpdir);
606de862555SMichael Klier    } else {
607de862555SMichael Klier        return false;
608de862555SMichael Klier    }
609de862555SMichael Klier}
610de862555SMichael Klier
611de862555SMichael Klier/**
61273ccfcb9Schris * downloads a file from the net and saves it
61373ccfcb9Schris *
61473ccfcb9Schris * if $useAttachment is false,
61573ccfcb9Schris * - $file is the full filename to save the file, incl. path
61673ccfcb9Schris * - if successful will return true, false otherwise
617db959ae3SAndreas Gohr *
61873ccfcb9Schris * if $useAttachment is true,
61973ccfcb9Schris * - $file is the directory where the file should be saved
62073ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
621b625487dSandi *
622b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
62373ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
62442ea7f44SGerrit Uitslag *
62542ea7f44SGerrit Uitslag * @param string $url           url to download
62642ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
62742ea7f44SGerrit Uitslag * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
62842ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
62942ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
63042ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
631b625487dSandi */
632847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
633ac9115b0STroels Liebe Bentsen    global $conf;
6349b307a83SAndreas Gohr    $http = new DokuHTTPClient();
635847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6369b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
637a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6389b307a83SAndreas Gohr
6399b307a83SAndreas Gohr    $data = $http->get($url);
6409b307a83SAndreas Gohr    if(!$data) return false;
6419b307a83SAndreas Gohr
64273ccfcb9Schris    $name = '';
643cd2f903bSMichael Hamann    if ($useAttachment) {
64473ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
64573ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
646ce070a9fSchris            $match=array();
64773ccfcb9Schris            if (is_string($content_disposition) &&
648ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
64973ccfcb9Schris
6503009a773SAndreas Gohr                $name = utf8_basename($match[1]);
65173ccfcb9Schris            }
65273ccfcb9Schris
65373ccfcb9Schris        }
65473ccfcb9Schris
65573ccfcb9Schris        if (!$name) {
65673ccfcb9Schris            if (!$defaultName) return false;
65773ccfcb9Schris            $name = $defaultName;
65873ccfcb9Schris        }
65973ccfcb9Schris
66073ccfcb9Schris        $file = $file.$name;
66173ccfcb9Schris    }
66273ccfcb9Schris
66379e79377SAndreas Gohr    $fileexists = file_exists($file);
6649b307a83SAndreas Gohr    $fp = @fopen($file,"w");
665b625487dSandi    if(!$fp) return false;
6669b307a83SAndreas Gohr    fwrite($fp,$data);
667b625487dSandi    fclose($fp);
6681ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
66973ccfcb9Schris    if ($useAttachment) return $name;
670b625487dSandi    return true;
671b625487dSandi}
672b625487dSandi
673b625487dSandi/**
674ac9115b0STroels Liebe Bentsen * Windows compatible rename
675bf5e5a5bSAndreas Gohr *
676bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
677bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
67842ea7f44SGerrit Uitslag *
67942ea7f44SGerrit Uitslag * @param string $from
68042ea7f44SGerrit Uitslag * @param string $to
68142ea7f44SGerrit Uitslag * @return bool succes or fail
682bf5e5a5bSAndreas Gohr */
683bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
684ac9115b0STroels Liebe Bentsen    global $conf;
685bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
686bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
6878e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
688bf5e5a5bSAndreas Gohr            @unlink($from);
689bf5e5a5bSAndreas Gohr            return true;
690bf5e5a5bSAndreas Gohr        }
691bf5e5a5bSAndreas Gohr        return false;
692bf5e5a5bSAndreas Gohr    }
693bf5e5a5bSAndreas Gohr    return true;
694bf5e5a5bSAndreas Gohr}
695bf5e5a5bSAndreas Gohr
696420edfd6STom N Harris/**
697420edfd6STom N Harris * Runs an external command with input and output pipes.
698420edfd6STom N Harris * Returns the exit code from the process.
699420edfd6STom N Harris *
700420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
70142ea7f44SGerrit Uitslag *
70242ea7f44SGerrit Uitslag * @param string $cmd
70342ea7f44SGerrit Uitslag * @param string $input  input pipe
70442ea7f44SGerrit Uitslag * @param string $output output pipe
70542ea7f44SGerrit Uitslag * @return int exit code from process
706420edfd6STom N Harris */
707420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
7086c528220STom N Harris    $descspec = array(
7096c528220STom N Harris            0=>array("pipe","r"),
7106c528220STom N Harris            1=>array("pipe","w"),
7116c528220STom N Harris            2=>array("pipe","w"));
7126c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
7136c528220STom N Harris    if(!$ph) return -1;
7146c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7156c528220STom N Harris    fwrite($pipes[0], $input);
7166c528220STom N Harris    fclose($pipes[0]);
7176c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7186c528220STom N Harris    fclose($pipes[1]);
7196c528220STom N Harris    return proc_close($ph);
720f3f0262cSandi}
721f3f0262cSandi
7227421c3ccSAndreas Gohr/**
7237421c3ccSAndreas Gohr * Search a file for matching lines
7247421c3ccSAndreas Gohr *
7257421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7267421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7277421c3ccSAndreas Gohr * at once.
7287421c3ccSAndreas Gohr *
7297421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7307421c3ccSAndreas Gohr * @param  string $file    The file to search
7317421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
7327421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
733cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
734cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
7357421c3ccSAndreas Gohr */
7367421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
7377421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
7387421c3ccSAndreas Gohr    if(!$fh) return false;
7397421c3ccSAndreas Gohr    $matches = array();
7407421c3ccSAndreas Gohr
7417421c3ccSAndreas Gohr    $cnt  = 0;
7427421c3ccSAndreas Gohr    $line = '';
7437421c3ccSAndreas Gohr    while (!feof($fh)) {
7447421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7457421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
7467421c3ccSAndreas Gohr
7477421c3ccSAndreas Gohr        // check if line matches
7487421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
7497421c3ccSAndreas Gohr            if($backref){
7507421c3ccSAndreas Gohr                $matches[] = $match;
7517421c3ccSAndreas Gohr            }else{
7527421c3ccSAndreas Gohr                $matches[] = $line;
7537421c3ccSAndreas Gohr            }
7547421c3ccSAndreas Gohr            $cnt++;
7557421c3ccSAndreas Gohr        }
7567421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
7577421c3ccSAndreas Gohr        $line = '';
7587421c3ccSAndreas Gohr    }
7597421c3ccSAndreas Gohr    fclose($fh);
7607421c3ccSAndreas Gohr    return $matches;
7617421c3ccSAndreas Gohr}
7627421c3ccSAndreas Gohr
763