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