5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
9 if(!defined('DOKU_INC')) die('meh.');
12 * Removes empty directories
14 * Sends IO_NAMESPACE_DELETED events for 'pages' and 'media' namespaces.
16 * $data[0] ns: The colon separated namespace path minus the trailing page name.
17 * $data[1] ns_type: 'pages' or 'media' namespace tree.
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 * @author Andreas Gohr <andi@splitbrain.org>
24 * @author Ben Coburn <btcoburn@silicodon.net>
26 function io_sweepNS($id,$basedir='datadir'){
28 $types = array ('datadir'=>'pages', 'mediadir'=>'media');
29 $ns_type = (isset($types[$basedir])?$types[$basedir]:false);
34 while(($id = getNS($id)) !== false){
35 $dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':','/',$id));
37 //try to delete dir else return
39 if ($ns_type!==false) {
40 $data = array($id, $ns_type);
41 $delone = true; // we deleted at least one dir
42 trigger_event('IO_NAMESPACE_DELETED', $data);
44 } else { return $delone; }
50 * Used to read in a DokuWiki page from file, and send IO_WIKIPAGE_READ events.
52 * Generates the action event which delegates to io_readFile().
53 * Action plugins are allowed to modify the page content in transit.
54 * The file path should not be changed.
57 * $data[0] The raw arguments for io_readFile as an array.
58 * $data[1] ns: The colon separated namespace path minus the trailing page name. (false if root ns)
59 * $data[2] page_name: The wiki page name.
60 * $data[3] rev: The page revision, false for current wiki pages.
62 * @author Ben Coburn <btcoburn@silicodon.net>
64 function io_readWikiPage($file, $id, $rev=false) {
65 if (empty($rev)) { $rev = false; }
66 $data = array(array($file, true), getNS($id), noNS($id), $rev);
67 return trigger_event('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
71 * Callback adapter for io_readFile().
72 * @author Ben Coburn <btcoburn@silicodon.net>
74 function _io_readWikiPage_action($data) {
75 if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
76 return call_user_func_array('io_readFile', $data[0]);
78 return ''; //callback error
83 * Returns content of $file as cleaned string.
85 * Uses gzip if extension is .gz
87 * If you want to use the returned value in unserialize
88 * be sure to set $clean to false!
90 * @author Andreas Gohr <andi@splitbrain.org>
92 function io_readFile($file,$clean=true){
94 if(@file_exists($file)){
95 if(substr($file,-3) == '.gz'){
96 $ret = join('',gzfile($file));
97 }else if(substr($file,-4) == '.bz2'){
100 $ret = file_get_contents($file);
104 return cleanText($ret);
110 * Returns the content of a .bz2 compressed file as string
111 * @author marcel senf <marcel@rucksackreinigung.de>
114 function bzfile($file){
115 $bz = bzopen($file,"r");
118 //8192 seems to be the maximum buffersize?
119 $str = $str . bzread($bz,8192);
127 * Used to write out a DokuWiki page to file, and send IO_WIKIPAGE_WRITE events.
129 * This generates an action event and delegates to io_saveFile().
130 * Action plugins are allowed to modify the page content in transit.
131 * The file path should not be changed.
132 * (The append parameter is set to false.)
135 * $data[0] The raw arguments for io_saveFile as an array.
136 * $data[1] ns: The colon separated namespace path minus the trailing page name. (false if root ns)
137 * $data[2] page_name: The wiki page name.
138 * $data[3] rev: The page revision, false for current wiki pages.
140 * @author Ben Coburn <btcoburn@silicodon.net>
142 function io_writeWikiPage($file, $content, $id, $rev=false) {
143 if (empty($rev)) { $rev = false; }
144 if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
145 $data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
146 return trigger_event('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
150 * Callback adapter for io_saveFile().
151 * @author Ben Coburn <btcoburn@silicodon.net>
153 function _io_writeWikiPage_action($data) {
154 if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
155 return call_user_func_array('io_saveFile', $data[0]);
157 return false; //callback error
162 * Saves $content to $file.
164 * If the third parameter is set to true the given content
167 * Uses gzip if extension is .gz
168 * and bz2 if extension is .bz2
170 * @author Andreas Gohr <andi@splitbrain.org>
171 * @return bool true on success
173 function io_saveFile($file,$content,$append=false){
175 $mode = ($append) ? 'ab' : 'wb';
177 $fileexists = @file_exists($file);
178 io_makeFileDir($file);
180 if(substr($file,-3) == '.gz'){
181 $fh = @gzopen($file,$mode.'9');
183 msg("Writing $file failed",-1);
187 gzwrite($fh, $content);
189 }else if(substr($file,-4) == '.bz2'){
190 $fh = @bzopen($file,$mode{0});
192 msg("Writing $file failed", -1);
196 bzwrite($fh, $content);
199 $fh = @fopen($file,$mode);
201 msg("Writing $file failed",-1);
205 fwrite($fh, $content);
209 if(!$fileexists and !empty($conf['fperm'])) chmod($file, $conf['fperm']);
215 * Delete exact linematch for $badline from $file.
217 * Be sure to include the trailing newline in $badline
219 * Uses gzip if extension is .gz
221 * 2005-10-14 : added regex option -- Christopher Smith <chris@jalakai.co.uk>
223 * @author Steven Danz <steven-danz@kc.rr.com>
224 * @return bool true on success
226 function io_deleteFromFile($file,$badline,$regex=false){
227 if (!@file_exists($file)) return true;
232 if(substr($file,-3) == '.gz'){
233 $lines = gzfile($file);
235 $lines = file($file);
238 // remove all matching lines
240 $lines = preg_grep($badline,$lines,PREG_GREP_INVERT);
242 $pos = array_search($badline,$lines); //return null or false if not found
245 $pos = array_search($badline,$lines);
250 $content = join('',$lines);
251 if(substr($file,-3) == '.gz'){
252 $fh = @gzopen($file,'wb9');
254 msg("Removing content from $file failed",-1);
258 gzwrite($fh, $content);
261 $fh = @fopen($file,'wb');
263 msg("Removing content from $file failed",-1);
267 fwrite($fh, $content);
279 * Tries to lock a file
281 * Locking is only done for io_savefile and uses directories
282 * inside $conf['lockdir']
284 * It waits maximal 3 seconds for the lock, after this time
285 * the lock is assumed to be stale and the function goes on
287 * @author Andreas Gohr <andi@splitbrain.org>
289 function io_lock($file){
291 // no locking if safemode hack
292 if($conf['safemodehack']) return;
294 $lockDir = $conf['lockdir'].'/'.md5($file);
295 @ignore_user_abort(1);
299 //waited longer than 3 seconds? -> stale lock
300 if ((time() - $timeStart) > 3) break;
301 $locked = @mkdir($lockDir, $conf['dmode']);
303 if(!empty($conf['dperm'])) chmod($lockDir, $conf['dperm']);
307 } while ($locked === false);
313 * @author Andreas Gohr <andi@splitbrain.org>
315 function io_unlock($file){
317 // no locking if safemode hack
318 if($conf['safemodehack']) return;
320 $lockDir = $conf['lockdir'].'/'.md5($file);
322 @ignore_user_abort(0);
326 * Create missing namespace directories and send the IO_NAMESPACE_CREATED events
327 * in the order of directory creation. (Parent directories first.)
330 * $data[0] ns: The colon separated namespace path minus the trailing page name.
331 * $data[1] ns_type: 'pages' or 'media' namespace tree.
333 * @author Ben Coburn <btcoburn@silicodon.net>
335 function io_createNamespace($id, $ns_type='pages') {
337 $types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
338 if (!isset($types[$ns_type])) {
339 trigger_error('Bad $ns_type parameter for io_createNamespace().');
344 $ns_stack = explode(':', $id);
346 $tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
347 while (!@is_dir($tmp) && !(@file_exists($tmp) && !is_dir($tmp))) {
348 array_pop($ns_stack);
349 $ns = implode(':', $ns_stack);
350 if (strlen($ns)==0) { break; }
352 $tmp = dirname(call_user_func($types[$ns_type], $ns));
355 io_makeFileDir($file);
357 $missing = array_reverse($missing); // inside out
358 foreach ($missing as $ns) {
359 $data = array($ns, $ns_type);
360 trigger_event('IO_NAMESPACE_CREATED', $data);
365 * Create the directory needed for the given file
367 * @author Andreas Gohr <andi@splitbrain.org>
369 function io_makeFileDir($file){
372 $dir = dirname($file);
374 io_mkdir_p($dir) || msg("Creating directory $dir failed",-1);
379 * Creates a directory hierachy.
381 * @link http://www.php.net/manual/en/function.mkdir.php
382 * @author <saint@corenova.com>
383 * @author Andreas Gohr <andi@splitbrain.org>
385 function io_mkdir_p($target){
387 if (@is_dir($target)||empty($target)) return 1; // best case check first
388 if (@file_exists($target) && !is_dir($target)) return 0;
390 if (io_mkdir_p(substr($target,0,strrpos($target,'/')))){
391 if($conf['safemodehack']){
392 $dir = preg_replace('/^'.preg_quote(fullpath($conf['ftp']['root']),'/').'/','', $target);
393 return io_mkdir_ftp($dir);
395 $ret = @mkdir($target,$conf['dmode']); // crawl back up & create dir tree
396 if($ret && $conf['dperm']) chmod($target, $conf['dperm']);
404 * Creates a directory using FTP
406 * This is used when the safemode workaround is enabled
408 * @author <andi@splitbrain.org>
410 function io_mkdir_ftp($dir){
413 if(!function_exists('ftp_connect')){
414 msg("FTP support not found - safemode workaround not usable",-1);
418 $conn = @ftp_connect($conf['ftp']['host'],$conf['ftp']['port'],10);
420 msg("FTP connection failed",-1);
424 if(!@ftp_login($conn, $conf['ftp']['user'], conf_decodeString($conf['ftp']['pass']))){
425 msg("FTP login failed",-1);
430 $ok = @ftp_mkdir($conn, $dir);
432 @ftp_site($conn,sprintf("CHMOD %04o %s",$conf['dmode'],$dir));
439 * Creates a unique temporary directory and returns
442 * @author Michael Klier <chi@chimeric.de>
444 function io_mktmpdir() {
447 $base = $conf['tmpdir'];
448 $dir = md5(uniqid(mt_rand(), true));
449 $tmpdir = $base.'/'.$dir;
451 if(io_mkdir_p($tmpdir)) {
459 * downloads a file from the net and saves it
461 * if $useAttachment is false,
462 * - $file is the full filename to save the file, incl. path
463 * - if successful will return true, false otherwise
465 * if $useAttachment is true,
466 * - $file is the directory where the file should be saved
467 * - if successful will return the name used for the saved file, false otherwise
469 * @author Andreas Gohr <andi@splitbrain.org>
470 * @author Chris Smith <chris@jalakai.co.uk>
472 function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
474 $http = new DokuHTTPClient();
475 $http->max_bodysize = $maxSize;
476 $http->timeout = 25; //max. 25 sec
478 $data = $http->get($url);
479 if(!$data) return false;
482 if ($useAttachment) {
483 if (isset($http->resp_headers['content-disposition'])) {
484 $content_disposition = $http->resp_headers['content-disposition'];
486 if (is_string($content_disposition) &&
487 preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
489 $name = utf8_basename($match[1]);
495 if (!$defaultName) return false;
496 $name = $defaultName;
502 $fileexists = @file_exists($file);
503 $fp = @fopen($file,"w");
504 if(!$fp) return false;
507 if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
508 if ($useAttachment) return $name;
513 * Windows compatible rename
515 * rename() can not overwrite existing files on Windows
516 * this function will use copy/unlink instead
518 function io_rename($from,$to){
520 if(!@rename($from,$to)){
521 if(@copy($from,$to)){
522 if($conf['fperm']) chmod($to, $conf['fperm']);
533 * Runs an external command and returns its output as string
535 * @author Harry Brueckner <harry_b@eml.cc>
536 * @author Andreas Gohr <andi@splitbrain.org>
539 function io_runcmd($cmd){
540 $fh = popen($cmd, "r");
541 if(!$fh) return false;
544 $ret .= fread($fh, 8192);
551 * Runs an external command with input and output pipes.
552 * Returns the exit code from the process.
554 * @author Tom N Harris <tnharris@whoopdedo.org>
556 function io_exec($cmd, $input, &$output){
558 0=>array("pipe","r"),
559 1=>array("pipe","w"),
560 2=>array("pipe","w"));
561 $ph = proc_open($cmd, $descspec, $pipes);
563 fclose($pipes[2]); // ignore stderr
564 fwrite($pipes[0], $input);
566 $output = stream_get_contents($pipes[1]);
568 return proc_close($ph);
572 * Search a file for matching lines
574 * This is probably not faster than file()+preg_grep() but less
575 * memory intensive because not the whole file needs to be loaded
578 * @author Andreas Gohr <andi@splitbrain.org>
579 * @param string $file The file to search
580 * @param string $pattern PCRE pattern
581 * @param int $max How many lines to return (0 for all)
582 * @param bool $backref When true returns array with backreferences instead of lines
583 * @return array matching lines or backref, false on error
585 function io_grep($file,$pattern,$max=0,$backref=false){
586 $fh = @fopen($file,'r');
587 if(!$fh) return false;
593 $line .= fgets($fh, 4096); // read full line
594 if(substr($line,-1) != "\n") continue;
596 // check if line matches
597 if(preg_match($pattern,$line,$match)){
605 if($max && $max == $cnt) break;