xref: /dokuwiki/inc/io.php (revision 1bd6bbdebc26f9cd916f8f287cd2cabc07bee8d1)
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 * Internal function to save contents to a file.
209 *
210 * @author  Andreas Gohr <andi@splitbrain.org>
211 *
212 * @param string $file filename path to file
213 * @param string $content
214 * @param bool   $append
215 * @return bool true on success, otherwise false
216 */
217function _io_saveFile($file, $content, $append) {
218    global $conf;
219    $mode = ($append) ? 'ab' : 'wb';
220    $fileexists = file_exists($file);
221
222    if(substr($file,-3) == '.gz'){
223        $fh = @gzopen($file,$mode.'9');
224        if(!$fh) return false;
225        gzwrite($fh, $content);
226        gzclose($fh);
227    }else if(substr($file,-4) == '.bz2'){
228        if($append) {
229            $bzcontent = bzfile($file);
230            if($bzcontent === false) return false;
231            $content = $bzcontent.$content;
232        }
233        $fh = @bzopen($file,'w');
234        if(!$fh) return false;
235        bzwrite($fh, $content);
236        bzclose($fh);
237    }else{
238        $fh = @fopen($file,$mode);
239        if(!$fh) return false;
240        fwrite($fh, $content);
241        fclose($fh);
242    }
243
244    if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
245    return true;
246}
247
248/**
249 * Saves $content to $file.
250 *
251 * If the third parameter is set to true the given content
252 * will be appended.
253 *
254 * Uses gzip if extension is .gz
255 * and bz2 if extension is .bz2
256 *
257 * @author  Andreas Gohr <andi@splitbrain.org>
258 *
259 * @param string $file filename path to file
260 * @param string $content
261 * @param bool   $append
262 * @return bool true on success, otherwise false
263 */
264function io_saveFile($file, $content, $append=false) {
265    io_makeFileDir($file);
266    io_lock($file);
267    if(!_io_saveFile($file, $content, $append)) {
268        msg("Writing $file failed",-1);
269        io_unlock($file);
270        return false;
271    }
272    io_unlock($file);
273    return true;
274}
275
276/**
277 * Replace one or more occurrences of a line in a file.
278 *
279 * The default, when $maxlines is 0 is to delete all matches then append a single line.
280 * If $maxlines is -1, then every $oldline will be replaced with $newline, and $regex is true
281 * then preg captures are used. If $maxlines is greater than 0 then the first $maxlines
282 * matches are replaced with $newline.
283 *
284 * Be sure to include the trailing newline in $oldline
285 *
286 * Uses gzip if extension is .gz
287 * and bz2 if extension is .bz2
288 *
289 * @author Steven Danz <steven-danz@kc.rr.com>
290 * @author Christopher Smith <chris@jalakai.co.uk>
291 * @author Patrick Brown <ptbrown@whoopdedo.org>
292 *
293 * @param string $file     filename
294 * @param string $oldline  exact linematch to remove
295 * @param string $newline  new line to insert
296 * @param bool   $regex    use regexp?
297 * @param int    $maxlines number of occurrences of the line to replace
298 * @return bool true on success
299 */
300function io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0) {
301    if (!file_exists($file)) return true;
302
303    io_lock($file);
304
305    // load into array
306    if(substr($file,-3) == '.gz'){
307        $lines = gzfile($file);
308    }else if(substr($file,-4) == '.bz2'){
309        $lines = bzfile($file, true);
310    }else{
311        $lines = file($file);
312    }
313
314    // remove all matching lines
315    if ($regex) {
316        if($maxlines == 0) {
317            $lines = preg_grep($oldline, $lines, PREG_GREP_INVERT);
318        } else {
319            $lines = preg_replace($oldline, $newline, $lines, $maxlines);
320        }
321    } else {
322        $count = 0;
323        $replaceline = $maxlines == 0 ? '' : $newline;
324        $pos = array_search($oldline,$lines); //return null or false if not found
325        while(is_int($pos)){
326            $lines[$pos] = $replaceline;
327            if($maxlines > 0 && ++$count >= $maxlines) break;
328            $pos = array_search($oldline,$lines);
329        }
330    }
331
332    if($maxlines == 0 && ((string)$newline) !== '') {
333        $lines[] = $newline;
334    }
335
336    if(count($lines)){
337        if(!_io_saveFile($file, join('',$lines), false)) {
338            msg("Removing content from $file failed",-1);
339            io_unlock($file);
340            return false;
341        }
342    }else{
343        @unlink($file);
344    }
345
346    io_unlock($file);
347    return true;
348}
349
350/**
351 * Delete lines that match $badline from $file.
352 *
353 * Be sure to include the trailing newline in $badline
354 *
355 * @author Patrick Brown <ptbrown@whoopdedo.org>
356 *
357 * @param string $file    filename
358 * @param string $badline exact linematch to remove
359 * @param bool   $regex   use regexp?
360 * @return bool true on success
361 */
362function io_deleteFromFile($file,$badline,$regex=false){
363    return io_replaceInFile($file,$badline,null,$regex,0);
364}
365
366/**
367 * Tries to lock a file
368 *
369 * Locking is only done for io_savefile and uses directories
370 * inside $conf['lockdir']
371 *
372 * It waits maximal 3 seconds for the lock, after this time
373 * the lock is assumed to be stale and the function goes on
374 *
375 * @author Andreas Gohr <andi@splitbrain.org>
376 *
377 * @param string $file filename
378 */
379function io_lock($file){
380    global $conf;
381    // no locking if safemode hack
382    if($conf['safemodehack']) return;
383
384    $lockDir = $conf['lockdir'].'/'.md5($file);
385    @ignore_user_abort(1);
386
387    $timeStart = time();
388    do {
389        //waited longer than 3 seconds? -> stale lock
390        if ((time() - $timeStart) > 3) break;
391        $locked = @mkdir($lockDir, $conf['dmode']);
392        if($locked){
393            if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
394            break;
395        }
396        usleep(50);
397    } while ($locked === false);
398}
399
400/**
401 * Unlocks a file
402 *
403 * @author Andreas Gohr <andi@splitbrain.org>
404 *
405 * @param string $file filename
406 */
407function io_unlock($file){
408    global $conf;
409    // no locking if safemode hack
410    if($conf['safemodehack']) return;
411
412    $lockDir = $conf['lockdir'].'/'.md5($file);
413    @rmdir($lockDir);
414    @ignore_user_abort(0);
415}
416
417/**
418 * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
419 * in the order of directory creation. (Parent directories first.)
420 *
421 * Event data:
422 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
423 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
424 *
425 * @author Ben Coburn <btcoburn@silicodon.net>
426 *
427 * @param string $id page id
428 * @param string $ns_type 'pages' or 'media'
429 */
430function io_createNamespace($id, $ns_type='pages') {
431    // verify ns_type
432    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
433    if (!isset($types[$ns_type])) {
434        trigger_error('Bad $ns_type parameter for io_createNamespace().');
435        return;
436    }
437    // make event list
438    $missing = array();
439    $ns_stack = explode(':', $id);
440    $ns = $id;
441    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
442    while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
443        array_pop($ns_stack);
444        $ns = implode(':', $ns_stack);
445        if (strlen($ns)==0) { break; }
446        $missing[] = $ns;
447        $tmp = dirname(call_user_func($types[$ns_type], $ns));
448    }
449    // make directories
450    io_makeFileDir($file);
451    // send the events
452    $missing = array_reverse($missing); // inside out
453    foreach ($missing as $ns) {
454        $data = array($ns, $ns_type);
455        trigger_event('IO_NAMESPACE_CREATED', $data);
456    }
457}
458
459/**
460 * Create the directory needed for the given file
461 *
462 * @author  Andreas Gohr <andi@splitbrain.org>
463 *
464 * @param string $file file name
465 */
466function io_makeFileDir($file){
467    $dir = dirname($file);
468    if(!@is_dir($dir)){
469        io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
470    }
471}
472
473/**
474 * Creates a directory hierachy.
475 *
476 * @link    http://www.php.net/manual/en/function.mkdir.php
477 * @author  <saint@corenova.com>
478 * @author  Andreas Gohr <andi@splitbrain.org>
479 *
480 * @param string $target filename
481 * @return bool|int|string
482 */
483function io_mkdir_p($target){
484    global $conf;
485    if (@is_dir($target)||empty($target)) return 1; // best case check first
486    if (file_exists($target) && !is_dir($target)) return 0;
487    //recursion
488    if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
489        if($conf['safemodehack']){
490            $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
491            return io_mkdir_ftp($dir);
492        }else{
493            $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
494            if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
495            return $ret;
496        }
497    }
498    return 0;
499}
500
501/**
502 * Recursively delete a directory
503 *
504 * @author Andreas Gohr <andi@splitbrain.org>
505 * @param string $path
506 * @param bool   $removefiles defaults to false which will delete empty directories only
507 * @return bool
508 */
509function io_rmdir($path, $removefiles = false) {
510    if(!is_string($path) || $path == "") return false;
511    if(!file_exists($path)) return true; // it's already gone or was never there, count as success
512
513    if(is_dir($path) && !is_link($path)) {
514        $dirs  = array();
515        $files = array();
516
517        if(!$dh = @opendir($path)) return false;
518        while(false !== ($f = readdir($dh))) {
519            if($f == '..' || $f == '.') continue;
520
521            // collect dirs and files first
522            if(is_dir("$path/$f") && !is_link("$path/$f")) {
523                $dirs[] = "$path/$f";
524            } else if($removefiles) {
525                $files[] = "$path/$f";
526            } else {
527                return false; // abort when non empty
528            }
529
530        }
531        closedir($dh);
532
533        // now traverse into  directories first
534        foreach($dirs as $dir) {
535            if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
536        }
537
538        // now delete files
539        foreach($files as $file) {
540            if(!@unlink($file)) return false; //abort on any error
541        }
542
543        // remove self
544        return @rmdir($path);
545    } else if($removefiles) {
546        return @unlink($path);
547    }
548    return false;
549}
550
551/**
552 * Creates a directory using FTP
553 *
554 * This is used when the safemode workaround is enabled
555 *
556 * @author <andi@splitbrain.org>
557 *
558 * @param string $dir name of the new directory
559 * @return false|string
560 */
561function io_mkdir_ftp($dir){
562    global $conf;
563
564    if(!function_exists('ftp_connect')){
565        msg("FTP support not found - safemode workaround not usable",-1);
566        return false;
567    }
568
569    $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
570    if(!$conn){
571        msg("FTP connection failed",-1);
572        return false;
573    }
574
575    if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
576        msg("FTP login failed",-1);
577        return false;
578    }
579
580    //create directory
581    $ok = @ftp_mkdir($conn, $dir);
582    //set permissions
583    @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
584
585    @ftp_close($conn);
586    return $ok;
587}
588
589/**
590 * Creates a unique temporary directory and returns
591 * its path.
592 *
593 * @author Michael Klier <chi@chimeric.de>
594 *
595 * @return false|string path to new directory or false
596 */
597function io_mktmpdir() {
598    global $conf;
599
600    $base = $conf['tmpdir'];
601    $dir  = md5(uniqid(mt_rand(), true));
602    $tmpdir = $base.'/'.$dir;
603
604    if(io_mkdir_p($tmpdir)) {
605        return($tmpdir);
606    } else {
607        return false;
608    }
609}
610
611/**
612 * downloads a file from the net and saves it
613 *
614 * if $useAttachment is false,
615 * - $file is the full filename to save the file, incl. path
616 * - if successful will return true, false otherwise
617 *
618 * if $useAttachment is true,
619 * - $file is the directory where the file should be saved
620 * - if successful will return the name used for the saved file, false otherwise
621 *
622 * @author Andreas Gohr <andi@splitbrain.org>
623 * @author Chris Smith <chris@jalakai.co.uk>
624 *
625 * @param string $url           url to download
626 * @param string $file          path to file or directory where to save
627 * @param bool   $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file
628 * @param string $defaultName   fallback for if using $useAttachment
629 * @param int    $maxSize       maximum file size
630 * @return bool|string          if failed false, otherwise true or the name of the file in the given dir
631 */
632function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
633    global $conf;
634    $http = new DokuHTTPClient();
635    $http->max_bodysize = $maxSize;
636    $http->timeout = 25; //max. 25 sec
637    $http->keep_alive = false; // we do single ops here, no need for keep-alive
638
639    $data = $http->get($url);
640    if(!$data) return false;
641
642    $name = '';
643    if ($useAttachment) {
644        if (isset($http->resp_headers['content-disposition'])) {
645            $content_disposition = $http->resp_headers['content-disposition'];
646            $match=array();
647            if (is_string($content_disposition) &&
648                    preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
649
650                $name = utf8_basename($match[1]);
651            }
652
653        }
654
655        if (!$name) {
656            if (!$defaultName) return false;
657            $name = $defaultName;
658        }
659
660        $file = $file.$name;
661    }
662
663    $fileexists = file_exists($file);
664    $fp = @fopen($file,"w");
665    if(!$fp) return false;
666    fwrite($fp,$data);
667    fclose($fp);
668    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
669    if ($useAttachment) return $name;
670    return true;
671}
672
673/**
674 * Windows compatible rename
675 *
676 * rename() can not overwrite existing files on Windows
677 * this function will use copy/unlink instead
678 *
679 * @param string $from
680 * @param string $to
681 * @return bool succes or fail
682 */
683function io_rename($from,$to){
684    global $conf;
685    if(!@rename($from,$to)){
686        if(@copy($from,$to)){
687            if($conf['fperm']) chmod($to, $conf['fperm']);
688            @unlink($from);
689            return true;
690        }
691        return false;
692    }
693    return true;
694}
695
696/**
697 * Runs an external command with input and output pipes.
698 * Returns the exit code from the process.
699 *
700 * @author Tom N Harris <tnharris@whoopdedo.org>
701 *
702 * @param string $cmd
703 * @param string $input  input pipe
704 * @param string $output output pipe
705 * @return int exit code from process
706 */
707function io_exec($cmd, $input, &$output){
708    $descspec = array(
709            0=>array("pipe","r"),
710            1=>array("pipe","w"),
711            2=>array("pipe","w"));
712    $ph = proc_open($cmd, $descspec, $pipes);
713    if(!$ph) return -1;
714    fclose($pipes[2]); // ignore stderr
715    fwrite($pipes[0], $input);
716    fclose($pipes[0]);
717    $output = stream_get_contents($pipes[1]);
718    fclose($pipes[1]);
719    return proc_close($ph);
720}
721
722/**
723 * Search a file for matching lines
724 *
725 * This is probably not faster than file()+preg_grep() but less
726 * memory intensive because not the whole file needs to be loaded
727 * at once.
728 *
729 * @author Andreas Gohr <andi@splitbrain.org>
730 * @param  string $file    The file to search
731 * @param  string $pattern PCRE pattern
732 * @param  int    $max     How many lines to return (0 for all)
733 * @param  bool   $backref When true returns array with backreferences instead of lines
734 * @return array matching lines or backref, false on error
735 */
736function io_grep($file,$pattern,$max=0,$backref=false){
737    $fh = @fopen($file,'r');
738    if(!$fh) return false;
739    $matches = array();
740
741    $cnt  = 0;
742    $line = '';
743    while (!feof($fh)) {
744        $line .= fgets($fh, 4096);  // read full line
745        if(substr($line,-1) != "\n") continue;
746
747        // check if line matches
748        if(preg_match($pattern,$line,$match)){
749            if($backref){
750                $matches[] = $match;
751            }else{
752                $matches[] = $line;
753            }
754            $cnt++;
755        }
756        if($max && $max == $cnt) break;
757        $line = '';
758    }
759    fclose($fh);
760    return $matches;
761}
762
763