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