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 // check if it's a hidden page 664 if(isHiddenPage($id)) return false; 665 666 // filter namespace 667 if (($ns) && (strpos($id,$ns.':') !== 0)) return false; 668 669 // exclude subnamespaces 670 if (($flags & RECENTS_SKIP_SUBSPACES) && (getNS($id) != $ns)) return false; 671 672 // check ACL 673 if (auth_quickaclcheck($id) < AUTH_READ) return false; 674 675 // check existance 676 if(!@file_exists(wikiFN($id))){ 677 if($flags & RECENTS_SKIP_DELETED){ 678 return false; 679 }else{ 680 $recent['del'] = true; 681 } 682 }else{ 683 $recent['del'] = false; 684 } 685 686 $recent['id'] = $id; 687 $recent['date'] = $dt; 688 $recent['ip'] = $ip; 689 $recent['user'] = $usr; 690 $recent['sum'] = $sum; 691 692 return $recent; 693} 694 695 696/** 697 * returns an array of recently changed files using the 698 * changelog 699 * 700 * The following constants can be used to control which changes are 701 * included. Add them together as needed. 702 * 703 * RECENTS_SKIP_DELETED - don't include deleted pages 704 * RECENTS_SKIP_MINORS - don't include minor changes 705 * RECENTS_SKIP_SUBSPACES - don't include subspaces 706 * 707 * @param int $first number of first entry returned (for paginating 708 * @param int $num return $num entries 709 * @param string $ns restrict to given namespace 710 * @param bool $flags see above 711 * 712 * @author Andreas Gohr <andi@splitbrain.org> 713 */ 714function getRecents($first,$num,$ns='',$flags=0){ 715 global $conf; 716 $recent = array(); 717 $count = 0; 718 719 if(!$num) 720 return $recent; 721 722 if(!@is_readable($conf['changelog'])){ 723 msg($conf['changelog'].' is not readable',-1); 724 return $recent; 725 } 726 727 $fh = fopen($conf['changelog'],'r'); 728 $buf = ''; 729 $csz = 4096; //chunksize 730 fseek($fh,0,SEEK_END); // jump to the end 731 $pos = ftell($fh); // position pointer 732 733 // now read backwards into buffer 734 while($pos > 0){ 735 $pos -= $csz; // seek to previous chunk... 736 if($pos < 0) $pos = 0; // ...or rest of file 737 fseek($fh,$pos); 738 739 $buf = fread($fh,$csz).$buf; // prepend to buffer 740 741 $lines = explode("\n",$buf); // split buffer into lines 742 743 if($pos > 0){ 744 $buf = array_shift($lines); // first one may be still incomplete 745 } 746 747 $cnt = count($lines); 748 if(!$cnt) continue; // no lines yet 749 750 // handle lines 751 for($i = $cnt-1; $i >= 0; $i--){ 752 $rec = _handleRecent($lines[$i],$ns,$flags); 753 if($rec !== false){ 754 if(--$first >= 0) continue; // skip first entries 755 $recent[] = $rec; 756 $count++; 757 758 // break while when we have enough entries 759 if($count >= $num){ 760 $pos = 0; // will break the while loop 761 break; // will break the for loop 762 } 763 } 764 } 765 }// end of while 766 767 fclose($fh); 768 return $recent; 769} 770 771/** 772 * gets additonal informations for a certain pagerevison 773 * from the changelog 774 * 775 * @author Andreas Gohr <andi@splitbrain.org> 776 */ 777function getRevisionInfo($id,$rev){ 778 global $conf; 779 780 if(!$rev) return(null); 781 782 $info = array(); 783 if(!@is_readable($conf['changelog'])){ 784 msg($conf['changelog'].' is not readable',-1); 785 return $recent; 786 } 787 $loglines = file($conf['changelog']); 788 $loglines = preg_grep("/$rev\t\d+\.\d+\.\d+\.\d+\t$id\t/",$loglines); 789 $loglines = array_reverse($loglines); //reverse sort on timestamp (shouldn't be needed) 790 $line = split("\t",$loglines[0]); 791 $info['date'] = $line[0]; 792 $info['ip'] = $line[1]; 793 $info['user'] = $line[3]; 794 $info['sum'] = $line[4]; 795 $info['minor'] = isMinor($info['sum']); 796 return $info; 797} 798 799/** 800 * Saves a wikitext by calling io_saveFile 801 * 802 * @author Andreas Gohr <andi@splitbrain.org> 803 */ 804function saveWikiText($id,$text,$summary,$minor=false){ 805 global $conf; 806 global $lang; 807 umask($conf['umask']); 808 // ignore if no changes were made 809 if($text == rawWiki($id,'')){ 810 return; 811 } 812 813 $file = wikiFN($id); 814 $old = saveOldRevision($id); 815 816 if (empty($text)){ 817 // remove empty file 818 @unlink($file); 819 // remove any meta info 820 $mfiles = metaFiles($id); 821 foreach ($mfiles as $mfile) { 822 if (file_exists($mfile)) @unlink($mfile); 823 } 824 $del = true; 825 //autoset summary on deletion 826 if(empty($summary)) $summary = $lang['deleted']; 827 //remove empty namespaces 828 io_sweepNS($id); 829 }else{ 830 // save file (datadir is created in io_saveFile) 831 io_saveFile($file,$text); 832 $del = false; 833 } 834 835 addLogEntry(@filemtime($file),$id,$summary,$minor); 836 // send notify mails 837 notify($id,'admin',$old,$summary,$minor); 838 notify($id,'subscribers',$old,$summary,$minor); 839 840 //purge cache on add by updating the purgefile 841 if($conf['purgeonadd'] && (!$old || $del)){ 842 io_saveFile($conf['cachedir'].'/purgefile',time()); 843 } 844} 845 846/** 847 * moves the current version to the attic and returns its 848 * revision date 849 * 850 * @author Andreas Gohr <andi@splitbrain.org> 851 */ 852function saveOldRevision($id){ 853 global $conf; 854 umask($conf['umask']); 855 $oldf = wikiFN($id); 856 if(!@file_exists($oldf)) return ''; 857 $date = filemtime($oldf); 858 $newf = wikiFN($id,$date); 859 if(substr($newf,-3)=='.gz'){ 860 io_saveFile($newf,rawWiki($id)); 861 }else{ 862 io_makeFileDir($newf); 863 copy($oldf, $newf); 864 } 865 return $date; 866} 867 868/** 869 * Sends a notify mail on page change 870 * 871 * @param string $id The changed page 872 * @param string $who Who to notify (admin|subscribers) 873 * @param int $rev Old page revision 874 * @param string $summary What changed 875 * @param boolean $minor Is this a minor edit? 876 * 877 * @author Andreas Gohr <andi@splitbrain.org> 878 */ 879function notify($id,$who,$rev='',$summary='',$minor=false){ 880 global $lang; 881 global $conf; 882 883 // decide if there is something to do 884 if($who == 'admin'){ 885 if(empty($conf['notify'])) return; //notify enabled? 886 $text = rawLocale('mailtext'); 887 $to = $conf['notify']; 888 $bcc = ''; 889 }elseif($who == 'subscribers'){ 890 if(!$conf['subscribers']) return; //subscribers enabled? 891 if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors 892 $bcc = subscriber_addresslist($id); 893 if(empty($bcc)) return; 894 $to = ''; 895 $text = rawLocale('subscribermail'); 896 }else{ 897 return; //just to be safe 898 } 899 900 $text = str_replace('@DATE@',date($conf['dformat']),$text); 901 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text); 902 $text = str_replace('@IPADDRESS@',$_SERVER['REMOTE_ADDR'],$text); 903 $text = str_replace('@HOSTNAME@',gethostbyaddr($_SERVER['REMOTE_ADDR']),$text); 904 $text = str_replace('@NEWPAGE@',wl($id,'',true),$text); 905 $text = str_replace('@PAGE@',$id,$text); 906 $text = str_replace('@TITLE@',$conf['title'],$text); 907 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 908 $text = str_replace('@SUMMARY@',$summary,$text); 909 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text); 910 911 if($rev){ 912 $subject = $lang['mail_changed'].' '.$id; 913 $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true),$text); 914 require_once(DOKU_INC.'inc/DifferenceEngine.php'); 915 $df = new Diff(split("\n",rawWiki($id,$rev)), 916 split("\n",rawWiki($id))); 917 $dformat = new UnifiedDiffFormatter(); 918 $diff = $dformat->format($df); 919 }else{ 920 $subject=$lang['mail_newpage'].' '.$id; 921 $text = str_replace('@OLDPAGE@','none',$text); 922 $diff = rawWiki($id); 923 } 924 $text = str_replace('@DIFF@',$diff,$text); 925 $subject = '['.$conf['title'].'] '.$subject; 926 927 mail_send($to,$subject,$text,$conf['mailfrom'],'',$bcc); 928} 929 930/** 931 * Return a list of available page revisons 932 * 933 * @author Andreas Gohr <andi@splitbrain.org> 934 */ 935function getRevisions($id){ 936 $revd = dirname(wikiFN($id,'foo')); 937 $revs = array(); 938 $clid = cleanID($id); 939 if(strrpos($clid,':')) $clid = substr($clid,strrpos($clid,':')+1); //remove path 940 $clid = utf8_encodeFN($clid); 941 942 if (is_dir($revd) && $dh = opendir($revd)) { 943 while (($file = readdir($dh)) !== false) { 944 if (is_dir($revd.'/'.$file)) continue; 945 if (preg_match('/^'.$clid.'\.(\d+)\.txt(\.gz)?$/',$file,$match)){ 946 $revs[]=$match[1]; 947 } 948 } 949 closedir($dh); 950 } 951 rsort($revs); 952 return $revs; 953} 954 955/** 956 * extracts the query from a google referer 957 * 958 * @todo should be more generic and support yahoo et al 959 * @author Andreas Gohr <andi@splitbrain.org> 960 */ 961function getGoogleQuery(){ 962 $url = parse_url($_SERVER['HTTP_REFERER']); 963 if(!$url) return ''; 964 965 if(!preg_match("#google\.#i",$url['host'])) return ''; 966 $query = array(); 967 parse_str($url['query'],$query); 968 969 return $query['q']; 970} 971 972/** 973 * Try to set correct locale 974 * 975 * @deprecated No longer used 976 * @author Andreas Gohr <andi@splitbrain.org> 977 */ 978function setCorrectLocale(){ 979 global $conf; 980 global $lang; 981 982 $enc = strtoupper($lang['encoding']); 983 foreach ($lang['locales'] as $loc){ 984 //try locale 985 if(@setlocale(LC_ALL,$loc)) return; 986 //try loceale with encoding 987 if(@setlocale(LC_ALL,"$loc.$enc")) return; 988 } 989 //still here? try to set from environment 990 @setlocale(LC_ALL,""); 991} 992 993/** 994 * Return the human readable size of a file 995 * 996 * @param int $size A file size 997 * @param int $dec A number of decimal places 998 * @author Martin Benjamin <b.martin@cybernet.ch> 999 * @author Aidan Lister <aidan@php.net> 1000 * @version 1.0.0 1001 */ 1002function filesize_h($size, $dec = 1){ 1003 $sizes = array('B', 'KB', 'MB', 'GB'); 1004 $count = count($sizes); 1005 $i = 0; 1006 1007 while ($size >= 1024 && ($i < $count - 1)) { 1008 $size /= 1024; 1009 $i++; 1010 } 1011 1012 return round($size, $dec) . ' ' . $sizes[$i]; 1013} 1014 1015/** 1016 * return an obfuscated email address in line with $conf['mailguard'] setting 1017 * 1018 * @author Harry Fuecks <hfuecks@gmail.com> 1019 * @author Christopher Smith <chris@jalakai.co.uk> 1020 */ 1021function obfuscate($email) { 1022 global $conf; 1023 1024 switch ($conf['mailguard']) { 1025 case 'visible' : 1026 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '); 1027 return strtr($email, $obfuscate); 1028 1029 case 'hex' : 1030 $encode = ''; 1031 for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';'; 1032 return $encode; 1033 1034 case 'none' : 1035 default : 1036 return $email; 1037 } 1038} 1039 1040/** 1041 * Return DokuWikis version 1042 * 1043 * @author Andreas Gohr <andi@splitbrain.org> 1044 */ 1045function getVersion(){ 1046 //import version string 1047 if(@file_exists('VERSION')){ 1048 //official release 1049 return 'Release '.trim(io_readfile(DOKU_INC.'/VERSION')); 1050 }elseif(is_dir('_darcs')){ 1051 //darcs checkout 1052 $inv = file('_darcs/inventory'); 1053 $inv = preg_grep('#\*\*\d{14}[\]$]#',$inv); 1054 $cur = array_pop($inv); 1055 preg_match('#\*\*(\d{4})(\d{2})(\d{2})#',$cur,$matches); 1056 return 'Darcs '.$matches[1].'-'.$matches[2].'-'.$matches[3]; 1057 }else{ 1058 return 'snapshot?'; 1059 } 1060} 1061 1062/** 1063 * Run a few sanity checks 1064 * 1065 * @author Andreas Gohr <andi@splitbrain.org> 1066 */ 1067function check(){ 1068 global $conf; 1069 global $INFO; 1070 1071 msg('DokuWiki version: '.getVersion(),1); 1072 1073 if(version_compare(phpversion(),'4.3.0','<')){ 1074 msg('Your PHP version is too old ('.phpversion().' vs. 4.3.+ recommended)',-1); 1075 }elseif(version_compare(phpversion(),'4.3.10','<')){ 1076 msg('Consider upgrading PHP to 4.3.10 or higher for security reasons (your version: '.phpversion().')',0); 1077 }else{ 1078 msg('PHP version '.phpversion(),1); 1079 } 1080 1081 if(is_writable($conf['changelog'])){ 1082 msg('Changelog is writable',1); 1083 }else{ 1084 msg('Changelog is not writable',-1); 1085 } 1086 1087 if(is_writable($conf['datadir'])){ 1088 msg('Datadir is writable',1); 1089 }else{ 1090 msg('Datadir is not writable',-1); 1091 } 1092 1093 if(is_writable($conf['olddir'])){ 1094 msg('Attic is writable',1); 1095 }else{ 1096 msg('Attic is not writable',-1); 1097 } 1098 1099 if(is_writable($conf['mediadir'])){ 1100 msg('Mediadir is writable',1); 1101 }else{ 1102 msg('Mediadir is not writable',-1); 1103 } 1104 1105 if(is_writable($conf['cachedir'])){ 1106 msg('Cachedir is writable',1); 1107 }else{ 1108 msg('Cachedir is not writable',-1); 1109 } 1110 1111 if(is_writable(DOKU_CONF.'users.auth.php')){ 1112 msg('conf/users.auth.php is writable',1); 1113 }else{ 1114 msg('conf/users.auth.php is not writable',0); 1115 } 1116 1117 if(function_exists('mb_strpos')){ 1118 if(defined('UTF8_NOMBSTRING')){ 1119 msg('mb_string extension is available but will not be used',0); 1120 }else{ 1121 msg('mb_string extension is available and will be used',1); 1122 } 1123 }else{ 1124 msg('mb_string extension not available - PHP only replacements will be used',0); 1125 } 1126 1127 if($conf['allowdebug']){ 1128 msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1); 1129 }else{ 1130 msg('Debugging support is disabled',1); 1131 } 1132 1133 msg('Your current permission for this page is '.$INFO['perm'],0); 1134 1135 if(is_writable($INFO['filepath'])){ 1136 msg('The current page is writable by the webserver',0); 1137 }else{ 1138 msg('The current page is not writable by the webserver',0); 1139 } 1140 1141 if($INFO['writable']){ 1142 msg('The current page is writable by you',0); 1143 }else{ 1144 msg('The current page is not writable you',0); 1145 } 1146} 1147 1148/** 1149 * Let us know if a user is tracking a page 1150 * 1151 * @author Andreas Gohr <andi@splitbrain.org> 1152 */ 1153function is_subscribed($id,$uid){ 1154 $file=metaFN($id,'.mlist'); 1155 if (@file_exists($file)) { 1156 $mlist = file($file); 1157 $pos = array_search($uid."\n",$mlist); 1158 return is_int($pos); 1159 } 1160 1161 return false; 1162} 1163 1164/** 1165 * Return a string with the email addresses of all the 1166 * users subscribed to a page 1167 * 1168 * @author Steven Danz <steven-danz@kc.rr.com> 1169 */ 1170function subscriber_addresslist($id){ 1171 global $conf; 1172 1173 $emails = ''; 1174 1175 if (!$conf['subscribers']) return; 1176 1177 $mlist = array(); 1178 $file=metaFN($id,'.mlist'); 1179 if (file_exists($file)) { 1180 $mlist = file($file); 1181 } 1182 if(count($mlist) > 0) { 1183 foreach ($mlist as $who) { 1184 $who = rtrim($who); 1185 $info = auth_getUserData($who); 1186 $level = auth_aclcheck($id,$who,$info['grps']); 1187 if ($level >= AUTH_READ) { 1188 if (strcasecmp($info['mail'],$conf['notify']) != 0) { 1189 if (empty($emails)) { 1190 $emails = $info['mail']; 1191 } else { 1192 $emails = "$emails,".$info['mail']; 1193 } 1194 } 1195 } 1196 } 1197 } 1198 1199 return $emails; 1200} 1201 1202/** 1203 * Removes quoting backslashes 1204 * 1205 * @author Andreas Gohr <andi@splitbrain.org> 1206 */ 1207function unslash($string,$char="'"){ 1208 return str_replace('\\'.$char,$char,$string); 1209} 1210 1211//Setup VIM: ex: et ts=2 enc=utf-8 : 1212