xref: /dokuwiki/inc/io.php (revision 4d47e8e3bcbb31435593de9d567723e5d87641bd)
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
2353d6ccfeSandi * @author  Andreas Gohr <andi@splitbrain.org>
24cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
2553d6ccfeSandi */
26755f1e03SAndreas Gohrfunction io_sweepNS($id,$basedir='datadir'){
2753d6ccfeSandi    global $conf;
28cc7d0c94SBen Coburn    $types = array ('datadir'=>'pages', 'mediadir'=>'media');
29cc7d0c94SBen Coburn    $ns_type = (isset($types[$basedir])?$types[$basedir]:false);
3053d6ccfeSandi
31d186898bSAndreas Gohr    $delone = false;
32d186898bSAndreas Gohr
3353d6ccfeSandi    //scan all namespaces
3453d6ccfeSandi    while(($id = getNS($id)) !== false){
35755f1e03SAndreas Gohr        $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':','/',$id));
3653d6ccfeSandi
3753d6ccfeSandi        //try to delete dir else return
38cc7d0c94SBen Coburn        if(@rmdir($dir)) {
39cc7d0c94SBen Coburn            if ($ns_type!==false) {
40cc7d0c94SBen Coburn                $data = array($id, $ns_type);
41d186898bSAndreas Gohr                $delone = true; // we deleted at least one dir
42cc7d0c94SBen Coburn                trigger_event('IO_NAMESPACE_DELETED', $data);
43cc7d0c94SBen Coburn            }
44d186898bSAndreas Gohr        } else { return $delone; }
45cc7d0c94SBen Coburn    }
46d186898bSAndreas Gohr    return $delone;
47cc7d0c94SBen Coburn}
48cc7d0c94SBen Coburn
49cc7d0c94SBen Coburn/**
50cc7d0c94SBen Coburn * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
51cc7d0c94SBen Coburn *
52cc7d0c94SBen Coburn * Generates the action event which delegates to io_readFile().
53cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
54cc7d0c94SBen Coburn * The file path should not be changed.
55cc7d0c94SBen Coburn *
56cc7d0c94SBen Coburn * Event data:
57cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_readFile as an array.
58cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
59cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
60cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
61cc7d0c94SBen Coburn *
62cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
63cc7d0c94SBen Coburn */
64cc7d0c94SBen Coburnfunction io_readWikiPage($file, $id, $rev=false) {
65cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
667651b376SAndreas Gohr    $data = array(array($file, true), getNS($id), noNS($id), $rev);
67cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
68cc7d0c94SBen Coburn}
69cc7d0c94SBen Coburn
70cc7d0c94SBen Coburn/**
71cc7d0c94SBen Coburn * Callback adapter for io_readFile().
72cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
73cc7d0c94SBen Coburn */
74cc7d0c94SBen Coburnfunction _io_readWikiPage_action($data) {
75cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
76cc7d0c94SBen Coburn        return call_user_func_array('io_readFile', $data[0]);
77cc7d0c94SBen Coburn    } else {
78cc7d0c94SBen Coburn        return ''; //callback error
7953d6ccfeSandi    }
8053d6ccfeSandi}
8153d6ccfeSandi
8253d6ccfeSandi/**
8315fae107Sandi * Returns content of $file as cleaned string.
8415fae107Sandi *
8515fae107Sandi * Uses gzip if extension is .gz
8615fae107Sandi *
87ee4c4a1bSAndreas Gohr * If you want to use the returned value in unserialize
88ee4c4a1bSAndreas Gohr * be sure to set $clean to false!
89ee4c4a1bSAndreas Gohr *
9015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
91f3f0262cSandi */
92e34c0709SAndreas Gohrfunction io_readFile($file,$clean=true){
93f3f0262cSandi    $ret = '';
94f3f0262cSandi    if(@file_exists($file)){
95f3f0262cSandi        if(substr($file,-3) == '.gz'){
96f3f0262cSandi            $ret = join('',gzfile($file));
97ff3ed99fSmarcel        }else if(substr($file,-4) == '.bz2'){
98ff3ed99fSmarcel            $ret = bzfile($file);
99f3f0262cSandi        }else{
10043078d10SAndreas Gohr            $ret = file_get_contents($file);
101f3f0262cSandi        }
102f3f0262cSandi    }
103e34c0709SAndreas Gohr    if($clean){
104f3f0262cSandi        return cleanText($ret);
105e34c0709SAndreas Gohr    }else{
106e34c0709SAndreas Gohr        return $ret;
107e34c0709SAndreas Gohr    }
108f3f0262cSandi}
109ff3ed99fSmarcel/**
110ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
111ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
112ff3ed99fSmarcel */
113ff3ed99fSmarcel
114ff3ed99fSmarcelfunction bzfile($file){
115ff3ed99fSmarcel    $bz = bzopen($file,"r");
116cd2f903bSMichael Hamann    $str = '';
117ff3ed99fSmarcel    while (!feof($bz)){
118ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
119ff3ed99fSmarcel        $str = $str . bzread($bz,8192);
120ff3ed99fSmarcel    }
121ff3ed99fSmarcel    bzclose($bz);
122ff3ed99fSmarcel    return $str;
123ff3ed99fSmarcel}
124ff3ed99fSmarcel
125f3f0262cSandi
126f3f0262cSandi/**
127cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
128cc7d0c94SBen Coburn *
129cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
130cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
131cc7d0c94SBen Coburn * The file path should not be changed.
132cc7d0c94SBen Coburn * (The append parameter is set to false.)
133cc7d0c94SBen Coburn *
134cc7d0c94SBen Coburn * Event data:
135cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
136cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
137cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
138cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
139cc7d0c94SBen Coburn *
140cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
141cc7d0c94SBen Coburn */
142cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
143cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
144cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
145cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
146cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
147cc7d0c94SBen Coburn}
148cc7d0c94SBen Coburn
149cc7d0c94SBen Coburn/**
150cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
151cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
152cc7d0c94SBen Coburn */
153cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
154cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
155cc7d0c94SBen Coburn        return call_user_func_array('io_saveFile', $data[0]);
156cc7d0c94SBen Coburn    } else {
157cc7d0c94SBen Coburn        return false; //callback error
158cc7d0c94SBen Coburn    }
159cc7d0c94SBen Coburn}
160cc7d0c94SBen Coburn
161cc7d0c94SBen Coburn/**
16215fae107Sandi * Saves $content to $file.
163f3f0262cSandi *
1641380fc45SAndreas Gohr * If the third parameter is set to true the given content
1651380fc45SAndreas Gohr * will be appended.
1661380fc45SAndreas Gohr *
16715fae107Sandi * Uses gzip if extension is .gz
168ff3ed99fSmarcel * and bz2 if extension is .bz2
16915fae107Sandi *
17015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
17115fae107Sandi * @return bool true on success
172f3f0262cSandi */
1731380fc45SAndreas Gohrfunction io_saveFile($file,$content,$append=false){
174ac9115b0STroels Liebe Bentsen    global $conf;
1751380fc45SAndreas Gohr    $mode = ($append) ? 'ab' : 'wb';
1761380fc45SAndreas Gohr
177d8186216SBen Coburn    $fileexists = @file_exists($file);
178f3f0262cSandi    io_makeFileDir($file);
17990eb8392Sandi    io_lock($file);
180f3f0262cSandi    if(substr($file,-3) == '.gz'){
1811380fc45SAndreas Gohr        $fh = @gzopen($file,$mode.'9');
182f3f0262cSandi        if(!$fh){
183f3f0262cSandi            msg("Writing $file failed",-1);
184fb7125eeSAndreas Gohr            io_unlock($file);
185f3f0262cSandi            return false;
186f3f0262cSandi        }
187f3f0262cSandi        gzwrite($fh, $content);
188f3f0262cSandi        gzclose($fh);
189ff3ed99fSmarcel    }else if(substr($file,-4) == '.bz2'){
190ece639c7SAndreas Gohr        $fh = @bzopen($file,$mode{0});
191ff3ed99fSmarcel        if(!$fh){
192ff3ed99fSmarcel            msg("Writing $file failed", -1);
193fb7125eeSAndreas Gohr            io_unlock($file);
194ff3ed99fSmarcel            return false;
195ff3ed99fSmarcel        }
196ff3ed99fSmarcel        bzwrite($fh, $content);
197ff3ed99fSmarcel        bzclose($fh);
198f3f0262cSandi    }else{
1991380fc45SAndreas Gohr        $fh = @fopen($file,$mode);
200f3f0262cSandi        if(!$fh){
201f3f0262cSandi            msg("Writing $file failed",-1);
202fb7125eeSAndreas Gohr            io_unlock($file);
203f3f0262cSandi            return false;
204f3f0262cSandi        }
205f3f0262cSandi        fwrite($fh, $content);
206f3f0262cSandi        fclose($fh);
207f3f0262cSandi    }
208ac9115b0STroels Liebe Bentsen
209bb4866bdSchris    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
21090eb8392Sandi    io_unlock($file);
211f3f0262cSandi    return true;
212f3f0262cSandi}
213f3f0262cSandi
214f3f0262cSandi/**
2151380fc45SAndreas Gohr * Delete exact linematch for $badline from $file.
2161380fc45SAndreas Gohr *
2171380fc45SAndreas Gohr * Be sure to include the trailing newline in $badline
218b158d625SSteven Danz *
219b158d625SSteven Danz * Uses gzip if extension is .gz
220b158d625SSteven Danz *
2218b06d178Schris * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
2228b06d178Schris *
223b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
224b158d625SSteven Danz * @return bool true on success
225b158d625SSteven Danz */
2268b06d178Schrisfunction io_deleteFromFile($file,$badline,$regex=false){
2271380fc45SAndreas Gohr    if (!@file_exists($file)) return true;
2281380fc45SAndreas Gohr
229b158d625SSteven Danz    io_lock($file);
2301380fc45SAndreas Gohr
2311380fc45SAndreas Gohr    // load into array
232b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
2331380fc45SAndreas Gohr        $lines = gzfile($file);
234b158d625SSteven Danz    }else{
2351380fc45SAndreas Gohr        $lines = file($file);
236b158d625SSteven Danz    }
237b158d625SSteven Danz
2381380fc45SAndreas Gohr    // remove all matching lines
2398b06d178Schris    if ($regex) {
2408b06d178Schris        $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
2418b06d178Schris    } else {
2421380fc45SAndreas Gohr        $pos = array_search($badline,$lines); //return null or false if not found
2431380fc45SAndreas Gohr        while(is_int($pos)){
2441380fc45SAndreas Gohr            unset($lines[$pos]);
2451380fc45SAndreas Gohr            $pos = array_search($badline,$lines);
246b158d625SSteven Danz        }
2478b06d178Schris    }
248b158d625SSteven Danz
2491380fc45SAndreas Gohr    if(count($lines)){
2501380fc45SAndreas Gohr        $content = join('',$lines);
251b158d625SSteven Danz        if(substr($file,-3) == '.gz'){
252b158d625SSteven Danz            $fh = @gzopen($file,'wb9');
253b158d625SSteven Danz            if(!$fh){
254b158d625SSteven Danz                msg("Removing content from $file failed",-1);
255fb7125eeSAndreas Gohr                io_unlock($file);
256b158d625SSteven Danz                return false;
257b158d625SSteven Danz            }
258b158d625SSteven Danz            gzwrite($fh, $content);
259b158d625SSteven Danz            gzclose($fh);
260b158d625SSteven Danz        }else{
261b158d625SSteven Danz            $fh = @fopen($file,'wb');
262b158d625SSteven Danz            if(!$fh){
263b158d625SSteven Danz                msg("Removing content from $file failed",-1);
264fb7125eeSAndreas Gohr                io_unlock($file);
265b158d625SSteven Danz                return false;
266b158d625SSteven Danz            }
267b158d625SSteven Danz            fwrite($fh, $content);
268b158d625SSteven Danz            fclose($fh);
269b158d625SSteven Danz        }
270b158d625SSteven Danz    }else{
271b158d625SSteven Danz        @unlink($file);
272b158d625SSteven Danz    }
273b158d625SSteven Danz
274b158d625SSteven Danz    io_unlock($file);
275b158d625SSteven Danz    return true;
276b158d625SSteven Danz}
277b158d625SSteven Danz
278b158d625SSteven Danz/**
27990eb8392Sandi * Tries to lock a file
28090eb8392Sandi *
28190eb8392Sandi * Locking is only done for io_savefile and uses directories
28290eb8392Sandi * inside $conf['lockdir']
28390eb8392Sandi *
28490eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
28590eb8392Sandi * the lock is assumed to be stale and the function goes on
28690eb8392Sandi *
28790eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
28890eb8392Sandi */
28990eb8392Sandifunction io_lock($file){
29090eb8392Sandi    global $conf;
29190eb8392Sandi    // no locking if safemode hack
29290eb8392Sandi    if($conf['safemodehack']) return;
29390eb8392Sandi
29490eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
29590eb8392Sandi    @ignore_user_abort(1);
29690eb8392Sandi
29790eb8392Sandi    $timeStart = time();
29890eb8392Sandi    do {
29990eb8392Sandi        //waited longer than 3 seconds? -> stale lock
30090eb8392Sandi        if ((time() - $timeStart) > 3) break;
30144881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
30277b98903SAndreas Gohr        if($locked){
303bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
30477b98903SAndreas Gohr            break;
30577b98903SAndreas Gohr        }
30677b98903SAndreas Gohr        usleep(50);
30790eb8392Sandi    } while ($locked === false);
30890eb8392Sandi}
30990eb8392Sandi
31090eb8392Sandi/**
31190eb8392Sandi * Unlocks a file
31290eb8392Sandi *
31390eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
31490eb8392Sandi */
31590eb8392Sandifunction io_unlock($file){
31690eb8392Sandi    global $conf;
31790eb8392Sandi    // no locking if safemode hack
31890eb8392Sandi    if($conf['safemodehack']) return;
31990eb8392Sandi
32090eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
32190eb8392Sandi    @rmdir($lockDir);
32290eb8392Sandi    @ignore_user_abort(0);
32390eb8392Sandi}
32490eb8392Sandi
32590eb8392Sandi/**
326cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
327cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
328cc7d0c94SBen Coburn *
329cc7d0c94SBen Coburn * Event data:
330cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
331cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
332cc7d0c94SBen Coburn *
333cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
334cc7d0c94SBen Coburn */
335cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
336cc7d0c94SBen Coburn    // verify ns_type
337cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
338cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
339cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
340cc7d0c94SBen Coburn        return;
341cc7d0c94SBen Coburn    }
342cc7d0c94SBen Coburn    // make event list
343cc7d0c94SBen Coburn    $missing = array();
344cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
345cc7d0c94SBen Coburn    $ns = $id;
346cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
347cc7d0c94SBen Coburn    while (!@is_dir($tmp) && !(@file_exists($tmp) && !is_dir($tmp))) {
348cc7d0c94SBen Coburn        array_pop($ns_stack);
349cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
350cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
351cc7d0c94SBen Coburn        $missing[] = $ns;
352cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
353cc7d0c94SBen Coburn    }
354cc7d0c94SBen Coburn    // make directories
355cc7d0c94SBen Coburn    io_makeFileDir($file);
356cc7d0c94SBen Coburn    // send the events
357cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
358cc7d0c94SBen Coburn    foreach ($missing as $ns) {
359cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
360cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
361cc7d0c94SBen Coburn    }
362cc7d0c94SBen Coburn}
363cc7d0c94SBen Coburn
364cc7d0c94SBen Coburn/**
365f3f0262cSandi * Create the directory needed for the given file
36615fae107Sandi *
36715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
368f3f0262cSandi */
369f3f0262cSandifunction io_makeFileDir($file){
370f3f0262cSandi    global $conf;
371f3f0262cSandi
372f3f0262cSandi    $dir = dirname($file);
3730d8850c4SAndreas Gohr    if(!@is_dir($dir)){
374f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
375f3f0262cSandi    }
376f3f0262cSandi}
377f3f0262cSandi
378f3f0262cSandi/**
379f3f0262cSandi * Creates a directory hierachy.
380f3f0262cSandi *
38115fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
382f3f0262cSandi * @author  <saint@corenova.com>
3833dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
384f3f0262cSandi */
385f3f0262cSandifunction io_mkdir_p($target){
3863dc3a5f1Sandi    global $conf;
3870d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
388f3f0262cSandi    if (@file_exists($target) && !is_dir($target)) return 0;
3893dc3a5f1Sandi    //recursion
3903dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
3913dc3a5f1Sandi        if($conf['safemodehack']){
39200976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
393034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
3943dc3a5f1Sandi        }else{
39544881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
396443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
39744881d27STroels Liebe Bentsen            return $ret;
3983dc3a5f1Sandi        }
3993dc3a5f1Sandi    }
400f3f0262cSandi    return 0;
401f3f0262cSandi}
402f3f0262cSandi
403f3f0262cSandi/**
404*4d47e8e3SAndreas Gohr * Recursively delete a directory
405*4d47e8e3SAndreas Gohr *
406*4d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
407*4d47e8e3SAndreas Gohr * @param string $path
408*4d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
409*4d47e8e3SAndreas Gohr * @return bool
410*4d47e8e3SAndreas Gohr */
411*4d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
412*4d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
413*4d47e8e3SAndreas Gohr
414*4d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
415*4d47e8e3SAndreas Gohr        $dirs  = array();
416*4d47e8e3SAndreas Gohr        $files = array();
417*4d47e8e3SAndreas Gohr
418*4d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
419*4d47e8e3SAndreas Gohr        while($f = readdir($dh)) {
420*4d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
421*4d47e8e3SAndreas Gohr
422*4d47e8e3SAndreas Gohr            // collect dirs and files first
423*4d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
424*4d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
425*4d47e8e3SAndreas Gohr            } else if($removefiles) {
426*4d47e8e3SAndreas Gohr                $files[] = "$path/$f";
427*4d47e8e3SAndreas Gohr            } else {
428*4d47e8e3SAndreas Gohr                return false; // abort when non empty
429*4d47e8e3SAndreas Gohr            }
430*4d47e8e3SAndreas Gohr
431*4d47e8e3SAndreas Gohr        }
432*4d47e8e3SAndreas Gohr        closedir($dh);
433*4d47e8e3SAndreas Gohr
434*4d47e8e3SAndreas Gohr        // now traverse into  directories first
435*4d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
436*4d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
437*4d47e8e3SAndreas Gohr        }
438*4d47e8e3SAndreas Gohr
439*4d47e8e3SAndreas Gohr        // now delete files
440*4d47e8e3SAndreas Gohr        foreach($files as $file) {
441*4d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
442*4d47e8e3SAndreas Gohr        }
443*4d47e8e3SAndreas Gohr
444*4d47e8e3SAndreas Gohr        // remove self
445*4d47e8e3SAndreas Gohr        return @rmdir($path);
446*4d47e8e3SAndreas Gohr    } else if($removefiles) {
447*4d47e8e3SAndreas Gohr        return @unlink($path);
448*4d47e8e3SAndreas Gohr    }
449*4d47e8e3SAndreas Gohr    return false;
450*4d47e8e3SAndreas Gohr}
451*4d47e8e3SAndreas Gohr
452*4d47e8e3SAndreas Gohr/**
4533dc3a5f1Sandi * Creates a directory using FTP
4543dc3a5f1Sandi *
4553dc3a5f1Sandi * This is used when the safemode workaround is enabled
4563dc3a5f1Sandi *
4573dc3a5f1Sandi * @author <andi@splitbrain.org>
4583dc3a5f1Sandi */
4593dc3a5f1Sandifunction io_mkdir_ftp($dir){
4603dc3a5f1Sandi    global $conf;
4613dc3a5f1Sandi
4623dc3a5f1Sandi    if(!function_exists('ftp_connect')){
4633dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
4643dc3a5f1Sandi        return false;
4653dc3a5f1Sandi    }
4663dc3a5f1Sandi
4673dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
4683dc3a5f1Sandi    if(!$conn){
4693dc3a5f1Sandi        msg("FTP connection failed",-1);
4703dc3a5f1Sandi        return false;
4713dc3a5f1Sandi    }
4723dc3a5f1Sandi
4733994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
4743dc3a5f1Sandi        msg("FTP login failed",-1);
4753dc3a5f1Sandi        return false;
4763dc3a5f1Sandi    }
4773dc3a5f1Sandi
4783dc3a5f1Sandi    //create directory
479034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
4801ca31cfeSAndreas Gohr    //set permissions
4811ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
4823dc3a5f1Sandi
483034138e2SRainer Weinhold    @ftp_close($conn);
4843dc3a5f1Sandi    return $ok;
4853dc3a5f1Sandi}
4863dc3a5f1Sandi
4873dc3a5f1Sandi/**
488de862555SMichael Klier * Creates a unique temporary directory and returns
489de862555SMichael Klier * its path.
490de862555SMichael Klier *
491de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
492de862555SMichael Klier */
493de862555SMichael Klierfunction io_mktmpdir() {
494de862555SMichael Klier    global $conf;
495de862555SMichael Klier
496da1e1077SChris Smith    $base = $conf['tmpdir'];
497da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
498287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
499de862555SMichael Klier
500de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
501de862555SMichael Klier        return($tmpdir);
502de862555SMichael Klier    } else {
503de862555SMichael Klier        return false;
504de862555SMichael Klier    }
505de862555SMichael Klier}
506de862555SMichael Klier
507de862555SMichael Klier/**
50873ccfcb9Schris * downloads a file from the net and saves it
50973ccfcb9Schris *
51073ccfcb9Schris * if $useAttachment is false,
51173ccfcb9Schris * - $file is the full filename to save the file, incl. path
51273ccfcb9Schris * - if successful will return true, false otherwise
513db959ae3SAndreas Gohr *
51473ccfcb9Schris * if $useAttachment is true,
51573ccfcb9Schris * - $file is the directory where the file should be saved
51673ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
517b625487dSandi *
518b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
51973ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
520b625487dSandi */
521847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
522ac9115b0STroels Liebe Bentsen    global $conf;
5239b307a83SAndreas Gohr    $http = new DokuHTTPClient();
524847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
5259b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
526a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
5279b307a83SAndreas Gohr
5289b307a83SAndreas Gohr    $data = $http->get($url);
5299b307a83SAndreas Gohr    if(!$data) return false;
5309b307a83SAndreas Gohr
53173ccfcb9Schris    $name = '';
532cd2f903bSMichael Hamann    if ($useAttachment) {
53373ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
53473ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
535ce070a9fSchris            $match=array();
53673ccfcb9Schris            if (is_string($content_disposition) &&
537ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
53873ccfcb9Schris
5393009a773SAndreas Gohr                $name = utf8_basename($match[1]);
54073ccfcb9Schris            }
54173ccfcb9Schris
54273ccfcb9Schris        }
54373ccfcb9Schris
54473ccfcb9Schris        if (!$name) {
54573ccfcb9Schris            if (!$defaultName) return false;
54673ccfcb9Schris            $name = $defaultName;
54773ccfcb9Schris        }
54873ccfcb9Schris
54973ccfcb9Schris        $file = $file.$name;
55073ccfcb9Schris    }
55173ccfcb9Schris
552d8186216SBen Coburn    $fileexists = @file_exists($file);
5539b307a83SAndreas Gohr    $fp = @fopen($file,"w");
554b625487dSandi    if(!$fp) return false;
5559b307a83SAndreas Gohr    fwrite($fp,$data);
556b625487dSandi    fclose($fp);
5571ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
55873ccfcb9Schris    if ($useAttachment) return $name;
559b625487dSandi    return true;
560b625487dSandi}
561b625487dSandi
562b625487dSandi/**
563ac9115b0STroels Liebe Bentsen * Windows compatible rename
564bf5e5a5bSAndreas Gohr *
565bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
566bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
567bf5e5a5bSAndreas Gohr */
568bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
569ac9115b0STroels Liebe Bentsen    global $conf;
570bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
571bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
5728e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
573bf5e5a5bSAndreas Gohr            @unlink($from);
574bf5e5a5bSAndreas Gohr            return true;
575bf5e5a5bSAndreas Gohr        }
576bf5e5a5bSAndreas Gohr        return false;
577bf5e5a5bSAndreas Gohr    }
578bf5e5a5bSAndreas Gohr    return true;
579bf5e5a5bSAndreas Gohr}
580bf5e5a5bSAndreas Gohr
581420edfd6STom N Harris/**
582420edfd6STom N Harris * Runs an external command with input and output pipes.
583420edfd6STom N Harris * Returns the exit code from the process.
584420edfd6STom N Harris *
585420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
586420edfd6STom N Harris */
587420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
5886c528220STom N Harris    $descspec = array(
5896c528220STom N Harris            0=>array("pipe","r"),
5906c528220STom N Harris            1=>array("pipe","w"),
5916c528220STom N Harris            2=>array("pipe","w"));
5926c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
5936c528220STom N Harris    if(!$ph) return -1;
5946c528220STom N Harris    fclose($pipes[2]); // ignore stderr
5956c528220STom N Harris    fwrite($pipes[0], $input);
5966c528220STom N Harris    fclose($pipes[0]);
5976c528220STom N Harris    $output = stream_get_contents($pipes[1]);
5986c528220STom N Harris    fclose($pipes[1]);
5996c528220STom N Harris    return proc_close($ph);
600f3f0262cSandi}
601f3f0262cSandi
6027421c3ccSAndreas Gohr/**
6037421c3ccSAndreas Gohr * Search a file for matching lines
6047421c3ccSAndreas Gohr *
6057421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
6067421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
6077421c3ccSAndreas Gohr * at once.
6087421c3ccSAndreas Gohr *
6097421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6107421c3ccSAndreas Gohr * @param  string $file    The file to search
6117421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
6127421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
613cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
614cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
6157421c3ccSAndreas Gohr */
6167421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
6177421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
6187421c3ccSAndreas Gohr    if(!$fh) return false;
6197421c3ccSAndreas Gohr    $matches = array();
6207421c3ccSAndreas Gohr
6217421c3ccSAndreas Gohr    $cnt  = 0;
6227421c3ccSAndreas Gohr    $line = '';
6237421c3ccSAndreas Gohr    while (!feof($fh)) {
6247421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
6257421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
6267421c3ccSAndreas Gohr
6277421c3ccSAndreas Gohr        // check if line matches
6287421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
6297421c3ccSAndreas Gohr            if($backref){
6307421c3ccSAndreas Gohr                $matches[] = $match;
6317421c3ccSAndreas Gohr            }else{
6327421c3ccSAndreas Gohr                $matches[] = $line;
6337421c3ccSAndreas Gohr            }
6347421c3ccSAndreas Gohr            $cnt++;
6357421c3ccSAndreas Gohr        }
6367421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
6377421c3ccSAndreas Gohr        $line = '';
6387421c3ccSAndreas Gohr    }
6397421c3ccSAndreas Gohr    fclose($fh);
6407421c3ccSAndreas Gohr    return $matches;
6417421c3ccSAndreas Gohr}
6427421c3ccSAndreas Gohr
643