xref: /dokuwiki/inc/io.php (revision 79e79377626799a77c11aa7849cb9c64305590c8)
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
10442ea7f44SGerrit Uitslag * @return string
105f3f0262cSandi */
106e34c0709SAndreas Gohrfunction io_readFile($file,$clean=true){
107f3f0262cSandi    $ret = '';
108*79e79377SAndreas 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    }
117e34c0709SAndreas Gohr    if($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>
12742ea7f44SGerrit Uitslag *
12842ea7f44SGerrit Uitslag * @param string $file filename
12942ea7f44SGerrit Uitslag * @return string content
130ff3ed99fSmarcel */
131ff3ed99fSmarcelfunction bzfile($file){
132ff3ed99fSmarcel    $bz = bzopen($file,"r");
133cd2f903bSMichael Hamann    $str = '';
134ff3ed99fSmarcel    while (!feof($bz)){
135ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
136ff3ed99fSmarcel        $str = $str . bzread($bz,8192);
137ff3ed99fSmarcel    }
138ff3ed99fSmarcel    bzclose($bz);
139ff3ed99fSmarcel    return $str;
140ff3ed99fSmarcel}
141ff3ed99fSmarcel
142f3f0262cSandi
143f3f0262cSandi/**
144cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
145cc7d0c94SBen Coburn *
146cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
147cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
148cc7d0c94SBen Coburn * The file path should not be changed.
149cc7d0c94SBen Coburn * (The append parameter is set to false.)
150cc7d0c94SBen Coburn *
151cc7d0c94SBen Coburn * Event data:
152cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
153cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
154cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
155cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
156cc7d0c94SBen Coburn *
157cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
15842ea7f44SGerrit Uitslag *
15942ea7f44SGerrit Uitslag * @param string $file      filename
16042ea7f44SGerrit Uitslag * @param string $content
16142ea7f44SGerrit Uitslag * @param string $id        page id
16242ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
16342ea7f44SGerrit Uitslag * @return bool
164cc7d0c94SBen Coburn */
165cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
166cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
167cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
168cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
169cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
170cc7d0c94SBen Coburn}
171cc7d0c94SBen Coburn
172cc7d0c94SBen Coburn/**
173cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
174cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
17542ea7f44SGerrit Uitslag *
17642ea7f44SGerrit Uitslag * @param array $data event data
17742ea7f44SGerrit Uitslag * @return bool
178cc7d0c94SBen Coburn */
179cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
180cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
181cc7d0c94SBen Coburn        return call_user_func_array('io_saveFile', $data[0]);
182cc7d0c94SBen Coburn    } else {
183cc7d0c94SBen Coburn        return false; //callback error
184cc7d0c94SBen Coburn    }
185cc7d0c94SBen Coburn}
186cc7d0c94SBen Coburn
187cc7d0c94SBen Coburn/**
18815fae107Sandi * Saves $content to $file.
189f3f0262cSandi *
1901380fc45SAndreas Gohr * If the third parameter is set to true the given content
1911380fc45SAndreas Gohr * will be appended.
1921380fc45SAndreas Gohr *
19315fae107Sandi * Uses gzip if extension is .gz
194ff3ed99fSmarcel * and bz2 if extension is .bz2
19515fae107Sandi *
19615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
19742ea7f44SGerrit Uitslag *
19842ea7f44SGerrit Uitslag * @param string $file filename path to file
19942ea7f44SGerrit Uitslag * @param string $content
20042ea7f44SGerrit Uitslag * @param bool   $append
20142ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
202f3f0262cSandi */
2031380fc45SAndreas Gohrfunction io_saveFile($file,$content,$append=false){
204ac9115b0STroels Liebe Bentsen    global $conf;
2051380fc45SAndreas Gohr    $mode = ($append) ? 'ab' : 'wb';
2061380fc45SAndreas Gohr
207*79e79377SAndreas Gohr    $fileexists = file_exists($file);
208f3f0262cSandi    io_makeFileDir($file);
20990eb8392Sandi    io_lock($file);
210f3f0262cSandi    if(substr($file,-3) == '.gz'){
2111380fc45SAndreas Gohr        $fh = @gzopen($file,$mode.'9');
212f3f0262cSandi        if(!$fh){
213f3f0262cSandi            msg("Writing $file failed",-1);
214fb7125eeSAndreas Gohr            io_unlock($file);
215f3f0262cSandi            return false;
216f3f0262cSandi        }
217f3f0262cSandi        gzwrite($fh, $content);
218f3f0262cSandi        gzclose($fh);
219ff3ed99fSmarcel    }else if(substr($file,-4) == '.bz2'){
220ece639c7SAndreas Gohr        $fh = @bzopen($file,$mode{0});
221ff3ed99fSmarcel        if(!$fh){
222ff3ed99fSmarcel            msg("Writing $file failed", -1);
223fb7125eeSAndreas Gohr            io_unlock($file);
224ff3ed99fSmarcel            return false;
225ff3ed99fSmarcel        }
226ff3ed99fSmarcel        bzwrite($fh, $content);
227ff3ed99fSmarcel        bzclose($fh);
228f3f0262cSandi    }else{
2291380fc45SAndreas Gohr        $fh = @fopen($file,$mode);
230f3f0262cSandi        if(!$fh){
231f3f0262cSandi            msg("Writing $file failed",-1);
232fb7125eeSAndreas Gohr            io_unlock($file);
233f3f0262cSandi            return false;
234f3f0262cSandi        }
235f3f0262cSandi        fwrite($fh, $content);
236f3f0262cSandi        fclose($fh);
237f3f0262cSandi    }
238ac9115b0STroels Liebe Bentsen
239bb4866bdSchris    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
24090eb8392Sandi    io_unlock($file);
241f3f0262cSandi    return true;
242f3f0262cSandi}
243f3f0262cSandi
244f3f0262cSandi/**
2451380fc45SAndreas Gohr * Delete exact linematch for $badline from $file.
2461380fc45SAndreas Gohr *
2471380fc45SAndreas Gohr * Be sure to include the trailing newline in $badline
248b158d625SSteven Danz *
249b158d625SSteven Danz * Uses gzip if extension is .gz
250b158d625SSteven Danz *
2518b06d178Schris * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
2528b06d178Schris *
253b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
25442ea7f44SGerrit Uitslag *
25542ea7f44SGerrit Uitslag * @param string $file    filename
25642ea7f44SGerrit Uitslag * @param string $badline exact linematch to remove
25742ea7f44SGerrit Uitslag * @param bool   $regex   use regexp?
258b158d625SSteven Danz * @return bool true on success
259b158d625SSteven Danz */
2608b06d178Schrisfunction io_deleteFromFile($file,$badline,$regex=false){
261*79e79377SAndreas Gohr    if (!file_exists($file)) return true;
2621380fc45SAndreas Gohr
263b158d625SSteven Danz    io_lock($file);
2641380fc45SAndreas Gohr
2651380fc45SAndreas Gohr    // load into array
266b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
2671380fc45SAndreas Gohr        $lines = gzfile($file);
268b158d625SSteven Danz    }else{
2691380fc45SAndreas Gohr        $lines = file($file);
270b158d625SSteven Danz    }
271b158d625SSteven Danz
2721380fc45SAndreas Gohr    // remove all matching lines
2738b06d178Schris    if ($regex) {
2748b06d178Schris        $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
2758b06d178Schris    } else {
2761380fc45SAndreas Gohr        $pos = array_search($badline,$lines); //return null or false if not found
2771380fc45SAndreas Gohr        while(is_int($pos)){
2781380fc45SAndreas Gohr            unset($lines[$pos]);
2791380fc45SAndreas Gohr            $pos = array_search($badline,$lines);
280b158d625SSteven Danz        }
2818b06d178Schris    }
282b158d625SSteven Danz
2831380fc45SAndreas Gohr    if(count($lines)){
2841380fc45SAndreas Gohr        $content = join('',$lines);
285b158d625SSteven Danz        if(substr($file,-3) == '.gz'){
286b158d625SSteven Danz            $fh = @gzopen($file,'wb9');
287b158d625SSteven Danz            if(!$fh){
288b158d625SSteven Danz                msg("Removing content from $file failed",-1);
289fb7125eeSAndreas Gohr                io_unlock($file);
290b158d625SSteven Danz                return false;
291b158d625SSteven Danz            }
292b158d625SSteven Danz            gzwrite($fh, $content);
293b158d625SSteven Danz            gzclose($fh);
294b158d625SSteven Danz        }else{
295b158d625SSteven Danz            $fh = @fopen($file,'wb');
296b158d625SSteven Danz            if(!$fh){
297b158d625SSteven Danz                msg("Removing content from $file failed",-1);
298fb7125eeSAndreas Gohr                io_unlock($file);
299b158d625SSteven Danz                return false;
300b158d625SSteven Danz            }
301b158d625SSteven Danz            fwrite($fh, $content);
302b158d625SSteven Danz            fclose($fh);
303b158d625SSteven Danz        }
304b158d625SSteven Danz    }else{
305b158d625SSteven Danz        @unlink($file);
306b158d625SSteven Danz    }
307b158d625SSteven Danz
308b158d625SSteven Danz    io_unlock($file);
309b158d625SSteven Danz    return true;
310b158d625SSteven Danz}
311b158d625SSteven Danz
312b158d625SSteven Danz/**
31390eb8392Sandi * Tries to lock a file
31490eb8392Sandi *
31590eb8392Sandi * Locking is only done for io_savefile and uses directories
31690eb8392Sandi * inside $conf['lockdir']
31790eb8392Sandi *
31890eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
31990eb8392Sandi * the lock is assumed to be stale and the function goes on
32090eb8392Sandi *
32190eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
32242ea7f44SGerrit Uitslag *
32342ea7f44SGerrit Uitslag * @param string $file filename
32490eb8392Sandi */
32590eb8392Sandifunction io_lock($file){
32690eb8392Sandi    global $conf;
32790eb8392Sandi    // no locking if safemode hack
32890eb8392Sandi    if($conf['safemodehack']) return;
32990eb8392Sandi
33090eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
33190eb8392Sandi    @ignore_user_abort(1);
33290eb8392Sandi
33390eb8392Sandi    $timeStart = time();
33490eb8392Sandi    do {
33590eb8392Sandi        //waited longer than 3 seconds? -> stale lock
33690eb8392Sandi        if ((time() - $timeStart) > 3) break;
33744881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
33877b98903SAndreas Gohr        if($locked){
339bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
34077b98903SAndreas Gohr            break;
34177b98903SAndreas Gohr        }
34277b98903SAndreas Gohr        usleep(50);
34390eb8392Sandi    } while ($locked === false);
34490eb8392Sandi}
34590eb8392Sandi
34690eb8392Sandi/**
34790eb8392Sandi * Unlocks a file
34890eb8392Sandi *
34990eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
35042ea7f44SGerrit Uitslag *
35142ea7f44SGerrit Uitslag * @param string $file filename
35290eb8392Sandi */
35390eb8392Sandifunction io_unlock($file){
35490eb8392Sandi    global $conf;
35590eb8392Sandi    // no locking if safemode hack
35690eb8392Sandi    if($conf['safemodehack']) return;
35790eb8392Sandi
35890eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
35990eb8392Sandi    @rmdir($lockDir);
36090eb8392Sandi    @ignore_user_abort(0);
36190eb8392Sandi}
36290eb8392Sandi
36390eb8392Sandi/**
364cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
365cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
366cc7d0c94SBen Coburn *
367cc7d0c94SBen Coburn * Event data:
368cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
369cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
370cc7d0c94SBen Coburn *
371cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
37242ea7f44SGerrit Uitslag *
37342ea7f44SGerrit Uitslag * @param string $id page id
37442ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
375cc7d0c94SBen Coburn */
376cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
377cc7d0c94SBen Coburn    // verify ns_type
378cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
379cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
380cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
381cc7d0c94SBen Coburn        return;
382cc7d0c94SBen Coburn    }
383cc7d0c94SBen Coburn    // make event list
384cc7d0c94SBen Coburn    $missing = array();
385cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
386cc7d0c94SBen Coburn    $ns = $id;
387cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
388*79e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
389cc7d0c94SBen Coburn        array_pop($ns_stack);
390cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
391cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
392cc7d0c94SBen Coburn        $missing[] = $ns;
393cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
394cc7d0c94SBen Coburn    }
395cc7d0c94SBen Coburn    // make directories
396cc7d0c94SBen Coburn    io_makeFileDir($file);
397cc7d0c94SBen Coburn    // send the events
398cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
399cc7d0c94SBen Coburn    foreach ($missing as $ns) {
400cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
401cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
402cc7d0c94SBen Coburn    }
403cc7d0c94SBen Coburn}
404cc7d0c94SBen Coburn
405cc7d0c94SBen Coburn/**
406f3f0262cSandi * Create the directory needed for the given file
40715fae107Sandi *
40815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40942ea7f44SGerrit Uitslag *
41042ea7f44SGerrit Uitslag * @param string $file file name
411f3f0262cSandi */
412f3f0262cSandifunction io_makeFileDir($file){
413f3f0262cSandi    $dir = dirname($file);
4140d8850c4SAndreas Gohr    if(!@is_dir($dir)){
415f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
416f3f0262cSandi    }
417f3f0262cSandi}
418f3f0262cSandi
419f3f0262cSandi/**
420f3f0262cSandi * Creates a directory hierachy.
421f3f0262cSandi *
42215fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
423f3f0262cSandi * @author  <saint@corenova.com>
4243dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
42542ea7f44SGerrit Uitslag *
42642ea7f44SGerrit Uitslag * @param string $target filename
42742ea7f44SGerrit Uitslag * @return bool|int|string
428f3f0262cSandi */
429f3f0262cSandifunction io_mkdir_p($target){
4303dc3a5f1Sandi    global $conf;
4310d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
432*79e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
4333dc3a5f1Sandi    //recursion
4343dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
4353dc3a5f1Sandi        if($conf['safemodehack']){
43600976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
437034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
4383dc3a5f1Sandi        }else{
43944881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
440443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
44144881d27STroels Liebe Bentsen            return $ret;
4423dc3a5f1Sandi        }
4433dc3a5f1Sandi    }
444f3f0262cSandi    return 0;
445f3f0262cSandi}
446f3f0262cSandi
447f3f0262cSandi/**
4484d47e8e3SAndreas Gohr * Recursively delete a directory
4494d47e8e3SAndreas Gohr *
4504d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4514d47e8e3SAndreas Gohr * @param string $path
4524d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
4534d47e8e3SAndreas Gohr * @return bool
4544d47e8e3SAndreas Gohr */
4554d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
4564d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
457d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
4584d47e8e3SAndreas Gohr
4594d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
4604d47e8e3SAndreas Gohr        $dirs  = array();
4614d47e8e3SAndreas Gohr        $files = array();
4624d47e8e3SAndreas Gohr
4634d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
4648426a3eeSAndreas Gohr        while(false !== ($f = readdir($dh))) {
4654d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
4664d47e8e3SAndreas Gohr
4674d47e8e3SAndreas Gohr            // collect dirs and files first
4684d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
4694d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
4704d47e8e3SAndreas Gohr            } else if($removefiles) {
4714d47e8e3SAndreas Gohr                $files[] = "$path/$f";
4724d47e8e3SAndreas Gohr            } else {
4734d47e8e3SAndreas Gohr                return false; // abort when non empty
4744d47e8e3SAndreas Gohr            }
4754d47e8e3SAndreas Gohr
4764d47e8e3SAndreas Gohr        }
4774d47e8e3SAndreas Gohr        closedir($dh);
4784d47e8e3SAndreas Gohr
4794d47e8e3SAndreas Gohr        // now traverse into  directories first
4804d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
4814d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
4824d47e8e3SAndreas Gohr        }
4834d47e8e3SAndreas Gohr
4844d47e8e3SAndreas Gohr        // now delete files
4854d47e8e3SAndreas Gohr        foreach($files as $file) {
4864d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
4874d47e8e3SAndreas Gohr        }
4884d47e8e3SAndreas Gohr
4894d47e8e3SAndreas Gohr        // remove self
4904d47e8e3SAndreas Gohr        return @rmdir($path);
4914d47e8e3SAndreas Gohr    } else if($removefiles) {
4924d47e8e3SAndreas Gohr        return @unlink($path);
4934d47e8e3SAndreas Gohr    }
4944d47e8e3SAndreas Gohr    return false;
4954d47e8e3SAndreas Gohr}
4964d47e8e3SAndreas Gohr
4974d47e8e3SAndreas Gohr/**
4983dc3a5f1Sandi * Creates a directory using FTP
4993dc3a5f1Sandi *
5003dc3a5f1Sandi * This is used when the safemode workaround is enabled
5013dc3a5f1Sandi *
5023dc3a5f1Sandi * @author <andi@splitbrain.org>
50342ea7f44SGerrit Uitslag *
50442ea7f44SGerrit Uitslag * @param string $dir name of the new directory
50542ea7f44SGerrit Uitslag * @return false|string
5063dc3a5f1Sandi */
5073dc3a5f1Sandifunction io_mkdir_ftp($dir){
5083dc3a5f1Sandi    global $conf;
5093dc3a5f1Sandi
5103dc3a5f1Sandi    if(!function_exists('ftp_connect')){
5113dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
5123dc3a5f1Sandi        return false;
5133dc3a5f1Sandi    }
5143dc3a5f1Sandi
5153dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
5163dc3a5f1Sandi    if(!$conn){
5173dc3a5f1Sandi        msg("FTP connection failed",-1);
5183dc3a5f1Sandi        return false;
5193dc3a5f1Sandi    }
5203dc3a5f1Sandi
5213994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
5223dc3a5f1Sandi        msg("FTP login failed",-1);
5233dc3a5f1Sandi        return false;
5243dc3a5f1Sandi    }
5253dc3a5f1Sandi
5263dc3a5f1Sandi    //create directory
527034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
5281ca31cfeSAndreas Gohr    //set permissions
5291ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
5303dc3a5f1Sandi
531034138e2SRainer Weinhold    @ftp_close($conn);
5323dc3a5f1Sandi    return $ok;
5333dc3a5f1Sandi}
5343dc3a5f1Sandi
5353dc3a5f1Sandi/**
536de862555SMichael Klier * Creates a unique temporary directory and returns
537de862555SMichael Klier * its path.
538de862555SMichael Klier *
539de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
54042ea7f44SGerrit Uitslag *
54142ea7f44SGerrit Uitslag * @return false|string path to new directory or false
542de862555SMichael Klier */
543de862555SMichael Klierfunction io_mktmpdir() {
544de862555SMichael Klier    global $conf;
545de862555SMichael Klier
546da1e1077SChris Smith    $base = $conf['tmpdir'];
547da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
548287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
549de862555SMichael Klier
550de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
551de862555SMichael Klier        return($tmpdir);
552de862555SMichael Klier    } else {
553de862555SMichael Klier        return false;
554de862555SMichael Klier    }
555de862555SMichael Klier}
556de862555SMichael Klier
557de862555SMichael Klier/**
55873ccfcb9Schris * downloads a file from the net and saves it
55973ccfcb9Schris *
56073ccfcb9Schris * if $useAttachment is false,
56173ccfcb9Schris * - $file is the full filename to save the file, incl. path
56273ccfcb9Schris * - if successful will return true, false otherwise
563db959ae3SAndreas Gohr *
56473ccfcb9Schris * if $useAttachment is true,
56573ccfcb9Schris * - $file is the directory where the file should be saved
56673ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
567b625487dSandi *
568b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
56973ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
57042ea7f44SGerrit Uitslag *
57142ea7f44SGerrit Uitslag * @param string $url           url to download
57242ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
57342ea7f44SGerrit Uitslag * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
57442ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
57542ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
57642ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
577b625487dSandi */
578847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
579ac9115b0STroels Liebe Bentsen    global $conf;
5809b307a83SAndreas Gohr    $http = new DokuHTTPClient();
581847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
5829b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
583a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
5849b307a83SAndreas Gohr
5859b307a83SAndreas Gohr    $data = $http->get($url);
5869b307a83SAndreas Gohr    if(!$data) return false;
5879b307a83SAndreas Gohr
58873ccfcb9Schris    $name = '';
589cd2f903bSMichael Hamann    if ($useAttachment) {
59073ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
59173ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
592ce070a9fSchris            $match=array();
59373ccfcb9Schris            if (is_string($content_disposition) &&
594ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
59573ccfcb9Schris
5963009a773SAndreas Gohr                $name = utf8_basename($match[1]);
59773ccfcb9Schris            }
59873ccfcb9Schris
59973ccfcb9Schris        }
60073ccfcb9Schris
60173ccfcb9Schris        if (!$name) {
60273ccfcb9Schris            if (!$defaultName) return false;
60373ccfcb9Schris            $name = $defaultName;
60473ccfcb9Schris        }
60573ccfcb9Schris
60673ccfcb9Schris        $file = $file.$name;
60773ccfcb9Schris    }
60873ccfcb9Schris
609*79e79377SAndreas Gohr    $fileexists = file_exists($file);
6109b307a83SAndreas Gohr    $fp = @fopen($file,"w");
611b625487dSandi    if(!$fp) return false;
6129b307a83SAndreas Gohr    fwrite($fp,$data);
613b625487dSandi    fclose($fp);
6141ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
61573ccfcb9Schris    if ($useAttachment) return $name;
616b625487dSandi    return true;
617b625487dSandi}
618b625487dSandi
619b625487dSandi/**
620ac9115b0STroels Liebe Bentsen * Windows compatible rename
621bf5e5a5bSAndreas Gohr *
622bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
623bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
62442ea7f44SGerrit Uitslag *
62542ea7f44SGerrit Uitslag * @param string $from
62642ea7f44SGerrit Uitslag * @param string $to
62742ea7f44SGerrit Uitslag * @return bool succes or fail
628bf5e5a5bSAndreas Gohr */
629bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
630ac9115b0STroels Liebe Bentsen    global $conf;
631bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
632bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
6338e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
634bf5e5a5bSAndreas Gohr            @unlink($from);
635bf5e5a5bSAndreas Gohr            return true;
636bf5e5a5bSAndreas Gohr        }
637bf5e5a5bSAndreas Gohr        return false;
638bf5e5a5bSAndreas Gohr    }
639bf5e5a5bSAndreas Gohr    return true;
640bf5e5a5bSAndreas Gohr}
641bf5e5a5bSAndreas Gohr
642420edfd6STom N Harris/**
643420edfd6STom N Harris * Runs an external command with input and output pipes.
644420edfd6STom N Harris * Returns the exit code from the process.
645420edfd6STom N Harris *
646420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
64742ea7f44SGerrit Uitslag *
64842ea7f44SGerrit Uitslag * @param string $cmd
64942ea7f44SGerrit Uitslag * @param string $input  input pipe
65042ea7f44SGerrit Uitslag * @param string $output output pipe
65142ea7f44SGerrit Uitslag * @return int exit code from process
652420edfd6STom N Harris */
653420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
6546c528220STom N Harris    $descspec = array(
6556c528220STom N Harris            0=>array("pipe","r"),
6566c528220STom N Harris            1=>array("pipe","w"),
6576c528220STom N Harris            2=>array("pipe","w"));
6586c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
6596c528220STom N Harris    if(!$ph) return -1;
6606c528220STom N Harris    fclose($pipes[2]); // ignore stderr
6616c528220STom N Harris    fwrite($pipes[0], $input);
6626c528220STom N Harris    fclose($pipes[0]);
6636c528220STom N Harris    $output = stream_get_contents($pipes[1]);
6646c528220STom N Harris    fclose($pipes[1]);
6656c528220STom N Harris    return proc_close($ph);
666f3f0262cSandi}
667f3f0262cSandi
6687421c3ccSAndreas Gohr/**
6697421c3ccSAndreas Gohr * Search a file for matching lines
6707421c3ccSAndreas Gohr *
6717421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
6727421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
6737421c3ccSAndreas Gohr * at once.
6747421c3ccSAndreas Gohr *
6757421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6767421c3ccSAndreas Gohr * @param  string $file    The file to search
6777421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
6787421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
679cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
680cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
6817421c3ccSAndreas Gohr */
6827421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
6837421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
6847421c3ccSAndreas Gohr    if(!$fh) return false;
6857421c3ccSAndreas Gohr    $matches = array();
6867421c3ccSAndreas Gohr
6877421c3ccSAndreas Gohr    $cnt  = 0;
6887421c3ccSAndreas Gohr    $line = '';
6897421c3ccSAndreas Gohr    while (!feof($fh)) {
6907421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
6917421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
6927421c3ccSAndreas Gohr
6937421c3ccSAndreas Gohr        // check if line matches
6947421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
6957421c3ccSAndreas Gohr            if($backref){
6967421c3ccSAndreas Gohr                $matches[] = $match;
6977421c3ccSAndreas Gohr            }else{
6987421c3ccSAndreas Gohr                $matches[] = $line;
6997421c3ccSAndreas Gohr            }
7007421c3ccSAndreas Gohr            $cnt++;
7017421c3ccSAndreas Gohr        }
7027421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
7037421c3ccSAndreas Gohr        $line = '';
7047421c3ccSAndreas Gohr    }
7057421c3ccSAndreas Gohr    fclose($fh);
7067421c3ccSAndreas Gohr    return $matches;
7077421c3ccSAndreas Gohr}
7087421c3ccSAndreas Gohr
709