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