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