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