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