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 9if(!defined('DOKU_INC')) die('meh.'); 10require_once(DOKU_INC.'inc/io.php'); 11require_once(DOKU_INC.'inc/changelog.php'); 12require_once(DOKU_INC.'inc/utf8.php'); 13require_once(DOKU_INC.'inc/mail.php'); 14require_once(DOKU_INC.'inc/parserutils.php'); 15require_once(DOKU_INC.'inc/infoutils.php'); 16 17/** 18 * These constants are used with the recents function 19 */ 20define('RECENTS_SKIP_DELETED',2); 21define('RECENTS_SKIP_MINORS',4); 22define('RECENTS_SKIP_SUBSPACES',8); 23define('RECENTS_MEDIA_CHANGES',16); 24 25/** 26 * Wrapper around htmlspecialchars() 27 * 28 * @author Andreas Gohr <andi@splitbrain.org> 29 * @see htmlspecialchars() 30 */ 31function hsc($string){ 32 return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); 33} 34 35/** 36 * print a newline terminated string 37 * 38 * You can give an indention as optional parameter 39 * 40 * @author Andreas Gohr <andi@splitbrain.org> 41 */ 42function ptln($string,$indent=0){ 43 echo str_repeat(' ', $indent)."$string\n"; 44} 45 46/** 47 * strips control characters (<32) from the given string 48 * 49 * @author Andreas Gohr <andi@splitbrain.org> 50 */ 51function stripctl($string){ 52 return preg_replace('/[\x00-\x1F]+/s','',$string); 53} 54 55/** 56 * Return a secret token to be used for CSRF attack prevention 57 * 58 * @author Andreas Gohr <andi@splitbrain.org> 59 * @link http://en.wikipedia.org/wiki/Cross-site_request_forgery 60 * @link http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html 61 * @return string 62 */ 63function getSecurityToken(){ 64 return md5(auth_cookiesalt().session_id()); 65} 66 67/** 68 * Check the secret CSRF token 69 */ 70function checkSecurityToken($token=null){ 71 if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check 72 73 if(is_null($token)) $token = $_REQUEST['sectok']; 74 if(getSecurityToken() != $token){ 75 msg('Security Token did not match. Possible CSRF attack.',-1); 76 return false; 77 } 78 return true; 79} 80 81/** 82 * Print a hidden form field with a secret CSRF token 83 * 84 * @author Andreas Gohr <andi@splitbrain.org> 85 */ 86function formSecurityToken($print=true){ 87 $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n"; 88 if($print){ 89 echo $ret; 90 }else{ 91 return $ret; 92 } 93} 94 95/** 96 * Return info about the current document as associative 97 * array. 98 * 99 * @author Andreas Gohr <andi@splitbrain.org> 100 */ 101function pageinfo(){ 102 global $ID; 103 global $REV; 104 global $RANGE; 105 global $USERINFO; 106 global $conf; 107 global $lang; 108 109 // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml 110 // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary 111 $info['id'] = $ID; 112 $info['rev'] = $REV; 113 114 // set info about manager/admin status. 115 $info['isadmin'] = false; 116 $info['ismanager'] = false; 117 if(isset($_SERVER['REMOTE_USER'])){ 118 $info['userinfo'] = $USERINFO; 119 $info['perm'] = auth_quickaclcheck($ID); 120 $info['subscribed'] = is_subscribed($ID,$_SERVER['REMOTE_USER'],false); 121 $info['subscribedns'] = is_subscribed($ID,$_SERVER['REMOTE_USER'],true); 122 $info['client'] = $_SERVER['REMOTE_USER']; 123 124 if($info['perm'] == AUTH_ADMIN){ 125 $info['isadmin'] = true; 126 $info['ismanager'] = true; 127 }elseif(auth_ismanager()){ 128 $info['ismanager'] = true; 129 } 130 131 // if some outside auth were used only REMOTE_USER is set 132 if(!$info['userinfo']['name']){ 133 $info['userinfo']['name'] = $_SERVER['REMOTE_USER']; 134 } 135 136 }else{ 137 $info['perm'] = auth_aclcheck($ID,'',null); 138 $info['subscribed'] = false; 139 $info['client'] = clientIP(true); 140 } 141 142 $info['namespace'] = getNS($ID); 143 $info['locked'] = checklock($ID); 144 $info['filepath'] = fullpath(wikiFN($ID)); 145 $info['exists'] = @file_exists($info['filepath']); 146 if($REV){ 147 //check if current revision was meant 148 if($info['exists'] && (@filemtime($info['filepath'])==$REV)){ 149 $REV = ''; 150 }elseif($RANGE){ 151 //section editing does not work with old revisions! 152 $REV = ''; 153 $RANGE = ''; 154 msg($lang['nosecedit'],0); 155 }else{ 156 //really use old revision 157 $info['filepath'] = fullpath(wikiFN($ID,$REV)); 158 $info['exists'] = @file_exists($info['filepath']); 159 } 160 } 161 $info['rev'] = $REV; 162 if($info['exists']){ 163 $info['writable'] = (is_writable($info['filepath']) && 164 ($info['perm'] >= AUTH_EDIT)); 165 }else{ 166 $info['writable'] = ($info['perm'] >= AUTH_CREATE); 167 } 168 $info['editable'] = ($info['writable'] && empty($info['lock'])); 169 $info['lastmod'] = @filemtime($info['filepath']); 170 171 //load page meta data 172 $info['meta'] = p_get_metadata($ID); 173 174 //who's the editor 175 if($REV){ 176 $revinfo = getRevisionInfo($ID, $REV, 1024); 177 }else{ 178 if (is_array($info['meta']['last_change'])) { 179 $revinfo = $info['meta']['last_change']; 180 } else { 181 $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024); 182 // cache most recent changelog line in metadata if missing and still valid 183 if ($revinfo!==false) { 184 $info['meta']['last_change'] = $revinfo; 185 p_set_metadata($ID, array('last_change' => $revinfo)); 186 } 187 } 188 } 189 //and check for an external edit 190 if($revinfo!==false && $revinfo['date']!=$info['lastmod']){ 191 // cached changelog line no longer valid 192 $revinfo = false; 193 $info['meta']['last_change'] = $revinfo; 194 p_set_metadata($ID, array('last_change' => $revinfo)); 195 } 196 197 $info['ip'] = $revinfo['ip']; 198 $info['user'] = $revinfo['user']; 199 $info['sum'] = $revinfo['sum']; 200 // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID. 201 // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor']. 202 203 if($revinfo['user']){ 204 $info['editor'] = $revinfo['user']; 205 }else{ 206 $info['editor'] = $revinfo['ip']; 207 } 208 209 // draft 210 $draft = getCacheName($info['client'].$ID,'.draft'); 211 if(@file_exists($draft)){ 212 if(@filemtime($draft) < @filemtime(wikiFN($ID))){ 213 // remove stale draft 214 @unlink($draft); 215 }else{ 216 $info['draft'] = $draft; 217 } 218 } 219 220 // mobile detection 221 $info['ismobile'] = clientismobile(); 222 223 return $info; 224} 225 226/** 227 * Build an string of URL parameters 228 * 229 * @author Andreas Gohr 230 */ 231function buildURLparams($params, $sep='&'){ 232 $url = ''; 233 $amp = false; 234 foreach($params as $key => $val){ 235 if($amp) $url .= $sep; 236 237 $url .= $key.'='; 238 $url .= rawurlencode((string)$val); 239 $amp = true; 240 } 241 return $url; 242} 243 244/** 245 * Build an string of html tag attributes 246 * 247 * Skips keys starting with '_', values get HTML encoded 248 * 249 * @author Andreas Gohr 250 */ 251function buildAttributes($params,$skipempty=false){ 252 $url = ''; 253 foreach($params as $key => $val){ 254 if($key{0} == '_') continue; 255 if($val === '' && $skipempty) continue; 256 257 $url .= $key.'="'; 258 $url .= htmlspecialchars ($val); 259 $url .= '" '; 260 } 261 return $url; 262} 263 264 265/** 266 * This builds the breadcrumb trail and returns it as array 267 * 268 * @author Andreas Gohr <andi@splitbrain.org> 269 */ 270function breadcrumbs(){ 271 // we prepare the breadcrumbs early for quick session closing 272 static $crumbs = null; 273 if($crumbs != null) return $crumbs; 274 275 global $ID; 276 global $ACT; 277 global $conf; 278 279 //first visit? 280 $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array(); 281 //we only save on show and existing wiki documents 282 $file = wikiFN($ID); 283 if($ACT != 'show' || !@file_exists($file)){ 284 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs; 285 return $crumbs; 286 } 287 288 // page names 289 $name = noNSorNS($ID); 290 if (useHeading('navigation')) { 291 // get page title 292 $title = p_get_first_heading($ID,true); 293 if ($title) { 294 $name = $title; 295 } 296 } 297 298 //remove ID from array 299 if (isset($crumbs[$ID])) { 300 unset($crumbs[$ID]); 301 } 302 303 //add to array 304 $crumbs[$ID] = $name; 305 //reduce size 306 while(count($crumbs) > $conf['breadcrumbs']){ 307 array_shift($crumbs); 308 } 309 //save to session 310 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs; 311 return $crumbs; 312} 313 314/** 315 * Filter for page IDs 316 * 317 * This is run on a ID before it is outputted somewhere 318 * currently used to replace the colon with something else 319 * on Windows systems and to have proper URL encoding 320 * 321 * Urlencoding is ommitted when the second parameter is false 322 * 323 * @author Andreas Gohr <andi@splitbrain.org> 324 */ 325function idfilter($id,$ue=true){ 326 global $conf; 327 if ($conf['useslash'] && $conf['userewrite']){ 328 $id = strtr($id,':','/'); 329 }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && 330 $conf['userewrite']) { 331 $id = strtr($id,':',';'); 332 } 333 if($ue){ 334 $id = rawurlencode($id); 335 $id = str_replace('%3A',':',$id); //keep as colon 336 $id = str_replace('%2F','/',$id); //keep as slash 337 } 338 return $id; 339} 340 341/** 342 * This builds a link to a wikipage 343 * 344 * It handles URL rewriting and adds additional parameter if 345 * given in $more 346 * 347 * @author Andreas Gohr <andi@splitbrain.org> 348 */ 349function wl($id='',$more='',$abs=false,$sep='&'){ 350 global $conf; 351 if(is_array($more)){ 352 $more = buildURLparams($more,$sep); 353 }else{ 354 $more = str_replace(',',$sep,$more); 355 } 356 357 $id = idfilter($id); 358 if($abs){ 359 $xlink = DOKU_URL; 360 }else{ 361 $xlink = DOKU_BASE; 362 } 363 364 if($conf['userewrite'] == 2){ 365 $xlink .= DOKU_SCRIPT.'/'.$id; 366 if($more) $xlink .= '?'.$more; 367 }elseif($conf['userewrite']){ 368 $xlink .= $id; 369 if($more) $xlink .= '?'.$more; 370 }elseif($id){ 371 $xlink .= DOKU_SCRIPT.'?id='.$id; 372 if($more) $xlink .= $sep.$more; 373 }else{ 374 $xlink .= DOKU_SCRIPT; 375 if($more) $xlink .= '?'.$more; 376 } 377 378 return $xlink; 379} 380 381/** 382 * This builds a link to an alternate page format 383 * 384 * Handles URL rewriting if enabled. Follows the style of wl(). 385 * 386 * @author Ben Coburn <btcoburn@silicodon.net> 387 */ 388function exportlink($id='',$format='raw',$more='',$abs=false,$sep='&'){ 389 global $conf; 390 if(is_array($more)){ 391 $more = buildURLparams($more,$sep); 392 }else{ 393 $more = str_replace(',',$sep,$more); 394 } 395 396 $format = rawurlencode($format); 397 $id = idfilter($id); 398 if($abs){ 399 $xlink = DOKU_URL; 400 }else{ 401 $xlink = DOKU_BASE; 402 } 403 404 if($conf['userewrite'] == 2){ 405 $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format; 406 if($more) $xlink .= $sep.$more; 407 }elseif($conf['userewrite'] == 1){ 408 $xlink .= '_export/'.$format.'/'.$id; 409 if($more) $xlink .= '?'.$more; 410 }else{ 411 $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id; 412 if($more) $xlink .= $sep.$more; 413 } 414 415 return $xlink; 416} 417 418/** 419 * Build a link to a media file 420 * 421 * Will return a link to the detail page if $direct is false 422 * 423 * The $more parameter should always be given as array, the function then 424 * will strip default parameters to produce even cleaner URLs 425 * 426 * @param string $id - the media file id or URL 427 * @param mixed $more - string or array with additional parameters 428 * @param boolean $direct - link to detail page if false 429 * @param string $sep - URL parameter separator 430 * @param boolean $abs - Create an absolute URL 431 */ 432function ml($id='',$more='',$direct=true,$sep='&',$abs=false){ 433 global $conf; 434 if(is_array($more)){ 435 // strip defaults for shorter URLs 436 if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']); 437 if(!$more['w']) unset($more['w']); 438 if(!$more['h']) unset($more['h']); 439 if(isset($more['id']) && $direct) unset($more['id']); 440 $more = buildURLparams($more,$sep); 441 }else{ 442 $more = str_replace('cache=cache','',$more); //skip default 443 $more = str_replace(',,',',',$more); 444 $more = str_replace(',',$sep,$more); 445 } 446 447 if($abs){ 448 $xlink = DOKU_URL; 449 }else{ 450 $xlink = DOKU_BASE; 451 } 452 453 // external URLs are always direct without rewriting 454 if(preg_match('#^(https?|ftp)://#i',$id)){ 455 $xlink .= 'lib/exe/fetch.php'; 456 // add hash: 457 $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6); 458 if($more){ 459 $xlink .= $sep.$more; 460 $xlink .= $sep.'media='.rawurlencode($id); 461 }else{ 462 $xlink .= $sep.'media='.rawurlencode($id); 463 } 464 return $xlink; 465 } 466 467 $id = idfilter($id); 468 469 // decide on scriptname 470 if($direct){ 471 if($conf['userewrite'] == 1){ 472 $script = '_media'; 473 }else{ 474 $script = 'lib/exe/fetch.php'; 475 } 476 }else{ 477 if($conf['userewrite'] == 1){ 478 $script = '_detail'; 479 }else{ 480 $script = 'lib/exe/detail.php'; 481 } 482 } 483 484 // build URL based on rewrite mode 485 if($conf['userewrite']){ 486 $xlink .= $script.'/'.$id; 487 if($more) $xlink .= '?'.$more; 488 }else{ 489 if($more){ 490 $xlink .= $script.'?'.$more; 491 $xlink .= $sep.'media='.$id; 492 }else{ 493 $xlink .= $script.'?media='.$id; 494 } 495 } 496 497 return $xlink; 498} 499 500 501 502/** 503 * Just builds a link to a script 504 * 505 * @todo maybe obsolete 506 * @author Andreas Gohr <andi@splitbrain.org> 507 */ 508function script($script='doku.php'){ 509 return DOKU_BASE.DOKU_SCRIPT; 510} 511 512/** 513 * Spamcheck against wordlist 514 * 515 * Checks the wikitext against a list of blocked expressions 516 * returns true if the text contains any bad words 517 * 518 * Triggers COMMON_WORDBLOCK_BLOCKED 519 * 520 * Action Plugins can use this event to inspect the blocked data 521 * and gain information about the user who was blocked. 522 * 523 * Event data: 524 * data['matches'] - array of matches 525 * data['userinfo'] - information about the blocked user 526 * [ip] - ip address 527 * [user] - username (if logged in) 528 * [mail] - mail address (if logged in) 529 * [name] - real name (if logged in) 530 * 531 * @author Andreas Gohr <andi@splitbrain.org> 532 * @author Michael Klier <chi@chimeric.de> 533 * @param string $text - optional text to check, if not given the globals are used 534 * @return bool - true if a spam word was found 535 */ 536function checkwordblock($text=''){ 537 global $TEXT; 538 global $PRE; 539 global $SUF; 540 global $conf; 541 global $INFO; 542 543 if(!$conf['usewordblock']) return false; 544 545 if(!$text) $text = "$PRE $TEXT $SUF"; 546 547 // we prepare the text a tiny bit to prevent spammers circumventing URL checks 548 $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text); 549 550 $wordblocks = getWordblocks(); 551 // how many lines to read at once (to work around some PCRE limits) 552 if(version_compare(phpversion(),'4.3.0','<')){ 553 // old versions of PCRE define a maximum of parenthesises even if no 554 // backreferences are used - the maximum is 99 555 // this is very bad performancewise and may even be too high still 556 $chunksize = 40; 557 }else{ 558 // read file in chunks of 200 - this should work around the 559 // MAX_PATTERN_SIZE in modern PCRE 560 $chunksize = 200; 561 } 562 while($blocks = array_splice($wordblocks,0,$chunksize)){ 563 $re = array(); 564 // build regexp from blocks 565 foreach($blocks as $block){ 566 $block = preg_replace('/#.*$/','',$block); 567 $block = trim($block); 568 if(empty($block)) continue; 569 $re[] = $block; 570 } 571 if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) { 572 // prepare event data 573 $data['matches'] = $matches; 574 $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR']; 575 if($_SERVER['REMOTE_USER']) { 576 $data['userinfo']['user'] = $_SERVER['REMOTE_USER']; 577 $data['userinfo']['name'] = $INFO['userinfo']['name']; 578 $data['userinfo']['mail'] = $INFO['userinfo']['mail']; 579 } 580 $callback = create_function('', 'return true;'); 581 return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true); 582 } 583 } 584 return false; 585} 586 587/** 588 * Return the IP of the client 589 * 590 * Honours X-Forwarded-For and X-Real-IP Proxy Headers 591 * 592 * It returns a comma separated list of IPs if the above mentioned 593 * headers are set. If the single parameter is set, it tries to return 594 * a routable public address, prefering the ones suplied in the X 595 * headers 596 * 597 * @param boolean $single If set only a single IP is returned 598 * @author Andreas Gohr <andi@splitbrain.org> 599 */ 600function clientIP($single=false){ 601 $ip = array(); 602 $ip[] = $_SERVER['REMOTE_ADDR']; 603 if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) 604 $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])); 605 if(!empty($_SERVER['HTTP_X_REAL_IP'])) 606 $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP'])); 607 608 // some IPv4/v6 regexps borrowed from Feyd 609 // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479 610 $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])'; 611 $hex_digit = '[A-Fa-f0-9]'; 612 $h16 = "{$hex_digit}{1,4}"; 613 $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet"; 614 $ls32 = "(?:$h16:$h16|$IPv4Address)"; 615 $IPv6Address = 616 "(?:(?:{$IPv4Address})|(?:". 617 "(?:$h16:){6}$ls32" . 618 "|::(?:$h16:){5}$ls32" . 619 "|(?:$h16)?::(?:$h16:){4}$ls32" . 620 "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" . 621 "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" . 622 "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" . 623 "|(?:(?:$h16:){0,4}$h16)?::$ls32" . 624 "|(?:(?:$h16:){0,5}$h16)?::$h16" . 625 "|(?:(?:$h16:){0,6}$h16)?::" . 626 ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)"; 627 628 // remove any non-IP stuff 629 $cnt = count($ip); 630 $match = array(); 631 for($i=0; $i<$cnt; $i++){ 632 if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) { 633 $ip[$i] = $match[0]; 634 } else { 635 $ip[$i] = ''; 636 } 637 if(empty($ip[$i])) unset($ip[$i]); 638 } 639 $ip = array_values(array_unique($ip)); 640 if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP 641 642 if(!$single) return join(',',$ip); 643 644 // decide which IP to use, trying to avoid local addresses 645 $ip = array_reverse($ip); 646 foreach($ip as $i){ 647 if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){ 648 continue; 649 }else{ 650 return $i; 651 } 652 } 653 // still here? just use the first (last) address 654 return $ip[0]; 655} 656 657/** 658 * Check if the browser is on a mobile device 659 * 660 * Adapted from the example code at url below 661 * 662 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code 663 */ 664function clientismobile(){ 665 666 if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true; 667 668 if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true; 669 670 if(!isset($_SERVER['HTTP_USER_AGENT'])) return false; 671 672 $uamatches = 'midp|j2me|avantg|docomo|novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up\.b|audio|SIE\-|SEC\-|samsung|HTC|mot\-|mitsu|sagem|sony|alcatel|lg|erics|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|\d\d\di|moto'; 673 674 if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true; 675 676 return false; 677} 678 679 680/** 681 * Convert one or more comma separated IPs to hostnames 682 * 683 * @author Glen Harris <astfgl@iamnota.org> 684 * @returns a comma separated list of hostnames 685 */ 686function gethostsbyaddrs($ips){ 687 $hosts = array(); 688 $ips = explode(',',$ips); 689 690 if(is_array($ips)) { 691 foreach($ips as $ip){ 692 $hosts[] = gethostbyaddr(trim($ip)); 693 } 694 return join(',',$hosts); 695 } else { 696 return gethostbyaddr(trim($ips)); 697 } 698} 699 700/** 701 * Checks if a given page is currently locked. 702 * 703 * removes stale lockfiles 704 * 705 * @author Andreas Gohr <andi@splitbrain.org> 706 */ 707function checklock($id){ 708 global $conf; 709 $lock = wikiLockFN($id); 710 711 //no lockfile 712 if(!@file_exists($lock)) return false; 713 714 //lockfile expired 715 if((time() - filemtime($lock)) > $conf['locktime']){ 716 @unlink($lock); 717 return false; 718 } 719 720 //my own lock 721 $ip = io_readFile($lock); 722 if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){ 723 return false; 724 } 725 726 return $ip; 727} 728 729/** 730 * Lock a page for editing 731 * 732 * @author Andreas Gohr <andi@splitbrain.org> 733 */ 734function lock($id){ 735 $lock = wikiLockFN($id); 736 if($_SERVER['REMOTE_USER']){ 737 io_saveFile($lock,$_SERVER['REMOTE_USER']); 738 }else{ 739 io_saveFile($lock,clientIP()); 740 } 741} 742 743/** 744 * Unlock a page if it was locked by the user 745 * 746 * @author Andreas Gohr <andi@splitbrain.org> 747 * @return bool true if a lock was removed 748 */ 749function unlock($id){ 750 $lock = wikiLockFN($id); 751 if(@file_exists($lock)){ 752 $ip = io_readFile($lock); 753 if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){ 754 @unlink($lock); 755 return true; 756 } 757 } 758 return false; 759} 760 761/** 762 * convert line ending to unix format 763 * 764 * @see formText() for 2crlf conversion 765 * @author Andreas Gohr <andi@splitbrain.org> 766 */ 767function cleanText($text){ 768 $text = preg_replace("/(\015\012)|(\015)/","\012",$text); 769 return $text; 770} 771 772/** 773 * Prepares text for print in Webforms by encoding special chars. 774 * It also converts line endings to Windows format which is 775 * pseudo standard for webforms. 776 * 777 * @see cleanText() for 2unix conversion 778 * @author Andreas Gohr <andi@splitbrain.org> 779 */ 780function formText($text){ 781 $text = str_replace("\012","\015\012",$text); 782 return htmlspecialchars($text); 783} 784 785/** 786 * Returns the specified local text in raw format 787 * 788 * @author Andreas Gohr <andi@splitbrain.org> 789 */ 790function rawLocale($id){ 791 return io_readFile(localeFN($id)); 792} 793 794/** 795 * Returns the raw WikiText 796 * 797 * @author Andreas Gohr <andi@splitbrain.org> 798 */ 799function rawWiki($id,$rev=''){ 800 return io_readWikiPage(wikiFN($id, $rev), $id, $rev); 801} 802 803/** 804 * Returns the pagetemplate contents for the ID's namespace 805 * 806 * @author Andreas Gohr <andi@splitbrain.org> 807 */ 808function pageTemplate($data){ 809 $id = $data[0]; 810 global $conf; 811 global $INFO; 812 813 $path = dirname(wikiFN($id)); 814 815 if(@file_exists($path.'/_template.txt')){ 816 $tpl = io_readFile($path.'/_template.txt'); 817 }else{ 818 // search upper namespaces for templates 819 $len = strlen(rtrim($conf['datadir'],'/')); 820 while (strlen($path) >= $len){ 821 if(@file_exists($path.'/__template.txt')){ 822 $tpl = io_readFile($path.'/__template.txt'); 823 break; 824 } 825 $path = substr($path, 0, strrpos($path, '/')); 826 } 827 } 828 if(!$tpl) return ''; 829 830 // replace placeholders 831 $file = noNS($id); 832 $page = strtr($file,'_',' '); 833 834 $tpl = str_replace(array( 835 '@ID@', 836 '@NS@', 837 '@FILE@', 838 '@!FILE@', 839 '@!FILE!@', 840 '@PAGE@', 841 '@!PAGE@', 842 '@!!PAGE@', 843 '@!PAGE!@', 844 '@USER@', 845 '@NAME@', 846 '@MAIL@', 847 '@DATE@', 848 ), 849 array( 850 $id, 851 getNS($id), 852 $file, 853 utf8_ucfirst($file), 854 utf8_strtoupper($file), 855 $page, 856 utf8_ucfirst($page), 857 utf8_ucwords($page), 858 utf8_strtoupper($page), 859 $_SERVER['REMOTE_USER'], 860 $INFO['userinfo']['name'], 861 $INFO['userinfo']['mail'], 862 $conf['dformat'], 863 ), $tpl); 864 865 // we need the callback to work around strftime's char limit 866 $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl); 867 868 return $tpl; 869} 870 871 872/** 873 * Returns the raw Wiki Text in three slices. 874 * 875 * The range parameter needs to have the form "from-to" 876 * and gives the range of the section in bytes - no 877 * UTF-8 awareness is needed. 878 * The returned order is prefix, section and suffix. 879 * 880 * @author Andreas Gohr <andi@splitbrain.org> 881 */ 882function rawWikiSlices($range,$id,$rev=''){ 883 list($from,$to) = explode('-',$range,2); 884 $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev); 885 if(!$from) $from = 0; 886 if(!$to) $to = strlen($text)+1; 887 888 $slices[0] = substr($text,0,$from-1); 889 $slices[1] = substr($text,$from-1,$to-$from); 890 $slices[2] = substr($text,$to); 891 892 return $slices; 893} 894 895/** 896 * Joins wiki text slices 897 * 898 * function to join the text slices with correct lineendings again. 899 * When the pretty parameter is set to true it adds additional empty 900 * lines between sections if needed (used on saving). 901 * 902 * @author Andreas Gohr <andi@splitbrain.org> 903 */ 904function con($pre,$text,$suf,$pretty=false){ 905 if($pretty){ 906 if($pre && substr($pre,-1) != "\n") $pre .= "\n"; 907 if($suf && substr($text,-1) != "\n") $text .= "\n"; 908 } 909 910 // Avoid double newline above section when saving section edit 911 //if($pre) $pre .= "\n"; 912 if($suf) $text .= "\n"; 913 return $pre.$text.$suf; 914} 915 916/** 917 * Saves a wikitext by calling io_writeWikiPage. 918 * Also directs changelog and attic updates. 919 * 920 * @author Andreas Gohr <andi@splitbrain.org> 921 * @author Ben Coburn <btcoburn@silicodon.net> 922 */ 923function saveWikiText($id,$text,$summary,$minor=false){ 924 /* Note to developers: 925 This code is subtle and delicate. Test the behavior of 926 the attic and changelog with dokuwiki and external edits 927 after any changes. External edits change the wiki page 928 directly without using php or dokuwiki. 929 */ 930 global $conf; 931 global $lang; 932 global $REV; 933 // ignore if no changes were made 934 if($text == rawWiki($id,'')){ 935 return; 936 } 937 938 $file = wikiFN($id); 939 $old = @filemtime($file); // from page 940 $wasRemoved = empty($text); 941 $wasCreated = !@file_exists($file); 942 $wasReverted = ($REV==true); 943 $newRev = false; 944 $oldRev = getRevisions($id, -1, 1, 1024); // from changelog 945 $oldRev = (int)(empty($oldRev)?0:$oldRev[0]); 946 if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) { 947 // add old revision to the attic if missing 948 saveOldRevision($id); 949 // add a changelog entry if this edit came from outside dokuwiki 950 if ($old>$oldRev) { 951 addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true)); 952 // remove soon to be stale instructions 953 $cache = new cache_instructions($id, $file); 954 $cache->removeCache(); 955 } 956 } 957 958 if ($wasRemoved){ 959 // Send "update" event with empty data, so plugins can react to page deletion 960 $data = array(array($file, '', false), getNS($id), noNS($id), false); 961 trigger_event('IO_WIKIPAGE_WRITE', $data); 962 // pre-save deleted revision 963 @touch($file); 964 clearstatcache(); 965 $newRev = saveOldRevision($id); 966 // remove empty file 967 @unlink($file); 968 // remove old meta info... 969 $mfiles = metaFiles($id); 970 $changelog = metaFN($id, '.changes'); 971 $metadata = metaFN($id, '.meta'); 972 foreach ($mfiles as $mfile) { 973 // but keep per-page changelog to preserve page history and keep meta data 974 if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); } 975 } 976 // purge meta data 977 p_purge_metadata($id); 978 $del = true; 979 // autoset summary on deletion 980 if(empty($summary)) $summary = $lang['deleted']; 981 // remove empty namespaces 982 io_sweepNS($id, 'datadir'); 983 io_sweepNS($id, 'mediadir'); 984 }else{ 985 // save file (namespace dir is created in io_writeWikiPage) 986 io_writeWikiPage($file, $text, $id); 987 // pre-save the revision, to keep the attic in sync 988 $newRev = saveOldRevision($id); 989 $del = false; 990 } 991 992 // select changelog line type 993 $extra = ''; 994 $type = DOKU_CHANGE_TYPE_EDIT; 995 if ($wasReverted) { 996 $type = DOKU_CHANGE_TYPE_REVERT; 997 $extra = $REV; 998 } 999 else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; } 1000 else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; } 1001 else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users 1002 1003 addLogEntry($newRev, $id, $type, $summary, $extra); 1004 // send notify mails 1005 notify($id,'admin',$old,$summary,$minor); 1006 notify($id,'subscribers',$old,$summary,$minor); 1007 1008 // update the purgefile (timestamp of the last time anything within the wiki was changed) 1009 io_saveFile($conf['cachedir'].'/purgefile',time()); 1010 1011 // if useheading is enabled, purge the cache of all linking pages 1012 if(useHeading('content')){ 1013 require_once(DOKU_INC.'inc/fulltext.php'); 1014 $pages = ft_backlinks($id); 1015 foreach ($pages as $page) { 1016 $cache = new cache_renderer($page, wikiFN($page), 'xhtml'); 1017 $cache->removeCache(); 1018 } 1019 } 1020} 1021 1022/** 1023 * moves the current version to the attic and returns its 1024 * revision date 1025 * 1026 * @author Andreas Gohr <andi@splitbrain.org> 1027 */ 1028function saveOldRevision($id){ 1029 global $conf; 1030 $oldf = wikiFN($id); 1031 if(!@file_exists($oldf)) return ''; 1032 $date = filemtime($oldf); 1033 $newf = wikiFN($id,$date); 1034 io_writeWikiPage($newf, rawWiki($id), $id, $date); 1035 return $date; 1036} 1037 1038/** 1039 * Sends a notify mail on page change or registration 1040 * 1041 * @param string $id The changed page 1042 * @param string $who Who to notify (admin|subscribers|register) 1043 * @param int $rev Old page revision 1044 * @param string $summary What changed 1045 * @param boolean $minor Is this a minor edit? 1046 * @param array $replace Additional string substitutions, @KEY@ to be replaced by value 1047 * 1048 * @author Andreas Gohr <andi@splitbrain.org> 1049 */ 1050function notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){ 1051 global $lang; 1052 global $conf; 1053 global $INFO; 1054 1055 // decide if there is something to do 1056 if($who == 'admin'){ 1057 if(empty($conf['notify'])) return; //notify enabled? 1058 $text = rawLocale('mailtext'); 1059 $to = $conf['notify']; 1060 $bcc = ''; 1061 }elseif($who == 'subscribers'){ 1062 if(!$conf['subscribers']) return; //subscribers enabled? 1063 if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors 1064 $bcc = subscriber_addresslist($id,false); 1065 if(empty($bcc)) return; 1066 $to = ''; 1067 $text = rawLocale('subscribermail'); 1068 }elseif($who == 'register'){ 1069 if(empty($conf['registernotify'])) return; 1070 $text = rawLocale('registermail'); 1071 $to = $conf['registernotify']; 1072 $bcc = ''; 1073 }else{ 1074 return; //just to be safe 1075 } 1076 1077 $ip = clientIP(); 1078 $text = str_replace('@DATE@',dformat(),$text); 1079 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text); 1080 $text = str_replace('@IPADDRESS@',$ip,$text); 1081 $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text); 1082 $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text); 1083 $text = str_replace('@PAGE@',$id,$text); 1084 $text = str_replace('@TITLE@',$conf['title'],$text); 1085 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 1086 $text = str_replace('@SUMMARY@',$summary,$text); 1087 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text); 1088 1089 foreach ($replace as $key => $substitution) { 1090 $text = str_replace('@'.strtoupper($key).'@',$substitution, $text); 1091 } 1092 1093 if($who == 'register'){ 1094 $subject = $lang['mail_new_user'].' '.$summary; 1095 }elseif($rev){ 1096 $subject = $lang['mail_changed'].' '.$id; 1097 $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text); 1098 require_once(DOKU_INC.'inc/DifferenceEngine.php'); 1099 $df = new Diff(explode("\n",rawWiki($id,$rev)), 1100 explode("\n",rawWiki($id))); 1101 $dformat = new UnifiedDiffFormatter(); 1102 $diff = $dformat->format($df); 1103 }else{ 1104 $subject=$lang['mail_newpage'].' '.$id; 1105 $text = str_replace('@OLDPAGE@','none',$text); 1106 $diff = rawWiki($id); 1107 } 1108 $text = str_replace('@DIFF@',$diff,$text); 1109 $subject = '['.$conf['title'].'] '.$subject; 1110 1111 $from = $conf['mailfrom']; 1112 $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from); 1113 $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from); 1114 $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from); 1115 1116 mail_send($to,$subject,$text,$from,'',$bcc); 1117} 1118 1119/** 1120 * extracts the query from a search engine referrer 1121 * 1122 * @author Andreas Gohr <andi@splitbrain.org> 1123 * @author Todd Augsburger <todd@rollerorgans.com> 1124 */ 1125function getGoogleQuery(){ 1126 if (!isset($_SERVER['HTTP_REFERER'])) { 1127 return ''; 1128 } 1129 $url = parse_url($_SERVER['HTTP_REFERER']); 1130 1131 $query = array(); 1132 1133 // temporary workaround against PHP bug #49733 1134 // see http://bugs.php.net/bug.php?id=49733 1135 if(UTF8_MBSTRING) $enc = mb_internal_encoding(); 1136 parse_str($url['query'],$query); 1137 if(UTF8_MBSTRING) mb_internal_encoding($enc); 1138 1139 $q = ''; 1140 if(isset($query['q'])) 1141 $q = $query['q']; // google, live/msn, aol, ask, altavista, alltheweb, gigablast 1142 elseif(isset($query['p'])) 1143 $q = $query['p']; // yahoo 1144 elseif(isset($query['query'])) 1145 $q = $query['query']; // lycos, netscape, clusty, hotbot 1146 elseif(preg_match("#a9\.com#i",$url['host'])) // a9 1147 $q = urldecode(ltrim($url['path'],'/')); 1148 1149 if($q === '') return ''; 1150 $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY); 1151 return $q; 1152} 1153 1154/** 1155 * Try to set correct locale 1156 * 1157 * @deprecated No longer used 1158 * @author Andreas Gohr <andi@splitbrain.org> 1159 */ 1160function setCorrectLocale(){ 1161 global $conf; 1162 global $lang; 1163 1164 $enc = strtoupper($lang['encoding']); 1165 foreach ($lang['locales'] as $loc){ 1166 //try locale 1167 if(@setlocale(LC_ALL,$loc)) return; 1168 //try loceale with encoding 1169 if(@setlocale(LC_ALL,"$loc.$enc")) return; 1170 } 1171 //still here? try to set from environment 1172 @setlocale(LC_ALL,""); 1173} 1174 1175/** 1176 * Return the human readable size of a file 1177 * 1178 * @param int $size A file size 1179 * @param int $dec A number of decimal places 1180 * @author Martin Benjamin <b.martin@cybernet.ch> 1181 * @author Aidan Lister <aidan@php.net> 1182 * @version 1.0.0 1183 */ 1184function filesize_h($size, $dec = 1){ 1185 $sizes = array('B', 'KB', 'MB', 'GB'); 1186 $count = count($sizes); 1187 $i = 0; 1188 1189 while ($size >= 1024 && ($i < $count - 1)) { 1190 $size /= 1024; 1191 $i++; 1192 } 1193 1194 return round($size, $dec) . ' ' . $sizes[$i]; 1195} 1196 1197/** 1198 * Return the given timestamp as human readable, fuzzy age 1199 * 1200 * @author Andreas Gohr <gohr@cosmocode.de> 1201 */ 1202function datetime_h($dt){ 1203 global $lang; 1204 1205 $ago = time() - $dt; 1206 if($ago > 24*60*60*30*12*2){ 1207 return sprintf($lang['years'], round($ago/(24*60*60*30*12))); 1208 } 1209 if($ago > 24*60*60*30*2){ 1210 return sprintf($lang['months'], round($ago/(24*60*60*30))); 1211 } 1212 if($ago > 24*60*60*7*2){ 1213 return sprintf($lang['weeks'], round($ago/(24*60*60*7))); 1214 } 1215 if($ago > 24*60*60*2){ 1216 return sprintf($lang['days'], round($ago/(24*60*60))); 1217 } 1218 if($ago > 60*60*2){ 1219 return sprintf($lang['hours'], round($ago/(60*60))); 1220 } 1221 if($ago > 60*2){ 1222 return sprintf($lang['minutes'], round($ago/(60))); 1223 } 1224 return sprintf($lang['seconds'], $ago); 1225} 1226 1227/** 1228 * Wraps around strftime but provides support for fuzzy dates 1229 * 1230 * The format default to $conf['dformat']. It is passed to 1231 * strftime - %f can be used to get the value from datetime_h() 1232 * 1233 * @see datetime_h 1234 * @author Andreas Gohr <gohr@cosmocode.de> 1235 */ 1236function dformat($dt=null,$format=''){ 1237 global $conf; 1238 1239 if(is_null($dt)) $dt = time(); 1240 $dt = (int) $dt; 1241 if(!$format) $format = $conf['dformat']; 1242 1243 $format = str_replace('%f',datetime_h($dt),$format); 1244 return strftime($format,$dt); 1245} 1246 1247/** 1248 * return an obfuscated email address in line with $conf['mailguard'] setting 1249 * 1250 * @author Harry Fuecks <hfuecks@gmail.com> 1251 * @author Christopher Smith <chris@jalakai.co.uk> 1252 */ 1253function obfuscate($email) { 1254 global $conf; 1255 1256 switch ($conf['mailguard']) { 1257 case 'visible' : 1258 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '); 1259 return strtr($email, $obfuscate); 1260 1261 case 'hex' : 1262 $encode = ''; 1263 $len = strlen($email); 1264 for ($x=0; $x < $len; $x++){ 1265 $encode .= '&#x' . bin2hex($email{$x}).';'; 1266 } 1267 return $encode; 1268 1269 case 'none' : 1270 default : 1271 return $email; 1272 } 1273} 1274 1275/** 1276 * Let us know if a user is tracking a page or a namespace 1277 * 1278 * @author Andreas Gohr <andi@splitbrain.org> 1279 */ 1280function is_subscribed($id,$uid,$ns=false){ 1281 if(!$ns) { 1282 $file=metaFN($id,'.mlist'); 1283 } else { 1284 if(!getNS($id)) { 1285 $file = metaFN(getNS($id),'.mlist'); 1286 } else { 1287 $file = metaFN(getNS($id),'/.mlist'); 1288 } 1289 } 1290 if (@file_exists($file)) { 1291 $mlist = file($file); 1292 $pos = array_search($uid."\n",$mlist); 1293 return is_int($pos); 1294 } 1295 1296 return false; 1297} 1298 1299/** 1300 * Return a string with the email addresses of all the 1301 * users subscribed to a page 1302 * 1303 * @author Steven Danz <steven-danz@kc.rr.com> 1304 */ 1305function subscriber_addresslist($id,$self=true){ 1306 global $conf; 1307 global $auth; 1308 1309 if (!$conf['subscribers']) return ''; 1310 1311 $users = array(); 1312 $emails = array(); 1313 1314 // load the page mlist file content 1315 $mlist = array(); 1316 $file=metaFN($id,'.mlist'); 1317 if (@file_exists($file)) { 1318 $mlist = file($file); 1319 foreach ($mlist as $who) { 1320 $who = rtrim($who); 1321 if(!$self && $who == $_SERVER['REMOTE_USER']) continue; 1322 $users[$who] = true; 1323 } 1324 } 1325 1326 // load also the namespace mlist file content 1327 $ns = getNS($id); 1328 while ($ns) { 1329 $nsfile = metaFN($ns,'/.mlist'); 1330 if (@file_exists($nsfile)) { 1331 $mlist = file($nsfile); 1332 foreach ($mlist as $who) { 1333 $who = rtrim($who); 1334 if(!$self && $who == $_SERVER['REMOTE_USER']) continue; 1335 $users[$who] = true; 1336 } 1337 } 1338 $ns = getNS($ns); 1339 } 1340 // root namespace 1341 $nsfile = metaFN('','.mlist'); 1342 if (@file_exists($nsfile)) { 1343 $mlist = file($nsfile); 1344 foreach ($mlist as $who) { 1345 $who = rtrim($who); 1346 if(!$self && $who == $_SERVER['REMOTE_USER']) continue; 1347 $users[$who] = true; 1348 } 1349 } 1350 if(!empty($users)) { 1351 foreach (array_keys($users) as $who) { 1352 $info = $auth->getUserData($who); 1353 if($info === false) continue; 1354 $level = auth_aclcheck($id,$who,$info['grps']); 1355 if ($level >= AUTH_READ) { 1356 if (strcasecmp($info['mail'],$conf['notify']) != 0) { 1357 $emails[] = $info['mail']; 1358 } 1359 } 1360 } 1361 } 1362 1363 return implode(',',$emails); 1364} 1365 1366/** 1367 * Removes quoting backslashes 1368 * 1369 * @author Andreas Gohr <andi@splitbrain.org> 1370 */ 1371function unslash($string,$char="'"){ 1372 return str_replace('\\'.$char,$char,$string); 1373} 1374 1375/** 1376 * Convert php.ini shorthands to byte 1377 * 1378 * @author <gilthans dot NO dot SPAM at gmail dot com> 1379 * @link http://de3.php.net/manual/en/ini.core.php#79564 1380 */ 1381function php_to_byte($v){ 1382 $l = substr($v, -1); 1383 $ret = substr($v, 0, -1); 1384 switch(strtoupper($l)){ 1385 case 'P': 1386 $ret *= 1024; 1387 case 'T': 1388 $ret *= 1024; 1389 case 'G': 1390 $ret *= 1024; 1391 case 'M': 1392 $ret *= 1024; 1393 case 'K': 1394 $ret *= 1024; 1395 break; 1396 } 1397 return $ret; 1398} 1399 1400/** 1401 * Wrapper around preg_quote adding the default delimiter 1402 */ 1403function preg_quote_cb($string){ 1404 return preg_quote($string,'/'); 1405} 1406 1407/** 1408 * Shorten a given string by removing data from the middle 1409 * 1410 * You can give the string in two parts, the first part $keep 1411 * will never be shortened. The second part $short will be cut 1412 * in the middle to shorten but only if at least $min chars are 1413 * left to display it. Otherwise it will be left off. 1414 * 1415 * @param string $keep the part to keep 1416 * @param string $short the part to shorten 1417 * @param int $max maximum chars you want for the whole string 1418 * @param int $min minimum number of chars to have left for middle shortening 1419 * @param string $char the shortening character to use 1420 */ 1421function shorten($keep,$short,$max,$min=9,$char='…'){ 1422 $max = $max - utf8_strlen($keep); 1423 if($max < $min) return $keep; 1424 $len = utf8_strlen($short); 1425 if($len <= $max) return $keep.$short; 1426 $half = floor($max/2); 1427 return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half); 1428} 1429 1430/** 1431 * Return the users realname or e-mail address for use 1432 * in page footer and recent changes pages 1433 * 1434 * @author Andy Webber <dokuwiki AT andywebber DOT com> 1435 */ 1436function editorinfo($username){ 1437 global $conf; 1438 global $auth; 1439 1440 switch($conf['showuseras']){ 1441 case 'username': 1442 case 'email': 1443 case 'email_link': 1444 if($auth) $info = $auth->getUserData($username); 1445 break; 1446 default: 1447 return hsc($username); 1448 } 1449 1450 if(isset($info) && $info) { 1451 switch($conf['showuseras']){ 1452 case 'username': 1453 return hsc($info['name']); 1454 case 'email': 1455 return obfuscate($info['mail']); 1456 case 'email_link': 1457 $mail=obfuscate($info['mail']); 1458 return '<a href="mailto:'.$mail.'">'.$mail.'</a>'; 1459 default: 1460 return hsc($username); 1461 } 1462 } else { 1463 return hsc($username); 1464 } 1465} 1466 1467/** 1468 * Returns the path to a image file for the currently chosen license. 1469 * When no image exists, returns an empty string 1470 * 1471 * @author Andreas Gohr <andi@splitbrain.org> 1472 * @param string $type - type of image 'badge' or 'button' 1473 */ 1474function license_img($type){ 1475 global $license; 1476 global $conf; 1477 if(!$conf['license']) return ''; 1478 if(!is_array($license[$conf['license']])) return ''; 1479 $lic = $license[$conf['license']]; 1480 $try = array(); 1481 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png'; 1482 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif'; 1483 if(substr($conf['license'],0,3) == 'cc-'){ 1484 $try[] = 'lib/images/license/'.$type.'/cc.png'; 1485 } 1486 foreach($try as $src){ 1487 if(@file_exists(DOKU_INC.$src)) return $src; 1488 } 1489 return ''; 1490} 1491 1492/** 1493 * Checks if the given amount of memory is available 1494 * 1495 * If the memory_get_usage() function is not available the 1496 * function just assumes $bytes of already allocated memory 1497 * 1498 * @param int $mem Size of memory you want to allocate in bytes 1499 * @param int $used already allocated memory (see above) 1500 * @author Filip Oscadal <webmaster@illusionsoftworks.cz> 1501 * @author Andreas Gohr <andi@splitbrain.org> 1502 */ 1503function is_mem_available($mem,$bytes=1048576){ 1504 $limit = trim(ini_get('memory_limit')); 1505 if(empty($limit)) return true; // no limit set! 1506 1507 // parse limit to bytes 1508 $limit = php_to_byte($limit); 1509 1510 // get used memory if possible 1511 if(function_exists('memory_get_usage')){ 1512 $used = memory_get_usage(); 1513 }else{ 1514 $used = $bytes; 1515 } 1516 1517 if($used+$mem > $limit){ 1518 return false; 1519 } 1520 1521 return true; 1522} 1523 1524/** 1525 * Send a HTTP redirect to the browser 1526 * 1527 * Works arround Microsoft IIS cookie sending bug. Exits the script. 1528 * 1529 * @link http://support.microsoft.com/kb/q176113/ 1530 * @author Andreas Gohr <andi@splitbrain.org> 1531 */ 1532function send_redirect($url){ 1533 // always close the session 1534 session_write_close(); 1535 1536 // check if running on IIS < 6 with CGI-PHP 1537 if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) && 1538 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) && 1539 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) && 1540 $matches[1] < 6 ){ 1541 header('Refresh: 0;url='.$url); 1542 }else{ 1543 header('Location: '.$url); 1544 } 1545 exit; 1546} 1547 1548//Setup VIM: ex: et ts=4 enc=utf-8 : 1549