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