xref: /dokuwiki/inc/io.php (revision cfb71e37ca8859c4ad9a1db73de0a293ffc7a902)
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
130*cfb71e37SPatrick Brown * @param bool   $array return array of lines
131*cfb71e37SPatrick Brown * @return string|array|bool content or false on error
132ff3ed99fSmarcel */
133*cfb71e37SPatrick Brownfunction bzfile($file, $array=false) {
134ff3ed99fSmarcel    $bz = bzopen($file,"r");
135d387bf5eSAndreas Gohr    if($bz === false) return false;
136d387bf5eSAndreas Gohr
137*cfb71e37SPatrick 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;
146*cfb71e37SPatrick Brown        if($array) {
147*cfb71e37SPatrick Brown            $pos = strpos($str, "\n");
148*cfb71e37SPatrick Brown            while($pos !== false) {
149*cfb71e37SPatrick Brown                $lines[] = substr($str, 0, $pos+1);
150*cfb71e37SPatrick Brown                $str = substr($str, $pos+1);
151*cfb71e37SPatrick Brown                $pos = strpos($str, "\n");
152*cfb71e37SPatrick Brown            }
153*cfb71e37SPatrick Brown        }
154ff3ed99fSmarcel    }
155ff3ed99fSmarcel    bzclose($bz);
156*cfb71e37SPatrick Brown    if($array) {
157*cfb71e37SPatrick Brown        if($str !== '') $lines[] = $str;
158*cfb71e37SPatrick Brown        return $lines;
159*cfb71e37SPatrick 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/**
20815fae107Sandi * Saves $content to $file.
209f3f0262cSandi *
2101380fc45SAndreas Gohr * If the third parameter is set to true the given content
2111380fc45SAndreas Gohr * will be appended.
2121380fc45SAndreas Gohr *
21315fae107Sandi * Uses gzip if extension is .gz
214ff3ed99fSmarcel * and bz2 if extension is .bz2
21515fae107Sandi *
21615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
21742ea7f44SGerrit Uitslag *
21842ea7f44SGerrit Uitslag * @param string $file filename path to file
21942ea7f44SGerrit Uitslag * @param string $content
22042ea7f44SGerrit Uitslag * @param bool   $append
22142ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
222f3f0262cSandi */
2231380fc45SAndreas Gohrfunction io_saveFile($file,$content,$append=false){
224ac9115b0STroels Liebe Bentsen    global $conf;
2251380fc45SAndreas Gohr    $mode = ($append) ? 'ab' : 'wb';
2261380fc45SAndreas Gohr
22779e79377SAndreas Gohr    $fileexists = file_exists($file);
228f3f0262cSandi    io_makeFileDir($file);
22990eb8392Sandi    io_lock($file);
230f3f0262cSandi    if(substr($file,-3) == '.gz'){
2311380fc45SAndreas Gohr        $fh = @gzopen($file,$mode.'9');
232f3f0262cSandi        if(!$fh){
233f3f0262cSandi            msg("Writing $file failed",-1);
234fb7125eeSAndreas Gohr            io_unlock($file);
235f3f0262cSandi            return false;
236f3f0262cSandi        }
237f3f0262cSandi        gzwrite($fh, $content);
238f3f0262cSandi        gzclose($fh);
239ff3ed99fSmarcel    }else if(substr($file,-4) == '.bz2'){
24036907582SPatrick Brown        if($append) {
24136907582SPatrick Brown            $bzcontent = bzfile($file);
24236907582SPatrick Brown            if($bzcontent === false) {
24336907582SPatrick Brown                msg("Writing $file failed", -1);
24436907582SPatrick Brown                io_unlock($file);
24536907582SPatrick Brown                return false;
24636907582SPatrick Brown            }
24736907582SPatrick Brown            $content = $bzcontent.$content;
24836907582SPatrick Brown        }
24936907582SPatrick Brown        $fh = @bzopen($file,'w');
250ff3ed99fSmarcel        if(!$fh){
251ff3ed99fSmarcel            msg("Writing $file failed", -1);
252fb7125eeSAndreas Gohr            io_unlock($file);
253ff3ed99fSmarcel            return false;
254ff3ed99fSmarcel        }
255ff3ed99fSmarcel        bzwrite($fh, $content);
256ff3ed99fSmarcel        bzclose($fh);
257f3f0262cSandi    }else{
2581380fc45SAndreas Gohr        $fh = @fopen($file,$mode);
259f3f0262cSandi        if(!$fh){
260f3f0262cSandi            msg("Writing $file failed",-1);
261fb7125eeSAndreas Gohr            io_unlock($file);
262f3f0262cSandi            return false;
263f3f0262cSandi        }
264f3f0262cSandi        fwrite($fh, $content);
265f3f0262cSandi        fclose($fh);
266f3f0262cSandi    }
267ac9115b0STroels Liebe Bentsen
268bb4866bdSchris    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
26990eb8392Sandi    io_unlock($file);
270f3f0262cSandi    return true;
271f3f0262cSandi}
272f3f0262cSandi
273f3f0262cSandi/**
2741380fc45SAndreas Gohr * Delete exact linematch for $badline from $file.
2751380fc45SAndreas Gohr *
2761380fc45SAndreas Gohr * Be sure to include the trailing newline in $badline
277b158d625SSteven Danz *
278b158d625SSteven Danz * Uses gzip if extension is .gz
279b158d625SSteven Danz *
2808b06d178Schris * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
2818b06d178Schris *
282b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
28342ea7f44SGerrit Uitslag *
28442ea7f44SGerrit Uitslag * @param string $file    filename
28542ea7f44SGerrit Uitslag * @param string $badline exact linematch to remove
28642ea7f44SGerrit Uitslag * @param bool   $regex   use regexp?
287b158d625SSteven Danz * @return bool true on success
288b158d625SSteven Danz */
2898b06d178Schrisfunction io_deleteFromFile($file,$badline,$regex=false){
29079e79377SAndreas Gohr    if (!file_exists($file)) return true;
2911380fc45SAndreas Gohr
292b158d625SSteven Danz    io_lock($file);
2931380fc45SAndreas Gohr
2941380fc45SAndreas Gohr    // load into array
295b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
2961380fc45SAndreas Gohr        $lines = gzfile($file);
297*cfb71e37SPatrick Brown    }else if(substr($file,-4) == '.bz2'){
298*cfb71e37SPatrick Brown        $lines = bzfile($file, true);
299b158d625SSteven Danz    }else{
3001380fc45SAndreas Gohr        $lines = file($file);
301b158d625SSteven Danz    }
302b158d625SSteven Danz
3031380fc45SAndreas Gohr    // remove all matching lines
3048b06d178Schris    if ($regex) {
3058b06d178Schris        $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
3068b06d178Schris    } else {
3071380fc45SAndreas Gohr        $pos = array_search($badline,$lines); //return null or false if not found
3081380fc45SAndreas Gohr        while(is_int($pos)){
3091380fc45SAndreas Gohr            unset($lines[$pos]);
3101380fc45SAndreas Gohr            $pos = array_search($badline,$lines);
311b158d625SSteven Danz        }
3128b06d178Schris    }
313b158d625SSteven Danz
3141380fc45SAndreas Gohr    if(count($lines)){
3151380fc45SAndreas Gohr        $content = join('',$lines);
316b158d625SSteven Danz        if(substr($file,-3) == '.gz'){
317b158d625SSteven Danz            $fh = @gzopen($file,'wb9');
318b158d625SSteven Danz            if(!$fh){
319b158d625SSteven Danz                msg("Removing content from $file failed",-1);
320fb7125eeSAndreas Gohr                io_unlock($file);
321b158d625SSteven Danz                return false;
322b158d625SSteven Danz            }
323b158d625SSteven Danz            gzwrite($fh, $content);
324b158d625SSteven Danz            gzclose($fh);
325*cfb71e37SPatrick Brown        }else if(substr($file,-4) == '.bz2'){
326*cfb71e37SPatrick Brown            $fh = @bzopen($file,'w');
327*cfb71e37SPatrick Brown            if(!$fh){
328*cfb71e37SPatrick Brown                msg("Removing content from $file failed",-1);
329*cfb71e37SPatrick Brown                io_unlock($file);
330*cfb71e37SPatrick Brown                return false;
331*cfb71e37SPatrick Brown            }
332*cfb71e37SPatrick Brown            bzwrite($fh, $content);
333*cfb71e37SPatrick Brown            bzclose($fh);
334b158d625SSteven Danz        }else{
335b158d625SSteven Danz            $fh = @fopen($file,'wb');
336b158d625SSteven Danz            if(!$fh){
337b158d625SSteven Danz                msg("Removing content from $file failed",-1);
338fb7125eeSAndreas Gohr                io_unlock($file);
339b158d625SSteven Danz                return false;
340b158d625SSteven Danz            }
341b158d625SSteven Danz            fwrite($fh, $content);
342b158d625SSteven Danz            fclose($fh);
343b158d625SSteven Danz        }
344b158d625SSteven Danz    }else{
345b158d625SSteven Danz        @unlink($file);
346b158d625SSteven Danz    }
347b158d625SSteven Danz
348b158d625SSteven Danz    io_unlock($file);
349b158d625SSteven Danz    return true;
350b158d625SSteven Danz}
351b158d625SSteven Danz
352b158d625SSteven Danz/**
35390eb8392Sandi * Tries to lock a file
35490eb8392Sandi *
35590eb8392Sandi * Locking is only done for io_savefile and uses directories
35690eb8392Sandi * inside $conf['lockdir']
35790eb8392Sandi *
35890eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
35990eb8392Sandi * the lock is assumed to be stale and the function goes on
36090eb8392Sandi *
36190eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
36242ea7f44SGerrit Uitslag *
36342ea7f44SGerrit Uitslag * @param string $file filename
36490eb8392Sandi */
36590eb8392Sandifunction io_lock($file){
36690eb8392Sandi    global $conf;
36790eb8392Sandi    // no locking if safemode hack
36890eb8392Sandi    if($conf['safemodehack']) return;
36990eb8392Sandi
37090eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
37190eb8392Sandi    @ignore_user_abort(1);
37290eb8392Sandi
37390eb8392Sandi    $timeStart = time();
37490eb8392Sandi    do {
37590eb8392Sandi        //waited longer than 3 seconds? -> stale lock
37690eb8392Sandi        if ((time() - $timeStart) > 3) break;
37744881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
37877b98903SAndreas Gohr        if($locked){
379bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
38077b98903SAndreas Gohr            break;
38177b98903SAndreas Gohr        }
38277b98903SAndreas Gohr        usleep(50);
38390eb8392Sandi    } while ($locked === false);
38490eb8392Sandi}
38590eb8392Sandi
38690eb8392Sandi/**
38790eb8392Sandi * Unlocks a file
38890eb8392Sandi *
38990eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
39042ea7f44SGerrit Uitslag *
39142ea7f44SGerrit Uitslag * @param string $file filename
39290eb8392Sandi */
39390eb8392Sandifunction io_unlock($file){
39490eb8392Sandi    global $conf;
39590eb8392Sandi    // no locking if safemode hack
39690eb8392Sandi    if($conf['safemodehack']) return;
39790eb8392Sandi
39890eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
39990eb8392Sandi    @rmdir($lockDir);
40090eb8392Sandi    @ignore_user_abort(0);
40190eb8392Sandi}
40290eb8392Sandi
40390eb8392Sandi/**
404cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
405cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
406cc7d0c94SBen Coburn *
407cc7d0c94SBen Coburn * Event data:
408cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
409cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
410cc7d0c94SBen Coburn *
411cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
41242ea7f44SGerrit Uitslag *
41342ea7f44SGerrit Uitslag * @param string $id page id
41442ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
415cc7d0c94SBen Coburn */
416cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
417cc7d0c94SBen Coburn    // verify ns_type
418cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
419cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
420cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
421cc7d0c94SBen Coburn        return;
422cc7d0c94SBen Coburn    }
423cc7d0c94SBen Coburn    // make event list
424cc7d0c94SBen Coburn    $missing = array();
425cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
426cc7d0c94SBen Coburn    $ns = $id;
427cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
42879e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
429cc7d0c94SBen Coburn        array_pop($ns_stack);
430cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
431cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
432cc7d0c94SBen Coburn        $missing[] = $ns;
433cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
434cc7d0c94SBen Coburn    }
435cc7d0c94SBen Coburn    // make directories
436cc7d0c94SBen Coburn    io_makeFileDir($file);
437cc7d0c94SBen Coburn    // send the events
438cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
439cc7d0c94SBen Coburn    foreach ($missing as $ns) {
440cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
441cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
442cc7d0c94SBen Coburn    }
443cc7d0c94SBen Coburn}
444cc7d0c94SBen Coburn
445cc7d0c94SBen Coburn/**
446f3f0262cSandi * Create the directory needed for the given file
44715fae107Sandi *
44815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
44942ea7f44SGerrit Uitslag *
45042ea7f44SGerrit Uitslag * @param string $file file name
451f3f0262cSandi */
452f3f0262cSandifunction io_makeFileDir($file){
453f3f0262cSandi    $dir = dirname($file);
4540d8850c4SAndreas Gohr    if(!@is_dir($dir)){
455f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
456f3f0262cSandi    }
457f3f0262cSandi}
458f3f0262cSandi
459f3f0262cSandi/**
460f3f0262cSandi * Creates a directory hierachy.
461f3f0262cSandi *
46215fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
463f3f0262cSandi * @author  <saint@corenova.com>
4643dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
46542ea7f44SGerrit Uitslag *
46642ea7f44SGerrit Uitslag * @param string $target filename
46742ea7f44SGerrit Uitslag * @return bool|int|string
468f3f0262cSandi */
469f3f0262cSandifunction io_mkdir_p($target){
4703dc3a5f1Sandi    global $conf;
4710d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
47279e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
4733dc3a5f1Sandi    //recursion
4743dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
4753dc3a5f1Sandi        if($conf['safemodehack']){
47600976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
477034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
4783dc3a5f1Sandi        }else{
47944881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
480443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
48144881d27STroels Liebe Bentsen            return $ret;
4823dc3a5f1Sandi        }
4833dc3a5f1Sandi    }
484f3f0262cSandi    return 0;
485f3f0262cSandi}
486f3f0262cSandi
487f3f0262cSandi/**
4884d47e8e3SAndreas Gohr * Recursively delete a directory
4894d47e8e3SAndreas Gohr *
4904d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4914d47e8e3SAndreas Gohr * @param string $path
4924d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
4934d47e8e3SAndreas Gohr * @return bool
4944d47e8e3SAndreas Gohr */
4954d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
4964d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
497d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
4984d47e8e3SAndreas Gohr
4994d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
5004d47e8e3SAndreas Gohr        $dirs  = array();
5014d47e8e3SAndreas Gohr        $files = array();
5024d47e8e3SAndreas Gohr
5034d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
5048426a3eeSAndreas Gohr        while(false !== ($f = readdir($dh))) {
5054d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
5064d47e8e3SAndreas Gohr
5074d47e8e3SAndreas Gohr            // collect dirs and files first
5084d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
5094d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
5104d47e8e3SAndreas Gohr            } else if($removefiles) {
5114d47e8e3SAndreas Gohr                $files[] = "$path/$f";
5124d47e8e3SAndreas Gohr            } else {
5134d47e8e3SAndreas Gohr                return false; // abort when non empty
5144d47e8e3SAndreas Gohr            }
5154d47e8e3SAndreas Gohr
5164d47e8e3SAndreas Gohr        }
5174d47e8e3SAndreas Gohr        closedir($dh);
5184d47e8e3SAndreas Gohr
5194d47e8e3SAndreas Gohr        // now traverse into  directories first
5204d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
5214d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
5224d47e8e3SAndreas Gohr        }
5234d47e8e3SAndreas Gohr
5244d47e8e3SAndreas Gohr        // now delete files
5254d47e8e3SAndreas Gohr        foreach($files as $file) {
5264d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
5274d47e8e3SAndreas Gohr        }
5284d47e8e3SAndreas Gohr
5294d47e8e3SAndreas Gohr        // remove self
5304d47e8e3SAndreas Gohr        return @rmdir($path);
5314d47e8e3SAndreas Gohr    } else if($removefiles) {
5324d47e8e3SAndreas Gohr        return @unlink($path);
5334d47e8e3SAndreas Gohr    }
5344d47e8e3SAndreas Gohr    return false;
5354d47e8e3SAndreas Gohr}
5364d47e8e3SAndreas Gohr
5374d47e8e3SAndreas Gohr/**
5383dc3a5f1Sandi * Creates a directory using FTP
5393dc3a5f1Sandi *
5403dc3a5f1Sandi * This is used when the safemode workaround is enabled
5413dc3a5f1Sandi *
5423dc3a5f1Sandi * @author <andi@splitbrain.org>
54342ea7f44SGerrit Uitslag *
54442ea7f44SGerrit Uitslag * @param string $dir name of the new directory
54542ea7f44SGerrit Uitslag * @return false|string
5463dc3a5f1Sandi */
5473dc3a5f1Sandifunction io_mkdir_ftp($dir){
5483dc3a5f1Sandi    global $conf;
5493dc3a5f1Sandi
5503dc3a5f1Sandi    if(!function_exists('ftp_connect')){
5513dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
5523dc3a5f1Sandi        return false;
5533dc3a5f1Sandi    }
5543dc3a5f1Sandi
5553dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
5563dc3a5f1Sandi    if(!$conn){
5573dc3a5f1Sandi        msg("FTP connection failed",-1);
5583dc3a5f1Sandi        return false;
5593dc3a5f1Sandi    }
5603dc3a5f1Sandi
5613994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
5623dc3a5f1Sandi        msg("FTP login failed",-1);
5633dc3a5f1Sandi        return false;
5643dc3a5f1Sandi    }
5653dc3a5f1Sandi
5663dc3a5f1Sandi    //create directory
567034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
5681ca31cfeSAndreas Gohr    //set permissions
5691ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
5703dc3a5f1Sandi
571034138e2SRainer Weinhold    @ftp_close($conn);
5723dc3a5f1Sandi    return $ok;
5733dc3a5f1Sandi}
5743dc3a5f1Sandi
5753dc3a5f1Sandi/**
576de862555SMichael Klier * Creates a unique temporary directory and returns
577de862555SMichael Klier * its path.
578de862555SMichael Klier *
579de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
58042ea7f44SGerrit Uitslag *
58142ea7f44SGerrit Uitslag * @return false|string path to new directory or false
582de862555SMichael Klier */
583de862555SMichael Klierfunction io_mktmpdir() {
584de862555SMichael Klier    global $conf;
585de862555SMichael Klier
586da1e1077SChris Smith    $base = $conf['tmpdir'];
587da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
588287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
589de862555SMichael Klier
590de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
591de862555SMichael Klier        return($tmpdir);
592de862555SMichael Klier    } else {
593de862555SMichael Klier        return false;
594de862555SMichael Klier    }
595de862555SMichael Klier}
596de862555SMichael Klier
597de862555SMichael Klier/**
59873ccfcb9Schris * downloads a file from the net and saves it
59973ccfcb9Schris *
60073ccfcb9Schris * if $useAttachment is false,
60173ccfcb9Schris * - $file is the full filename to save the file, incl. path
60273ccfcb9Schris * - if successful will return true, false otherwise
603db959ae3SAndreas Gohr *
60473ccfcb9Schris * if $useAttachment is true,
60573ccfcb9Schris * - $file is the directory where the file should be saved
60673ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
607b625487dSandi *
608b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
60973ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
61042ea7f44SGerrit Uitslag *
61142ea7f44SGerrit Uitslag * @param string $url           url to download
61242ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
61342ea7f44SGerrit Uitslag * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
61442ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
61542ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
61642ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
617b625487dSandi */
618847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
619ac9115b0STroels Liebe Bentsen    global $conf;
6209b307a83SAndreas Gohr    $http = new DokuHTTPClient();
621847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
6229b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
623a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
6249b307a83SAndreas Gohr
6259b307a83SAndreas Gohr    $data = $http->get($url);
6269b307a83SAndreas Gohr    if(!$data) return false;
6279b307a83SAndreas Gohr
62873ccfcb9Schris    $name = '';
629cd2f903bSMichael Hamann    if ($useAttachment) {
63073ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
63173ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
632ce070a9fSchris            $match=array();
63373ccfcb9Schris            if (is_string($content_disposition) &&
634ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
63573ccfcb9Schris
6363009a773SAndreas Gohr                $name = utf8_basename($match[1]);
63773ccfcb9Schris            }
63873ccfcb9Schris
63973ccfcb9Schris        }
64073ccfcb9Schris
64173ccfcb9Schris        if (!$name) {
64273ccfcb9Schris            if (!$defaultName) return false;
64373ccfcb9Schris            $name = $defaultName;
64473ccfcb9Schris        }
64573ccfcb9Schris
64673ccfcb9Schris        $file = $file.$name;
64773ccfcb9Schris    }
64873ccfcb9Schris
64979e79377SAndreas Gohr    $fileexists = file_exists($file);
6509b307a83SAndreas Gohr    $fp = @fopen($file,"w");
651b625487dSandi    if(!$fp) return false;
6529b307a83SAndreas Gohr    fwrite($fp,$data);
653b625487dSandi    fclose($fp);
6541ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
65573ccfcb9Schris    if ($useAttachment) return $name;
656b625487dSandi    return true;
657b625487dSandi}
658b625487dSandi
659b625487dSandi/**
660ac9115b0STroels Liebe Bentsen * Windows compatible rename
661bf5e5a5bSAndreas Gohr *
662bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
663bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
66442ea7f44SGerrit Uitslag *
66542ea7f44SGerrit Uitslag * @param string $from
66642ea7f44SGerrit Uitslag * @param string $to
66742ea7f44SGerrit Uitslag * @return bool succes or fail
668bf5e5a5bSAndreas Gohr */
669bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
670ac9115b0STroels Liebe Bentsen    global $conf;
671bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
672bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
6738e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
674bf5e5a5bSAndreas Gohr            @unlink($from);
675bf5e5a5bSAndreas Gohr            return true;
676bf5e5a5bSAndreas Gohr        }
677bf5e5a5bSAndreas Gohr        return false;
678bf5e5a5bSAndreas Gohr    }
679bf5e5a5bSAndreas Gohr    return true;
680bf5e5a5bSAndreas Gohr}
681bf5e5a5bSAndreas Gohr
682420edfd6STom N Harris/**
683420edfd6STom N Harris * Runs an external command with input and output pipes.
684420edfd6STom N Harris * Returns the exit code from the process.
685420edfd6STom N Harris *
686420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
68742ea7f44SGerrit Uitslag *
68842ea7f44SGerrit Uitslag * @param string $cmd
68942ea7f44SGerrit Uitslag * @param string $input  input pipe
69042ea7f44SGerrit Uitslag * @param string $output output pipe
69142ea7f44SGerrit Uitslag * @return int exit code from process
692420edfd6STom N Harris */
693420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
6946c528220STom N Harris    $descspec = array(
6956c528220STom N Harris            0=>array("pipe","r"),
6966c528220STom N Harris            1=>array("pipe","w"),
6976c528220STom N Harris            2=>array("pipe","w"));
6986c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
6996c528220STom N Harris    if(!$ph) return -1;
7006c528220STom N Harris    fclose($pipes[2]); // ignore stderr
7016c528220STom N Harris    fwrite($pipes[0], $input);
7026c528220STom N Harris    fclose($pipes[0]);
7036c528220STom N Harris    $output = stream_get_contents($pipes[1]);
7046c528220STom N Harris    fclose($pipes[1]);
7056c528220STom N Harris    return proc_close($ph);
706f3f0262cSandi}
707f3f0262cSandi
7087421c3ccSAndreas Gohr/**
7097421c3ccSAndreas Gohr * Search a file for matching lines
7107421c3ccSAndreas Gohr *
7117421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
7127421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
7137421c3ccSAndreas Gohr * at once.
7147421c3ccSAndreas Gohr *
7157421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7167421c3ccSAndreas Gohr * @param  string $file    The file to search
7177421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
7187421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
719cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
720cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
7217421c3ccSAndreas Gohr */
7227421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
7237421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
7247421c3ccSAndreas Gohr    if(!$fh) return false;
7257421c3ccSAndreas Gohr    $matches = array();
7267421c3ccSAndreas Gohr
7277421c3ccSAndreas Gohr    $cnt  = 0;
7287421c3ccSAndreas Gohr    $line = '';
7297421c3ccSAndreas Gohr    while (!feof($fh)) {
7307421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7317421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
7327421c3ccSAndreas Gohr
7337421c3ccSAndreas Gohr        // check if line matches
7347421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
7357421c3ccSAndreas Gohr            if($backref){
7367421c3ccSAndreas Gohr                $matches[] = $match;
7377421c3ccSAndreas Gohr            }else{
7387421c3ccSAndreas Gohr                $matches[] = $line;
7397421c3ccSAndreas Gohr            }
7407421c3ccSAndreas Gohr            $cnt++;
7417421c3ccSAndreas Gohr        }
7427421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
7437421c3ccSAndreas Gohr        $line = '';
7447421c3ccSAndreas Gohr    }
7457421c3ccSAndreas Gohr    fclose($fh);
7467421c3ccSAndreas Gohr    return $matches;
7477421c3ccSAndreas Gohr}
7487421c3ccSAndreas Gohr
749