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 = array(); 124 $info['isadmin'] = false; 125 $info['ismanager'] = false; 126 if($INPUT->server->has('REMOTE_USER')) { 127 $info['userinfo'] = $USERINFO; 128 $info['perm'] = auth_quickaclcheck($id); 129 $info['client'] = $INPUT->server->str('REMOTE_USER'); 130 131 if($info['perm'] == AUTH_ADMIN) { 132 $info['isadmin'] = true; 133 $info['ismanager'] = true; 134 } elseif(auth_ismanager()) { 135 $info['ismanager'] = true; 136 } 137 138 // if some outside auth were used only REMOTE_USER is set 139 if(!$info['userinfo']['name']) { 140 $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER'); 141 } 142 143 } else { 144 $info['perm'] = auth_aclcheck($id, '', null); 145 $info['client'] = clientIP(true); 146 } 147 148 $info['namespace'] = getNS($id); 149 150 // mobile detection 151 if ($htmlClient) { 152 $info['ismobile'] = clientismobile(); 153 } 154 155 return $info; 156 } 157 158/** 159 * Return info about the current document as associative 160 * array. 161 * 162 * @author Andreas Gohr <andi@splitbrain.org> 163 * 164 * @return array with info about current document 165 */ 166function pageinfo() { 167 global $ID; 168 global $REV; 169 global $RANGE; 170 global $lang; 171 /* @var Input $INPUT */ 172 global $INPUT; 173 174 $info = basicinfo($ID); 175 176 // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml 177 // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary 178 $info['id'] = $ID; 179 $info['rev'] = $REV; 180 181 if($INPUT->server->has('REMOTE_USER')) { 182 $sub = new Subscription(); 183 $info['subscribed'] = $sub->user_subscription(); 184 } else { 185 $info['subscribed'] = false; 186 } 187 188 $info['locked'] = checklock($ID); 189 $info['filepath'] = fullpath(wikiFN($ID)); 190 $info['exists'] = @file_exists($info['filepath']); 191 $info['currentrev'] = @filemtime($info['filepath']); 192 if($REV) { 193 //check if current revision was meant 194 if($info['exists'] && ($info['currentrev'] == $REV)) { 195 $REV = ''; 196 } elseif($RANGE) { 197 //section editing does not work with old revisions! 198 $REV = ''; 199 $RANGE = ''; 200 msg($lang['nosecedit'], 0); 201 } else { 202 //really use old revision 203 $info['filepath'] = fullpath(wikiFN($ID, $REV)); 204 $info['exists'] = @file_exists($info['filepath']); 205 } 206 } 207 $info['rev'] = $REV; 208 if($info['exists']) { 209 $info['writable'] = (is_writable($info['filepath']) && 210 ($info['perm'] >= AUTH_EDIT)); 211 } else { 212 $info['writable'] = ($info['perm'] >= AUTH_CREATE); 213 } 214 $info['editable'] = ($info['writable'] && empty($info['locked'])); 215 $info['lastmod'] = @filemtime($info['filepath']); 216 217 //load page meta data 218 $info['meta'] = p_get_metadata($ID); 219 220 //who's the editor 221 $pagelog = new PageChangeLog($ID, 1024); 222 if($REV) { 223 $revinfo = $pagelog->getRevisionInfo($REV); 224 } else { 225 if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) { 226 $revinfo = $info['meta']['last_change']; 227 } else { 228 $revinfo = $pagelog->getRevisionInfo($info['lastmod']); 229 // cache most recent changelog line in metadata if missing and still valid 230 if($revinfo !== false) { 231 $info['meta']['last_change'] = $revinfo; 232 p_set_metadata($ID, array('last_change' => $revinfo)); 233 } 234 } 235 } 236 //and check for an external edit 237 if($revinfo !== false && $revinfo['date'] != $info['lastmod']) { 238 // cached changelog line no longer valid 239 $revinfo = false; 240 $info['meta']['last_change'] = $revinfo; 241 p_set_metadata($ID, array('last_change' => $revinfo)); 242 } 243 244 $info['ip'] = $revinfo['ip']; 245 $info['user'] = $revinfo['user']; 246 $info['sum'] = $revinfo['sum']; 247 // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID. 248 // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor']. 249 250 if($revinfo['user']) { 251 $info['editor'] = $revinfo['user']; 252 } else { 253 $info['editor'] = $revinfo['ip']; 254 } 255 256 // draft 257 $draft = getCacheName($info['client'].$ID, '.draft'); 258 if(@file_exists($draft)) { 259 if(@filemtime($draft) < @filemtime(wikiFN($ID))) { 260 // remove stale draft 261 @unlink($draft); 262 } else { 263 $info['draft'] = $draft; 264 } 265 } 266 267 return $info; 268} 269 270/** 271 * Return information about the current media item as an associative array. 272 * 273 * @return array with info about current media item 274 */ 275function mediainfo(){ 276 global $NS; 277 global $IMG; 278 279 $info = basicinfo("$NS:*"); 280 $info['image'] = $IMG; 281 282 return $info; 283} 284 285/** 286 * Build an string of URL parameters 287 * 288 * @author Andreas Gohr 289 * 290 * @param array $params array with key-value pairs 291 * @param string $sep series of pairs are separated by this character 292 * @return string query string 293 */ 294function buildURLparams($params, $sep = '&') { 295 $url = ''; 296 $amp = false; 297 foreach($params as $key => $val) { 298 if($amp) $url .= $sep; 299 300 $url .= rawurlencode($key).'='; 301 $url .= rawurlencode((string) $val); 302 $amp = true; 303 } 304 return $url; 305} 306 307/** 308 * Build an string of html tag attributes 309 * 310 * Skips keys starting with '_', values get HTML encoded 311 * 312 * @author Andreas Gohr 313 * 314 * @param array $params array with (attribute name-attribute value) pairs 315 * @param bool $skipempty skip empty string values? 316 * @return string 317 */ 318function buildAttributes($params, $skipempty = false) { 319 $url = ''; 320 $white = false; 321 foreach($params as $key => $val) { 322 if($key{0} == '_') continue; 323 if($val === '' && $skipempty) continue; 324 if($white) $url .= ' '; 325 326 $url .= $key.'="'; 327 $url .= htmlspecialchars($val); 328 $url .= '"'; 329 $white = true; 330 } 331 return $url; 332} 333 334/** 335 * This builds the breadcrumb trail and returns it as array 336 * 337 * @author Andreas Gohr <andi@splitbrain.org> 338 * 339 * @return array(pageid=>name, ... ) 340 */ 341function breadcrumbs() { 342 // we prepare the breadcrumbs early for quick session closing 343 static $crumbs = null; 344 if($crumbs != null) return $crumbs; 345 346 global $ID; 347 global $ACT; 348 global $conf; 349 350 //first visit? 351 $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array(); 352 //we only save on show and existing wiki documents 353 $file = wikiFN($ID); 354 if($ACT != 'show' || !@file_exists($file)) { 355 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs; 356 return $crumbs; 357 } 358 359 // page names 360 $name = noNSorNS($ID); 361 if(useHeading('navigation')) { 362 // get page title 363 $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE); 364 if($title) { 365 $name = $title; 366 } 367 } 368 369 //remove ID from array 370 if(isset($crumbs[$ID])) { 371 unset($crumbs[$ID]); 372 } 373 374 //add to array 375 $crumbs[$ID] = $name; 376 //reduce size 377 while(count($crumbs) > $conf['breadcrumbs']) { 378 array_shift($crumbs); 379 } 380 //save to session 381 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs; 382 return $crumbs; 383} 384 385/** 386 * Filter for page IDs 387 * 388 * This is run on a ID before it is outputted somewhere 389 * currently used to replace the colon with something else 390 * on Windows (non-IIS) systems and to have proper URL encoding 391 * 392 * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and 393 * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of 394 * unaffected servers instead of blacklisting affected servers here. 395 * 396 * Urlencoding is ommitted when the second parameter is false 397 * 398 * @author Andreas Gohr <andi@splitbrain.org> 399 * 400 * @param string $id pageid being filtered 401 * @param bool $ue apply urlencoding? 402 * @return string 403 */ 404function idfilter($id, $ue = true) { 405 global $conf; 406 /* @var Input $INPUT */ 407 global $INPUT; 408 409 if($conf['useslash'] && $conf['userewrite']) { 410 $id = strtr($id, ':', '/'); 411 } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && 412 $conf['userewrite'] && 413 strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false 414 ) { 415 $id = strtr($id, ':', ';'); 416 } 417 if($ue) { 418 $id = rawurlencode($id); 419 $id = str_replace('%3A', ':', $id); //keep as colon 420 $id = str_replace('%3B', ';', $id); //keep as semicolon 421 $id = str_replace('%2F', '/', $id); //keep as slash 422 } 423 return $id; 424} 425 426/** 427 * This builds a link to a wikipage 428 * 429 * It handles URL rewriting and adds additional parameters 430 * 431 * @author Andreas Gohr <andi@splitbrain.org> 432 * 433 * @param string $id page id, defaults to start page 434 * @param string|array $urlParameters URL parameters, associative array recommended 435 * @param bool $absolute request an absolute URL instead of relative 436 * @param string $separator parameter separator 437 * @return string 438 */ 439function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&') { 440 global $conf; 441 if(is_array($urlParameters)) { 442 $urlParameters = buildURLparams($urlParameters, $separator); 443 } else { 444 $urlParameters = str_replace(',', $separator, $urlParameters); 445 } 446 if($id === '') { 447 $id = $conf['start']; 448 } 449 $id = idfilter($id); 450 if($absolute) { 451 $xlink = DOKU_URL; 452 } else { 453 $xlink = DOKU_BASE; 454 } 455 456 if($conf['userewrite'] == 2) { 457 $xlink .= DOKU_SCRIPT.'/'.$id; 458 if($urlParameters) $xlink .= '?'.$urlParameters; 459 } elseif($conf['userewrite']) { 460 $xlink .= $id; 461 if($urlParameters) $xlink .= '?'.$urlParameters; 462 } elseif($id) { 463 $xlink .= DOKU_SCRIPT.'?id='.$id; 464 if($urlParameters) $xlink .= $separator.$urlParameters; 465 } else { 466 $xlink .= DOKU_SCRIPT; 467 if($urlParameters) $xlink .= '?'.$urlParameters; 468 } 469 470 return $xlink; 471} 472 473/** 474 * This builds a link to an alternate page format 475 * 476 * Handles URL rewriting if enabled. Follows the style of wl(). 477 * 478 * @author Ben Coburn <btcoburn@silicodon.net> 479 * @param string $id page id, defaults to start page 480 * @param string $format the export renderer to use 481 * @param string|array $urlParameters URL parameters, associative array recommended 482 * @param bool $abs request an absolute URL instead of relative 483 * @param string $sep parameter separator 484 * @return string 485 */ 486function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&') { 487 global $conf; 488 if(is_array($urlParameters)) { 489 $urlParameters = buildURLparams($urlParameters, $sep); 490 } else { 491 $urlParameters = str_replace(',', $sep, $urlParameters); 492 } 493 494 $format = rawurlencode($format); 495 $id = idfilter($id); 496 if($abs) { 497 $xlink = DOKU_URL; 498 } else { 499 $xlink = DOKU_BASE; 500 } 501 502 if($conf['userewrite'] == 2) { 503 $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format; 504 if($urlParameters) $xlink .= $sep.$urlParameters; 505 } elseif($conf['userewrite'] == 1) { 506 $xlink .= '_export/'.$format.'/'.$id; 507 if($urlParameters) $xlink .= '?'.$urlParameters; 508 } else { 509 $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id; 510 if($urlParameters) $xlink .= $sep.$urlParameters; 511 } 512 513 return $xlink; 514} 515 516/** 517 * Build a link to a media file 518 * 519 * Will return a link to the detail page if $direct is false 520 * 521 * The $more parameter should always be given as array, the function then 522 * will strip default parameters to produce even cleaner URLs 523 * 524 * @param string $id the media file id or URL 525 * @param mixed $more string or array with additional parameters 526 * @param bool $direct link to detail page if false 527 * @param string $sep URL parameter separator 528 * @param bool $abs Create an absolute URL 529 * @return string 530 */ 531function ml($id = '', $more = '', $direct = true, $sep = '&', $abs = false) { 532 global $conf; 533 $isexternalimage = media_isexternal($id); 534 if(!$isexternalimage) { 535 $id = cleanID($id); 536 } 537 538 if(is_array($more)) { 539 // add token for resized images 540 if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){ 541 $more['tok'] = media_get_token($id,$more['w'],$more['h']); 542 } 543 // strip defaults for shorter URLs 544 if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']); 545 if(empty($more['w'])) unset($more['w']); 546 if(empty($more['h'])) unset($more['h']); 547 if(isset($more['id']) && $direct) unset($more['id']); 548 $more = buildURLparams($more, $sep); 549 } else { 550 $matches = array(); 551 if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){ 552 $resize = array('w'=>0, 'h'=>0); 553 foreach ($matches as $match){ 554 $resize[$match[1]] = $match[2]; 555 } 556 $more .= $more === '' ? '' : $sep; 557 $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']); 558 } 559 $more = str_replace('cache=cache', '', $more); //skip default 560 $more = str_replace(',,', ',', $more); 561 $more = str_replace(',', $sep, $more); 562 } 563 564 if($abs) { 565 $xlink = DOKU_URL; 566 } else { 567 $xlink = DOKU_BASE; 568 } 569 570 // external URLs are always direct without rewriting 571 if($isexternalimage) { 572 $xlink .= 'lib/exe/fetch.php'; 573 $xlink .= '?'.$more; 574 $xlink .= $sep.'media='.rawurlencode($id); 575 return $xlink; 576 } 577 578 $id = idfilter($id); 579 580 // decide on scriptname 581 if($direct) { 582 if($conf['userewrite'] == 1) { 583 $script = '_media'; 584 } else { 585 $script = 'lib/exe/fetch.php'; 586 } 587 } else { 588 if($conf['userewrite'] == 1) { 589 $script = '_detail'; 590 } else { 591 $script = 'lib/exe/detail.php'; 592 } 593 } 594 595 // build URL based on rewrite mode 596 if($conf['userewrite']) { 597 $xlink .= $script.'/'.$id; 598 if($more) $xlink .= '?'.$more; 599 } else { 600 if($more) { 601 $xlink .= $script.'?'.$more; 602 $xlink .= $sep.'media='.$id; 603 } else { 604 $xlink .= $script.'?media='.$id; 605 } 606 } 607 608 return $xlink; 609} 610 611/** 612 * Returns the URL to the DokuWiki base script 613 * 614 * Consider using wl() instead, unless you absoutely need the doku.php endpoint 615 * 616 * @author Andreas Gohr <andi@splitbrain.org> 617 * 618 * @return string 619 */ 620function script() { 621 return DOKU_BASE.DOKU_SCRIPT; 622} 623 624/** 625 * Spamcheck against wordlist 626 * 627 * Checks the wikitext against a list of blocked expressions 628 * returns true if the text contains any bad words 629 * 630 * Triggers COMMON_WORDBLOCK_BLOCKED 631 * 632 * Action Plugins can use this event to inspect the blocked data 633 * and gain information about the user who was blocked. 634 * 635 * Event data: 636 * data['matches'] - array of matches 637 * data['userinfo'] - information about the blocked user 638 * [ip] - ip address 639 * [user] - username (if logged in) 640 * [mail] - mail address (if logged in) 641 * [name] - real name (if logged in) 642 * 643 * @author Andreas Gohr <andi@splitbrain.org> 644 * @author Michael Klier <chi@chimeric.de> 645 * 646 * @param string $text - optional text to check, if not given the globals are used 647 * @return bool - true if a spam word was found 648 */ 649function checkwordblock($text = '') { 650 global $TEXT; 651 global $PRE; 652 global $SUF; 653 global $SUM; 654 global $conf; 655 global $INFO; 656 /* @var Input $INPUT */ 657 global $INPUT; 658 659 if(!$conf['usewordblock']) return false; 660 661 if(!$text) $text = "$PRE $TEXT $SUF $SUM"; 662 663 // we prepare the text a tiny bit to prevent spammers circumventing URL checks 664 $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text); 665 666 $wordblocks = getWordblocks(); 667 // how many lines to read at once (to work around some PCRE limits) 668 if(version_compare(phpversion(), '4.3.0', '<')) { 669 // old versions of PCRE define a maximum of parenthesises even if no 670 // backreferences are used - the maximum is 99 671 // this is very bad performancewise and may even be too high still 672 $chunksize = 40; 673 } else { 674 // read file in chunks of 200 - this should work around the 675 // MAX_PATTERN_SIZE in modern PCRE 676 $chunksize = 200; 677 } 678 while($blocks = array_splice($wordblocks, 0, $chunksize)) { 679 $re = array(); 680 // build regexp from blocks 681 foreach($blocks as $block) { 682 $block = preg_replace('/#.*$/', '', $block); 683 $block = trim($block); 684 if(empty($block)) continue; 685 $re[] = $block; 686 } 687 if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) { 688 // prepare event data 689 $data = array(); 690 $data['matches'] = $matches; 691 $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR'); 692 if($INPUT->server->str('REMOTE_USER')) { 693 $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER'); 694 $data['userinfo']['name'] = $INFO['userinfo']['name']; 695 $data['userinfo']['mail'] = $INFO['userinfo']['mail']; 696 } 697 $callback = create_function('', 'return true;'); 698 return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true); 699 } 700 } 701 return false; 702} 703 704/** 705 * Return the IP of the client 706 * 707 * Honours X-Forwarded-For and X-Real-IP Proxy Headers 708 * 709 * It returns a comma separated list of IPs if the above mentioned 710 * headers are set. If the single parameter is set, it tries to return 711 * a routable public address, prefering the ones suplied in the X 712 * headers 713 * 714 * @author Andreas Gohr <andi@splitbrain.org> 715 * 716 * @param boolean $single If set only a single IP is returned 717 * @return string 718 */ 719function clientIP($single = false) { 720 /* @var Input $INPUT */ 721 global $INPUT; 722 723 $ip = array(); 724 $ip[] = $INPUT->server->str('REMOTE_ADDR'); 725 if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) { 726 $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR')))); 727 } 728 if($INPUT->server->str('HTTP_X_REAL_IP')) { 729 $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP')))); 730 } 731 732 // some IPv4/v6 regexps borrowed from Feyd 733 // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479 734 $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])'; 735 $hex_digit = '[A-Fa-f0-9]'; 736 $h16 = "{$hex_digit}{1,4}"; 737 $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet"; 738 $ls32 = "(?:$h16:$h16|$IPv4Address)"; 739 $IPv6Address = 740 "(?:(?:{$IPv4Address})|(?:". 741 "(?:$h16:){6}$ls32". 742 "|::(?:$h16:){5}$ls32". 743 "|(?:$h16)?::(?:$h16:){4}$ls32". 744 "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32". 745 "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32". 746 "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32". 747 "|(?:(?:$h16:){0,4}$h16)?::$ls32". 748 "|(?:(?:$h16:){0,5}$h16)?::$h16". 749 "|(?:(?:$h16:){0,6}$h16)?::". 750 ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)"; 751 752 // remove any non-IP stuff 753 $cnt = count($ip); 754 $match = array(); 755 for($i = 0; $i < $cnt; $i++) { 756 if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) { 757 $ip[$i] = $match[0]; 758 } else { 759 $ip[$i] = ''; 760 } 761 if(empty($ip[$i])) unset($ip[$i]); 762 } 763 $ip = array_values(array_unique($ip)); 764 if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP 765 766 if(!$single) return join(',', $ip); 767 768 // decide which IP to use, trying to avoid local addresses 769 $ip = array_reverse($ip); 770 foreach($ip as $i) { 771 if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) { 772 continue; 773 } else { 774 return $i; 775 } 776 } 777 // still here? just use the first (last) address 778 return $ip[0]; 779} 780 781/** 782 * Check if the browser is on a mobile device 783 * 784 * Adapted from the example code at url below 785 * 786 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code 787 * 788 * @return bool if true, client is mobile browser; otherwise false 789 */ 790function clientismobile() { 791 /* @var Input $INPUT */ 792 global $INPUT; 793 794 if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true; 795 796 if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true; 797 798 if(!$INPUT->server->has('HTTP_USER_AGENT')) return false; 799 800 $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'; 801 802 if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true; 803 804 return false; 805} 806 807/** 808 * Convert one or more comma separated IPs to hostnames 809 * 810 * If $conf['dnslookups'] is disabled it simply returns the input string 811 * 812 * @author Glen Harris <astfgl@iamnota.org> 813 * 814 * @param string $ips comma separated list of IP addresses 815 * @return string a comma separated list of hostnames 816 */ 817function gethostsbyaddrs($ips) { 818 global $conf; 819 if(!$conf['dnslookups']) return $ips; 820 821 $hosts = array(); 822 $ips = explode(',', $ips); 823 824 if(is_array($ips)) { 825 foreach($ips as $ip) { 826 $hosts[] = gethostbyaddr(trim($ip)); 827 } 828 return join(',', $hosts); 829 } else { 830 return gethostbyaddr(trim($ips)); 831 } 832} 833 834/** 835 * Checks if a given page is currently locked. 836 * 837 * removes stale lockfiles 838 * 839 * @author Andreas Gohr <andi@splitbrain.org> 840 * 841 * @param string $id page id 842 * @return bool page is locked? 843 */ 844function checklock($id) { 845 global $conf; 846 /* @var Input $INPUT */ 847 global $INPUT; 848 849 $lock = wikiLockFN($id); 850 851 //no lockfile 852 if(!@file_exists($lock)) return false; 853 854 //lockfile expired 855 if((time() - filemtime($lock)) > $conf['locktime']) { 856 @unlink($lock); 857 return false; 858 } 859 860 //my own lock 861 @list($ip, $session) = explode("\n", io_readFile($lock)); 862 if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) { 863 return false; 864 } 865 866 return $ip; 867} 868 869/** 870 * Lock a page for editing 871 * 872 * @author Andreas Gohr <andi@splitbrain.org> 873 * 874 * @param string $id page id to lock 875 */ 876function lock($id) { 877 global $conf; 878 /* @var Input $INPUT */ 879 global $INPUT; 880 881 if($conf['locktime'] == 0) { 882 return; 883 } 884 885 $lock = wikiLockFN($id); 886 if($INPUT->server->str('REMOTE_USER')) { 887 io_saveFile($lock, $INPUT->server->str('REMOTE_USER')); 888 } else { 889 io_saveFile($lock, clientIP()."\n".session_id()); 890 } 891} 892 893/** 894 * Unlock a page if it was locked by the user 895 * 896 * @author Andreas Gohr <andi@splitbrain.org> 897 * 898 * @param string $id page id to unlock 899 * @return bool true if a lock was removed 900 */ 901function unlock($id) { 902 /* @var Input $INPUT */ 903 global $INPUT; 904 905 $lock = wikiLockFN($id); 906 if(@file_exists($lock)) { 907 @list($ip, $session) = explode("\n", io_readFile($lock)); 908 if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) { 909 @unlink($lock); 910 return true; 911 } 912 } 913 return false; 914} 915 916/** 917 * convert line ending to unix format 918 * 919 * also makes sure the given text is valid UTF-8 920 * 921 * @see formText() for 2crlf conversion 922 * @author Andreas Gohr <andi@splitbrain.org> 923 * 924 * @param string $text 925 * @return string 926 */ 927function cleanText($text) { 928 $text = preg_replace("/(\015\012)|(\015)/", "\012", $text); 929 930 // if the text is not valid UTF-8 we simply assume latin1 931 // this won't break any worse than it breaks with the wrong encoding 932 // but might actually fix the problem in many cases 933 if(!utf8_check($text)) $text = utf8_encode($text); 934 935 return $text; 936} 937 938/** 939 * Prepares text for print in Webforms by encoding special chars. 940 * It also converts line endings to Windows format which is 941 * pseudo standard for webforms. 942 * 943 * @see cleanText() for 2unix conversion 944 * @author Andreas Gohr <andi@splitbrain.org> 945 * 946 * @param string $text 947 * @return string 948 */ 949function formText($text) { 950 $text = str_replace("\012", "\015\012", $text); 951 return htmlspecialchars($text); 952} 953 954/** 955 * Returns the specified local text in raw format 956 * 957 * @author Andreas Gohr <andi@splitbrain.org> 958 * 959 * @param string $id page id 960 * @param string $ext extension of file being read, default 'txt' 961 * @return string 962 */ 963function rawLocale($id, $ext = 'txt') { 964 return io_readFile(localeFN($id, $ext)); 965} 966 967/** 968 * Returns the raw WikiText 969 * 970 * @author Andreas Gohr <andi@splitbrain.org> 971 * 972 * @param string $id page id 973 * @param string|int $rev timestamp when a revision of wikitext is desired 974 * @return string 975 */ 976function rawWiki($id, $rev = '') { 977 return io_readWikiPage(wikiFN($id, $rev), $id, $rev); 978} 979 980/** 981 * Returns the pagetemplate contents for the ID's namespace 982 * 983 * @triggers COMMON_PAGETPL_LOAD 984 * @author Andreas Gohr <andi@splitbrain.org> 985 * 986 * @param string $id the id of the page to be created 987 * @return string parsed pagetemplate content 988 */ 989function pageTemplate($id) { 990 global $conf; 991 992 if(is_array($id)) $id = $id[0]; 993 994 // prepare initial event data 995 $data = array( 996 'id' => $id, // the id of the page to be created 997 'tpl' => '', // the text used as template 998 'tplfile' => '', // the file above text was/should be loaded from 999 'doreplace' => true // should wildcard replacements be done on the text? 1000 ); 1001 1002 $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data); 1003 if($evt->advise_before(true)) { 1004 // the before event might have loaded the content already 1005 if(empty($data['tpl'])) { 1006 // if the before event did not set a template file, try to find one 1007 if(empty($data['tplfile'])) { 1008 $path = dirname(wikiFN($id)); 1009 if(@file_exists($path.'/_template.txt')) { 1010 $data['tplfile'] = $path.'/_template.txt'; 1011 } else { 1012 // search upper namespaces for templates 1013 $len = strlen(rtrim($conf['datadir'], '/')); 1014 while(strlen($path) >= $len) { 1015 if(@file_exists($path.'/__template.txt')) { 1016 $data['tplfile'] = $path.'/__template.txt'; 1017 break; 1018 } 1019 $path = substr($path, 0, strrpos($path, '/')); 1020 } 1021 } 1022 } 1023 // load the content 1024 $data['tpl'] = io_readFile($data['tplfile']); 1025 } 1026 if($data['doreplace']) parsePageTemplate($data); 1027 } 1028 $evt->advise_after(); 1029 unset($evt); 1030 1031 return $data['tpl']; 1032} 1033 1034/** 1035 * Performs common page template replacements 1036 * This works on data from COMMON_PAGETPL_LOAD 1037 * 1038 * @author Andreas Gohr <andi@splitbrain.org> 1039 * 1040 * @param array $data array with event data 1041 * @return string 1042 */ 1043function parsePageTemplate(&$data) { 1044 /** 1045 * @var string $id the id of the page to be created 1046 * @var string $tpl the text used as template 1047 * @var string $tplfile the file above text was/should be loaded from 1048 * @var bool $doreplace should wildcard replacements be done on the text? 1049 */ 1050 extract($data); 1051 1052 global $USERINFO; 1053 global $conf; 1054 /* @var Input $INPUT */ 1055 global $INPUT; 1056 1057 // replace placeholders 1058 $file = noNS($id); 1059 $page = strtr($file, $conf['sepchar'], ' '); 1060 1061 $tpl = str_replace( 1062 array( 1063 '@ID@', 1064 '@NS@', 1065 '@FILE@', 1066 '@!FILE@', 1067 '@!FILE!@', 1068 '@PAGE@', 1069 '@!PAGE@', 1070 '@!!PAGE@', 1071 '@!PAGE!@', 1072 '@USER@', 1073 '@NAME@', 1074 '@MAIL@', 1075 '@DATE@', 1076 ), 1077 array( 1078 $id, 1079 getNS($id), 1080 $file, 1081 utf8_ucfirst($file), 1082 utf8_strtoupper($file), 1083 $page, 1084 utf8_ucfirst($page), 1085 utf8_ucwords($page), 1086 utf8_strtoupper($page), 1087 $INPUT->server->str('REMOTE_USER'), 1088 $USERINFO['name'], 1089 $USERINFO['mail'], 1090 $conf['dformat'], 1091 ), $tpl 1092 ); 1093 1094 // we need the callback to work around strftime's char limit 1095 $tpl = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl); 1096 $data['tpl'] = $tpl; 1097 return $tpl; 1098} 1099 1100/** 1101 * Returns the raw Wiki Text in three slices. 1102 * 1103 * The range parameter needs to have the form "from-to" 1104 * and gives the range of the section in bytes - no 1105 * UTF-8 awareness is needed. 1106 * The returned order is prefix, section and suffix. 1107 * 1108 * @author Andreas Gohr <andi@splitbrain.org> 1109 * 1110 * @param string $range in form "from-to" 1111 * @param string $id page id 1112 * @param string $rev optional, the revision timestamp 1113 * @return array with three slices 1114 */ 1115function rawWikiSlices($range, $id, $rev = '') { 1116 $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev); 1117 1118 // Parse range 1119 list($from, $to) = explode('-', $range, 2); 1120 // Make range zero-based, use defaults if marker is missing 1121 $from = !$from ? 0 : ($from - 1); 1122 $to = !$to ? strlen($text) : ($to - 1); 1123 1124 $slices = array(); 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