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