xref: /dokuwiki/inc/io.php (revision 369075828e13e37a65a2f8062a74e89f98dd3fac)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * File IO functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
815fae107Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10f3f0262cSandi
11f3f0262cSandi/**
1253d6ccfeSandi * Removes empty directories
1353d6ccfeSandi *
14cc7d0c94SBen Coburn * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
15cc7d0c94SBen Coburn * Event data:
16cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
17cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
18cc7d0c94SBen Coburn *
1953d6ccfeSandi * @todo use safemode hack
20d186898bSAndreas Gohr * @param string $id      - a pageid, the namespace of that id will be tried to deleted
21cd2f903bSMichael Hamann * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
22cd2f903bSMichael Hamann * @return bool - true if at least one namespace was deleted
2342ea7f44SGerrit Uitslag *
2453d6ccfeSandi * @author  Andreas Gohr <andi@splitbrain.org>
25cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
2653d6ccfeSandi */
27755f1e03SAndreas Gohrfunction io_sweepNS($id,$basedir='datadir'){
2853d6ccfeSandi    global $conf;
29cc7d0c94SBen Coburn    $types = array ('datadir'=>'pages', 'mediadir'=>'media');
30cc7d0c94SBen Coburn    $ns_type = (isset($types[$basedir])?$types[$basedir]:false);
3153d6ccfeSandi
32d186898bSAndreas Gohr    $delone = false;
33d186898bSAndreas Gohr
3453d6ccfeSandi    //scan all namespaces
3553d6ccfeSandi    while(($id = getNS($id)) !== false){
36755f1e03SAndreas Gohr        $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':','/',$id));
3753d6ccfeSandi
3853d6ccfeSandi        //try to delete dir else return
39cc7d0c94SBen Coburn        if(@rmdir($dir)) {
40cc7d0c94SBen Coburn            if ($ns_type!==false) {
41cc7d0c94SBen Coburn                $data = array($id, $ns_type);
42d186898bSAndreas Gohr                $delone = true; // we deleted at least one dir
43cc7d0c94SBen Coburn                trigger_event('IO_NAMESPACE_DELETED', $data);
44cc7d0c94SBen Coburn            }
45d186898bSAndreas Gohr        } else { return $delone; }
46cc7d0c94SBen Coburn    }
47d186898bSAndreas Gohr    return $delone;
48cc7d0c94SBen Coburn}
49cc7d0c94SBen Coburn
50cc7d0c94SBen Coburn/**
51cc7d0c94SBen Coburn * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
52cc7d0c94SBen Coburn *
53cc7d0c94SBen Coburn * Generates the action event which delegates to io_readFile().
54cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
55cc7d0c94SBen Coburn * The file path should not be changed.
56cc7d0c94SBen Coburn *
57cc7d0c94SBen Coburn * Event data:
58cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_readFile as an array.
59cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
60cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
61cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
62cc7d0c94SBen Coburn *
63cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
6442ea7f44SGerrit Uitslag *
6542ea7f44SGerrit Uitslag * @param string   $file filename
6642ea7f44SGerrit Uitslag * @param string   $id page id
6742ea7f44SGerrit Uitslag * @param bool|int $rev revision timestamp
6842ea7f44SGerrit Uitslag * @return string
69cc7d0c94SBen Coburn */
70cc7d0c94SBen Coburnfunction io_readWikiPage($file, $id, $rev=false) {
71cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
727651b376SAndreas Gohr    $data = array(array($file, true), getNS($id), noNS($id), $rev);
73cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
74cc7d0c94SBen Coburn}
75cc7d0c94SBen Coburn
76cc7d0c94SBen Coburn/**
77cc7d0c94SBen Coburn * Callback adapter for io_readFile().
7842ea7f44SGerrit Uitslag *
79cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
8042ea7f44SGerrit Uitslag *
8142ea7f44SGerrit Uitslag * @param array $data event data
8242ea7f44SGerrit Uitslag * @return string
83cc7d0c94SBen Coburn */
84cc7d0c94SBen Coburnfunction _io_readWikiPage_action($data) {
85cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
86cc7d0c94SBen Coburn        return call_user_func_array('io_readFile', $data[0]);
87cc7d0c94SBen Coburn    } else {
88cc7d0c94SBen Coburn        return ''; //callback error
8953d6ccfeSandi    }
9053d6ccfeSandi}
9153d6ccfeSandi
9253d6ccfeSandi/**
9315fae107Sandi * Returns content of $file as cleaned string.
9415fae107Sandi *
9515fae107Sandi * Uses gzip if extension is .gz
9615fae107Sandi *
97ee4c4a1bSAndreas Gohr * If you want to use the returned value in unserialize
98ee4c4a1bSAndreas Gohr * be sure to set $clean to false!
99ee4c4a1bSAndreas Gohr *
10015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
10142ea7f44SGerrit Uitslag *
10242ea7f44SGerrit Uitslag * @param string $file  filename
10342ea7f44SGerrit Uitslag * @param bool   $clean
104d387bf5eSAndreas Gohr * @return string|bool the file contents or false on error
105f3f0262cSandi */
106e34c0709SAndreas Gohrfunction io_readFile($file,$clean=true){
107f3f0262cSandi    $ret = '';
10879e79377SAndreas Gohr    if(file_exists($file)){
109f3f0262cSandi        if(substr($file,-3) == '.gz'){
110f3f0262cSandi            $ret = join('',gzfile($file));
111ff3ed99fSmarcel        }else if(substr($file,-4) == '.bz2'){
112ff3ed99fSmarcel            $ret = bzfile($file);
113f3f0262cSandi        }else{
11443078d10SAndreas Gohr            $ret = file_get_contents($file);
115f3f0262cSandi        }
116f3f0262cSandi    }
117d387bf5eSAndreas Gohr    if($ret !== false && $clean){
118f3f0262cSandi        return cleanText($ret);
119e34c0709SAndreas Gohr    }else{
120e34c0709SAndreas Gohr        return $ret;
121e34c0709SAndreas Gohr    }
122f3f0262cSandi}
123ff3ed99fSmarcel/**
124ff3ed99fSmarcel * Returns the content of a .bz2 compressed file as string
12542ea7f44SGerrit Uitslag *
126ff3ed99fSmarcel * @author marcel senf <marcel@rucksackreinigung.de>
127d387bf5eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
12842ea7f44SGerrit Uitslag *
12942ea7f44SGerrit Uitslag * @param string $file filename
130d387bf5eSAndreas Gohr * @return string|bool content or false on error
131ff3ed99fSmarcel */
132ff3ed99fSmarcelfunction bzfile($file){
133ff3ed99fSmarcel    $bz = bzopen($file,"r");
134d387bf5eSAndreas Gohr    if($bz === false) return false;
135d387bf5eSAndreas Gohr
136cd2f903bSMichael Hamann    $str = '';
137ff3ed99fSmarcel    while (!feof($bz)){
138ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
139d387bf5eSAndreas Gohr        $buffer = bzread($bz,8192);
140d387bf5eSAndreas Gohr        if(($buffer === false) || (bzerrno($bz) !== 0)) {
141d387bf5eSAndreas Gohr            return false;
142d387bf5eSAndreas Gohr        }
143d387bf5eSAndreas Gohr        $str = $str . $buffer;
144ff3ed99fSmarcel    }
145ff3ed99fSmarcel    bzclose($bz);
146ff3ed99fSmarcel    return $str;
147ff3ed99fSmarcel}
148ff3ed99fSmarcel
149f3f0262cSandi/**
150cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
151cc7d0c94SBen Coburn *
152cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
153cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
154cc7d0c94SBen Coburn * The file path should not be changed.
155cc7d0c94SBen Coburn * (The append parameter is set to false.)
156cc7d0c94SBen Coburn *
157cc7d0c94SBen Coburn * Event data:
158cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
159cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
160cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
161cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
162cc7d0c94SBen Coburn *
163cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
16442ea7f44SGerrit Uitslag *
16542ea7f44SGerrit Uitslag * @param string $file      filename
16642ea7f44SGerrit Uitslag * @param string $content
16742ea7f44SGerrit Uitslag * @param string $id        page id
16842ea7f44SGerrit Uitslag * @param int|bool $rev timestamp of revision
16942ea7f44SGerrit Uitslag * @return bool
170cc7d0c94SBen Coburn */
171cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
172cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
173cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
174cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
175cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
176cc7d0c94SBen Coburn}
177cc7d0c94SBen Coburn
178cc7d0c94SBen Coburn/**
179cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
180cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
18142ea7f44SGerrit Uitslag *
18242ea7f44SGerrit Uitslag * @param array $data event data
18342ea7f44SGerrit Uitslag * @return bool
184cc7d0c94SBen Coburn */
185cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
186cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
187cc7d0c94SBen Coburn        return call_user_func_array('io_saveFile', $data[0]);
188cc7d0c94SBen Coburn    } else {
189cc7d0c94SBen Coburn        return false; //callback error
190cc7d0c94SBen Coburn    }
191cc7d0c94SBen Coburn}
192cc7d0c94SBen Coburn
193cc7d0c94SBen Coburn/**
19415fae107Sandi * Saves $content to $file.
195f3f0262cSandi *
1961380fc45SAndreas Gohr * If the third parameter is set to true the given content
1971380fc45SAndreas Gohr * will be appended.
1981380fc45SAndreas Gohr *
19915fae107Sandi * Uses gzip if extension is .gz
200ff3ed99fSmarcel * and bz2 if extension is .bz2
20115fae107Sandi *
20215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20342ea7f44SGerrit Uitslag *
20442ea7f44SGerrit Uitslag * @param string $file filename path to file
20542ea7f44SGerrit Uitslag * @param string $content
20642ea7f44SGerrit Uitslag * @param bool   $append
20742ea7f44SGerrit Uitslag * @return bool true on success, otherwise false
208f3f0262cSandi */
2091380fc45SAndreas Gohrfunction io_saveFile($file,$content,$append=false){
210ac9115b0STroels Liebe Bentsen    global $conf;
2111380fc45SAndreas Gohr    $mode = ($append) ? 'ab' : 'wb';
2121380fc45SAndreas Gohr
21379e79377SAndreas Gohr    $fileexists = file_exists($file);
214f3f0262cSandi    io_makeFileDir($file);
21590eb8392Sandi    io_lock($file);
216f3f0262cSandi    if(substr($file,-3) == '.gz'){
2171380fc45SAndreas Gohr        $fh = @gzopen($file,$mode.'9');
218f3f0262cSandi        if(!$fh){
219f3f0262cSandi            msg("Writing $file failed",-1);
220fb7125eeSAndreas Gohr            io_unlock($file);
221f3f0262cSandi            return false;
222f3f0262cSandi        }
223f3f0262cSandi        gzwrite($fh, $content);
224f3f0262cSandi        gzclose($fh);
225ff3ed99fSmarcel    }else if(substr($file,-4) == '.bz2'){
226*36907582SPatrick Brown        if($append) {
227*36907582SPatrick Brown            $bzcontent = bzfile($file);
228*36907582SPatrick Brown            if($bzcontent === false) {
229*36907582SPatrick Brown                msg("Writing $file failed", -1);
230*36907582SPatrick Brown                io_unlock($file);
231*36907582SPatrick Brown                return false;
232*36907582SPatrick Brown            }
233*36907582SPatrick Brown            $content = $bzcontent.$content;
234*36907582SPatrick Brown        }
235*36907582SPatrick Brown        $fh = @bzopen($file,'w');
236ff3ed99fSmarcel        if(!$fh){
237ff3ed99fSmarcel            msg("Writing $file failed", -1);
238fb7125eeSAndreas Gohr            io_unlock($file);
239ff3ed99fSmarcel            return false;
240ff3ed99fSmarcel        }
241ff3ed99fSmarcel        bzwrite($fh, $content);
242ff3ed99fSmarcel        bzclose($fh);
243f3f0262cSandi    }else{
2441380fc45SAndreas Gohr        $fh = @fopen($file,$mode);
245f3f0262cSandi        if(!$fh){
246f3f0262cSandi            msg("Writing $file failed",-1);
247fb7125eeSAndreas Gohr            io_unlock($file);
248f3f0262cSandi            return false;
249f3f0262cSandi        }
250f3f0262cSandi        fwrite($fh, $content);
251f3f0262cSandi        fclose($fh);
252f3f0262cSandi    }
253ac9115b0STroels Liebe Bentsen
254bb4866bdSchris    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
25590eb8392Sandi    io_unlock($file);
256f3f0262cSandi    return true;
257f3f0262cSandi}
258f3f0262cSandi
259f3f0262cSandi/**
2601380fc45SAndreas Gohr * Delete exact linematch for $badline from $file.
2611380fc45SAndreas Gohr *
2621380fc45SAndreas Gohr * Be sure to include the trailing newline in $badline
263b158d625SSteven Danz *
264b158d625SSteven Danz * Uses gzip if extension is .gz
265b158d625SSteven Danz *
2668b06d178Schris * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
2678b06d178Schris *
268b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
26942ea7f44SGerrit Uitslag *
27042ea7f44SGerrit Uitslag * @param string $file    filename
27142ea7f44SGerrit Uitslag * @param string $badline exact linematch to remove
27242ea7f44SGerrit Uitslag * @param bool   $regex   use regexp?
273b158d625SSteven Danz * @return bool true on success
274b158d625SSteven Danz */
2758b06d178Schrisfunction io_deleteFromFile($file,$badline,$regex=false){
27679e79377SAndreas Gohr    if (!file_exists($file)) return true;
2771380fc45SAndreas Gohr
278b158d625SSteven Danz    io_lock($file);
2791380fc45SAndreas Gohr
2801380fc45SAndreas Gohr    // load into array
281b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
2821380fc45SAndreas Gohr        $lines = gzfile($file);
283b158d625SSteven Danz    }else{
2841380fc45SAndreas Gohr        $lines = file($file);
285b158d625SSteven Danz    }
286b158d625SSteven Danz
2871380fc45SAndreas Gohr    // remove all matching lines
2888b06d178Schris    if ($regex) {
2898b06d178Schris        $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
2908b06d178Schris    } else {
2911380fc45SAndreas Gohr        $pos = array_search($badline,$lines); //return null or false if not found
2921380fc45SAndreas Gohr        while(is_int($pos)){
2931380fc45SAndreas Gohr            unset($lines[$pos]);
2941380fc45SAndreas Gohr            $pos = array_search($badline,$lines);
295b158d625SSteven Danz        }
2968b06d178Schris    }
297b158d625SSteven Danz
2981380fc45SAndreas Gohr    if(count($lines)){
2991380fc45SAndreas Gohr        $content = join('',$lines);
300b158d625SSteven Danz        if(substr($file,-3) == '.gz'){
301b158d625SSteven Danz            $fh = @gzopen($file,'wb9');
302b158d625SSteven Danz            if(!$fh){
303b158d625SSteven Danz                msg("Removing content from $file failed",-1);
304fb7125eeSAndreas Gohr                io_unlock($file);
305b158d625SSteven Danz                return false;
306b158d625SSteven Danz            }
307b158d625SSteven Danz            gzwrite($fh, $content);
308b158d625SSteven Danz            gzclose($fh);
309b158d625SSteven Danz        }else{
310b158d625SSteven Danz            $fh = @fopen($file,'wb');
311b158d625SSteven Danz            if(!$fh){
312b158d625SSteven Danz                msg("Removing content from $file failed",-1);
313fb7125eeSAndreas Gohr                io_unlock($file);
314b158d625SSteven Danz                return false;
315b158d625SSteven Danz            }
316b158d625SSteven Danz            fwrite($fh, $content);
317b158d625SSteven Danz            fclose($fh);
318b158d625SSteven Danz        }
319b158d625SSteven Danz    }else{
320b158d625SSteven Danz        @unlink($file);
321b158d625SSteven Danz    }
322b158d625SSteven Danz
323b158d625SSteven Danz    io_unlock($file);
324b158d625SSteven Danz    return true;
325b158d625SSteven Danz}
326b158d625SSteven Danz
327b158d625SSteven Danz/**
32890eb8392Sandi * Tries to lock a file
32990eb8392Sandi *
33090eb8392Sandi * Locking is only done for io_savefile and uses directories
33190eb8392Sandi * inside $conf['lockdir']
33290eb8392Sandi *
33390eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
33490eb8392Sandi * the lock is assumed to be stale and the function goes on
33590eb8392Sandi *
33690eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
33742ea7f44SGerrit Uitslag *
33842ea7f44SGerrit Uitslag * @param string $file filename
33990eb8392Sandi */
34090eb8392Sandifunction io_lock($file){
34190eb8392Sandi    global $conf;
34290eb8392Sandi    // no locking if safemode hack
34390eb8392Sandi    if($conf['safemodehack']) return;
34490eb8392Sandi
34590eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
34690eb8392Sandi    @ignore_user_abort(1);
34790eb8392Sandi
34890eb8392Sandi    $timeStart = time();
34990eb8392Sandi    do {
35090eb8392Sandi        //waited longer than 3 seconds? -> stale lock
35190eb8392Sandi        if ((time() - $timeStart) > 3) break;
35244881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
35377b98903SAndreas Gohr        if($locked){
354bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
35577b98903SAndreas Gohr            break;
35677b98903SAndreas Gohr        }
35777b98903SAndreas Gohr        usleep(50);
35890eb8392Sandi    } while ($locked === false);
35990eb8392Sandi}
36090eb8392Sandi
36190eb8392Sandi/**
36290eb8392Sandi * Unlocks a file
36390eb8392Sandi *
36490eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
36542ea7f44SGerrit Uitslag *
36642ea7f44SGerrit Uitslag * @param string $file filename
36790eb8392Sandi */
36890eb8392Sandifunction io_unlock($file){
36990eb8392Sandi    global $conf;
37090eb8392Sandi    // no locking if safemode hack
37190eb8392Sandi    if($conf['safemodehack']) return;
37290eb8392Sandi
37390eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
37490eb8392Sandi    @rmdir($lockDir);
37590eb8392Sandi    @ignore_user_abort(0);
37690eb8392Sandi}
37790eb8392Sandi
37890eb8392Sandi/**
379cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
380cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
381cc7d0c94SBen Coburn *
382cc7d0c94SBen Coburn * Event data:
383cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
384cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
385cc7d0c94SBen Coburn *
386cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
38742ea7f44SGerrit Uitslag *
38842ea7f44SGerrit Uitslag * @param string $id page id
38942ea7f44SGerrit Uitslag * @param string $ns_type 'pages' or 'media'
390cc7d0c94SBen Coburn */
391cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
392cc7d0c94SBen Coburn    // verify ns_type
393cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
394cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
395cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
396cc7d0c94SBen Coburn        return;
397cc7d0c94SBen Coburn    }
398cc7d0c94SBen Coburn    // make event list
399cc7d0c94SBen Coburn    $missing = array();
400cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
401cc7d0c94SBen Coburn    $ns = $id;
402cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
40379e79377SAndreas Gohr    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
404cc7d0c94SBen Coburn        array_pop($ns_stack);
405cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
406cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
407cc7d0c94SBen Coburn        $missing[] = $ns;
408cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
409cc7d0c94SBen Coburn    }
410cc7d0c94SBen Coburn    // make directories
411cc7d0c94SBen Coburn    io_makeFileDir($file);
412cc7d0c94SBen Coburn    // send the events
413cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
414cc7d0c94SBen Coburn    foreach ($missing as $ns) {
415cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
416cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
417cc7d0c94SBen Coburn    }
418cc7d0c94SBen Coburn}
419cc7d0c94SBen Coburn
420cc7d0c94SBen Coburn/**
421f3f0262cSandi * Create the directory needed for the given file
42215fae107Sandi *
42315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
42442ea7f44SGerrit Uitslag *
42542ea7f44SGerrit Uitslag * @param string $file file name
426f3f0262cSandi */
427f3f0262cSandifunction io_makeFileDir($file){
428f3f0262cSandi    $dir = dirname($file);
4290d8850c4SAndreas Gohr    if(!@is_dir($dir)){
430f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
431f3f0262cSandi    }
432f3f0262cSandi}
433f3f0262cSandi
434f3f0262cSandi/**
435f3f0262cSandi * Creates a directory hierachy.
436f3f0262cSandi *
43715fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
438f3f0262cSandi * @author  <saint@corenova.com>
4393dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
44042ea7f44SGerrit Uitslag *
44142ea7f44SGerrit Uitslag * @param string $target filename
44242ea7f44SGerrit Uitslag * @return bool|int|string
443f3f0262cSandi */
444f3f0262cSandifunction io_mkdir_p($target){
4453dc3a5f1Sandi    global $conf;
4460d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
44779e79377SAndreas Gohr    if (file_exists($target) && !is_dir($target)) return 0;
4483dc3a5f1Sandi    //recursion
4493dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
4503dc3a5f1Sandi        if($conf['safemodehack']){
45100976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
452034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
4533dc3a5f1Sandi        }else{
45444881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
455443e135dSChristopher Smith            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
45644881d27STroels Liebe Bentsen            return $ret;
4573dc3a5f1Sandi        }
4583dc3a5f1Sandi    }
459f3f0262cSandi    return 0;
460f3f0262cSandi}
461f3f0262cSandi
462f3f0262cSandi/**
4634d47e8e3SAndreas Gohr * Recursively delete a directory
4644d47e8e3SAndreas Gohr *
4654d47e8e3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4664d47e8e3SAndreas Gohr * @param string $path
4674d47e8e3SAndreas Gohr * @param bool   $removefiles defaults to false which will delete empty directories only
4684d47e8e3SAndreas Gohr * @return bool
4694d47e8e3SAndreas Gohr */
4704d47e8e3SAndreas Gohrfunction io_rmdir($path, $removefiles = false) {
4714d47e8e3SAndreas Gohr    if(!is_string($path) || $path == "") return false;
472d8cf4dd4SAndreas Gohr    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
4734d47e8e3SAndreas Gohr
4744d47e8e3SAndreas Gohr    if(is_dir($path) && !is_link($path)) {
4754d47e8e3SAndreas Gohr        $dirs  = array();
4764d47e8e3SAndreas Gohr        $files = array();
4774d47e8e3SAndreas Gohr
4784d47e8e3SAndreas Gohr        if(!$dh = @opendir($path)) return false;
4798426a3eeSAndreas Gohr        while(false !== ($f = readdir($dh))) {
4804d47e8e3SAndreas Gohr            if($f == '..' || $f == '.') continue;
4814d47e8e3SAndreas Gohr
4824d47e8e3SAndreas Gohr            // collect dirs and files first
4834d47e8e3SAndreas Gohr            if(is_dir("$path/$f") && !is_link("$path/$f")) {
4844d47e8e3SAndreas Gohr                $dirs[] = "$path/$f";
4854d47e8e3SAndreas Gohr            } else if($removefiles) {
4864d47e8e3SAndreas Gohr                $files[] = "$path/$f";
4874d47e8e3SAndreas Gohr            } else {
4884d47e8e3SAndreas Gohr                return false; // abort when non empty
4894d47e8e3SAndreas Gohr            }
4904d47e8e3SAndreas Gohr
4914d47e8e3SAndreas Gohr        }
4924d47e8e3SAndreas Gohr        closedir($dh);
4934d47e8e3SAndreas Gohr
4944d47e8e3SAndreas Gohr        // now traverse into  directories first
4954d47e8e3SAndreas Gohr        foreach($dirs as $dir) {
4964d47e8e3SAndreas Gohr            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
4974d47e8e3SAndreas Gohr        }
4984d47e8e3SAndreas Gohr
4994d47e8e3SAndreas Gohr        // now delete files
5004d47e8e3SAndreas Gohr        foreach($files as $file) {
5014d47e8e3SAndreas Gohr            if(!@unlink($file)) return false; //abort on any error
5024d47e8e3SAndreas Gohr        }
5034d47e8e3SAndreas Gohr
5044d47e8e3SAndreas Gohr        // remove self
5054d47e8e3SAndreas Gohr        return @rmdir($path);
5064d47e8e3SAndreas Gohr    } else if($removefiles) {
5074d47e8e3SAndreas Gohr        return @unlink($path);
5084d47e8e3SAndreas Gohr    }
5094d47e8e3SAndreas Gohr    return false;
5104d47e8e3SAndreas Gohr}
5114d47e8e3SAndreas Gohr
5124d47e8e3SAndreas Gohr/**
5133dc3a5f1Sandi * Creates a directory using FTP
5143dc3a5f1Sandi *
5153dc3a5f1Sandi * This is used when the safemode workaround is enabled
5163dc3a5f1Sandi *
5173dc3a5f1Sandi * @author <andi@splitbrain.org>
51842ea7f44SGerrit Uitslag *
51942ea7f44SGerrit Uitslag * @param string $dir name of the new directory
52042ea7f44SGerrit Uitslag * @return false|string
5213dc3a5f1Sandi */
5223dc3a5f1Sandifunction io_mkdir_ftp($dir){
5233dc3a5f1Sandi    global $conf;
5243dc3a5f1Sandi
5253dc3a5f1Sandi    if(!function_exists('ftp_connect')){
5263dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
5273dc3a5f1Sandi        return false;
5283dc3a5f1Sandi    }
5293dc3a5f1Sandi
5303dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
5313dc3a5f1Sandi    if(!$conn){
5323dc3a5f1Sandi        msg("FTP connection failed",-1);
5333dc3a5f1Sandi        return false;
5343dc3a5f1Sandi    }
5353dc3a5f1Sandi
5363994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
5373dc3a5f1Sandi        msg("FTP login failed",-1);
5383dc3a5f1Sandi        return false;
5393dc3a5f1Sandi    }
5403dc3a5f1Sandi
5413dc3a5f1Sandi    //create directory
542034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
5431ca31cfeSAndreas Gohr    //set permissions
5441ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
5453dc3a5f1Sandi
546034138e2SRainer Weinhold    @ftp_close($conn);
5473dc3a5f1Sandi    return $ok;
5483dc3a5f1Sandi}
5493dc3a5f1Sandi
5503dc3a5f1Sandi/**
551de862555SMichael Klier * Creates a unique temporary directory and returns
552de862555SMichael Klier * its path.
553de862555SMichael Klier *
554de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
55542ea7f44SGerrit Uitslag *
55642ea7f44SGerrit Uitslag * @return false|string path to new directory or false
557de862555SMichael Klier */
558de862555SMichael Klierfunction io_mktmpdir() {
559de862555SMichael Klier    global $conf;
560de862555SMichael Klier
561da1e1077SChris Smith    $base = $conf['tmpdir'];
562da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
563287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
564de862555SMichael Klier
565de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
566de862555SMichael Klier        return($tmpdir);
567de862555SMichael Klier    } else {
568de862555SMichael Klier        return false;
569de862555SMichael Klier    }
570de862555SMichael Klier}
571de862555SMichael Klier
572de862555SMichael Klier/**
57373ccfcb9Schris * downloads a file from the net and saves it
57473ccfcb9Schris *
57573ccfcb9Schris * if $useAttachment is false,
57673ccfcb9Schris * - $file is the full filename to save the file, incl. path
57773ccfcb9Schris * - if successful will return true, false otherwise
578db959ae3SAndreas Gohr *
57973ccfcb9Schris * if $useAttachment is true,
58073ccfcb9Schris * - $file is the directory where the file should be saved
58173ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
582b625487dSandi *
583b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
58473ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
58542ea7f44SGerrit Uitslag *
58642ea7f44SGerrit Uitslag * @param string $url           url to download
58742ea7f44SGerrit Uitslag * @param string $file          path to file or directory where to save
58842ea7f44SGerrit Uitslag * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
58942ea7f44SGerrit Uitslag * @param string $defaultName   fallback for if using $useAttachment
59042ea7f44SGerrit Uitslag * @param int    $maxSize       maximum file size
59142ea7f44SGerrit Uitslag * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
592b625487dSandi */
593847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
594ac9115b0STroels Liebe Bentsen    global $conf;
5959b307a83SAndreas Gohr    $http = new DokuHTTPClient();
596847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
5979b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
598a5951419SAndreas Gohr    $http->keep_alive = false; // we do single ops here, no need for keep-alive
5999b307a83SAndreas Gohr
6009b307a83SAndreas Gohr    $data = $http->get($url);
6019b307a83SAndreas Gohr    if(!$data) return false;
6029b307a83SAndreas Gohr
60373ccfcb9Schris    $name = '';
604cd2f903bSMichael Hamann    if ($useAttachment) {
60573ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
60673ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
607ce070a9fSchris            $match=array();
60873ccfcb9Schris            if (is_string($content_disposition) &&
609ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
61073ccfcb9Schris
6113009a773SAndreas Gohr                $name = utf8_basename($match[1]);
61273ccfcb9Schris            }
61373ccfcb9Schris
61473ccfcb9Schris        }
61573ccfcb9Schris
61673ccfcb9Schris        if (!$name) {
61773ccfcb9Schris            if (!$defaultName) return false;
61873ccfcb9Schris            $name = $defaultName;
61973ccfcb9Schris        }
62073ccfcb9Schris
62173ccfcb9Schris        $file = $file.$name;
62273ccfcb9Schris    }
62373ccfcb9Schris
62479e79377SAndreas Gohr    $fileexists = file_exists($file);
6259b307a83SAndreas Gohr    $fp = @fopen($file,"w");
626b625487dSandi    if(!$fp) return false;
6279b307a83SAndreas Gohr    fwrite($fp,$data);
628b625487dSandi    fclose($fp);
6291ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
63073ccfcb9Schris    if ($useAttachment) return $name;
631b625487dSandi    return true;
632b625487dSandi}
633b625487dSandi
634b625487dSandi/**
635ac9115b0STroels Liebe Bentsen * Windows compatible rename
636bf5e5a5bSAndreas Gohr *
637bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
638bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
63942ea7f44SGerrit Uitslag *
64042ea7f44SGerrit Uitslag * @param string $from
64142ea7f44SGerrit Uitslag * @param string $to
64242ea7f44SGerrit Uitslag * @return bool succes or fail
643bf5e5a5bSAndreas Gohr */
644bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
645ac9115b0STroels Liebe Bentsen    global $conf;
646bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
647bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
6488e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
649bf5e5a5bSAndreas Gohr            @unlink($from);
650bf5e5a5bSAndreas Gohr            return true;
651bf5e5a5bSAndreas Gohr        }
652bf5e5a5bSAndreas Gohr        return false;
653bf5e5a5bSAndreas Gohr    }
654bf5e5a5bSAndreas Gohr    return true;
655bf5e5a5bSAndreas Gohr}
656bf5e5a5bSAndreas Gohr
657420edfd6STom N Harris/**
658420edfd6STom N Harris * Runs an external command with input and output pipes.
659420edfd6STom N Harris * Returns the exit code from the process.
660420edfd6STom N Harris *
661420edfd6STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
66242ea7f44SGerrit Uitslag *
66342ea7f44SGerrit Uitslag * @param string $cmd
66442ea7f44SGerrit Uitslag * @param string $input  input pipe
66542ea7f44SGerrit Uitslag * @param string $output output pipe
66642ea7f44SGerrit Uitslag * @return int exit code from process
667420edfd6STom N Harris */
668420edfd6STom N Harrisfunction io_exec($cmd, $input, &$output){
6696c528220STom N Harris    $descspec = array(
6706c528220STom N Harris            0=>array("pipe","r"),
6716c528220STom N Harris            1=>array("pipe","w"),
6726c528220STom N Harris            2=>array("pipe","w"));
6736c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
6746c528220STom N Harris    if(!$ph) return -1;
6756c528220STom N Harris    fclose($pipes[2]); // ignore stderr
6766c528220STom N Harris    fwrite($pipes[0], $input);
6776c528220STom N Harris    fclose($pipes[0]);
6786c528220STom N Harris    $output = stream_get_contents($pipes[1]);
6796c528220STom N Harris    fclose($pipes[1]);
6806c528220STom N Harris    return proc_close($ph);
681f3f0262cSandi}
682f3f0262cSandi
6837421c3ccSAndreas Gohr/**
6847421c3ccSAndreas Gohr * Search a file for matching lines
6857421c3ccSAndreas Gohr *
6867421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
6877421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
6887421c3ccSAndreas Gohr * at once.
6897421c3ccSAndreas Gohr *
6907421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6917421c3ccSAndreas Gohr * @param  string $file    The file to search
6927421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
6937421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
694cd2f903bSMichael Hamann * @param  bool   $backref When true returns array with backreferences instead of lines
695cd2f903bSMichael Hamann * @return array matching lines or backref, false on error
6967421c3ccSAndreas Gohr */
6977421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
6987421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
6997421c3ccSAndreas Gohr    if(!$fh) return false;
7007421c3ccSAndreas Gohr    $matches = array();
7017421c3ccSAndreas Gohr
7027421c3ccSAndreas Gohr    $cnt  = 0;
7037421c3ccSAndreas Gohr    $line = '';
7047421c3ccSAndreas Gohr    while (!feof($fh)) {
7057421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
7067421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
7077421c3ccSAndreas Gohr
7087421c3ccSAndreas Gohr        // check if line matches
7097421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
7107421c3ccSAndreas Gohr            if($backref){
7117421c3ccSAndreas Gohr                $matches[] = $match;
7127421c3ccSAndreas Gohr            }else{
7137421c3ccSAndreas Gohr                $matches[] = $line;
7147421c3ccSAndreas Gohr            }
7157421c3ccSAndreas Gohr            $cnt++;
7167421c3ccSAndreas Gohr        }
7177421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
7187421c3ccSAndreas Gohr        $line = '';
7197421c3ccSAndreas Gohr    }
7207421c3ccSAndreas Gohr    fclose($fh);
7217421c3ccSAndreas Gohr    return $matches;
7227421c3ccSAndreas Gohr}
7237421c3ccSAndreas Gohr
724