xref: /dokuwiki/inc/io.php (revision cfb71e37ca8859c4ad9a1db73de0a293ffc7a902)
1<?php
2/**
3 * File IO functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10
11/**
12 * Removes empty directories
13 *
14 * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
15 * Event data:
16 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
17 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
18 *
19 * @todo use safemode hack
20 * @param string $id      - a pageid, the namespace of that id will be tried to deleted
21 * @param string $basedir - the config name of the type to delete (datadir or mediadir usally)
22 * @return bool - true if at least one namespace was deleted
23 *
24 * @author  Andreas Gohr <andi@splitbrain.org>
25 * @author Ben Coburn <btcoburn@silicodon.net>
26 */
27function io_sweepNS($id,$basedir='datadir'){
28    global $conf;
29    $types = array ('datadir'=>'pages', 'mediadir'=>'media');
30    $ns_type = (isset($types[$basedir])?$types[$basedir]:false);
31
32    $delone = false;
33
34    //scan all namespaces
35    while(($id = getNS($id)) !== false){
36        $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':','/',$id));
37
38        //try to delete dir else return
39        if(@rmdir($dir)) {
40            if ($ns_type!==false) {
41                $data = array($id, $ns_type);
42                $delone = true; // we deleted at least one dir
43                trigger_event('IO_NAMESPACE_DELETED', $data);
44            }
45        } else { return $delone; }
46    }
47    return $delone;
48}
49
50/**
51 * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
52 *
53 * Generates the action event which delegates to io_readFile().
54 * Action plugins are allowed to modify the page content in transit.
55 * The file path should not be changed.
56 *
57 * Event data:
58 * $data[0]    The raw arguments for io_readFile as an array.
59 * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
60 * $data[2]    page_name: The wiki page name.
61 * $data[3]    rev: The page revision, false for current wiki pages.
62 *
63 * @author Ben Coburn <btcoburn@silicodon.net>
64 *
65 * @param string   $file filename
66 * @param string   $id page id
67 * @param bool|int $rev revision timestamp
68 * @return string
69 */
70function io_readWikiPage($file, $id, $rev=false) {
71    if (empty($rev)) { $rev = false; }
72    $data = array(array($file, true), getNS($id), noNS($id), $rev);
73    return trigger_event('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
74}
75
76/**
77 * Callback adapter for io_readFile().
78 *
79 * @author Ben Coburn <btcoburn@silicodon.net>
80 *
81 * @param array $data event data
82 * @return string
83 */
84function _io_readWikiPage_action($data) {
85    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
86        return call_user_func_array('io_readFile', $data[0]);
87    } else {
88        return ''; //callback error
89    }
90}
91
92/**
93 * Returns content of $file as cleaned string.
94 *
95 * Uses gzip if extension is .gz
96 *
97 * If you want to use the returned value in unserialize
98 * be sure to set $clean to false!
99 *
100 * @author  Andreas Gohr <andi@splitbrain.org>
101 *
102 * @param string $file  filename
103 * @param bool   $clean
104 * @return string|bool the file contents or false on error
105 */
106function io_readFile($file,$clean=true){
107    $ret = '';
108    if(file_exists($file)){
109        if(substr($file,-3) == '.gz'){
110            $ret = join('',gzfile($file));
111        }else if(substr($file,-4) == '.bz2'){
112            $ret = bzfile($file);
113        }else{
114            $ret = file_get_contents($file);
115        }
116    }
117    if($ret !== false && $clean){
118        return cleanText($ret);
119    }else{
120        return $ret;
121    }
122}
123/**
124 * Returns the content of a .bz2 compressed file as string
125 *
126 * @author marcel senf <marcel@rucksackreinigung.de>
127 * @author  Andreas Gohr <andi@splitbrain.org>
128 *
129 * @param string $file filename
130 * @param bool   $array return array of lines
131 * @return string|array|bool content or false on error
132 */
133function bzfile($file, $array=false) {
134    $bz = bzopen($file,"r");
135    if($bz === false) return false;
136
137    if($array) $lines = array();
138    $str = '';
139    while (!feof($bz)) {
140        //8192 seems to be the maximum buffersize?
141        $buffer = bzread($bz,8192);
142        if(($buffer === false) || (bzerrno($bz) !== 0)) {
143            return false;
144        }
145        $str = $str . $buffer;
146        if($array) {
147            $pos = strpos($str, "\n");
148            while($pos !== false) {
149                $lines[] = substr($str, 0, $pos+1);
150                $str = substr($str, $pos+1);
151                $pos = strpos($str, "\n");
152            }
153        }
154    }
155    bzclose($bz);
156    if($array) {
157        if($str !== '') $lines[] = $str;
158        return $lines;
159    }
160    return $str;
161}
162
163/**
164 * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
165 *
166 * This generates an action event and delegates to io_saveFile().
167 * Action plugins are allowed to modify the page content in transit.
168 * The file path should not be changed.
169 * (The append parameter is set to false.)
170 *
171 * Event data:
172 * $data[0]    The raw arguments for io_saveFile as an array.
173 * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
174 * $data[2]    page_name: The wiki page name.
175 * $data[3]    rev: The page revision, false for current wiki pages.
176 *
177 * @author Ben Coburn <btcoburn@silicodon.net>
178 *
179 * @param string $file      filename
180 * @param string $content
181 * @param string $id        page id
182 * @param int|bool $rev timestamp of revision
183 * @return bool
184 */
185function io_writeWikiPage($file, $content, $id, $rev=false) {
186    if (empty($rev)) { $rev = false; }
187    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
188    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
189    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
190}
191
192/**
193 * Callback adapter for io_saveFile().
194 * @author Ben Coburn <btcoburn@silicodon.net>
195 *
196 * @param array $data event data
197 * @return bool
198 */
199function _io_writeWikiPage_action($data) {
200    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
201        return call_user_func_array('io_saveFile', $data[0]);
202    } else {
203        return false; //callback error
204    }
205}
206
207/**
208 * Saves $content to $file.
209 *
210 * If the third parameter is set to true the given content
211 * will be appended.
212 *
213 * Uses gzip if extension is .gz
214 * and bz2 if extension is .bz2
215 *
216 * @author  Andreas Gohr <andi@splitbrain.org>
217 *
218 * @param string $file filename path to file
219 * @param string $content
220 * @param bool   $append
221 * @return bool true on success, otherwise false
222 */
223function io_saveFile($file,$content,$append=false){
224    global $conf;
225    $mode = ($append) ? 'ab' : 'wb';
226
227    $fileexists = file_exists($file);
228    io_makeFileDir($file);
229    io_lock($file);
230    if(substr($file,-3) == '.gz'){
231        $fh = @gzopen($file,$mode.'9');
232        if(!$fh){
233            msg("Writing $file failed",-1);
234            io_unlock($file);
235            return false;
236        }
237        gzwrite($fh, $content);
238        gzclose($fh);
239    }else if(substr($file,-4) == '.bz2'){
240        if($append) {
241            $bzcontent = bzfile($file);
242            if($bzcontent === false) {
243                msg("Writing $file failed", -1);
244                io_unlock($file);
245                return false;
246            }
247            $content = $bzcontent.$content;
248        }
249        $fh = @bzopen($file,'w');
250        if(!$fh){
251            msg("Writing $file failed", -1);
252            io_unlock($file);
253            return false;
254        }
255        bzwrite($fh, $content);
256        bzclose($fh);
257    }else{
258        $fh = @fopen($file,$mode);
259        if(!$fh){
260            msg("Writing $file failed",-1);
261            io_unlock($file);
262            return false;
263        }
264        fwrite($fh, $content);
265        fclose($fh);
266    }
267
268    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
269    io_unlock($file);
270    return true;
271}
272
273/**
274 * Delete exact linematch for $badline from $file.
275 *
276 * Be sure to include the trailing newline in $badline
277 *
278 * Uses gzip if extension is .gz
279 *
280 * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
281 *
282 * @author Steven Danz <steven-danz@kc.rr.com>
283 *
284 * @param string $file    filename
285 * @param string $badline exact linematch to remove
286 * @param bool   $regex   use regexp?
287 * @return bool true on success
288 */
289function io_deleteFromFile($file,$badline,$regex=false){
290    if (!file_exists($file)) return true;
291
292    io_lock($file);
293
294    // load into array
295    if(substr($file,-3) == '.gz'){
296        $lines = gzfile($file);
297    }else if(substr($file,-4) == '.bz2'){
298        $lines = bzfile($file, true);
299    }else{
300        $lines = file($file);
301    }
302
303    // remove all matching lines
304    if ($regex) {
305        $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
306    } else {
307        $pos = array_search($badline,$lines); //return null or false if not found
308        while(is_int($pos)){
309            unset($lines[$pos]);
310            $pos = array_search($badline,$lines);
311        }
312    }
313
314    if(count($lines)){
315        $content = join('',$lines);
316        if(substr($file,-3) == '.gz'){
317            $fh = @gzopen($file,'wb9');
318            if(!$fh){
319                msg("Removing content from $file failed",-1);
320                io_unlock($file);
321                return false;
322            }
323            gzwrite($fh, $content);
324            gzclose($fh);
325        }else if(substr($file,-4) == '.bz2'){
326            $fh = @bzopen($file,'w');
327            if(!$fh){
328                msg("Removing content from $file failed",-1);
329                io_unlock($file);
330                return false;
331            }
332            bzwrite($fh, $content);
333            bzclose($fh);
334        }else{
335            $fh = @fopen($file,'wb');
336            if(!$fh){
337                msg("Removing content from $file failed",-1);
338                io_unlock($file);
339                return false;
340            }
341            fwrite($fh, $content);
342            fclose($fh);
343        }
344    }else{
345        @unlink($file);
346    }
347
348    io_unlock($file);
349    return true;
350}
351
352/**
353 * Tries to lock a file
354 *
355 * Locking is only done for io_savefile and uses directories
356 * inside $conf['lockdir']
357 *
358 * It waits maximal 3 seconds for the lock, after this time
359 * the lock is assumed to be stale and the function goes on
360 *
361 * @author Andreas Gohr <andi@splitbrain.org>
362 *
363 * @param string $file filename
364 */
365function io_lock($file){
366    global $conf;
367    // no locking if safemode hack
368    if($conf['safemodehack']) return;
369
370    $lockDir = $conf['lockdir'].'/'.md5($file);
371    @ignore_user_abort(1);
372
373    $timeStart = time();
374    do {
375        //waited longer than 3 seconds? -> stale lock
376        if ((time() - $timeStart) > 3) break;
377        $locked = @mkdir($lockDir, $conf['dmode']);
378        if($locked){
379            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
380            break;
381        }
382        usleep(50);
383    } while ($locked === false);
384}
385
386/**
387 * Unlocks a file
388 *
389 * @author Andreas Gohr <andi@splitbrain.org>
390 *
391 * @param string $file filename
392 */
393function io_unlock($file){
394    global $conf;
395    // no locking if safemode hack
396    if($conf['safemodehack']) return;
397
398    $lockDir = $conf['lockdir'].'/'.md5($file);
399    @rmdir($lockDir);
400    @ignore_user_abort(0);
401}
402
403/**
404 * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
405 * in the order of directory creation. (Parent directories first.)
406 *
407 * Event data:
408 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
409 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
410 *
411 * @author Ben Coburn <btcoburn@silicodon.net>
412 *
413 * @param string $id page id
414 * @param string $ns_type 'pages' or 'media'
415 */
416function io_createNamespace($id, $ns_type='pages') {
417    // verify ns_type
418    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
419    if (!isset($types[$ns_type])) {
420        trigger_error('Bad $ns_type parameter for io_createNamespace().');
421        return;
422    }
423    // make event list
424    $missing = array();
425    $ns_stack = explode(':', $id);
426    $ns = $id;
427    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
428    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
429        array_pop($ns_stack);
430        $ns = implode(':', $ns_stack);
431        if (strlen($ns)==0) { break; }
432        $missing[] = $ns;
433        $tmp = dirname(call_user_func($types[$ns_type], $ns));
434    }
435    // make directories
436    io_makeFileDir($file);
437    // send the events
438    $missing = array_reverse($missing); // inside out
439    foreach ($missing as $ns) {
440        $data = array($ns, $ns_type);
441        trigger_event('IO_NAMESPACE_CREATED', $data);
442    }
443}
444
445/**
446 * Create the directory needed for the given file
447 *
448 * @author  Andreas Gohr <andi@splitbrain.org>
449 *
450 * @param string $file file name
451 */
452function io_makeFileDir($file){
453    $dir = dirname($file);
454    if(!@is_dir($dir)){
455        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
456    }
457}
458
459/**
460 * Creates a directory hierachy.
461 *
462 * @link    http://www.php.net/manual/en/function.mkdir.php
463 * @author  <saint@corenova.com>
464 * @author  Andreas Gohr <andi@splitbrain.org>
465 *
466 * @param string $target filename
467 * @return bool|int|string
468 */
469function io_mkdir_p($target){
470    global $conf;
471    if (@is_dir($target)||empty($target)) return 1; // best case check first
472    if (file_exists($target) && !is_dir($target)) return 0;
473    //recursion
474    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
475        if($conf['safemodehack']){
476            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
477            return io_mkdir_ftp($dir);
478        }else{
479            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
480            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
481            return $ret;
482        }
483    }
484    return 0;
485}
486
487/**
488 * Recursively delete a directory
489 *
490 * @author Andreas Gohr <andi@splitbrain.org>
491 * @param string $path
492 * @param bool   $removefiles defaults to false which will delete empty directories only
493 * @return bool
494 */
495function io_rmdir($path, $removefiles = false) {
496    if(!is_string($path) || $path == "") return false;
497    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
498
499    if(is_dir($path) && !is_link($path)) {
500        $dirs  = array();
501        $files = array();
502
503        if(!$dh = @opendir($path)) return false;
504        while(false !== ($f = readdir($dh))) {
505            if($f == '..' || $f == '.') continue;
506
507            // collect dirs and files first
508            if(is_dir("$path/$f") && !is_link("$path/$f")) {
509                $dirs[] = "$path/$f";
510            } else if($removefiles) {
511                $files[] = "$path/$f";
512            } else {
513                return false; // abort when non empty
514            }
515
516        }
517        closedir($dh);
518
519        // now traverse into  directories first
520        foreach($dirs as $dir) {
521            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
522        }
523
524        // now delete files
525        foreach($files as $file) {
526            if(!@unlink($file)) return false; //abort on any error
527        }
528
529        // remove self
530        return @rmdir($path);
531    } else if($removefiles) {
532        return @unlink($path);
533    }
534    return false;
535}
536
537/**
538 * Creates a directory using FTP
539 *
540 * This is used when the safemode workaround is enabled
541 *
542 * @author <andi@splitbrain.org>
543 *
544 * @param string $dir name of the new directory
545 * @return false|string
546 */
547function io_mkdir_ftp($dir){
548    global $conf;
549
550    if(!function_exists('ftp_connect')){
551        msg("FTP support not found - safemode workaround not usable",-1);
552        return false;
553    }
554
555    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
556    if(!$conn){
557        msg("FTP connection failed",-1);
558        return false;
559    }
560
561    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
562        msg("FTP login failed",-1);
563        return false;
564    }
565
566    //create directory
567    $ok = @ftp_mkdir($conn, $dir);
568    //set permissions
569    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
570
571    @ftp_close($conn);
572    return $ok;
573}
574
575/**
576 * Creates a unique temporary directory and returns
577 * its path.
578 *
579 * @author Michael Klier <chi@chimeric.de>
580 *
581 * @return false|string path to new directory or false
582 */
583function io_mktmpdir() {
584    global $conf;
585
586    $base = $conf['tmpdir'];
587    $dir  = md5(uniqid(mt_rand(), true));
588    $tmpdir = $base.'/'.$dir;
589
590    if(io_mkdir_p($tmpdir)) {
591        return($tmpdir);
592    } else {
593        return false;
594    }
595}
596
597/**
598 * downloads a file from the net and saves it
599 *
600 * if $useAttachment is false,
601 * - $file is the full filename to save the file, incl. path
602 * - if successful will return true, false otherwise
603 *
604 * if $useAttachment is true,
605 * - $file is the directory where the file should be saved
606 * - if successful will return the name used for the saved file, false otherwise
607 *
608 * @author Andreas Gohr <andi@splitbrain.org>
609 * @author Chris Smith <chris@jalakai.co.uk>
610 *
611 * @param string $url           url to download
612 * @param string $file          path to file or directory where to save
613 * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
614 * @param string $defaultName   fallback for if using $useAttachment
615 * @param int    $maxSize       maximum file size
616 * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
617 */
618function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
619    global $conf;
620    $http = new DokuHTTPClient();
621    $http->max_bodysize = $maxSize;
622    $http->timeout = 25; //max. 25 sec
623    $http->keep_alive = false; // we do single ops here, no need for keep-alive
624
625    $data = $http->get($url);
626    if(!$data) return false;
627
628    $name = '';
629    if ($useAttachment) {
630        if (isset($http->resp_headers['content-disposition'])) {
631            $content_disposition = $http->resp_headers['content-disposition'];
632            $match=array();
633            if (is_string($content_disposition) &&
634                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
635
636                $name = utf8_basename($match[1]);
637            }
638
639        }
640
641        if (!$name) {
642            if (!$defaultName) return false;
643            $name = $defaultName;
644        }
645
646        $file = $file.$name;
647    }
648
649    $fileexists = file_exists($file);
650    $fp = @fopen($file,"w");
651    if(!$fp) return false;
652    fwrite($fp,$data);
653    fclose($fp);
654    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
655    if ($useAttachment) return $name;
656    return true;
657}
658
659/**
660 * Windows compatible rename
661 *
662 * rename() can not overwrite existing files on Windows
663 * this function will use copy/unlink instead
664 *
665 * @param string $from
666 * @param string $to
667 * @return bool succes or fail
668 */
669function io_rename($from,$to){
670    global $conf;
671    if(!@rename($from,$to)){
672        if(@copy($from,$to)){
673            if($conf['fperm']) chmod($to, $conf['fperm']);
674            @unlink($from);
675            return true;
676        }
677        return false;
678    }
679    return true;
680}
681
682/**
683 * Runs an external command with input and output pipes.
684 * Returns the exit code from the process.
685 *
686 * @author Tom N Harris <tnharris@whoopdedo.org>
687 *
688 * @param string $cmd
689 * @param string $input  input pipe
690 * @param string $output output pipe
691 * @return int exit code from process
692 */
693function io_exec($cmd, $input, &$output){
694    $descspec = array(
695            0=>array("pipe","r"),
696            1=>array("pipe","w"),
697            2=>array("pipe","w"));
698    $ph = proc_open($cmd, $descspec, $pipes);
699    if(!$ph) return -1;
700    fclose($pipes[2]); // ignore stderr
701    fwrite($pipes[0], $input);
702    fclose($pipes[0]);
703    $output = stream_get_contents($pipes[1]);
704    fclose($pipes[1]);
705    return proc_close($ph);
706}
707
708/**
709 * Search a file for matching lines
710 *
711 * This is probably not faster than file()+preg_grep() but less
712 * memory intensive because not the whole file needs to be loaded
713 * at once.
714 *
715 * @author Andreas Gohr <andi@splitbrain.org>
716 * @param  string $file    The file to search
717 * @param  string $pattern PCRE pattern
718 * @param  int    $max     How many lines to return (0 for all)
719 * @param  bool   $backref When true returns array with backreferences instead of lines
720 * @return array matching lines or backref, false on error
721 */
722function io_grep($file,$pattern,$max=0,$backref=false){
723    $fh = @fopen($file,'r');
724    if(!$fh) return false;
725    $matches = array();
726
727    $cnt  = 0;
728    $line = '';
729    while (!feof($fh)) {
730        $line .= fgets($fh, 4096);  // read full line
731        if(substr($line,-1) != "\n") continue;
732
733        // check if line matches
734        if(preg_match($pattern,$line,$match)){
735            if($backref){
736                $matches[] = $match;
737            }else{
738                $matches[] = $line;
739            }
740            $cnt++;
741        }
742        if($max && $max == $cnt) break;
743        $line = '';
744    }
745    fclose($fh);
746    return $matches;
747}
748
749