xref: /dokuwiki/inc/io.php (revision d8cf4dd43ecd37c371acf9bc6c17998b65d42ba4)
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/**
4044d47e8e3SAndreas Gohr * Recursively delete a directory
4054d47e8e3SAndreas Gohr *
4064d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4074d47e8e3SAndreas Gohr * @param string $path
4084d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
4094d47e8e3SAndreas Gohr * @return bool
4104d47e8e3SAndreas Gohr */
4114d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
4124d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
413*d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
4144d47e8e3SAndreas Gohr
4154d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
4164d47e8e3SAndreas Gohr        $dirs  = array();
4174d47e8e3SAndreas Gohr        $files = array();
4184d47e8e3SAndreas Gohr
4194d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
4204d47e8e3SAndreas Gohr        while($f = readdir($dh)) {
4214d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
4224d47e8e3SAndreas Gohr
4234d47e8e3SAndreas Gohr            // collect dirs and files first
4244d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
4254d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
4264d47e8e3SAndreas Gohr            } else if($removefiles) {
4274d47e8e3SAndreas Gohr                $files[] = "$path/$f";
4284d47e8e3SAndreas Gohr            } else {
4294d47e8e3SAndreas Gohr                return false; // abort when non empty
4304d47e8e3SAndreas Gohr            }
4314d47e8e3SAndreas Gohr
4324d47e8e3SAndreas Gohr        }
4334d47e8e3SAndreas Gohr        closedir($dh);
4344d47e8e3SAndreas Gohr
4354d47e8e3SAndreas Gohr        // now traverse into  directories first
4364d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
4374d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
4384d47e8e3SAndreas Gohr        }
4394d47e8e3SAndreas Gohr
4404d47e8e3SAndreas Gohr        // now delete files
4414d47e8e3SAndreas Gohr        foreach($files as $file) {
4424d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
4434d47e8e3SAndreas Gohr        }
4444d47e8e3SAndreas Gohr
4454d47e8e3SAndreas Gohr        // remove self
4464d47e8e3SAndreas Gohr        return @rmdir($path);
4474d47e8e3SAndreas Gohr    } else if($removefiles) {
4484d47e8e3SAndreas Gohr        return @unlink($path);
4494d47e8e3SAndreas Gohr    }
4504d47e8e3SAndreas Gohr    return false;
4514d47e8e3SAndreas Gohr}
4524d47e8e3SAndreas Gohr
4534d47e8e3SAndreas Gohr/**
4543dc3a5f1Sandi * Creates a directory using FTP
4553dc3a5f1Sandi *
4563dc3a5f1Sandi * This is used when the safemode workaround is enabled
4573dc3a5f1Sandi *
4583dc3a5f1Sandi * @author <andi@splitbrain.org>
4593dc3a5f1Sandi */
4603dc3a5f1Sandifunction io_mkdir_ftp($dir){
4613dc3a5f1Sandi    global $conf;
4623dc3a5f1Sandi
4633dc3a5f1Sandi    if(!function_exists('ftp_connect')){
4643dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
4653dc3a5f1Sandi        return false;
4663dc3a5f1Sandi    }
4673dc3a5f1Sandi
4683dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
4693dc3a5f1Sandi    if(!$conn){
4703dc3a5f1Sandi        msg("FTP connection failed",-1);
4713dc3a5f1Sandi        return false;
4723dc3a5f1Sandi    }
4733dc3a5f1Sandi
4743994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
4753dc3a5f1Sandi        msg("FTP login failed",-1);
4763dc3a5f1Sandi        return false;
4773dc3a5f1Sandi    }
4783dc3a5f1Sandi
4793dc3a5f1Sandi    //create directory
480034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
4811ca31cfeSAndreas Gohr    //set permissions
4821ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
4833dc3a5f1Sandi
484034138e2SRainer Weinhold    @ftp_close($conn);
4853dc3a5f1Sandi    return $ok;
4863dc3a5f1Sandi}
4873dc3a5f1Sandi
4883dc3a5f1Sandi/**
489de862555SMichael Klier * Creates a unique temporary directory and returns
490de862555SMichael Klier * its path.
491de862555SMichael Klier *
492de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
493de862555SMichael Klier */
494de862555SMichael Klierfunction io_mktmpdir() {
495de862555SMichael Klier    global $conf;
496de862555SMichael Klier
497da1e1077SChris Smith    $base = $conf['tmpdir'];
498da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
499287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
500de862555SMichael Klier
501de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
502de862555SMichael Klier        return($tmpdir);
503de862555SMichael Klier    } else {
504de862555SMichael Klier        return false;
505de862555SMichael Klier    }
506de862555SMichael Klier}
507de862555SMichael Klier
508de862555SMichael Klier/**
50973ccfcb9Schris * downloads a file from the net and saves it
51073ccfcb9Schris *
51173ccfcb9Schris * if $useAttachment is false,
51273ccfcb9Schris * - $file is the full filename to save the file, incl. path
51373ccfcb9Schris * - if successful will return true, false otherwise
514db959ae3SAndreas Gohr *
51573ccfcb9Schris * if $useAttachment is true,
51673ccfcb9Schris * - $file is the directory where the file should be saved
51773ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
518b625487dSandi *
519b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
52073ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
521b625487dSandi */
522847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
523ac9115b0STroels Liebe Bentsen    global $conf;
5249b307a83SAndreas Gohr    $http = new DokuHTTPClient();
525847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
5269b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
527a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
5289b307a83SAndreas Gohr
5299b307a83SAndreas Gohr    $data = $http->get($url);
5309b307a83SAndreas Gohr    if(!$data) return false;
5319b307a83SAndreas Gohr
53273ccfcb9Schris    $name = '';
533cd2f903bSMichael Hamann    if ($useAttachment) {
53473ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
53573ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
536ce070a9fSchris            $match=array();
53773ccfcb9Schris            if (is_string($content_disposition) &&
538ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
53973ccfcb9Schris
5403009a773SAndreas Gohr                $name = utf8_basename($match[1]);
54173ccfcb9Schris            }
54273ccfcb9Schris
54373ccfcb9Schris        }
54473ccfcb9Schris
54573ccfcb9Schris        if (!$name) {
54673ccfcb9Schris            if (!$defaultName) return false;
54773ccfcb9Schris            $name = $defaultName;
54873ccfcb9Schris        }
54973ccfcb9Schris
55073ccfcb9Schris        $file = $file.$name;
55173ccfcb9Schris    }
55273ccfcb9Schris
553d8186216SBen Coburn    $fileexists = @file_exists($file);
5549b307a83SAndreas Gohr    $fp = @fopen($file,"w");
555b625487dSandi    if(!$fp) return false;
5569b307a83SAndreas Gohr    fwrite($fp,$data);
557b625487dSandi    fclose($fp);
5581ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
55973ccfcb9Schris    if ($useAttachment) return $name;
560b625487dSandi    return true;
561b625487dSandi}
562b625487dSandi
563b625487dSandi/**
564ac9115b0STroels Liebe Bentsen * Windows compatible rename
565bf5e5a5bSAndreas Gohr *
566bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
567bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
568bf5e5a5bSAndreas Gohr */
569bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
570ac9115b0STroels Liebe Bentsen    global $conf;
571bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
572bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
5738e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
574bf5e5a5bSAndreas Gohr            @unlink($from);
575bf5e5a5bSAndreas Gohr            return true;
576bf5e5a5bSAndreas Gohr        }
577bf5e5a5bSAndreas Gohr        return false;
578bf5e5a5bSAndreas Gohr    }
579bf5e5a5bSAndreas Gohr    return true;
580bf5e5a5bSAndreas Gohr}
581bf5e5a5bSAndreas Gohr
582420edfd6STom N Harris/**
583420edfd6STom N Harris * Runs an external command with input and output pipes.
584420edfd6STom N Harris * Returns the exit code from the process.
585420edfd6STom N Harris *
586420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
587420edfd6STom N Harris */
588420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
5896c528220STom N Harris    $descspec = array(
5906c528220STom N Harris            0=>array("pipe","r"),
5916c528220STom N Harris            1=>array("pipe","w"),
5926c528220STom N Harris            2=>array("pipe","w"));
5936c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
5946c528220STom N Harris    if(!$ph) return -1;
5956c528220STom N Harris    fclose($pipes[2]); // ignore stderr
5966c528220STom N Harris    fwrite($pipes[0], $input);
5976c528220STom N Harris    fclose($pipes[0]);
5986c528220STom N Harris    $output = stream_get_contents($pipes[1]);
5996c528220STom N Harris    fclose($pipes[1]);
6006c528220STom N Harris    return proc_close($ph);
601f3f0262cSandi}
602f3f0262cSandi
6037421c3ccSAndreas Gohr/**
6047421c3ccSAndreas Gohr * Search a file for matching lines
6057421c3ccSAndreas Gohr *
6067421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
6077421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
6087421c3ccSAndreas Gohr * at once.
6097421c3ccSAndreas Gohr *
6107421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6117421c3ccSAndreas Gohr * @param  string $file    The file to search
6127421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
6137421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
614cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
615cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
6167421c3ccSAndreas Gohr */
6177421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
6187421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
6197421c3ccSAndreas Gohr    if(!$fh) return false;
6207421c3ccSAndreas Gohr    $matches = array();
6217421c3ccSAndreas Gohr
6227421c3ccSAndreas Gohr    $cnt  = 0;
6237421c3ccSAndreas Gohr    $line = '';
6247421c3ccSAndreas Gohr    while (!feof($fh)) {
6257421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
6267421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
6277421c3ccSAndreas Gohr
6287421c3ccSAndreas Gohr        // check if line matches
6297421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
6307421c3ccSAndreas Gohr            if($backref){
6317421c3ccSAndreas Gohr                $matches[] = $match;
6327421c3ccSAndreas Gohr            }else{
6337421c3ccSAndreas Gohr                $matches[] = $line;
6347421c3ccSAndreas Gohr            }
6357421c3ccSAndreas Gohr            $cnt++;
6367421c3ccSAndreas Gohr        }
6377421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
6387421c3ccSAndreas Gohr        $line = '';
6397421c3ccSAndreas Gohr    }
6407421c3ccSAndreas Gohr    fclose($fh);
6417421c3ccSAndreas Gohr    return $matches;
6427421c3ccSAndreas Gohr}
6437421c3ccSAndreas Gohr
644