xref: /dokuwiki/inc/io.php (revision 6c528220aaf62f4ba5890483797d6661352500bb)
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
21d186898bSAndreas Gohr * @param string $basadir - the config name of the type to delete (datadir or mediadir usally)
22d186898bSAndreas Gohr * @returns 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; }
66cc7d0c94SBen Coburn    $data = array(array($file, false), 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");
116ff3ed99fSmarcel    while (!feof($bz)){
117ff3ed99fSmarcel        //8192 seems to be the maximum buffersize?
118ff3ed99fSmarcel        $str = $str . bzread($bz,8192);
119ff3ed99fSmarcel    }
120ff3ed99fSmarcel    bzclose($bz);
121ff3ed99fSmarcel    return $str;
122ff3ed99fSmarcel}
123ff3ed99fSmarcel
124f3f0262cSandi
125f3f0262cSandi/**
126cc7d0c94SBen Coburn * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
127cc7d0c94SBen Coburn *
128cc7d0c94SBen Coburn * This generates an action event and delegates to io_saveFile().
129cc7d0c94SBen Coburn * Action plugins are allowed to modify the page content in transit.
130cc7d0c94SBen Coburn * The file path should not be changed.
131cc7d0c94SBen Coburn * (The append parameter is set to false.)
132cc7d0c94SBen Coburn *
133cc7d0c94SBen Coburn * Event data:
134cc7d0c94SBen Coburn * $data[0]    The raw arguments for io_saveFile as an array.
135cc7d0c94SBen Coburn * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
136cc7d0c94SBen Coburn * $data[2]    page_name: The wiki page name.
137cc7d0c94SBen Coburn * $data[3]    rev: The page revision, false for current wiki pages.
138cc7d0c94SBen Coburn *
139cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
140cc7d0c94SBen Coburn */
141cc7d0c94SBen Coburnfunction io_writeWikiPage($file, $content, $id, $rev=false) {
142cc7d0c94SBen Coburn    if (empty($rev)) { $rev = false; }
143cc7d0c94SBen Coburn    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
144cc7d0c94SBen Coburn    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
145cc7d0c94SBen Coburn    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
146cc7d0c94SBen Coburn}
147cc7d0c94SBen Coburn
148cc7d0c94SBen Coburn/**
149cc7d0c94SBen Coburn * Callback adapter for io_saveFile().
150cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
151cc7d0c94SBen Coburn */
152cc7d0c94SBen Coburnfunction _io_writeWikiPage_action($data) {
153cc7d0c94SBen Coburn    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
154cc7d0c94SBen Coburn        return call_user_func_array('io_saveFile', $data[0]);
155cc7d0c94SBen Coburn    } else {
156cc7d0c94SBen Coburn        return false; //callback error
157cc7d0c94SBen Coburn    }
158cc7d0c94SBen Coburn}
159cc7d0c94SBen Coburn
160cc7d0c94SBen Coburn/**
16115fae107Sandi * Saves $content to $file.
162f3f0262cSandi *
1631380fc45SAndreas Gohr * If the third parameter is set to true the given content
1641380fc45SAndreas Gohr * will be appended.
1651380fc45SAndreas Gohr *
16615fae107Sandi * Uses gzip if extension is .gz
167ff3ed99fSmarcel * and bz2 if extension is .bz2
16815fae107Sandi *
16915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
17015fae107Sandi * @return bool true on success
171f3f0262cSandi */
1721380fc45SAndreas Gohrfunction io_saveFile($file,$content,$append=false){
173ac9115b0STroels Liebe Bentsen    global $conf;
1741380fc45SAndreas Gohr    $mode = ($append) ? 'ab' : 'wb';
1751380fc45SAndreas Gohr
176d8186216SBen Coburn    $fileexists = @file_exists($file);
177f3f0262cSandi    io_makeFileDir($file);
17890eb8392Sandi    io_lock($file);
179f3f0262cSandi    if(substr($file,-3) == '.gz'){
1801380fc45SAndreas Gohr        $fh = @gzopen($file,$mode.'9');
181f3f0262cSandi        if(!$fh){
182f3f0262cSandi            msg("Writing $file failed",-1);
183fb7125eeSAndreas Gohr            io_unlock($file);
184f3f0262cSandi            return false;
185f3f0262cSandi        }
186f3f0262cSandi        gzwrite($fh, $content);
187f3f0262cSandi        gzclose($fh);
188ff3ed99fSmarcel    }else if(substr($file,-4) == '.bz2'){
189ece639c7SAndreas Gohr        $fh = @bzopen($file,$mode{0});
190ff3ed99fSmarcel        if(!$fh){
191ff3ed99fSmarcel            msg("Writing $file failed", -1);
192fb7125eeSAndreas Gohr            io_unlock($file);
193ff3ed99fSmarcel            return false;
194ff3ed99fSmarcel        }
195ff3ed99fSmarcel        bzwrite($fh, $content);
196ff3ed99fSmarcel        bzclose($fh);
197f3f0262cSandi    }else{
1981380fc45SAndreas Gohr        $fh = @fopen($file,$mode);
199f3f0262cSandi        if(!$fh){
200f3f0262cSandi            msg("Writing $file failed",-1);
201fb7125eeSAndreas Gohr            io_unlock($file);
202f3f0262cSandi            return false;
203f3f0262cSandi        }
204f3f0262cSandi        fwrite($fh, $content);
205f3f0262cSandi        fclose($fh);
206f3f0262cSandi    }
207ac9115b0STroels Liebe Bentsen
208bb4866bdSchris    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
20990eb8392Sandi    io_unlock($file);
210f3f0262cSandi    return true;
211f3f0262cSandi}
212f3f0262cSandi
213f3f0262cSandi/**
2141380fc45SAndreas Gohr * Delete exact linematch for $badline from $file.
2151380fc45SAndreas Gohr *
2161380fc45SAndreas Gohr * Be sure to include the trailing newline in $badline
217b158d625SSteven Danz *
218b158d625SSteven Danz * Uses gzip if extension is .gz
219b158d625SSteven Danz *
2208b06d178Schris * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
2218b06d178Schris *
222b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
223b158d625SSteven Danz * @return bool true on success
224b158d625SSteven Danz */
2258b06d178Schrisfunction io_deleteFromFile($file,$badline,$regex=false){
2261380fc45SAndreas Gohr    if (!@file_exists($file)) return true;
2271380fc45SAndreas Gohr
228b158d625SSteven Danz    io_lock($file);
2291380fc45SAndreas Gohr
2301380fc45SAndreas Gohr    // load into array
231b158d625SSteven Danz    if(substr($file,-3) == '.gz'){
2321380fc45SAndreas Gohr        $lines = gzfile($file);
233b158d625SSteven Danz    }else{
2341380fc45SAndreas Gohr        $lines = file($file);
235b158d625SSteven Danz    }
236b158d625SSteven Danz
2371380fc45SAndreas Gohr    // remove all matching lines
2388b06d178Schris    if ($regex) {
2398b06d178Schris        $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
2408b06d178Schris    } else {
2411380fc45SAndreas Gohr        $pos = array_search($badline,$lines); //return null or false if not found
2421380fc45SAndreas Gohr        while(is_int($pos)){
2431380fc45SAndreas Gohr            unset($lines[$pos]);
2441380fc45SAndreas Gohr            $pos = array_search($badline,$lines);
245b158d625SSteven Danz        }
2468b06d178Schris    }
247b158d625SSteven Danz
2481380fc45SAndreas Gohr    if(count($lines)){
2491380fc45SAndreas Gohr        $content = join('',$lines);
250b158d625SSteven Danz        if(substr($file,-3) == '.gz'){
251b158d625SSteven Danz            $fh = @gzopen($file,'wb9');
252b158d625SSteven Danz            if(!$fh){
253b158d625SSteven Danz                msg("Removing content from $file failed",-1);
254fb7125eeSAndreas Gohr                io_unlock($file);
255b158d625SSteven Danz                return false;
256b158d625SSteven Danz            }
257b158d625SSteven Danz            gzwrite($fh, $content);
258b158d625SSteven Danz            gzclose($fh);
259b158d625SSteven Danz        }else{
260b158d625SSteven Danz            $fh = @fopen($file,'wb');
261b158d625SSteven Danz            if(!$fh){
262b158d625SSteven Danz                msg("Removing content from $file failed",-1);
263fb7125eeSAndreas Gohr                io_unlock($file);
264b158d625SSteven Danz                return false;
265b158d625SSteven Danz            }
266b158d625SSteven Danz            fwrite($fh, $content);
267b158d625SSteven Danz            fclose($fh);
268b158d625SSteven Danz        }
269b158d625SSteven Danz    }else{
270b158d625SSteven Danz        @unlink($file);
271b158d625SSteven Danz    }
272b158d625SSteven Danz
273b158d625SSteven Danz    io_unlock($file);
274b158d625SSteven Danz    return true;
275b158d625SSteven Danz}
276b158d625SSteven Danz
277b158d625SSteven Danz/**
27890eb8392Sandi * Tries to lock a file
27990eb8392Sandi *
28090eb8392Sandi * Locking is only done for io_savefile and uses directories
28190eb8392Sandi * inside $conf['lockdir']
28290eb8392Sandi *
28390eb8392Sandi * It waits maximal 3 seconds for the lock, after this time
28490eb8392Sandi * the lock is assumed to be stale and the function goes on
28590eb8392Sandi *
28690eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
28790eb8392Sandi */
28890eb8392Sandifunction io_lock($file){
28990eb8392Sandi    global $conf;
29090eb8392Sandi    // no locking if safemode hack
29190eb8392Sandi    if($conf['safemodehack']) return;
29290eb8392Sandi
29390eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
29490eb8392Sandi    @ignore_user_abort(1);
29590eb8392Sandi
29690eb8392Sandi    $timeStart = time();
29790eb8392Sandi    do {
29890eb8392Sandi        //waited longer than 3 seconds? -> stale lock
29990eb8392Sandi        if ((time() - $timeStart) > 3) break;
30044881d27STroels Liebe Bentsen        $locked = @mkdir($lockDir, $conf['dmode']);
30177b98903SAndreas Gohr        if($locked){
302bb4866bdSchris            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
30377b98903SAndreas Gohr            break;
30477b98903SAndreas Gohr        }
30577b98903SAndreas Gohr        usleep(50);
30690eb8392Sandi    } while ($locked === false);
30790eb8392Sandi}
30890eb8392Sandi
30990eb8392Sandi/**
31090eb8392Sandi * Unlocks a file
31190eb8392Sandi *
31290eb8392Sandi * @author Andreas Gohr <andi@splitbrain.org>
31390eb8392Sandi */
31490eb8392Sandifunction io_unlock($file){
31590eb8392Sandi    global $conf;
31690eb8392Sandi    // no locking if safemode hack
31790eb8392Sandi    if($conf['safemodehack']) return;
31890eb8392Sandi
31990eb8392Sandi    $lockDir = $conf['lockdir'].'/'.md5($file);
32090eb8392Sandi    @rmdir($lockDir);
32190eb8392Sandi    @ignore_user_abort(0);
32290eb8392Sandi}
32390eb8392Sandi
32490eb8392Sandi/**
325cc7d0c94SBen Coburn * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
326cc7d0c94SBen Coburn * in the order of directory creation. (Parent directories first.)
327cc7d0c94SBen Coburn *
328cc7d0c94SBen Coburn * Event data:
329cc7d0c94SBen Coburn * $data[0]    ns: The colon separated namespace path minus the trailing page name.
330cc7d0c94SBen Coburn * $data[1]    ns_type: 'pages' or 'media' namespace tree.
331cc7d0c94SBen Coburn *
332cc7d0c94SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
333cc7d0c94SBen Coburn */
334cc7d0c94SBen Coburnfunction io_createNamespace($id, $ns_type='pages') {
335cc7d0c94SBen Coburn    // verify ns_type
336cc7d0c94SBen Coburn    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
337cc7d0c94SBen Coburn    if (!isset($types[$ns_type])) {
338cc7d0c94SBen Coburn        trigger_error('Bad $ns_type parameter for io_createNamespace().');
339cc7d0c94SBen Coburn        return;
340cc7d0c94SBen Coburn    }
341cc7d0c94SBen Coburn    // make event list
342cc7d0c94SBen Coburn    $missing = array();
343cc7d0c94SBen Coburn    $ns_stack = explode(':', $id);
344cc7d0c94SBen Coburn    $ns = $id;
345cc7d0c94SBen Coburn    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
346cc7d0c94SBen Coburn    while (!@is_dir($tmp) && !(@file_exists($tmp) && !is_dir($tmp))) {
347cc7d0c94SBen Coburn        array_pop($ns_stack);
348cc7d0c94SBen Coburn        $ns = implode(':', $ns_stack);
349cc7d0c94SBen Coburn        if (strlen($ns)==0) { break; }
350cc7d0c94SBen Coburn        $missing[] = $ns;
351cc7d0c94SBen Coburn        $tmp = dirname(call_user_func($types[$ns_type], $ns));
352cc7d0c94SBen Coburn    }
353cc7d0c94SBen Coburn    // make directories
354cc7d0c94SBen Coburn    io_makeFileDir($file);
355cc7d0c94SBen Coburn    // send the events
356cc7d0c94SBen Coburn    $missing = array_reverse($missing); // inside out
357cc7d0c94SBen Coburn    foreach ($missing as $ns) {
358cc7d0c94SBen Coburn        $data = array($ns, $ns_type);
359cc7d0c94SBen Coburn        trigger_event('IO_NAMESPACE_CREATED', $data);
360cc7d0c94SBen Coburn    }
361cc7d0c94SBen Coburn}
362cc7d0c94SBen Coburn
363cc7d0c94SBen Coburn/**
364f3f0262cSandi * Create the directory needed for the given file
36515fae107Sandi *
36615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
367f3f0262cSandi */
368f3f0262cSandifunction io_makeFileDir($file){
369f3f0262cSandi    global $conf;
370f3f0262cSandi
371f3f0262cSandi    $dir = dirname($file);
3720d8850c4SAndreas Gohr    if(!@is_dir($dir)){
373f3f0262cSandi        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
374f3f0262cSandi    }
375f3f0262cSandi}
376f3f0262cSandi
377f3f0262cSandi/**
378f3f0262cSandi * Creates a directory hierachy.
379f3f0262cSandi *
38015fae107Sandi * @link    http://www.php.net/manual/en/function.mkdir.php
381f3f0262cSandi * @author  <saint@corenova.com>
3823dc3a5f1Sandi * @author  Andreas Gohr <andi@splitbrain.org>
383f3f0262cSandi */
384f3f0262cSandifunction io_mkdir_p($target){
3853dc3a5f1Sandi    global $conf;
3860d8850c4SAndreas Gohr    if (@is_dir($target)||empty($target)) return 1; // best case check first
387f3f0262cSandi    if (@file_exists($target) && !is_dir($target)) return 0;
3883dc3a5f1Sandi    //recursion
3893dc3a5f1Sandi    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
3903dc3a5f1Sandi        if($conf['safemodehack']){
39100976812SAndreas Gohr            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
392034138e2SRainer Weinhold            return io_mkdir_ftp($dir);
3933dc3a5f1Sandi        }else{
39444881d27STroels Liebe Bentsen            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
3951ca31cfeSAndreas Gohr            if($ret && $conf['dperm']) chmod($target, $conf['dperm']);
39644881d27STroels Liebe Bentsen            return $ret;
3973dc3a5f1Sandi        }
3983dc3a5f1Sandi    }
399f3f0262cSandi    return 0;
400f3f0262cSandi}
401f3f0262cSandi
402f3f0262cSandi/**
4033dc3a5f1Sandi * Creates a directory using FTP
4043dc3a5f1Sandi *
4053dc3a5f1Sandi * This is used when the safemode workaround is enabled
4063dc3a5f1Sandi *
4073dc3a5f1Sandi * @author <andi@splitbrain.org>
4083dc3a5f1Sandi */
4093dc3a5f1Sandifunction io_mkdir_ftp($dir){
4103dc3a5f1Sandi    global $conf;
4113dc3a5f1Sandi
4123dc3a5f1Sandi    if(!function_exists('ftp_connect')){
4133dc3a5f1Sandi        msg("FTP support not found - safemode workaround not usable",-1);
4143dc3a5f1Sandi        return false;
4153dc3a5f1Sandi    }
4163dc3a5f1Sandi
4173dc3a5f1Sandi    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
4183dc3a5f1Sandi    if(!$conn){
4193dc3a5f1Sandi        msg("FTP connection failed",-1);
4203dc3a5f1Sandi        return false;
4213dc3a5f1Sandi    }
4223dc3a5f1Sandi
4233994772aSChris Smith    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
4243dc3a5f1Sandi        msg("FTP login failed",-1);
4253dc3a5f1Sandi        return false;
4263dc3a5f1Sandi    }
4273dc3a5f1Sandi
4283dc3a5f1Sandi    //create directory
429034138e2SRainer Weinhold    $ok = @ftp_mkdir($conn, $dir);
4301ca31cfeSAndreas Gohr    //set permissions
4311ca31cfeSAndreas Gohr    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
4323dc3a5f1Sandi
433034138e2SRainer Weinhold    @ftp_close($conn);
4343dc3a5f1Sandi    return $ok;
4353dc3a5f1Sandi}
4363dc3a5f1Sandi
4373dc3a5f1Sandi/**
438de862555SMichael Klier * Creates a unique temporary directory and returns
439de862555SMichael Klier * its path.
440de862555SMichael Klier *
441de862555SMichael Klier * @author Michael Klier <chi@chimeric.de>
442de862555SMichael Klier */
443de862555SMichael Klierfunction io_mktmpdir() {
444de862555SMichael Klier    global $conf;
445de862555SMichael Klier
446da1e1077SChris Smith    $base = $conf['tmpdir'];
447da1e1077SChris Smith    $dir  = md5(uniqid(mt_rand(), true));
448287f35bdSAndreas Gohr    $tmpdir = $base.'/'.$dir;
449de862555SMichael Klier
450de862555SMichael Klier    if(io_mkdir_p($tmpdir)) {
451de862555SMichael Klier        return($tmpdir);
452de862555SMichael Klier    } else {
453de862555SMichael Klier        return false;
454de862555SMichael Klier    }
455de862555SMichael Klier}
456de862555SMichael Klier
457de862555SMichael Klier/**
45873ccfcb9Schris * downloads a file from the net and saves it
45973ccfcb9Schris *
46073ccfcb9Schris * if $useAttachment is false,
46173ccfcb9Schris * - $file is the full filename to save the file, incl. path
46273ccfcb9Schris * - if successful will return true, false otherwise
463db959ae3SAndreas Gohr *
46473ccfcb9Schris * if $useAttachment is true,
46573ccfcb9Schris * - $file is the directory where the file should be saved
46673ccfcb9Schris * - if successful will return the name used for the saved file, false otherwise
467b625487dSandi *
468b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
46973ccfcb9Schris * @author Chris Smith <chris@jalakai.co.uk>
470b625487dSandi */
471847b8298SAndreas Gohrfunction io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
472ac9115b0STroels Liebe Bentsen    global $conf;
4739b307a83SAndreas Gohr    $http = new DokuHTTPClient();
474847b8298SAndreas Gohr    $http->max_bodysize = $maxSize;
4759b307a83SAndreas Gohr    $http->timeout = 25; //max. 25 sec
4769b307a83SAndreas Gohr
4779b307a83SAndreas Gohr    $data = $http->get($url);
4789b307a83SAndreas Gohr    if(!$data) return false;
4799b307a83SAndreas Gohr
48073ccfcb9Schris    if ($useAttachment) {
48173ccfcb9Schris        $name = '';
48273ccfcb9Schris        if (isset($http->resp_headers['content-disposition'])) {
48373ccfcb9Schris            $content_disposition = $http->resp_headers['content-disposition'];
484ce070a9fSchris            $match=array();
48573ccfcb9Schris            if (is_string($content_disposition) &&
486ce070a9fSchris                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
48773ccfcb9Schris
48873ccfcb9Schris                $name = basename($match[1]);
48973ccfcb9Schris        }
49073ccfcb9Schris
49173ccfcb9Schris        }
49273ccfcb9Schris
49373ccfcb9Schris        if (!$name) {
49473ccfcb9Schris            if (!$defaultName) return false;
49573ccfcb9Schris            $name = $defaultName;
49673ccfcb9Schris        }
49773ccfcb9Schris
49873ccfcb9Schris        $file = $file.$name;
49973ccfcb9Schris    }
50073ccfcb9Schris
501d8186216SBen Coburn    $fileexists = @file_exists($file);
5029b307a83SAndreas Gohr    $fp = @fopen($file,"w");
503b625487dSandi    if(!$fp) return false;
5049b307a83SAndreas Gohr    fwrite($fp,$data);
505b625487dSandi    fclose($fp);
5061ca31cfeSAndreas Gohr    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
50773ccfcb9Schris    if ($useAttachment) return $name;
508b625487dSandi    return true;
509b625487dSandi}
510b625487dSandi
511b625487dSandi/**
512ac9115b0STroels Liebe Bentsen * Windows compatible rename
513bf5e5a5bSAndreas Gohr *
514bf5e5a5bSAndreas Gohr * rename() can not overwrite existing files on Windows
515bf5e5a5bSAndreas Gohr * this function will use copy/unlink instead
516bf5e5a5bSAndreas Gohr */
517bf5e5a5bSAndreas Gohrfunction io_rename($from,$to){
518ac9115b0STroels Liebe Bentsen    global $conf;
519bf5e5a5bSAndreas Gohr    if(!@rename($from,$to)){
520bf5e5a5bSAndreas Gohr        if(@copy($from,$to)){
5218e0b019fSAndreas Gohr            if($conf['fperm']) chmod($to, $conf['fperm']);
522bf5e5a5bSAndreas Gohr            @unlink($from);
523bf5e5a5bSAndreas Gohr            return true;
524bf5e5a5bSAndreas Gohr        }
525bf5e5a5bSAndreas Gohr        return false;
526bf5e5a5bSAndreas Gohr    }
527bf5e5a5bSAndreas Gohr    return true;
528bf5e5a5bSAndreas Gohr}
529bf5e5a5bSAndreas Gohr
530bf5e5a5bSAndreas Gohr
531bf5e5a5bSAndreas Gohr/**
532f3f0262cSandi * Runs an external command and returns it's output as string
53315fae107Sandi *
53415fae107Sandi * @author Harry Brueckner <harry_b@eml.cc>
53515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
536f3f0262cSandi */
537*6c528220STom N Harrisfunction io_runcmd($cmd, $input, &$output){
538*6c528220STom N Harris    $descspec = array(
539*6c528220STom N Harris            0=>array("pipe","r"),
540*6c528220STom N Harris            1=>array("pipe","w"),
541*6c528220STom N Harris            2=>array("pipe","w"));
542*6c528220STom N Harris    $ph = proc_open($cmd, $descspec, $pipes);
543*6c528220STom N Harris    if(!$ph) return -1;
544*6c528220STom N Harris    fclose($pipes[2]); // ignore stderr
545*6c528220STom N Harris    fwrite($pipes[0], $input);
546*6c528220STom N Harris    fclose($pipes[0]);
547*6c528220STom N Harris    $output = stream_get_contents($pipes[1]);
548*6c528220STom N Harris    fclose($pipes[1]);
549*6c528220STom N Harris    return proc_close($ph);
550f3f0262cSandi}
551f3f0262cSandi
5527421c3ccSAndreas Gohr/**
5537421c3ccSAndreas Gohr * Search a file for matching lines
5547421c3ccSAndreas Gohr *
5557421c3ccSAndreas Gohr * This is probably not faster than file()+preg_grep() but less
5567421c3ccSAndreas Gohr * memory intensive because not the whole file needs to be loaded
5577421c3ccSAndreas Gohr * at once.
5587421c3ccSAndreas Gohr *
5597421c3ccSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5607421c3ccSAndreas Gohr * @param  string $file    The file to search
5617421c3ccSAndreas Gohr * @param  string $pattern PCRE pattern
5627421c3ccSAndreas Gohr * @param  int    $max     How many lines to return (0 for all)
5637421c3ccSAndreas Gohr * @param  bool   $baxkref When true returns array with backreferences instead of lines
5647421c3ccSAndreas Gohr * @return matching lines or backref, false on error
5657421c3ccSAndreas Gohr */
5667421c3ccSAndreas Gohrfunction io_grep($file,$pattern,$max=0,$backref=false){
5677421c3ccSAndreas Gohr    $fh = @fopen($file,'r');
5687421c3ccSAndreas Gohr    if(!$fh) return false;
5697421c3ccSAndreas Gohr    $matches = array();
5707421c3ccSAndreas Gohr
5717421c3ccSAndreas Gohr    $cnt  = 0;
5727421c3ccSAndreas Gohr    $line = '';
5737421c3ccSAndreas Gohr    while (!feof($fh)) {
5747421c3ccSAndreas Gohr        $line .= fgets($fh, 4096);  // read full line
5757421c3ccSAndreas Gohr        if(substr($line,-1) != "\n") continue;
5767421c3ccSAndreas Gohr
5777421c3ccSAndreas Gohr        // check if line matches
5787421c3ccSAndreas Gohr        if(preg_match($pattern,$line,$match)){
5797421c3ccSAndreas Gohr            if($backref){
5807421c3ccSAndreas Gohr                $matches[] = $match;
5817421c3ccSAndreas Gohr            }else{
5827421c3ccSAndreas Gohr                $matches[] = $line;
5837421c3ccSAndreas Gohr            }
5847421c3ccSAndreas Gohr            $cnt++;
5857421c3ccSAndreas Gohr        }
5867421c3ccSAndreas Gohr        if($max && $max == $cnt) break;
5877421c3ccSAndreas Gohr        $line = '';
5887421c3ccSAndreas Gohr    }
5897421c3ccSAndreas Gohr    fclose($fh);
5907421c3ccSAndreas Gohr    return $matches;
5917421c3ccSAndreas Gohr}
5927421c3ccSAndreas Gohr
593