xref: /dokuwiki/inc/io.php (revision b895ecb2051693e502fe5bfe4bee9ec53550e5da)
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
9  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10  require_once(DOKU_INC.'inc/common.php');
11  require_once(DOKU_INC.'inc/HTTPClient.php');
12  require_once(DOKU_INC.'inc/events.php');
13  require_once(DOKU_INC.'inc/utf8.php');
14
15/**
16 * Removes empty directories
17 *
18 * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
19 * Event data:
20 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
21 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
22 *
23 * @todo use safemode hack
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  //scan all namespaces
33  while(($id = getNS($id)) !== false){
34    $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':','/',$id));
35
36    //try to delete dir else return
37    if(@rmdir($dir)) {
38      if ($ns_type!==false) {
39        $data = array($id, $ns_type);
40        trigger_event('IO_NAMESPACE_DELETED', $data);
41      }
42    } else { return; }
43  }
44}
45
46/**
47 * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
48 *
49 * Generates the action event which delegates to io_readFile().
50 * Action plugins are allowed to modify the page content in transit.
51 * The file path should not be changed.
52 *
53 * Event data:
54 * $data[0]    The raw arguments for io_readFile as an array.
55 * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
56 * $data[2]    page_name: The wiki page name.
57 * $data[3]    rev: The page revision, false for current wiki pages.
58 *
59 * @author Ben Coburn <btcoburn@silicodon.net>
60 */
61function io_readWikiPage($file, $id, $rev=false) {
62    if (empty($rev)) { $rev = false; }
63    $data = array(array($file, false), getNS($id), noNS($id), $rev);
64    return trigger_event('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
65}
66
67/**
68 * Callback adapter for io_readFile().
69 * @author Ben Coburn <btcoburn@silicodon.net>
70 */
71function _io_readWikiPage_action($data) {
72    if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
73        return call_user_func_array('io_readFile', $data[0]);
74    } else {
75        return ''; //callback error
76    }
77}
78
79/**
80 * Returns content of $file as cleaned string.
81 *
82 * Uses gzip if extension is .gz
83 *
84 * If you want to use the returned value in unserialize
85 * be sure to set $clean to false!
86 *
87 * @author  Andreas Gohr <andi@splitbrain.org>
88 */
89function io_readFile($file,$clean=true){
90  $ret = '';
91  if(@file_exists($file)){
92    if(substr($file,-3) == '.gz'){
93      $ret = join('',gzfile($file));
94    }else{
95      $ret = join('',file($file));
96    }
97  }
98  if($clean){
99    return cleanText($ret);
100  }else{
101    return $ret;
102  }
103}
104
105/**
106 * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
107 *
108 * This generates an action event and delegates to io_saveFile().
109 * Action plugins are allowed to modify the page content in transit.
110 * The file path should not be changed.
111 * (The append parameter is set to false.)
112 *
113 * Event data:
114 * $data[0]    The raw arguments for io_saveFile as an array.
115 * $data[1]    ns: The colon separated namespace path minus the trailing page name. (false if root ns)
116 * $data[2]    page_name: The wiki page name.
117 * $data[3]    rev: The page revision, false for current wiki pages.
118 *
119 * @author Ben Coburn <btcoburn@silicodon.net>
120 */
121function io_writeWikiPage($file, $content, $id, $rev=false) {
122    if (empty($rev)) { $rev = false; }
123    if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
124    $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
125    return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
126}
127
128/**
129 * Callback adapter for io_saveFile().
130 * @author Ben Coburn <btcoburn@silicodon.net>
131 */
132function _io_writeWikiPage_action($data) {
133    if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
134        return call_user_func_array('io_saveFile', $data[0]);
135    } else {
136        return false; //callback error
137    }
138}
139
140/**
141 * Saves $content to $file.
142 *
143 * If the third parameter is set to true the given content
144 * will be appended.
145 *
146 * Uses gzip if extension is .gz
147 *
148 * @author  Andreas Gohr <andi@splitbrain.org>
149 * @return bool true on success
150 */
151function io_saveFile($file,$content,$append=false){
152  global $conf;
153  $mode = ($append) ? 'ab' : 'wb';
154
155  $fileexists = file_exists($file);
156  io_makeFileDir($file);
157  io_lock($file);
158  if(substr($file,-3) == '.gz'){
159    $fh = @gzopen($file,$mode.'9');
160    if(!$fh){
161      msg("Writing $file failed",-1);
162      return false;
163    }
164    gzwrite($fh, $content);
165    gzclose($fh);
166  }else{
167    $fh = @fopen($file,$mode);
168    if(!$fh){
169      msg("Writing $file failed",-1);
170      return false;
171    }
172    fwrite($fh, $content);
173    fclose($fh);
174  }
175
176  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
177  io_unlock($file);
178  return true;
179}
180
181/**
182 * Delete exact linematch for $badline from $file.
183 *
184 * Be sure to include the trailing newline in $badline
185 *
186 * Uses gzip if extension is .gz
187 *
188 * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
189 *
190 * @author Steven Danz <steven-danz@kc.rr.com>
191 * @return bool true on success
192 */
193function io_deleteFromFile($file,$badline,$regex=false){
194  if (!@file_exists($file)) return true;
195
196  io_lock($file);
197
198  // load into array
199  if(substr($file,-3) == '.gz'){
200    $lines = gzfile($file);
201  }else{
202    $lines = file($file);
203  }
204
205  // remove all matching lines
206  if ($regex) {
207    $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
208  } else {
209    $pos = array_search($badline,$lines); //return null or false if not found
210    while(is_int($pos)){
211      unset($lines[$pos]);
212      $pos = array_search($badline,$lines);
213    }
214  }
215
216  if(count($lines)){
217    $content = join('',$lines);
218    if(substr($file,-3) == '.gz'){
219      $fh = @gzopen($file,'wb9');
220      if(!$fh){
221        msg("Removing content from $file failed",-1);
222        return false;
223      }
224      gzwrite($fh, $content);
225      gzclose($fh);
226    }else{
227      $fh = @fopen($file,'wb');
228      if(!$fh){
229        msg("Removing content from $file failed",-1);
230        return false;
231      }
232      fwrite($fh, $content);
233      fclose($fh);
234    }
235  }else{
236    @unlink($file);
237  }
238
239  io_unlock($file);
240  return true;
241}
242
243/**
244 * Tries to lock a file
245 *
246 * Locking is only done for io_savefile and uses directories
247 * inside $conf['lockdir']
248 *
249 * It waits maximal 3 seconds for the lock, after this time
250 * the lock is assumed to be stale and the function goes on
251 *
252 * @author Andreas Gohr <andi@splitbrain.org>
253 */
254function io_lock($file){
255  global $conf;
256  // no locking if safemode hack
257  if($conf['safemodehack']) return;
258
259  $lockDir = $conf['lockdir'].'/'.md5($file);
260  @ignore_user_abort(1);
261
262  $timeStart = time();
263  do {
264    //waited longer than 3 seconds? -> stale lock
265    if ((time() - $timeStart) > 3) break;
266    $locked = @mkdir($lockDir, $conf['dmode']);
267    if($locked){
268      if($conf['dperm']) chmod($lockDir, $conf['dperm']);
269      break;
270    }
271    usleep(50);
272  } while ($locked === false);
273}
274
275/**
276 * Unlocks a file
277 *
278 * @author Andreas Gohr <andi@splitbrain.org>
279 */
280function io_unlock($file){
281  global $conf;
282  // no locking if safemode hack
283  if($conf['safemodehack']) return;
284
285  $lockDir = $conf['lockdir'].'/'.md5($file);
286  @rmdir($lockDir);
287  @ignore_user_abort(0);
288}
289
290/**
291 * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
292 * in the order of directory creation. (Parent directories first.)
293 *
294 * Event data:
295 * $data[0]    ns: The colon separated namespace path minus the trailing page name.
296 * $data[1]    ns_type: 'pages' or 'media' namespace tree.
297 *
298 * @author Ben Coburn <btcoburn@silicodon.net>
299 */
300function io_createNamespace($id, $ns_type='pages') {
301    // verify ns_type
302    $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
303    if (!isset($types[$ns_type])) {
304        trigger_error('Bad $ns_type parameter for io_createNamespace().');
305        return;
306    }
307    // make event list
308    $missing = array();
309    $ns_stack = explode(':', $id);
310    $ns = $id;
311    $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
312    while (!@is_dir($tmp) && !(@file_exists($tmp) && !is_dir($tmp))) {
313        array_pop($ns_stack);
314        $ns = implode(':', $ns_stack);
315        if (strlen($ns)==0) { break; }
316        $missing[] = $ns;
317        $tmp = dirname(call_user_func($types[$ns_type], $ns));
318    }
319    // make directories
320    io_makeFileDir($file);
321    // send the events
322    $missing = array_reverse($missing); // inside out
323    foreach ($missing as $ns) {
324        $data = array($ns, $ns_type);
325        trigger_event('IO_NAMESPACE_CREATED', $data);
326    }
327}
328
329/**
330 * Create the directory needed for the given file
331 *
332 * @author  Andreas Gohr <andi@splitbrain.org>
333 */
334function io_makeFileDir($file){
335  global $conf;
336
337  $dir = dirname($file);
338  if(!@is_dir($dir)){
339    io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
340  }
341}
342
343/**
344 * Creates a directory hierachy.
345 *
346 * @link    http://www.php.net/manual/en/function.mkdir.php
347 * @author  <saint@corenova.com>
348 * @author  Andreas Gohr <andi@splitbrain.org>
349 */
350function io_mkdir_p($target){
351  global $conf;
352  if (@is_dir($target)||empty($target)) return 1; // best case check first
353  if (@file_exists($target) && !is_dir($target)) return 0;
354  //recursion
355  if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
356    if($conf['safemodehack']){
357      $dir = preg_replace('/^'.preg_quote(realpath($conf['ftp']['root']),'/').'/','', $target);
358      return io_mkdir_ftp($dir);
359    }else{
360      $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
361      if($ret && $conf['dperm']) chmod($target, $conf['dperm']);
362      return $ret;
363    }
364  }
365  return 0;
366}
367
368/**
369 * Creates a directory using FTP
370 *
371 * This is used when the safemode workaround is enabled
372 *
373 * @author <andi@splitbrain.org>
374 */
375function io_mkdir_ftp($dir){
376  global $conf;
377
378  if(!function_exists('ftp_connect')){
379    msg("FTP support not found - safemode workaround not usable",-1);
380    return false;
381  }
382
383  $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
384  if(!$conn){
385    msg("FTP connection failed",-1);
386    return false;
387  }
388
389  if(!@ftp_login($conn, $conf['ftp']['user'], $conf['ftp']['pass'])){
390    msg("FTP login failed",-1);
391    return false;
392  }
393
394  //create directory
395  $ok = @ftp_mkdir($conn, $dir);
396  //set permissions
397  @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
398
399  @ftp_close($conn);
400  return $ok;
401}
402
403/**
404 * downloads a file from the net and saves it
405 *
406 * if $useAttachment is false,
407 * - $file is the full filename to save the file, incl. path
408 * - if successful will return true, false otherwise
409
410 * if $useAttachment is true,
411 * - $file is the directory where the file should be saved
412 * - if successful will return the name used for the saved file, false otherwise
413 *
414 * @author Andreas Gohr <andi@splitbrain.org>
415 * @author Chris Smith <chris@jalakai.co.uk>
416 */
417function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
418  global $conf;
419  $http = new DokuHTTPClient();
420  $http->max_bodysize = $maxSize;
421  $http->timeout = 25; //max. 25 sec
422
423  $data = $http->get($url);
424  if(!$data) return false;
425
426  if ($useAttachment) {
427    $name = '';
428      if (isset($http->resp_headers['content-disposition'])) {
429      $content_disposition = $http->resp_headers['content-disposition'];
430      $match=array();
431      if (is_string($content_disposition) &&
432          preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
433
434          $name = basename($match[1]);
435      }
436
437    }
438
439    if (!$name) {
440        if (!$defaultName) return false;
441        $name = $defaultName;
442    }
443
444    $file = $file.$name;
445  }
446
447  $fileexists = file_exists($file);
448  $fp = @fopen($file,"w");
449  if(!$fp) return false;
450  fwrite($fp,$data);
451  fclose($fp);
452  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
453  if ($useAttachment) return $name;
454  return true;
455}
456
457/**
458 * Windows compatible rename
459 *
460 * rename() can not overwrite existing files on Windows
461 * this function will use copy/unlink instead
462 */
463function io_rename($from,$to){
464  global $conf;
465  if(!@rename($from,$to)){
466    if(@copy($from,$to)){
467      if($conf['fperm']) chmod($file, $conf['fperm']);
468      @unlink($from);
469      return true;
470    }
471    return false;
472  }
473  return true;
474}
475
476
477/**
478 * Runs an external command and returns it's output as string
479 *
480 * @author Harry Brueckner <harry_b@eml.cc>
481 * @author Andreas Gohr <andi@splitbrain.org>
482 * @deprecated
483 */
484function io_runcmd($cmd){
485  $fh = popen($cmd, "r");
486  if(!$fh) return false;
487  $ret = '';
488  while (!feof($fh)) {
489    $ret .= fread($fh, 8192);
490  }
491  pclose($fh);
492  return $ret;
493}
494
495/**
496 * Search a file for matching lines
497 *
498 * This is probably not faster than file()+preg_grep() but less
499 * memory intensive because not the whole file needs to be loaded
500 * at once.
501 *
502 * @author Andreas Gohr <andi@splitbrain.org>
503 * @param  string $file    The file to search
504 * @param  string $pattern PCRE pattern
505 * @param  int    $max     How many lines to return (0 for all)
506 * @param  bool   $baxkref When true returns array with backreferences instead of lines
507 * @return matching lines or backref, false on error
508 */
509function io_grep($file,$pattern,$max=0,$backref=false){
510  $fh = @fopen($file,'r');
511  if(!$fh) return false;
512  $matches = array();
513
514  $cnt  = 0;
515  $line = '';
516  while (!feof($fh)) {
517    $line .= fgets($fh, 4096);  // read full line
518    if(substr($line,-1) != "\n") continue;
519
520    // check if line matches
521    if(preg_match($pattern,$line,$match)){
522      if($backref){
523        $matches[] = $match;
524      }else{
525        $matches[] = $line;
526      }
527      $cnt++;
528    }
529    if($max && $max == $cnt) break;
530    $line = '';
531  }
532  fclose($fh);
533  return $matches;
534}
535
536//Setup VIM: ex: et ts=2 enc=utf-8 :
537