1<?php 2/** 3 * Common DokuWiki 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_CONF.'dokuwiki.php'); 11 require_once(DOKU_INC.'inc/io.php'); 12 require_once(DOKU_INC.'inc/utf8.php'); 13 require_once(DOKU_INC.'inc/mail.php'); 14 require_once(DOKU_INC.'inc/parserutils.php'); 15 16/** 17 * These constants are used with the recents function 18 */ 19define('RECENTS_SKIP_DELETED',2); 20define('RECENTS_SKIP_MINORS',4); 21define('RECENTS_SKIP_SUBSPACES',8); 22 23/** 24 * Return info about the current document as associative 25 * array. 26 * 27 * @author Andreas Gohr <andi@splitbrain.org> 28 */ 29function pageinfo(){ 30 global $ID; 31 global $REV; 32 global $USERINFO; 33 global $conf; 34 35 if($_SERVER['REMOTE_USER']){ 36 $info['userinfo'] = $USERINFO; 37 $info['perm'] = auth_quickaclcheck($ID); 38 $info['subscribed'] = is_subscribed($ID,$_SERVER['REMOTE_USER']); 39 40 // if some outside auth were used only REMOTE_USER is set 41 if(!$info['userinfo']['name']){ 42 $info['userinfo']['name'] = $_SERVER['REMOTE_USER']; 43 } 44 }else{ 45 $info['perm'] = auth_aclcheck($ID,'',null); 46 $info['subscribed'] = false; 47 } 48 49 $info['namespace'] = getNS($ID); 50 $info['locked'] = checklock($ID); 51 $info['filepath'] = realpath(wikiFN($ID,$REV)); 52 $info['exists'] = @file_exists($info['filepath']); 53 if($REV && !$info['exists']){ 54 //check if current revision was meant 55 $cur = wikiFN($ID); 56 if(@file_exists($cur) && (@filemtime($cur) == $REV)){ 57 $info['filepath'] = realpath($cur); 58 $info['exists'] = true; 59 $REV = ''; 60 } 61 } 62 $info['rev'] = $REV; 63 if($info['exists']){ 64 $info['writable'] = (is_writable($info['filepath']) && 65 ($info['perm'] >= AUTH_EDIT)); 66 }else{ 67 $info['writable'] = ($info['perm'] >= AUTH_CREATE); 68 } 69 $info['editable'] = ($info['writable'] && empty($info['lock'])); 70 $info['lastmod'] = @filemtime($info['filepath']); 71 72 //who's the editor 73 if($REV){ 74 $revinfo = getRevisionInfo($ID,$REV); 75 }else{ 76 $revinfo = getRevisionInfo($ID,$info['lastmod']); 77 } 78 $info['ip'] = $revinfo['ip']; 79 $info['user'] = $revinfo['user']; 80 $info['sum'] = $revinfo['sum']; 81 $info['minor'] = $revinfo['minor']; 82 83 if($revinfo['user']){ 84 $info['editor'] = $revinfo['user']; 85 }else{ 86 $info['editor'] = $revinfo['ip']; 87 } 88 89 return $info; 90} 91 92/** 93 * Build an string of URL parameters 94 * 95 * @author Andreas Gohr 96 */ 97function buildURLparams($params){ 98 $url = ''; 99 $amp = false; 100 foreach($params as $key => $val){ 101 if($amp) $url .= '&'; 102 103 $url .= $key.'='; 104 $url .= urlencode($val); 105 $amp = true; 106 } 107 return $url; 108} 109 110/** 111 * Build an string of html tag attributes 112 * 113 * @author Andreas Gohr 114 */ 115function buildAttributes($params){ 116 $url = ''; 117 foreach($params as $key => $val){ 118 $url .= $key.'="'; 119 $url .= htmlspecialchars ($val); 120 $url .= '" '; 121 } 122 return $url; 123} 124 125 126/** 127 * print a message 128 * 129 * If HTTP headers were not sent yet the message is added 130 * to the global message array else it's printed directly 131 * using html_msgarea() 132 * 133 * 134 * Levels can be: 135 * 136 * -1 error 137 * 0 info 138 * 1 success 139 * 140 * @author Andreas Gohr <andi@splitbrain.org> 141 * @see html_msgarea 142 */ 143function msg($message,$lvl=0){ 144 global $MSG; 145 $errors[-1] = 'error'; 146 $errors[0] = 'info'; 147 $errors[1] = 'success'; 148 149 if(!headers_sent()){ 150 if(!isset($MSG)) $MSG = array(); 151 $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message); 152 }else{ 153 $MSG = array(); 154 $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message); 155 if(function_exists('html_msgarea')){ 156 html_msgarea(); 157 }else{ 158 print "ERROR($lvl) $message"; 159 } 160 } 161} 162 163/** 164 * This builds the breadcrumb trail and returns it as array 165 * 166 * @author Andreas Gohr <andi@splitbrain.org> 167 */ 168function breadcrumbs(){ 169 // we prepare the breadcrumbs early for quick session closing 170 static $crumbs = null; 171 if($crumbs != null) return $crumbs; 172 173 global $ID; 174 global $ACT; 175 global $conf; 176 $crumbs = $_SESSION[$conf['title']]['bc']; 177 178 //first visit? 179 if (!is_array($crumbs)){ 180 $crumbs = array(); 181 } 182 //we only save on show and existing wiki documents 183 $file = wikiFN($ID); 184 if($ACT != 'show' || !@file_exists($file)){ 185 $_SESSION[$conf['title']]['bc'] = $crumbs; 186 return $crumbs; 187 } 188 189 // page names 190 $name = noNS($ID); 191 if ($conf['useheading']) { 192 // get page title 193 $title = p_get_first_heading($ID); 194 if ($title) { 195 $name = $title; 196 } 197 } 198 199 //remove ID from array 200 if (isset($crumbs[$ID])) { 201 unset($crumbs[$ID]); 202 } 203 204 //add to array 205 $crumbs[$ID] = $name; 206 //reduce size 207 while(count($crumbs) > $conf['breadcrumbs']){ 208 array_shift($crumbs); 209 } 210 //save to session 211 $_SESSION[$conf['title']]['bc'] = $crumbs; 212 return $crumbs; 213} 214 215/** 216 * Filter for page IDs 217 * 218 * This is run on a ID before it is outputted somewhere 219 * currently used to replace the colon with something else 220 * on Windows systems and to have proper URL encoding 221 * 222 * Urlencoding is ommitted when the second parameter is false 223 * 224 * @author Andreas Gohr <andi@splitbrain.org> 225 */ 226function idfilter($id,$ue=true){ 227 global $conf; 228 if ($conf['useslash'] && $conf['userewrite']){ 229 $id = strtr($id,':','/'); 230 }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && 231 $conf['userewrite']) { 232 $id = strtr($id,':',';'); 233 } 234 if($ue){ 235 $id = urlencode($id); 236 $id = str_replace('%3A',':',$id); //keep as colon 237 $id = str_replace('%2F','/',$id); //keep as slash 238 } 239 return $id; 240} 241 242/** 243 * This builds a link to a wikipage 244 * 245 * It handles URL rewriting and adds additional parameter if 246 * given in $more 247 * 248 * @author Andreas Gohr <andi@splitbrain.org> 249 */ 250function wl($id='',$more='',$abs=false){ 251 global $conf; 252 if(is_array($more)){ 253 $more = buildURLparams($more); 254 }else{ 255 $more = str_replace(',','&',$more); 256 } 257 258 $id = idfilter($id); 259 if($abs){ 260 $xlink = DOKU_URL; 261 }else{ 262 $xlink = DOKU_BASE; 263 } 264 265 if($conf['userewrite'] == 2){ 266 $xlink .= DOKU_SCRIPT.'/'.$id; 267 if($more) $xlink .= '?'.$more; 268 }elseif($conf['userewrite']){ 269 $xlink .= $id; 270 if($more) $xlink .= '?'.$more; 271 }else{ 272 $xlink .= DOKU_SCRIPT.'?id='.$id; 273 if($more) $xlink .= '&'.$more; 274 } 275 276 return $xlink; 277} 278 279/** 280 * Build a link to a media file 281 * 282 * Will return a link to the detail page if $direct is false 283 */ 284function ml($id='',$more='',$direct=true){ 285 global $conf; 286 if(is_array($more)){ 287 $more = buildURLparams($more); 288 }else{ 289 $more = str_replace(',','&',$more); 290 } 291 292 $xlink = DOKU_BASE; 293 294 // external URLs are always direct without rewriting 295 if(preg_match('#^(https?|ftp)://#i',$id)){ 296 $xlink .= 'lib/exe/fetch.php'; 297 if($more){ 298 $xlink .= '?'.$more; 299 $xlink .= '&media='.urlencode($id); 300 }else{ 301 $xlink .= '?media='.urlencode($id); 302 } 303 return $xlink; 304 } 305 306 $id = idfilter($id); 307 308 // decide on scriptname 309 if($direct){ 310 if($conf['userewrite'] == 1){ 311 $script = '_media'; 312 }else{ 313 $script = 'lib/exe/fetch.php'; 314 } 315 }else{ 316 if($conf['userewrite'] == 1){ 317 $script = '_detail'; 318 }else{ 319 $script = 'lib/exe/detail.php'; 320 } 321 } 322 323 // build URL based on rewrite mode 324 if($conf['userewrite']){ 325 $xlink .= $script.'/'.$id; 326 if($more) $xlink .= '?'.$more; 327 }else{ 328 if($more){ 329 $xlink .= $script.'?'.$more; 330 $xlink .= '&media='.$id; 331 }else{ 332 $xlink .= $script.'?media='.$id; 333 } 334 } 335 336 return $xlink; 337} 338 339 340 341/** 342 * Just builds a link to a script 343 * 344 * @todo maybe obsolete 345 * @author Andreas Gohr <andi@splitbrain.org> 346 */ 347function script($script='doku.php'){ 348# $link = getBaseURL(); 349# $link .= $script; 350# return $link; 351 return DOKU_BASE.DOKU_SCRIPT; 352} 353 354/** 355 * Spamcheck against wordlist 356 * 357 * Checks the wikitext against a list of blocked expressions 358 * returns true if the text contains any bad words 359 * 360 * @author Andreas Gohr <andi@splitbrain.org> 361 */ 362function checkwordblock(){ 363 global $TEXT; 364 global $conf; 365 366 if(!$conf['usewordblock']) return false; 367 368 $blockfile = file(DOKU_CONF.'wordblock.conf'); 369 //how many lines to read at once (to work around some PCRE limits) 370 if(version_compare(phpversion(),'4.3.0','<')){ 371 //old versions of PCRE define a maximum of parenthesises even if no 372 //backreferences are used - the maximum is 99 373 //this is very bad performancewise and may even be too high still 374 $chunksize = 40; 375 }else{ 376 //read file in chunks of 600 - this should work around the 377 //MAX_PATTERN_SIZE in modern PCRE 378 $chunksize = 600; 379 } 380 while($blocks = array_splice($blockfile,0,$chunksize)){ 381 $re = array(); 382 #build regexp from blocks 383 foreach($blocks as $block){ 384 $block = preg_replace('/#.*$/','',$block); 385 $block = trim($block); 386 if(empty($block)) continue; 387 $re[] = $block; 388 } 389 if(preg_match('#('.join('|',$re).')#si',$TEXT)) return true; 390 } 391 return false; 392} 393 394/** 395 * Return the IP of the client 396 * 397 * Honours X-Forwarded-For Proxy Headers 398 * 399 * @author Andreas Gohr <andi@splitbrain.org> 400 */ 401function clientIP(){ 402 $my = $_SERVER['REMOTE_ADDR']; 403 if($_SERVER['HTTP_X_FORWARDED_FOR']){ 404 $my .= ' ('.$_SERVER['HTTP_X_FORWARDED_FOR'].')'; 405 } 406 return $my; 407} 408 409/** 410 * Checks if a given page is currently locked. 411 * 412 * removes stale lockfiles 413 * 414 * @author Andreas Gohr <andi@splitbrain.org> 415 */ 416function checklock($id){ 417 global $conf; 418 $lock = wikiFN($id).'.lock'; 419 420 //no lockfile 421 if(!@file_exists($lock)) return false; 422 423 //lockfile expired 424 if((time() - filemtime($lock)) > $conf['locktime']){ 425 unlink($lock); 426 return false; 427 } 428 429 //my own lock 430 $ip = io_readFile($lock); 431 if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){ 432 return false; 433 } 434 435 return $ip; 436} 437 438/** 439 * Lock a page for editing 440 * 441 * @author Andreas Gohr <andi@splitbrain.org> 442 */ 443function lock($id){ 444 $lock = wikiFN($id).'.lock'; 445 if($_SERVER['REMOTE_USER']){ 446 io_saveFile($lock,$_SERVER['REMOTE_USER']); 447 }else{ 448 io_saveFile($lock,clientIP()); 449 } 450} 451 452/** 453 * Unlock a page if it was locked by the user 454 * 455 * @author Andreas Gohr <andi@splitbrain.org> 456 * @return bool true if a lock was removed 457 */ 458function unlock($id){ 459 $lock = wikiFN($id).'.lock'; 460 if(@file_exists($lock)){ 461 $ip = io_readFile($lock); 462 if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){ 463 @unlink($lock); 464 return true; 465 } 466 } 467 return false; 468} 469 470/** 471 * convert line ending to unix format 472 * 473 * @see formText() for 2crlf conversion 474 * @author Andreas Gohr <andi@splitbrain.org> 475 */ 476function cleanText($text){ 477 $text = preg_replace("/(\015\012)|(\015)/","\012",$text); 478 return $text; 479} 480 481/** 482 * Prepares text for print in Webforms by encoding special chars. 483 * It also converts line endings to Windows format which is 484 * pseudo standard for webforms. 485 * 486 * @see cleanText() for 2unix conversion 487 * @author Andreas Gohr <andi@splitbrain.org> 488 */ 489function formText($text){ 490 $text = preg_replace("/\012/","\015\012",$text); 491 return htmlspecialchars($text); 492} 493 494/** 495 * Returns the specified local text in raw format 496 * 497 * @author Andreas Gohr <andi@splitbrain.org> 498 */ 499function rawLocale($id){ 500 return io_readFile(localeFN($id)); 501} 502 503/** 504 * Returns the raw WikiText 505 * 506 * @author Andreas Gohr <andi@splitbrain.org> 507 */ 508function rawWiki($id,$rev=''){ 509 return io_readFile(wikiFN($id,$rev)); 510} 511 512/** 513 * Returns the pagetemplate contents for the ID's namespace 514 * 515 * @author Andreas Gohr <andi@splitbrain.org> 516 */ 517function pageTemplate($id){ 518 global $conf; 519 global $INFO; 520 $tpl = io_readFile(dirname(wikiFN($id)).'/_template.txt'); 521 $tpl = str_replace('@ID@',$id,$tpl); 522 $tpl = str_replace('@NS@',getNS($id),$tpl); 523 $tpl = str_replace('@PAGE@',strtr(noNS($id),'_',' '),$tpl); 524 $tpl = str_replace('@USER@',$_SERVER['REMOTE_USER'],$tpl); 525 $tpl = str_replace('@NAME@',$INFO['userinfo']['name'],$tpl); 526 $tpl = str_replace('@MAIL@',$INFO['userinfo']['mail'],$tpl); 527 $tpl = str_replace('@DATE@',date($conf['dformat']),$tpl); 528 return $tpl; 529} 530 531 532/** 533 * Returns the raw Wiki Text in three slices. 534 * 535 * The range parameter needs to have the form "from-to" 536 * and gives the range of the section in bytes - no 537 * UTF-8 awareness is needed. 538 * The returned order is prefix, section and suffix. 539 * 540 * @author Andreas Gohr <andi@splitbrain.org> 541 */ 542function rawWikiSlices($range,$id,$rev=''){ 543 list($from,$to) = split('-',$range,2); 544 $text = io_readFile(wikiFN($id,$rev)); 545 if(!$from) $from = 0; 546 if(!$to) $to = strlen($text)+1; 547 548 $slices[0] = substr($text,0,$from-1); 549 $slices[1] = substr($text,$from-1,$to-$from); 550 $slices[2] = substr($text,$to); 551 552 return $slices; 553} 554 555/** 556 * Joins wiki text slices 557 * 558 * function to join the text slices with correct lineendings again. 559 * When the pretty parameter is set to true it adds additional empty 560 * lines between sections if needed (used on saving). 561 * 562 * @author Andreas Gohr <andi@splitbrain.org> 563 */ 564function con($pre,$text,$suf,$pretty=false){ 565 566 if($pretty){ 567 if($pre && substr($pre,-1) != "\n") $pre .= "\n"; 568 if($suf && substr($text,-1) != "\n") $text .= "\n"; 569 } 570 571 if($pre) $pre .= "\n"; 572 if($suf) $text .= "\n"; 573 return $pre.$text.$suf; 574} 575 576/** 577 * print debug messages 578 * 579 * little function to print the content of a var 580 * 581 * @author Andreas Gohr <andi@splitbrain.org> 582 */ 583function dbg($msg,$hidden=false){ 584 (!$hidden) ? print '<pre class="dbg">' : print "<!--\n"; 585 print_r($msg); 586 (!$hidden) ? print '</pre>' : print "\n-->"; 587} 588 589/** 590 * Add's an entry to the changelog 591 * 592 * @author Andreas Gohr <andi@splitbrain.org> 593 */ 594function addLogEntry($date,$id,$summary='',$minor=false){ 595 global $conf; 596 597 if(!@is_writable($conf['changelog'])){ 598 msg($conf['changelog'].' is not writable!',-1); 599 return; 600 } 601 602 if(!$date) $date = time(); //use current time if none supplied 603 $remote = $_SERVER['REMOTE_ADDR']; 604 $user = $_SERVER['REMOTE_USER']; 605 606 if($conf['useacl'] && $user && $minor){ 607 $summary = '*'.$summary; 608 }else{ 609 $summary = ' '.$summary; 610 } 611 612 $logline = join("\t",array($date,$remote,$id,$user,$summary))."\n"; 613 io_saveFile($conf['changelog'],$logline,true); 614} 615 616/** 617 * Checks an summary entry if it was a minor edit 618 * 619 * The summary is cleaned of the marker char 620 * 621 * @author Andreas Gohr <andi@splitbrain.org> 622 */ 623function isMinor(&$summary){ 624 if(substr($summary,0,1) == '*'){ 625 $summary = substr($summary,1); 626 return true; 627 } 628 $summary = trim($summary); 629 return false; 630} 631 632/** 633 * Internal function used by getRecents 634 * 635 * don't call directly 636 * 637 * @see getRecents() 638 * @author Andreas Gohr <andi@splitbrain.org> 639 */ 640function _handleRecent($line,$ns,$flags){ 641 static $seen = array(); //caches seen pages and skip them 642 if(empty($line)) return false; //skip empty lines 643 644 // split the line into parts 645 list($dt,$ip,$id,$usr,$sum) = explode("\t",$line); 646 647 // skip seen ones 648 if($seen[$id]) return false; 649 $recent = array(); 650 651 // check minors 652 if(isMinor($sum)){ 653 // skip minors 654 if($flags & RECENTS_SKIP_MINORS) return false; 655 $recent['minor'] = true; 656 }else{ 657 $recent['minor'] = false; 658 } 659 660 // remember in seen to skip additional sights 661 $seen[$id] = 1; 662 663 // filter namespace 664 if (($ns) && (strpos($id,$ns.':') !== 0)) return false; 665 666 // exclude subnamespaces 667 if (($flags & RECENTS_SKIP_SUBSPACES) && (getNS($id) != $ns)) return false; 668 669 // check ACL 670 if (auth_quickaclcheck($id) < AUTH_READ) return false; 671 672 // check existance 673 if(!@file_exists(wikiFN($id))){ 674 if($flags & RECENTS_SKIP_DELETED){ 675 return false; 676 }else{ 677 $recent['del'] = true; 678 } 679 }else{ 680 $recent['del'] = false; 681 } 682 683 $recent['id'] = $id; 684 $recent['date'] = $dt; 685 $recent['ip'] = $ip; 686 $recent['user'] = $usr; 687 $recent['sum'] = $sum; 688 689 return $recent; 690} 691 692 693/** 694 * returns an array of recently changed files using the 695 * changelog 696 * 697 * The following constants can be used to control which changes are 698 * included. Add them together as needed. 699 * 700 * RECENTS_SKIP_DELETED - don't include deleted pages 701 * RECENTS_SKIP_MINORS - don't include minor changes 702 * RECENTS_SKIP_SUBSPACES - don't include subspaces 703 * 704 * @param int $first number of first entry returned (for paginating 705 * @param int $num return $num entries 706 * @param string $ns restrict to given namespace 707 * @param bool $flags see above 708 * 709 * @author Andreas Gohr <andi@splitbrain.org> 710 */ 711function getRecents($first,$num,$ns='',$flags=0){ 712 global $conf; 713 $recent = array(); 714 $count = 0; 715 716 if(!$num) 717 return $recent; 718 719 if(!@is_readable($conf['changelog'])){ 720 msg($conf['changelog'].' is not readable',-1); 721 return $recent; 722 } 723 724 $fh = fopen($conf['changelog'],'r'); 725 $buf = ''; 726 $csz = 4096; //chunksize 727 fseek($fh,0,SEEK_END); // jump to the end 728 $pos = ftell($fh); // position pointer 729 730 // now read backwards into buffer 731 while($pos > 0){ 732 $pos -= $csz; // seek to previous chunk... 733 if($pos < 0) $pos = 0; // ...or rest of file 734 fseek($fh,$pos); 735 736 $buf = fread($fh,$csz).$buf; // prepend to buffer 737 738 $lines = explode("\n",$buf); // split buffer into lines 739 740 if($pos > 0){ 741 $buf = array_shift($lines); // first one may be still incomplete 742 } 743 744 $cnt = count($lines); 745 if(!$cnt) continue; // no lines yet 746 747 // handle lines 748 for($i = $cnt-1; $i >= 0; $i--){ 749 $rec = _handleRecent($lines[$i],$ns,$flags); 750 if($rec !== false){ 751 if(--$first >= 0) continue; // skip first entries 752 $recent[] = $rec; 753 $count++; 754 755 // break while when we have enough entries 756 if($count >= $num){ 757 $pos = 0; // will break the while loop 758 break; // will break the for loop 759 } 760 } 761 } 762 }// end of while 763 764 fclose($fh); 765 return $recent; 766} 767 768/** 769 * gets additonal informations for a certain pagerevison 770 * from the changelog 771 * 772 * @author Andreas Gohr <andi@splitbrain.org> 773 */ 774function getRevisionInfo($id,$rev){ 775 global $conf; 776 777 if(!$rev) return(null); 778 779 $info = array(); 780 if(!@is_readable($conf['changelog'])){ 781 msg($conf['changelog'].' is not readable',-1); 782 return $recent; 783 } 784 $loglines = file($conf['changelog']); 785 $loglines = preg_grep("/$rev\t\d+\.\d+\.\d+\.\d+\t$id\t/",$loglines); 786 $loglines = array_reverse($loglines); //reverse sort on timestamp (shouldn't be needed) 787 $line = split("\t",$loglines[0]); 788 $info['date'] = $line[0]; 789 $info['ip'] = $line[1]; 790 $info['user'] = $line[3]; 791 $info['sum'] = $line[4]; 792 $info['minor'] = isMinor($info['sum']); 793 return $info; 794} 795 796/** 797 * Saves a wikitext by calling io_saveFile 798 * 799 * @author Andreas Gohr <andi@splitbrain.org> 800 */ 801function saveWikiText($id,$text,$summary,$minor=false){ 802 global $conf; 803 global $lang; 804 umask($conf['umask']); 805 // ignore if no changes were made 806 if($text == rawWiki($id,'')){ 807 return; 808 } 809 810 $file = wikiFN($id); 811 $old = saveOldRevision($id); 812 813 if (empty($text)){ 814 // remove empty file 815 @unlink($file); 816 // remove any meta info 817 $mfiles = metaFiles($id); 818 foreach ($mfiles as $mfile) { 819 if (file_exists($mfile)) @unlink($mfile); 820 } 821 $del = true; 822 //autoset summary on deletion 823 if(empty($summary)) $summary = $lang['deleted']; 824 //remove empty namespaces 825 io_sweepNS($id); 826 }else{ 827 // save file (datadir is created in io_saveFile) 828 io_saveFile($file,$text); 829 $del = false; 830 } 831 832 addLogEntry(@filemtime($file),$id,$summary,$minor); 833 // send notify mails 834 notify($id,'admin',$old,$summary,$minor); 835 notify($id,'subscribers',$old,$summary,$minor); 836 837 //purge cache on add by updating the purgefile 838 if($conf['purgeonadd'] && (!$old || $del)){ 839 io_saveFile($conf['cachedir'].'/purgefile',time()); 840 } 841} 842 843/** 844 * moves the current version to the attic and returns its 845 * revision date 846 * 847 * @author Andreas Gohr <andi@splitbrain.org> 848 */ 849function saveOldRevision($id){ 850 global $conf; 851 umask($conf['umask']); 852 $oldf = wikiFN($id); 853 if(!@file_exists($oldf)) return ''; 854 $date = filemtime($oldf); 855 $newf = wikiFN($id,$date); 856 if(substr($newf,-3)=='.gz'){ 857 io_saveFile($newf,rawWiki($id)); 858 }else{ 859 io_makeFileDir($newf); 860 copy($oldf, $newf); 861 } 862 return $date; 863} 864 865/** 866 * Sends a notify mail on page change 867 * 868 * @param string $id The changed page 869 * @param string $who Who to notify (admin|subscribers) 870 * @param int $rev Old page revision 871 * @param string $summary What changed 872 * @param boolean $minor Is this a minor edit? 873 * 874 * @author Andreas Gohr <andi@splitbrain.org> 875 */ 876function notify($id,$who,$rev='',$summary='',$minor=false){ 877 global $lang; 878 global $conf; 879 880 // decide if there is something to do 881 if($who == 'admin'){ 882 if(empty($conf['notify'])) return; //notify enabled? 883 $text = rawLocale('mailtext'); 884 $to = $conf['notify']; 885 $bcc = ''; 886 }elseif($who == 'subscribers'){ 887 if(!$conf['subscribers']) return; //subscribers enabled? 888 if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors 889 $bcc = subscriber_addresslist($id); 890 if(empty($bcc)) return; 891 $to = ''; 892 $text = rawLocale('subscribermail'); 893 }else{ 894 return; //just to be safe 895 } 896 897 $text = str_replace('@DATE@',date($conf['dformat']),$text); 898 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text); 899 $text = str_replace('@IPADDRESS@',$_SERVER['REMOTE_ADDR'],$text); 900 $text = str_replace('@HOSTNAME@',gethostbyaddr($_SERVER['REMOTE_ADDR']),$text); 901 $text = str_replace('@NEWPAGE@',wl($id,'',true),$text); 902 $text = str_replace('@PAGE@',$id,$text); 903 $text = str_replace('@TITLE@',$conf['title'],$text); 904 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 905 $text = str_replace('@SUMMARY@',$summary,$text); 906 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text); 907 908 if($rev){ 909 $subject = $lang['mail_changed'].' '.$id; 910 $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true),$text); 911 require_once("inc/DifferenceEngine.php"); 912 $df = new Diff(split("\n",rawWiki($id,$rev)), 913 split("\n",rawWiki($id))); 914 $dformat = new UnifiedDiffFormatter(); 915 $diff = $dformat->format($df); 916 }else{ 917 $subject=$lang['mail_newpage'].' '.$id; 918 $text = str_replace('@OLDPAGE@','none',$text); 919 $diff = rawWiki($id); 920 } 921 $text = str_replace('@DIFF@',$diff,$text); 922 $subject = '['.$conf['title'].'] '.$subject; 923 924 mail_send($to,$subject,$text,$conf['mailfrom'],'',$bcc); 925} 926 927/** 928 * Return a list of available page revisons 929 * 930 * @author Andreas Gohr <andi@splitbrain.org> 931 */ 932function getRevisions($id){ 933 $revd = dirname(wikiFN($id,'foo')); 934 $revs = array(); 935 $clid = cleanID($id); 936 if(strrpos($clid,':')) $clid = substr($clid,strrpos($clid,':')+1); //remove path 937 $clid = utf8_encodeFN($clid); 938 939 if (is_dir($revd) && $dh = opendir($revd)) { 940 while (($file = readdir($dh)) !== false) { 941 if (is_dir($revd.'/'.$file)) continue; 942 if (preg_match('/^'.$clid.'\.(\d+)\.txt(\.gz)?$/',$file,$match)){ 943 $revs[]=$match[1]; 944 } 945 } 946 closedir($dh); 947 } 948 rsort($revs); 949 return $revs; 950} 951 952/** 953 * extracts the query from a google referer 954 * 955 * @todo should be more generic and support yahoo et al 956 * @author Andreas Gohr <andi@splitbrain.org> 957 */ 958function getGoogleQuery(){ 959 $url = parse_url($_SERVER['HTTP_REFERER']); 960 if(!$url) return ''; 961 962 if(!preg_match("#google\.#i",$url['host'])) return ''; 963 $query = array(); 964 parse_str($url['query'],$query); 965 966 return $query['q']; 967} 968 969/** 970 * Try to set correct locale 971 * 972 * @deprecated No longer used 973 * @author Andreas Gohr <andi@splitbrain.org> 974 */ 975function setCorrectLocale(){ 976 global $conf; 977 global $lang; 978 979 $enc = strtoupper($lang['encoding']); 980 foreach ($lang['locales'] as $loc){ 981 //try locale 982 if(@setlocale(LC_ALL,$loc)) return; 983 //try loceale with encoding 984 if(@setlocale(LC_ALL,"$loc.$enc")) return; 985 } 986 //still here? try to set from environment 987 @setlocale(LC_ALL,""); 988} 989 990/** 991 * Return the human readable size of a file 992 * 993 * @param int $size A file size 994 * @param int $dec A number of decimal places 995 * @author Martin Benjamin <b.martin@cybernet.ch> 996 * @author Aidan Lister <aidan@php.net> 997 * @version 1.0.0 998 */ 999function filesize_h($size, $dec = 1){ 1000 $sizes = array('B', 'KB', 'MB', 'GB'); 1001 $count = count($sizes); 1002 $i = 0; 1003 1004 while ($size >= 1024 && ($i < $count - 1)) { 1005 $size /= 1024; 1006 $i++; 1007 } 1008 1009 return round($size, $dec) . ' ' . $sizes[$i]; 1010} 1011 1012/** 1013 * return an obfuscated email address in line with $conf['mailguard'] setting 1014 * 1015 * @author Harry Fuecks <hfuecks@gmail.com> 1016 * @author Christopher Smith <chris@jalakai.co.uk> 1017 */ 1018function obfuscate($email) { 1019 global $conf; 1020 1021 switch ($conf['mailguard']) { 1022 case 'visible' : 1023 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '); 1024 return strtr($email, $obfuscate); 1025 1026 case 'hex' : 1027 $encode = ''; 1028 for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';'; 1029 return $encode; 1030 1031 case 'none' : 1032 default : 1033 return $email; 1034 } 1035} 1036 1037/** 1038 * Return DokuWikis version 1039 * 1040 * @author Andreas Gohr <andi@splitbrain.org> 1041 */ 1042function getVersion(){ 1043 //import version string 1044 if(@file_exists('VERSION')){ 1045 //official release 1046 return 'Release '.trim(io_readfile(DOKU_INC.'/VERSION')); 1047 }elseif(is_dir('_darcs')){ 1048 //darcs checkout 1049 $inv = file('_darcs/inventory'); 1050 $inv = preg_grep('#andi@splitbrain\.org\*\*\d{14}#',$inv); 1051 $cur = array_pop($inv); 1052 preg_match('#\*\*(\d{4})(\d{2})(\d{2})#',$cur,$matches); 1053 return 'Darcs '.$matches[1].'-'.$matches[2].'-'.$matches[3]; 1054 }else{ 1055 return 'snapshot?'; 1056 } 1057} 1058 1059/** 1060 * Run a few sanity checks 1061 * 1062 * @author Andreas Gohr <andi@splitbrain.org> 1063 */ 1064function check(){ 1065 global $conf; 1066 global $INFO; 1067 1068 msg('DokuWiki version: '.getVersion(),1); 1069 1070 if(version_compare(phpversion(),'4.3.0','<')){ 1071 msg('Your PHP version is too old ('.phpversion().' vs. 4.3.+ recommended)',-1); 1072 }elseif(version_compare(phpversion(),'4.3.10','<')){ 1073 msg('Consider upgrading PHP to 4.3.10 or higher for security reasons (your version: '.phpversion().')',0); 1074 }else{ 1075 msg('PHP version '.phpversion(),1); 1076 } 1077 1078 if(is_writable($conf['changelog'])){ 1079 msg('Changelog is writable',1); 1080 }else{ 1081 msg('Changelog is not writable',-1); 1082 } 1083 1084 if(is_writable($conf['datadir'])){ 1085 msg('Datadir is writable',1); 1086 }else{ 1087 msg('Datadir is not writable',-1); 1088 } 1089 1090 if(is_writable($conf['olddir'])){ 1091 msg('Attic is writable',1); 1092 }else{ 1093 msg('Attic is not writable',-1); 1094 } 1095 1096 if(is_writable($conf['mediadir'])){ 1097 msg('Mediadir is writable',1); 1098 }else{ 1099 msg('Mediadir is not writable',-1); 1100 } 1101 1102 if(is_writable($conf['cachedir'])){ 1103 msg('Cachedir is writable',1); 1104 }else{ 1105 msg('Cachedir is not writable',-1); 1106 } 1107 1108 if(is_writable(DOKU_CONF.'users.auth.php')){ 1109 msg('conf/users.auth.php is writable',1); 1110 }else{ 1111 msg('conf/users.auth.php is not writable',0); 1112 } 1113 1114 if(function_exists('mb_strpos')){ 1115 if(defined('UTF8_NOMBSTRING')){ 1116 msg('mb_string extension is available but will not be used',0); 1117 }else{ 1118 msg('mb_string extension is available and will be used',1); 1119 } 1120 }else{ 1121 msg('mb_string extension not available - PHP only replacements will be used',0); 1122 } 1123 1124 msg('Your current permission for this page is '.$INFO['perm'],0); 1125 1126 if(is_writable($INFO['filepath'])){ 1127 msg('The current page is writable by the webserver',0); 1128 }else{ 1129 msg('The current page is not writable by the webserver',0); 1130 } 1131 1132 if($INFO['writable']){ 1133 msg('The current page is writable by you',0); 1134 }else{ 1135 msg('The current page is not writable you',0); 1136 } 1137} 1138 1139/** 1140 * Let us know if a user is tracking a page 1141 * 1142 * @author Andreas Gohr <andi@splitbrain.org> 1143 */ 1144function is_subscribed($id,$uid){ 1145 $file=metaFN($id,'.mlist'); 1146 if (@file_exists($file)) { 1147 $mlist = file($file); 1148 $pos = array_search($uid."\n",$mlist); 1149 return is_int($pos); 1150 } 1151 1152 return false; 1153} 1154 1155/** 1156 * Return a string with the email addresses of all the 1157 * users subscribed to a page 1158 * 1159 * @author Steven Danz <steven-danz@kc.rr.com> 1160 */ 1161function subscriber_addresslist($id){ 1162 global $conf; 1163 1164 $emails = ''; 1165 1166 if (!$conf['subscribers']) return; 1167 1168 $mlist = array(); 1169 $file=metaFN($id,'.mlist'); 1170 if (file_exists($file)) { 1171 $mlist = file($file); 1172 } 1173 if(count($mlist) > 0) { 1174 foreach ($mlist as $who) { 1175 $who = rtrim($who); 1176 $info = auth_getUserData($who); 1177 $level = auth_aclcheck($id,$who,$info['grps']); 1178 if ($level >= AUTH_READ) { 1179 if (strcasecmp($info['mail'],$conf['notify']) != 0) { 1180 if (empty($emails)) { 1181 $emails = $info['mail']; 1182 } else { 1183 $emails = "$emails,".$info['mail']; 1184 } 1185 } 1186 } 1187 } 1188 } 1189 1190 return $emails; 1191} 1192 1193/** 1194 * Removes quoting backslashes 1195 * 1196 * @author Andreas Gohr <andi@splitbrain.org> 1197 */ 1198function unslash($string,$char="'"){ 1199 return str_replace('\\'.$char,$char,$string); 1200} 1201 1202//Setup VIM: ex: et ts=2 enc=utf-8 : 1203