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