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