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