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 // external edit, creation or deletion 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 // prepare data for event 1316 $svdta = array(); 1317 $svdta['id'] = $id; 1318 $svdta['file'] = wikiFN($id); 1319 $svdta['revertFrom'] = $REV; 1320 $svdta['oldRevision'] = @filemtime($svdta['file']); 1321 $svdta['newRevision'] = 0; 1322 $svdta['newContent'] = $text; 1323 $svdta['oldContent'] = rawWiki($id); 1324 $svdta['summary'] = $summary; 1325 $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']); 1326 $svdta['changeInfo'] = ''; 1327 $svdta['changeType'] = DOKU_CHANGE_TYPE_EDIT; 1328 $svdta['sizechange'] = null; 1329 1330 // select changelog line type 1331 if ($REV) { 1332 $svdta['changeType'] = DOKU_CHANGE_TYPE_REVERT; 1333 $svdta['changeInfo'] = $REV; 1334 } elseif (!file_exists($svdta['file'])) { 1335 $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE; 1336 } elseif (trim($text) == '') { 1337 // empty or whitespace only content deletes 1338 $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE; 1339 // autoset summary on deletion 1340 if (blank($svdta['summary'])) { 1341 $svdta['summary'] = $lang['deleted']; 1342 } 1343 } elseif ($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) { 1344 //minor edits only for logged in users 1345 $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT; 1346 } 1347 1348 $event = new Event('COMMON_WIKIPAGE_SAVE', $svdta); 1349 if (!$event->advise_before()) return; 1350 1351 // if the content has not been changed, no save happens (plugins may override this) 1352 if (!$svdta['contentChanged']) return; 1353 1354 // register external edit, creation or deletion as a regular changelog entry 1355 detectExternalEdit($id); 1356 1357 if ( 1358 ($svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE) || 1359 ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file'])) 1360 ) { 1361 $filesize_old = 0; 1362 } else { 1363 $filesize_old = filesize($svdta['file']); 1364 } 1365 if ($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) { 1366 // Send "update" event with empty data, so plugins can react to page deletion 1367 $data = array([$svdta['file'], '', false], getNS($id), noNS($id), false); 1368 Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data); 1369 // pre-save deleted revision 1370 @touch($svdta['file']); 1371 clearstatcache(); 1372 $svdta['newRevision'] = saveOldRevision($id); 1373 // remove empty file 1374 @unlink($svdta['file']); 1375 $filesize_new = 0; 1376 // don't remove old meta info as it should be saved, plugins can use 1377 // IO_WIKIPAGE_WRITE for removing their metadata... 1378 // purge non-persistant meta data 1379 p_purge_metadata($id); 1380 // remove empty namespaces 1381 io_sweepNS($id, 'datadir'); 1382 io_sweepNS($id, 'mediadir'); 1383 } else { 1384 // save file (namespace dir is created in io_writeWikiPage) 1385 io_writeWikiPage($svdta['file'], $svdta['newContent'], $id); 1386 // pre-save the revision, to keep the attic in sync 1387 $svdta['newRevision'] = saveOldRevision($id); 1388 $filesize_new = filesize($svdta['file']); 1389 } 1390 $svdta['sizechange'] = $filesize_new - $filesize_old; 1391 1392 $event->advise_after(); 1393 1394 // adds an entry to the changelog and saves the metadata for the page 1395 addLogEntry( 1396 $svdta['newRevision'], 1397 $svdta['id'], 1398 $svdta['changeType'], 1399 $svdta['summary'], 1400 $svdta['changeInfo'], 1401 null, 1402 $svdta['sizechange'] 1403 ); 1404 1405 // send notify mails 1406 notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor, $svdta['newRevision']); 1407 notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor, $svdta['newRevision']); 1408 1409 // update the purgefile (timestamp of the last time anything within the wiki was changed) 1410 io_saveFile($conf['cachedir'].'/purgefile', time()); 1411 1412 // if useheading is enabled, purge the cache of all linking pages 1413 if (useHeading('content')) { 1414 $pages = ft_backlinks($id, true); 1415 foreach ($pages as $page) { 1416 $cache = new CacheRenderer($page, wikiFN($page), 'xhtml'); 1417 $cache->removeCache(); 1418 } 1419 } 1420} 1421 1422/** 1423 * moves the current version to the attic and returns its 1424 * revision date 1425 * 1426 * @author Andreas Gohr <andi@splitbrain.org> 1427 * 1428 * @param string $id page id 1429 * @return int|string revision timestamp 1430 */ 1431function saveOldRevision($id) { 1432 $oldf = wikiFN($id); 1433 if (!file_exists($oldf)) return ''; 1434 $date = filemtime($oldf); 1435 $newf = wikiFN($id, $date); 1436 io_writeWikiPage($newf, rawWiki($id), $id, $date); 1437 return $date; 1438} 1439 1440/** 1441 * Sends a notify mail on page change or registration 1442 * 1443 * @param string $id The changed page 1444 * @param string $who Who to notify (admin|subscribers|register) 1445 * @param int|string $rev Old page revision 1446 * @param string $summary What changed 1447 * @param boolean $minor Is this a minor edit? 1448 * @param string[] $replace Additional string substitutions, @KEY@ to be replaced by value 1449 * @param int|string $current_rev New page revision 1450 * @return bool 1451 * 1452 * @author Andreas Gohr <andi@splitbrain.org> 1453 */ 1454function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array(), $current_rev = false) { 1455 global $conf; 1456 /* @var Input $INPUT */ 1457 global $INPUT; 1458 1459 // decide if there is something to do, eg. whom to mail 1460 if($who == 'admin') { 1461 if(empty($conf['notify'])) return false; //notify enabled? 1462 $tpl = 'mailtext'; 1463 $to = $conf['notify']; 1464 } elseif($who == 'subscribers') { 1465 if(!actionOK('subscribe')) return false; //subscribers enabled? 1466 if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors 1467 $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace); 1468 Event::createAndTrigger( 1469 'COMMON_NOTIFY_ADDRESSLIST', $data, 1470 array(new SubscriberManager(), 'notifyAddresses') 1471 ); 1472 $to = $data['addresslist']; 1473 if(empty($to)) return false; 1474 $tpl = 'subscr_single'; 1475 } else { 1476 return false; //just to be safe 1477 } 1478 1479 // prepare content 1480 $subscription = new PageSubscriptionSender(); 1481 return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev); 1482} 1483 1484/** 1485 * extracts the query from a search engine referrer 1486 * 1487 * @author Andreas Gohr <andi@splitbrain.org> 1488 * @author Todd Augsburger <todd@rollerorgans.com> 1489 * 1490 * @return array|string 1491 */ 1492function getGoogleQuery() { 1493 /* @var Input $INPUT */ 1494 global $INPUT; 1495 1496 if(!$INPUT->server->has('HTTP_REFERER')) { 1497 return ''; 1498 } 1499 $url = parse_url($INPUT->server->str('HTTP_REFERER')); 1500 1501 // only handle common SEs 1502 if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return ''; 1503 1504 $query = array(); 1505 parse_str($url['query'], $query); 1506 1507 $q = ''; 1508 if(isset($query['q'])){ 1509 $q = $query['q']; 1510 }elseif(isset($query['p'])){ 1511 $q = $query['p']; 1512 }elseif(isset($query['query'])){ 1513 $q = $query['query']; 1514 } 1515 $q = trim($q); 1516 1517 if(!$q) return ''; 1518 // ignore if query includes a full URL 1519 if(strpos($q, '//') !== false) return ''; 1520 $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY); 1521 return $q; 1522} 1523 1524/** 1525 * Return the human readable size of a file 1526 * 1527 * @param int $size A file size 1528 * @param int $dec A number of decimal places 1529 * @return string human readable size 1530 * 1531 * @author Martin Benjamin <b.martin@cybernet.ch> 1532 * @author Aidan Lister <aidan@php.net> 1533 * @version 1.0.0 1534 */ 1535function filesize_h($size, $dec = 1) { 1536 $sizes = array('B', 'KB', 'MB', 'GB'); 1537 $count = count($sizes); 1538 $i = 0; 1539 1540 while($size >= 1024 && ($i < $count - 1)) { 1541 $size /= 1024; 1542 $i++; 1543 } 1544 1545 return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space 1546} 1547 1548/** 1549 * Return the given timestamp as human readable, fuzzy age 1550 * 1551 * @author Andreas Gohr <gohr@cosmocode.de> 1552 * 1553 * @param int $dt timestamp 1554 * @return string 1555 */ 1556function datetime_h($dt) { 1557 global $lang; 1558 1559 $ago = time() - $dt; 1560 if($ago > 24 * 60 * 60 * 30 * 12 * 2) { 1561 return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12))); 1562 } 1563 if($ago > 24 * 60 * 60 * 30 * 2) { 1564 return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30))); 1565 } 1566 if($ago > 24 * 60 * 60 * 7 * 2) { 1567 return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7))); 1568 } 1569 if($ago > 24 * 60 * 60 * 2) { 1570 return sprintf($lang['days'], round($ago / (24 * 60 * 60))); 1571 } 1572 if($ago > 60 * 60 * 2) { 1573 return sprintf($lang['hours'], round($ago / (60 * 60))); 1574 } 1575 if($ago > 60 * 2) { 1576 return sprintf($lang['minutes'], round($ago / (60))); 1577 } 1578 return sprintf($lang['seconds'], $ago); 1579} 1580 1581/** 1582 * Wraps around strftime but provides support for fuzzy dates 1583 * 1584 * The format default to $conf['dformat']. It is passed to 1585 * strftime - %f can be used to get the value from datetime_h() 1586 * 1587 * @see datetime_h 1588 * @author Andreas Gohr <gohr@cosmocode.de> 1589 * 1590 * @param int|null $dt timestamp when given, null will take current timestamp 1591 * @param string $format empty default to $conf['dformat'], or provide format as recognized by strftime() 1592 * @return string 1593 */ 1594function dformat($dt = null, $format = '') { 1595 global $conf; 1596 1597 if(is_null($dt)) $dt = time(); 1598 $dt = (int) $dt; 1599 if(!$format) $format = $conf['dformat']; 1600 1601 $format = str_replace('%f', datetime_h($dt), $format); 1602 return strftime($format, $dt); 1603} 1604 1605/** 1606 * Formats a timestamp as ISO 8601 date 1607 * 1608 * @author <ungu at terong dot com> 1609 * @link http://php.net/manual/en/function.date.php#54072 1610 * 1611 * @param int $int_date current date in UNIX timestamp 1612 * @return string 1613 */ 1614function date_iso8601($int_date) { 1615 $date_mod = date('Y-m-d\TH:i:s', $int_date); 1616 $pre_timezone = date('O', $int_date); 1617 $time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2); 1618 $date_mod .= $time_zone; 1619 return $date_mod; 1620} 1621 1622/** 1623 * return an obfuscated email address in line with $conf['mailguard'] setting 1624 * 1625 * @author Harry Fuecks <hfuecks@gmail.com> 1626 * @author Christopher Smith <chris@jalakai.co.uk> 1627 * 1628 * @param string $email email address 1629 * @return string 1630 */ 1631function obfuscate($email) { 1632 global $conf; 1633 1634 switch($conf['mailguard']) { 1635 case 'visible' : 1636 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '); 1637 return strtr($email, $obfuscate); 1638 1639 case 'hex' : 1640 return \dokuwiki\Utf8\Conversion::toHtml($email, true); 1641 1642 case 'none' : 1643 default : 1644 return $email; 1645 } 1646} 1647 1648/** 1649 * Removes quoting backslashes 1650 * 1651 * @author Andreas Gohr <andi@splitbrain.org> 1652 * 1653 * @param string $string 1654 * @param string $char backslashed character 1655 * @return string 1656 */ 1657function unslash($string, $char = "'") { 1658 return str_replace('\\'.$char, $char, $string); 1659} 1660 1661/** 1662 * Convert php.ini shorthands to byte 1663 * 1664 * On 32 bit systems values >= 2GB will fail! 1665 * 1666 * -1 (infinite size) will be reported as -1 1667 * 1668 * @link https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes 1669 * @param string $value PHP size shorthand 1670 * @return int 1671 */ 1672function php_to_byte($value) { 1673 switch (strtoupper(substr($value,-1))) { 1674 case 'G': 1675 $ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024; 1676 break; 1677 case 'M': 1678 $ret = intval(substr($value, 0, -1)) * 1024 * 1024; 1679 break; 1680 case 'K': 1681 $ret = intval(substr($value, 0, -1)) * 1024; 1682 break; 1683 default: 1684 $ret = intval($value); 1685 break; 1686 } 1687 return $ret; 1688} 1689 1690/** 1691 * Wrapper around preg_quote adding the default delimiter 1692 * 1693 * @param string $string 1694 * @return string 1695 */ 1696function preg_quote_cb($string) { 1697 return preg_quote($string, '/'); 1698} 1699 1700/** 1701 * Shorten a given string by removing data from the middle 1702 * 1703 * You can give the string in two parts, the first part $keep 1704 * will never be shortened. The second part $short will be cut 1705 * in the middle to shorten but only if at least $min chars are 1706 * left to display it. Otherwise it will be left off. 1707 * 1708 * @param string $keep the part to keep 1709 * @param string $short the part to shorten 1710 * @param int $max maximum chars you want for the whole string 1711 * @param int $min minimum number of chars to have left for middle shortening 1712 * @param string $char the shortening character to use 1713 * @return string 1714 */ 1715function shorten($keep, $short, $max, $min = 9, $char = '…') { 1716 $max = $max - \dokuwiki\Utf8\PhpString::strlen($keep); 1717 if($max < $min) return $keep; 1718 $len = \dokuwiki\Utf8\PhpString::strlen($short); 1719 if($len <= $max) return $keep.$short; 1720 $half = floor($max / 2); 1721 return $keep . 1722 \dokuwiki\Utf8\PhpString::substr($short, 0, $half - 1) . 1723 $char . 1724 \dokuwiki\Utf8\PhpString::substr($short, $len - $half); 1725} 1726 1727/** 1728 * Return the users real name or e-mail address for use 1729 * in page footer and recent changes pages 1730 * 1731 * @param string|null $username or null when currently logged-in user should be used 1732 * @param bool $textonly true returns only plain text, true allows returning html 1733 * @return string html or plain text(not escaped) of formatted user name 1734 * 1735 * @author Andy Webber <dokuwiki AT andywebber DOT com> 1736 */ 1737function editorinfo($username, $textonly = false) { 1738 return userlink($username, $textonly); 1739} 1740 1741/** 1742 * Returns users realname w/o link 1743 * 1744 * @param string|null $username or null when currently logged-in user should be used 1745 * @param bool $textonly true returns only plain text, true allows returning html 1746 * @return string html or plain text(not escaped) of formatted user name 1747 * 1748 * @triggers COMMON_USER_LINK 1749 */ 1750function userlink($username = null, $textonly = false) { 1751 global $conf, $INFO; 1752 /** @var AuthPlugin $auth */ 1753 global $auth; 1754 /** @var Input $INPUT */ 1755 global $INPUT; 1756 1757 // prepare initial event data 1758 $data = array( 1759 'username' => $username, // the unique user name 1760 'name' => '', 1761 'link' => array( //setting 'link' to false disables linking 1762 'target' => '', 1763 'pre' => '', 1764 'suf' => '', 1765 'style' => '', 1766 'more' => '', 1767 'url' => '', 1768 'title' => '', 1769 'class' => '' 1770 ), 1771 'userlink' => '', // formatted user name as will be returned 1772 'textonly' => $textonly 1773 ); 1774 if($username === null) { 1775 $data['username'] = $username = $INPUT->server->str('REMOTE_USER'); 1776 if($textonly){ 1777 $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')'; 1778 }else { 1779 $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '. 1780 '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)'; 1781 } 1782 } 1783 1784 $evt = new Event('COMMON_USER_LINK', $data); 1785 if($evt->advise_before(true)) { 1786 if(empty($data['name'])) { 1787 if($auth) $info = $auth->getUserData($username); 1788 if($conf['showuseras'] != 'loginname' && isset($info) && $info) { 1789 switch($conf['showuseras']) { 1790 case 'username': 1791 case 'username_link': 1792 $data['name'] = $textonly ? $info['name'] : hsc($info['name']); 1793 break; 1794 case 'email': 1795 case 'email_link': 1796 $data['name'] = obfuscate($info['mail']); 1797 break; 1798 } 1799 } else { 1800 $data['name'] = $textonly ? $data['username'] : hsc($data['username']); 1801 } 1802 } 1803 1804 /** @var Doku_Renderer_xhtml $xhtml_renderer */ 1805 static $xhtml_renderer = null; 1806 1807 if(!$data['textonly'] && empty($data['link']['url'])) { 1808 1809 if(in_array($conf['showuseras'], array('email_link', 'username_link'))) { 1810 if(!isset($info)) { 1811 if($auth) $info = $auth->getUserData($username); 1812 } 1813 if(isset($info) && $info) { 1814 if($conf['showuseras'] == 'email_link') { 1815 $data['link']['url'] = 'mailto:' . obfuscate($info['mail']); 1816 } else { 1817 if(is_null($xhtml_renderer)) { 1818 $xhtml_renderer = p_get_renderer('xhtml'); 1819 } 1820 if(empty($xhtml_renderer->interwiki)) { 1821 $xhtml_renderer->interwiki = getInterwiki(); 1822 } 1823 $shortcut = 'user'; 1824 $exists = null; 1825 $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists); 1826 $data['link']['class'] .= ' interwiki iw_user'; 1827 if($exists !== null) { 1828 if($exists) { 1829 $data['link']['class'] .= ' wikilink1'; 1830 } else { 1831 $data['link']['class'] .= ' wikilink2'; 1832 $data['link']['rel'] = 'nofollow'; 1833 } 1834 } 1835 } 1836 } else { 1837 $data['textonly'] = true; 1838 } 1839 1840 } else { 1841 $data['textonly'] = true; 1842 } 1843 } 1844 1845 if($data['textonly']) { 1846 $data['userlink'] = $data['name']; 1847 } else { 1848 $data['link']['name'] = $data['name']; 1849 if(is_null($xhtml_renderer)) { 1850 $xhtml_renderer = p_get_renderer('xhtml'); 1851 } 1852 $data['userlink'] = $xhtml_renderer->_formatLink($data['link']); 1853 } 1854 } 1855 $evt->advise_after(); 1856 unset($evt); 1857 1858 return $data['userlink']; 1859} 1860 1861/** 1862 * Returns the path to a image file for the currently chosen license. 1863 * When no image exists, returns an empty string 1864 * 1865 * @author Andreas Gohr <andi@splitbrain.org> 1866 * 1867 * @param string $type - type of image 'badge' or 'button' 1868 * @return string 1869 */ 1870function license_img($type) { 1871 global $license; 1872 global $conf; 1873 if(!$conf['license']) return ''; 1874 if(!is_array($license[$conf['license']])) return ''; 1875 $try = array(); 1876 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png'; 1877 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif'; 1878 if(substr($conf['license'], 0, 3) == 'cc-') { 1879 $try[] = 'lib/images/license/'.$type.'/cc.png'; 1880 } 1881 foreach($try as $src) { 1882 if(file_exists(DOKU_INC.$src)) return $src; 1883 } 1884 return ''; 1885} 1886 1887/** 1888 * Checks if the given amount of memory is available 1889 * 1890 * If the memory_get_usage() function is not available the 1891 * function just assumes $bytes of already allocated memory 1892 * 1893 * @author Filip Oscadal <webmaster@illusionsoftworks.cz> 1894 * @author Andreas Gohr <andi@splitbrain.org> 1895 * 1896 * @param int $mem Size of memory you want to allocate in bytes 1897 * @param int $bytes already allocated memory (see above) 1898 * @return bool 1899 */ 1900function is_mem_available($mem, $bytes = 1048576) { 1901 $limit = trim(ini_get('memory_limit')); 1902 if(empty($limit)) return true; // no limit set! 1903 if($limit == -1) return true; // unlimited 1904 1905 // parse limit to bytes 1906 $limit = php_to_byte($limit); 1907 1908 // get used memory if possible 1909 if(function_exists('memory_get_usage')) { 1910 $used = memory_get_usage(); 1911 } else { 1912 $used = $bytes; 1913 } 1914 1915 if($used + $mem > $limit) { 1916 return false; 1917 } 1918 1919 return true; 1920} 1921 1922/** 1923 * Send a HTTP redirect to the browser 1924 * 1925 * Works arround Microsoft IIS cookie sending bug. Exits the script. 1926 * 1927 * @link http://support.microsoft.com/kb/q176113/ 1928 * @author Andreas Gohr <andi@splitbrain.org> 1929 * 1930 * @param string $url url being directed to 1931 */ 1932function send_redirect($url) { 1933 $url = stripctl($url); // defend against HTTP Response Splitting 1934 1935 /* @var Input $INPUT */ 1936 global $INPUT; 1937 1938 //are there any undisplayed messages? keep them in session for display 1939 global $MSG; 1940 if(isset($MSG) && count($MSG) && !defined('NOSESSION')) { 1941 //reopen session, store data and close session again 1942 @session_start(); 1943 $_SESSION[DOKU_COOKIE]['msg'] = $MSG; 1944 } 1945 1946 // always close the session 1947 session_write_close(); 1948 1949 // check if running on IIS < 6 with CGI-PHP 1950 if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') && 1951 (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) && 1952 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) && 1953 $matches[1] < 6 1954 ) { 1955 header('Refresh: 0;url='.$url); 1956 } else { 1957 header('Location: '.$url); 1958 } 1959 1960 // no exits during unit tests 1961 if(defined('DOKU_UNITTEST')) { 1962 // pass info about the redirect back to the test suite 1963 $testRequest = TestRequest::getRunning(); 1964 if($testRequest !== null) { 1965 $testRequest->addData('send_redirect', $url); 1966 } 1967 return; 1968 } 1969 1970 exit; 1971} 1972 1973/** 1974 * Validate a value using a set of valid values 1975 * 1976 * This function checks whether a specified value is set and in the array 1977 * $valid_values. If not, the function returns a default value or, if no 1978 * default is specified, throws an exception. 1979 * 1980 * @param string $param The name of the parameter 1981 * @param array $valid_values A set of valid values; Optionally a default may 1982 * be marked by the key “default”. 1983 * @param array $array The array containing the value (typically $_POST 1984 * or $_GET) 1985 * @param string $exc The text of the raised exception 1986 * 1987 * @throws Exception 1988 * @return mixed 1989 * @author Adrian Lang <lang@cosmocode.de> 1990 */ 1991function valid_input_set($param, $valid_values, $array, $exc = '') { 1992 if(isset($array[$param]) && in_array($array[$param], $valid_values)) { 1993 return $array[$param]; 1994 } elseif(isset($valid_values['default'])) { 1995 return $valid_values['default']; 1996 } else { 1997 throw new Exception($exc); 1998 } 1999} 2000 2001/** 2002 * Read a preference from the DokuWiki cookie 2003 * (remembering both keys & values are urlencoded) 2004 * 2005 * @param string $pref preference key 2006 * @param mixed $default value returned when preference not found 2007 * @return string preference value 2008 */ 2009function get_doku_pref($pref, $default) { 2010 $enc_pref = urlencode($pref); 2011 if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) { 2012 $parts = explode('#', $_COOKIE['DOKU_PREFS']); 2013 $cnt = count($parts); 2014 2015 // due to #2721 there might be duplicate entries, 2016 // so we read from the end 2017 for($i = $cnt-2; $i >= 0; $i -= 2) { 2018 if($parts[$i] == $enc_pref) { 2019 return urldecode($parts[$i + 1]); 2020 } 2021 } 2022 } 2023 return $default; 2024} 2025 2026/** 2027 * Add a preference to the DokuWiki cookie 2028 * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded) 2029 * Remove it by setting $val to false 2030 * 2031 * @param string $pref preference key 2032 * @param string $val preference value 2033 */ 2034function set_doku_pref($pref, $val) { 2035 global $conf; 2036 $orig = get_doku_pref($pref, false); 2037 $cookieVal = ''; 2038 2039 if($orig !== false && ($orig !== $val)) { 2040 $parts = explode('#', $_COOKIE['DOKU_PREFS']); 2041 $cnt = count($parts); 2042 // urlencode $pref for the comparison 2043 $enc_pref = rawurlencode($pref); 2044 $seen = false; 2045 for ($i = 0; $i < $cnt; $i += 2) { 2046 if ($parts[$i] == $enc_pref) { 2047 if (!$seen){ 2048 if ($val !== false) { 2049 $parts[$i + 1] = rawurlencode($val); 2050 } else { 2051 unset($parts[$i]); 2052 unset($parts[$i + 1]); 2053 } 2054 $seen = true; 2055 } else { 2056 // no break because we want to remove duplicate entries 2057 unset($parts[$i]); 2058 unset($parts[$i + 1]); 2059 } 2060 } 2061 } 2062 $cookieVal = implode('#', $parts); 2063 } else if ($orig === false && $val !== false) { 2064 $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') . 2065 rawurlencode($pref) . '#' . rawurlencode($val); 2066 } 2067 2068 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 2069 if(defined('DOKU_UNITTEST')) { 2070 $_COOKIE['DOKU_PREFS'] = $cookieVal; 2071 }else{ 2072 setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl())); 2073 } 2074} 2075 2076/** 2077 * Strips source mapping declarations from given text #601 2078 * 2079 * @param string &$text reference to the CSS or JavaScript code to clean 2080 */ 2081function stripsourcemaps(&$text){ 2082 $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text); 2083} 2084 2085/** 2086 * Returns the contents of a given SVG file for embedding 2087 * 2088 * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through 2089 * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small 2090 * files are embedded. 2091 * 2092 * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG! 2093 * 2094 * @param string $file full path to the SVG file 2095 * @param int $maxsize maximum allowed size for the SVG to be embedded 2096 * @return string|false the SVG content, false if the file couldn't be loaded 2097 */ 2098function inlineSVG($file, $maxsize = 2048) { 2099 $file = trim($file); 2100 if($file === '') return false; 2101 if(!file_exists($file)) return false; 2102 if(filesize($file) > $maxsize) return false; 2103 if(!is_readable($file)) return false; 2104 $content = file_get_contents($file); 2105 $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments 2106 $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header 2107 $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type 2108 $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags 2109 $content = trim($content); 2110 if(substr($content, 0, 5) !== '<svg ') return false; 2111 return $content; 2112} 2113 2114//Setup VIM: ex: et ts=2 : 2115