[ Index ] |
PHP Cross Reference of MediaWiki-1.24.0 |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * PHP parser that converts wiki markup to HTML. 4 * 5 * This program is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation; either version 2 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License along 16 * with this program; if not, write to the Free Software Foundation, Inc., 17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 * http://www.gnu.org/copyleft/gpl.html 19 * 20 * @file 21 * @ingroup Parser 22 */ 23 24 /** 25 * @defgroup Parser Parser 26 */ 27 28 /** 29 * PHP Parser - Processes wiki markup (which uses a more user-friendly 30 * syntax, such as "[[link]]" for making links), and provides a one-way 31 * transformation of that wiki markup it into (X)HTML output / markup 32 * (which in turn the browser understands, and can display). 33 * 34 * There are seven main entry points into the Parser class: 35 * 36 * - Parser::parse() 37 * produces HTML output 38 * - Parser::preSaveTransform(). 39 * produces altered wiki markup. 40 * - Parser::preprocess() 41 * removes HTML comments and expands templates 42 * - Parser::cleanSig() and Parser::cleanSigInSig() 43 * Cleans a signature before saving it to preferences 44 * - Parser::getSection() 45 * Return the content of a section from an article for section editing 46 * - Parser::replaceSection() 47 * Replaces a section by number inside an article 48 * - Parser::getPreloadText() 49 * Removes <noinclude> sections, and <includeonly> tags. 50 * 51 * Globals used: 52 * object: $wgContLang 53 * 54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away! 55 * 56 * @par Settings: 57 * $wgNamespacesWithSubpages 58 * 59 * @par Settings only within ParserOptions: 60 * $wgAllowExternalImages 61 * $wgAllowSpecialInclusion 62 * $wgInterwikiMagic 63 * $wgMaxArticleSize 64 * 65 * @ingroup Parser 66 */ 67 class Parser { 68 /** 69 * Update this version number when the ParserOutput format 70 * changes in an incompatible way, so the parser cache 71 * can automatically discard old data. 72 */ 73 const VERSION = '1.6.4'; 74 75 /** 76 * Update this version number when the output of serialiseHalfParsedText() 77 * changes in an incompatible way 78 */ 79 const HALF_PARSED_VERSION = 2; 80 81 # Flags for Parser::setFunctionHook 82 # Also available as global constants from Defines.php 83 const SFH_NO_HASH = 1; 84 const SFH_OBJECT_ARGS = 2; 85 86 # Constants needed for external link processing 87 # Everything except bracket, space, or control characters 88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20 89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052 90 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]'; 91 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+) 92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu'; 93 94 # State constants for the definition list colon extraction 95 const COLON_STATE_TEXT = 0; 96 const COLON_STATE_TAG = 1; 97 const COLON_STATE_TAGSTART = 2; 98 const COLON_STATE_CLOSETAG = 3; 99 const COLON_STATE_TAGSLASH = 4; 100 const COLON_STATE_COMMENT = 5; 101 const COLON_STATE_COMMENTDASH = 6; 102 const COLON_STATE_COMMENTDASHDASH = 7; 103 104 # Flags for preprocessToDom 105 const PTD_FOR_INCLUSION = 1; 106 107 # Allowed values for $this->mOutputType 108 # Parameter to startExternalParse(). 109 const OT_HTML = 1; # like parse() 110 const OT_WIKI = 2; # like preSaveTransform() 111 const OT_PREPROCESS = 3; # like preprocess() 112 const OT_MSG = 3; 113 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged. 114 115 # Marker Suffix needs to be accessible staticly. 116 const MARKER_SUFFIX = "-QINU\x7f"; 117 118 # Markers used for wrapping the table of contents 119 const TOC_START = '<mw:toc>'; 120 const TOC_END = '</mw:toc>'; 121 122 # Persistent: 123 public $mTagHooks = array(); 124 public $mTransparentTagHooks = array(); 125 public $mFunctionHooks = array(); 126 public $mFunctionSynonyms = array( 0 => array(), 1 => array() ); 127 public $mFunctionTagHooks = array(); 128 public $mStripList = array(); 129 public $mDefaultStripList = array(); 130 public $mVarCache = array(); 131 public $mImageParams = array(); 132 public $mImageParamsMagicArray = array(); 133 public $mMarkerIndex = 0; 134 public $mFirstCall = true; 135 136 # Initialised by initialiseVariables() 137 138 /** 139 * @var MagicWordArray 140 */ 141 public $mVariables; 142 143 /** 144 * @var MagicWordArray 145 */ 146 public $mSubstWords; 147 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor 148 149 # Cleared with clearState(): 150 /** 151 * @var ParserOutput 152 */ 153 public $mOutput; 154 public $mAutonumber, $mDTopen; 155 156 /** 157 * @var StripState 158 */ 159 public $mStripState; 160 161 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre; 162 /** 163 * @var LinkHolderArray 164 */ 165 public $mLinkHolders; 166 167 public $mLinkID; 168 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth; 169 public $mDefaultSort; 170 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores; 171 public $mExpensiveFunctionCount; # number of expensive parser function calls 172 public $mShowToc, $mForceTocPosition; 173 174 /** 175 * @var User 176 */ 177 public $mUser; # User object; only used when doing pre-save transform 178 179 # Temporary 180 # These are variables reset at least once per parse regardless of $clearState 181 182 /** 183 * @var ParserOptions 184 */ 185 public $mOptions; 186 187 /** 188 * @var Title 189 */ 190 public $mTitle; # Title context, used for self-link rendering and similar things 191 public $mOutputType; # Output type, one of the OT_xxx constants 192 public $ot; # Shortcut alias, see setOutputType() 193 public $mRevisionObject; # The revision object of the specified revision ID 194 public $mRevisionId; # ID to display in {{REVISIONID}} tags 195 public $mRevisionTimestamp; # The timestamp of the specified revision ID 196 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag 197 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable 198 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp 199 public $mInputSize = false; # For {{PAGESIZE}} on current page. 200 201 /** 202 * @var string 203 */ 204 public $mUniqPrefix; 205 206 /** 207 * @var array Array with the language name of each language link (i.e. the 208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending 209 * duplicate language links to the ParserOutput. 210 */ 211 public $mLangLinkLanguages; 212 213 /** 214 * @var bool Recursive call protection. 215 * This variable should be treated as if it were private. 216 */ 217 public $mInParse = false; 218 219 /** 220 * @param array $conf 221 */ 222 public function __construct( $conf = array() ) { 223 $this->mConf = $conf; 224 $this->mUrlProtocols = wfUrlProtocols(); 225 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' . 226 self::EXT_LINK_URL_CLASS . '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su'; 227 if ( isset( $conf['preprocessorClass'] ) ) { 228 $this->mPreprocessorClass = $conf['preprocessorClass']; 229 } elseif ( defined( 'HPHP_VERSION' ) ) { 230 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop 231 $this->mPreprocessorClass = 'Preprocessor_Hash'; 232 } elseif ( extension_loaded( 'domxml' ) ) { 233 # PECL extension that conflicts with the core DOM extension (bug 13770) 234 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" ); 235 $this->mPreprocessorClass = 'Preprocessor_Hash'; 236 } elseif ( extension_loaded( 'dom' ) ) { 237 $this->mPreprocessorClass = 'Preprocessor_DOM'; 238 } else { 239 $this->mPreprocessorClass = 'Preprocessor_Hash'; 240 } 241 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" ); 242 } 243 244 /** 245 * Reduce memory usage to reduce the impact of circular references 246 */ 247 public function __destruct() { 248 if ( isset( $this->mLinkHolders ) ) { 249 unset( $this->mLinkHolders ); 250 } 251 foreach ( $this as $name => $value ) { 252 unset( $this->$name ); 253 } 254 } 255 256 /** 257 * Allow extensions to clean up when the parser is cloned 258 */ 259 public function __clone() { 260 $this->mInParse = false; 261 wfRunHooks( 'ParserCloned', array( $this ) ); 262 } 263 264 /** 265 * Do various kinds of initialisation on the first call of the parser 266 */ 267 public function firstCallInit() { 268 if ( !$this->mFirstCall ) { 269 return; 270 } 271 $this->mFirstCall = false; 272 273 wfProfileIn( __METHOD__ ); 274 275 CoreParserFunctions::register( $this ); 276 CoreTagHooks::register( $this ); 277 $this->initialiseVariables(); 278 279 wfRunHooks( 'ParserFirstCallInit', array( &$this ) ); 280 wfProfileOut( __METHOD__ ); 281 } 282 283 /** 284 * Clear Parser state 285 * 286 * @private 287 */ 288 public function clearState() { 289 wfProfileIn( __METHOD__ ); 290 if ( $this->mFirstCall ) { 291 $this->firstCallInit(); 292 } 293 $this->mOutput = new ParserOutput; 294 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) ); 295 $this->mAutonumber = 0; 296 $this->mLastSection = ''; 297 $this->mDTopen = false; 298 $this->mIncludeCount = array(); 299 $this->mArgStack = false; 300 $this->mInPre = false; 301 $this->mLinkHolders = new LinkHolderArray( $this ); 302 $this->mLinkID = 0; 303 $this->mRevisionObject = $this->mRevisionTimestamp = 304 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null; 305 $this->mVarCache = array(); 306 $this->mUser = null; 307 $this->mLangLinkLanguages = array(); 308 309 /** 310 * Prefix for temporary replacement strings for the multipass parser. 311 * \x07 should never appear in input as it's disallowed in XML. 312 * Using it at the front also gives us a little extra robustness 313 * since it shouldn't match when butted up against identifier-like 314 * string constructs. 315 * 316 * Must not consist of all title characters, or else it will change 317 * the behavior of <nowiki> in a link. 318 */ 319 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString(); 320 $this->mStripState = new StripState( $this->mUniqPrefix ); 321 322 # Clear these on every parse, bug 4549 323 $this->mTplRedirCache = $this->mTplDomCache = array(); 324 325 $this->mShowToc = true; 326 $this->mForceTocPosition = false; 327 $this->mIncludeSizes = array( 328 'post-expand' => 0, 329 'arg' => 0, 330 ); 331 $this->mPPNodeCount = 0; 332 $this->mGeneratedPPNodeCount = 0; 333 $this->mHighestExpansionDepth = 0; 334 $this->mDefaultSort = false; 335 $this->mHeadings = array(); 336 $this->mDoubleUnderscores = array(); 337 $this->mExpensiveFunctionCount = 0; 338 339 # Fix cloning 340 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) { 341 $this->mPreprocessor = null; 342 } 343 344 wfRunHooks( 'ParserClearState', array( &$this ) ); 345 wfProfileOut( __METHOD__ ); 346 } 347 348 /** 349 * Convert wikitext to HTML 350 * Do not call this function recursively. 351 * 352 * @param string $text Text we want to parse 353 * @param Title $title 354 * @param ParserOptions $options 355 * @param bool $linestart 356 * @param bool $clearState 357 * @param int $revid Number to pass in {{REVISIONID}} 358 * @return ParserOutput A ParserOutput 359 */ 360 public function parse( $text, Title $title, ParserOptions $options, 361 $linestart = true, $clearState = true, $revid = null 362 ) { 363 /** 364 * First pass--just handle <nowiki> sections, pass the rest off 365 * to internalParse() which does all the real work. 366 */ 367 368 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames; 369 $fname = __METHOD__ . '-' . wfGetCaller(); 370 wfProfileIn( __METHOD__ ); 371 wfProfileIn( $fname ); 372 373 if ( $clearState ) { 374 $magicScopeVariable = $this->lock(); 375 } 376 377 $this->startParse( $title, $options, self::OT_HTML, $clearState ); 378 379 $this->mInputSize = strlen( $text ); 380 if ( $this->mOptions->getEnableLimitReport() ) { 381 $this->mOutput->resetParseStartTime(); 382 } 383 384 # Remove the strip marker tag prefix from the input, if present. 385 if ( $clearState ) { 386 $text = str_replace( $this->mUniqPrefix, '', $text ); 387 } 388 389 $oldRevisionId = $this->mRevisionId; 390 $oldRevisionObject = $this->mRevisionObject; 391 $oldRevisionTimestamp = $this->mRevisionTimestamp; 392 $oldRevisionUser = $this->mRevisionUser; 393 $oldRevisionSize = $this->mRevisionSize; 394 if ( $revid !== null ) { 395 $this->mRevisionId = $revid; 396 $this->mRevisionObject = null; 397 $this->mRevisionTimestamp = null; 398 $this->mRevisionUser = null; 399 $this->mRevisionSize = null; 400 } 401 402 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 403 # No more strip! 404 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 405 $text = $this->internalParse( $text ); 406 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) ); 407 408 $text = $this->mStripState->unstripGeneral( $text ); 409 410 # Clean up special characters, only run once, next-to-last before doBlockLevels 411 $fixtags = array( 412 # french spaces, last one Guillemet-left 413 # only if there is something before the space 414 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ', 415 # french spaces, Guillemet-right 416 '/(\\302\\253) /' => '\\1 ', 417 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874. 418 ); 419 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text ); 420 421 $text = $this->doBlockLevels( $text, $linestart ); 422 423 $this->replaceLinkHolders( $text ); 424 425 /** 426 * The input doesn't get language converted if 427 * a) It's disabled 428 * b) Content isn't converted 429 * c) It's a conversion table 430 * d) it is an interface message (which is in the user language) 431 */ 432 if ( !( $options->getDisableContentConversion() 433 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) ) 434 ) { 435 if ( !$this->mOptions->getInterfaceMessage() ) { 436 # The position of the convert() call should not be changed. it 437 # assumes that the links are all replaced and the only thing left 438 # is the <nowiki> mark. 439 $text = $this->getConverterLanguage()->convert( $text ); 440 } 441 } 442 443 /** 444 * A converted title will be provided in the output object if title and 445 * content conversion are enabled, the article text does not contain 446 * a conversion-suppressing double-underscore tag, and no 447 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over 448 * automatic link conversion. 449 */ 450 if ( !( $options->getDisableTitleConversion() 451 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) 452 || isset( $this->mDoubleUnderscores['notitleconvert'] ) 453 || $this->mOutput->getDisplayTitle() !== false ) 454 ) { 455 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle(); 456 if ( $convruletitle ) { 457 $this->mOutput->setTitleText( $convruletitle ); 458 } else { 459 $titleText = $this->getConverterLanguage()->convertTitle( $title ); 460 $this->mOutput->setTitleText( $titleText ); 461 } 462 } 463 464 $text = $this->mStripState->unstripNoWiki( $text ); 465 466 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) ); 467 468 $text = $this->replaceTransparentTags( $text ); 469 $text = $this->mStripState->unstripGeneral( $text ); 470 471 $text = Sanitizer::normalizeCharReferences( $text ); 472 473 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) { 474 $text = MWTidy::tidy( $text ); 475 } else { 476 # attempt to sanitize at least some nesting problems 477 # (bug #2702 and quite a few others) 478 $tidyregs = array( 479 # ''Something [http://www.cool.com cool''] --> 480 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a> 481 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' => 482 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9', 483 # fix up an anchor inside another anchor, only 484 # at least for a single single nested link (bug 3695) 485 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' => 486 '\\1\\2</a>\\3</a>\\1\\4</a>', 487 # fix div inside inline elements- doBlockLevels won't wrap a line which 488 # contains a div, so fix it up here; replace 489 # div with escaped text 490 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' => 491 '\\1\\3<div\\5>\\6</div>\\8\\9', 492 # remove empty italic or bold tag pairs, some 493 # introduced by rules above 494 '/<([bi])><\/\\1>/' => '', 495 ); 496 497 $text = preg_replace( 498 array_keys( $tidyregs ), 499 array_values( $tidyregs ), 500 $text ); 501 } 502 503 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) { 504 $this->limitationWarn( 'expensive-parserfunction', 505 $this->mExpensiveFunctionCount, 506 $this->mOptions->getExpensiveParserFunctionLimit() 507 ); 508 } 509 510 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) ); 511 512 # Information on include size limits, for the benefit of users who try to skirt them 513 if ( $this->mOptions->getEnableLimitReport() ) { 514 $max = $this->mOptions->getMaxIncludeSize(); 515 516 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' ); 517 if ( $cpuTime !== null ) { 518 $this->mOutput->setLimitReportData( 'limitreport-cputime', 519 sprintf( "%.3f", $cpuTime ) 520 ); 521 } 522 523 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' ); 524 $this->mOutput->setLimitReportData( 'limitreport-walltime', 525 sprintf( "%.3f", $wallTime ) 526 ); 527 528 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes', 529 array( $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() ) 530 ); 531 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes', 532 array( $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() ) 533 ); 534 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize', 535 array( $this->mIncludeSizes['post-expand'], $max ) 536 ); 537 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize', 538 array( $this->mIncludeSizes['arg'], $max ) 539 ); 540 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth', 541 array( $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() ) 542 ); 543 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount', 544 array( $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() ) 545 ); 546 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput ) ); 547 548 $limitReport = "NewPP limit report\n"; 549 if ( $wgShowHostnames ) { 550 $limitReport .= 'Parsed by ' . wfHostname() . "\n"; 551 } 552 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) { 553 if ( wfRunHooks( 'ParserLimitReportFormat', 554 array( $key, &$value, &$limitReport, false, false ) 555 ) ) { 556 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false ); 557 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) ) 558 ->inLanguage( 'en' )->useDatabase( false ); 559 if ( !$valueMsg->exists() ) { 560 $valueMsg = new RawMessage( '$1' ); 561 } 562 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) { 563 $valueMsg->params( $value ); 564 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n"; 565 } 566 } 567 } 568 // Since we're not really outputting HTML, decode the entities and 569 // then re-encode the things that need hiding inside HTML comments. 570 $limitReport = htmlspecialchars_decode( $limitReport ); 571 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) ); 572 573 // Sanitize for comment. Note '‐' in the replacement is U+2010, 574 // which looks much like the problematic '-'. 575 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport ); 576 $text .= "\n<!-- \n$limitReport-->\n"; 577 578 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) { 579 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' . 580 $this->mTitle->getPrefixedDBkey() ); 581 } 582 } 583 $this->mOutput->setText( $text ); 584 585 $this->mRevisionId = $oldRevisionId; 586 $this->mRevisionObject = $oldRevisionObject; 587 $this->mRevisionTimestamp = $oldRevisionTimestamp; 588 $this->mRevisionUser = $oldRevisionUser; 589 $this->mRevisionSize = $oldRevisionSize; 590 $this->mInputSize = false; 591 wfProfileOut( $fname ); 592 wfProfileOut( __METHOD__ ); 593 594 return $this->mOutput; 595 } 596 597 /** 598 * Recursive parser entry point that can be called from an extension tag 599 * hook. 600 * 601 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded 602 * 603 * @param string $text Text extension wants to have parsed 604 * @param bool|PPFrame $frame The frame to use for expanding any template variables 605 * 606 * @return string 607 */ 608 public function recursiveTagParse( $text, $frame = false ) { 609 wfProfileIn( __METHOD__ ); 610 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 611 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 612 $text = $this->internalParse( $text, false, $frame ); 613 wfProfileOut( __METHOD__ ); 614 return $text; 615 } 616 617 /** 618 * Expand templates and variables in the text, producing valid, static wikitext. 619 * Also removes comments. 620 * Do not call this function recursively. 621 * @param string $text 622 * @param Title $title 623 * @param ParserOptions $options 624 * @param int|null $revid 625 * @param bool|PPFrame $frame 626 * @return mixed|string 627 */ 628 public function preprocess( $text, Title $title = null, ParserOptions $options, $revid = null, $frame = false ) { 629 wfProfileIn( __METHOD__ ); 630 $magicScopeVariable = $this->lock(); 631 $this->startParse( $title, $options, self::OT_PREPROCESS, true ); 632 if ( $revid !== null ) { 633 $this->mRevisionId = $revid; 634 } 635 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 636 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 637 $text = $this->replaceVariables( $text, $frame ); 638 $text = $this->mStripState->unstripBoth( $text ); 639 wfProfileOut( __METHOD__ ); 640 return $text; 641 } 642 643 /** 644 * Recursive parser entry point that can be called from an extension tag 645 * hook. 646 * 647 * @param string $text Text to be expanded 648 * @param bool|PPFrame $frame The frame to use for expanding any template variables 649 * @return string 650 * @since 1.19 651 */ 652 public function recursivePreprocess( $text, $frame = false ) { 653 wfProfileIn( __METHOD__ ); 654 $text = $this->replaceVariables( $text, $frame ); 655 $text = $this->mStripState->unstripBoth( $text ); 656 wfProfileOut( __METHOD__ ); 657 return $text; 658 } 659 660 /** 661 * Process the wikitext for the "?preload=" feature. (bug 5210) 662 * 663 * "<noinclude>", "<includeonly>" etc. are parsed as for template 664 * transclusion, comments, templates, arguments, tags hooks and parser 665 * functions are untouched. 666 * 667 * @param string $text 668 * @param Title $title 669 * @param ParserOptions $options 670 * @param array $params 671 * @return string 672 */ 673 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = array() ) { 674 $msg = new RawMessage( $text ); 675 $text = $msg->params( $params )->plain(); 676 677 # Parser (re)initialisation 678 $magicScopeVariable = $this->lock(); 679 $this->startParse( $title, $options, self::OT_PLAIN, true ); 680 681 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES; 682 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 683 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags ); 684 $text = $this->mStripState->unstripBoth( $text ); 685 return $text; 686 } 687 688 /** 689 * Get a random string 690 * 691 * @return string 692 */ 693 public static function getRandomString() { 694 return wfRandomString( 16 ); 695 } 696 697 /** 698 * Set the current user. 699 * Should only be used when doing pre-save transform. 700 * 701 * @param User|null $user User object or null (to reset) 702 */ 703 public function setUser( $user ) { 704 $this->mUser = $user; 705 } 706 707 /** 708 * Accessor for mUniqPrefix. 709 * 710 * @return string 711 */ 712 public function uniqPrefix() { 713 if ( !isset( $this->mUniqPrefix ) ) { 714 # @todo FIXME: This is probably *horribly wrong* 715 # LanguageConverter seems to want $wgParser's uniqPrefix, however 716 # if this is called for a parser cache hit, the parser may not 717 # have ever been initialized in the first place. 718 # Not really sure what the heck is supposed to be going on here. 719 return ''; 720 # throw new MWException( "Accessing uninitialized mUniqPrefix" ); 721 } 722 return $this->mUniqPrefix; 723 } 724 725 /** 726 * Set the context title 727 * 728 * @param Title $t 729 */ 730 public function setTitle( $t ) { 731 if ( !$t ) { 732 $t = Title::newFromText( 'NO TITLE' ); 733 } 734 735 if ( $t->hasFragment() ) { 736 # Strip the fragment to avoid various odd effects 737 $this->mTitle = clone $t; 738 $this->mTitle->setFragment( '' ); 739 } else { 740 $this->mTitle = $t; 741 } 742 } 743 744 /** 745 * Accessor for the Title object 746 * 747 * @return Title 748 */ 749 public function getTitle() { 750 return $this->mTitle; 751 } 752 753 /** 754 * Accessor/mutator for the Title object 755 * 756 * @param Title $x Title object or null to just get the current one 757 * @return Title 758 */ 759 public function Title( $x = null ) { 760 return wfSetVar( $this->mTitle, $x ); 761 } 762 763 /** 764 * Set the output type 765 * 766 * @param int $ot New value 767 */ 768 public function setOutputType( $ot ) { 769 $this->mOutputType = $ot; 770 # Shortcut alias 771 $this->ot = array( 772 'html' => $ot == self::OT_HTML, 773 'wiki' => $ot == self::OT_WIKI, 774 'pre' => $ot == self::OT_PREPROCESS, 775 'plain' => $ot == self::OT_PLAIN, 776 ); 777 } 778 779 /** 780 * Accessor/mutator for the output type 781 * 782 * @param int|null $x New value or null to just get the current one 783 * @return int 784 */ 785 public function OutputType( $x = null ) { 786 return wfSetVar( $this->mOutputType, $x ); 787 } 788 789 /** 790 * Get the ParserOutput object 791 * 792 * @return ParserOutput 793 */ 794 public function getOutput() { 795 return $this->mOutput; 796 } 797 798 /** 799 * Get the ParserOptions object 800 * 801 * @return ParserOptions 802 */ 803 public function getOptions() { 804 return $this->mOptions; 805 } 806 807 /** 808 * Accessor/mutator for the ParserOptions object 809 * 810 * @param ParserOptions $x New value or null to just get the current one 811 * @return ParserOptions Current ParserOptions object 812 */ 813 public function Options( $x = null ) { 814 return wfSetVar( $this->mOptions, $x ); 815 } 816 817 /** 818 * @return int 819 */ 820 public function nextLinkID() { 821 return $this->mLinkID++; 822 } 823 824 /** 825 * @param int $id 826 */ 827 public function setLinkID( $id ) { 828 $this->mLinkID = $id; 829 } 830 831 /** 832 * Get a language object for use in parser functions such as {{FORMATNUM:}} 833 * @return Language 834 */ 835 public function getFunctionLang() { 836 return $this->getTargetLanguage(); 837 } 838 839 /** 840 * Get the target language for the content being parsed. This is usually the 841 * language that the content is in. 842 * 843 * @since 1.19 844 * 845 * @throws MWException 846 * @return Language 847 */ 848 public function getTargetLanguage() { 849 $target = $this->mOptions->getTargetLanguage(); 850 851 if ( $target !== null ) { 852 return $target; 853 } elseif ( $this->mOptions->getInterfaceMessage() ) { 854 return $this->mOptions->getUserLangObj(); 855 } elseif ( is_null( $this->mTitle ) ) { 856 throw new MWException( __METHOD__ . ': $this->mTitle is null' ); 857 } 858 859 return $this->mTitle->getPageLanguage(); 860 } 861 862 /** 863 * Get the language object for language conversion 864 * @return Language|null 865 */ 866 public function getConverterLanguage() { 867 return $this->getTargetLanguage(); 868 } 869 870 /** 871 * Get a User object either from $this->mUser, if set, or from the 872 * ParserOptions object otherwise 873 * 874 * @return User 875 */ 876 public function getUser() { 877 if ( !is_null( $this->mUser ) ) { 878 return $this->mUser; 879 } 880 return $this->mOptions->getUser(); 881 } 882 883 /** 884 * Get a preprocessor object 885 * 886 * @return Preprocessor 887 */ 888 public function getPreprocessor() { 889 if ( !isset( $this->mPreprocessor ) ) { 890 $class = $this->mPreprocessorClass; 891 $this->mPreprocessor = new $class( $this ); 892 } 893 return $this->mPreprocessor; 894 } 895 896 /** 897 * Replaces all occurrences of HTML-style comments and the given tags 898 * in the text with a random marker and returns the next text. The output 899 * parameter $matches will be an associative array filled with data in 900 * the form: 901 * 902 * @code 903 * 'UNIQ-xxxxx' => array( 904 * 'element', 905 * 'tag content', 906 * array( 'param' => 'x' ), 907 * '<element param="x">tag content</element>' ) ) 908 * @endcode 909 * 910 * @param array $elements List of element names. Comments are always extracted. 911 * @param string $text Source text string. 912 * @param array $matches Out parameter, Array: extracted tags 913 * @param string $uniq_prefix 914 * @return string Stripped text 915 */ 916 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) { 917 static $n = 1; 918 $stripped = ''; 919 $matches = array(); 920 921 $taglist = implode( '|', $elements ); 922 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i"; 923 924 while ( $text != '' ) { 925 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE ); 926 $stripped .= $p[0]; 927 if ( count( $p ) < 5 ) { 928 break; 929 } 930 if ( count( $p ) > 5 ) { 931 # comment 932 $element = $p[4]; 933 $attributes = ''; 934 $close = ''; 935 $inside = $p[5]; 936 } else { 937 # tag 938 $element = $p[1]; 939 $attributes = $p[2]; 940 $close = $p[3]; 941 $inside = $p[4]; 942 } 943 944 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX; 945 $stripped .= $marker; 946 947 if ( $close === '/>' ) { 948 # Empty element tag, <tag /> 949 $content = null; 950 $text = $inside; 951 $tail = null; 952 } else { 953 if ( $element === '!--' ) { 954 $end = '/(-->)/'; 955 } else { 956 $end = "/(<\\/$element\\s*>)/i"; 957 } 958 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE ); 959 $content = $q[0]; 960 if ( count( $q ) < 3 ) { 961 # No end tag -- let it run out to the end of the text. 962 $tail = ''; 963 $text = ''; 964 } else { 965 $tail = $q[1]; 966 $text = $q[2]; 967 } 968 } 969 970 $matches[$marker] = array( $element, 971 $content, 972 Sanitizer::decodeTagAttributes( $attributes ), 973 "<$element$attributes$close$content$tail" ); 974 } 975 return $stripped; 976 } 977 978 /** 979 * Get a list of strippable XML-like elements 980 * 981 * @return array 982 */ 983 public function getStripList() { 984 return $this->mStripList; 985 } 986 987 /** 988 * Add an item to the strip state 989 * Returns the unique tag which must be inserted into the stripped text 990 * The tag will be replaced with the original text in unstrip() 991 * 992 * @param string $text 993 * 994 * @return string 995 */ 996 public function insertStripItem( $text ) { 997 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX; 998 $this->mMarkerIndex++; 999 $this->mStripState->addGeneral( $rnd, $text ); 1000 return $rnd; 1001 } 1002 1003 /** 1004 * parse the wiki syntax used to render tables 1005 * 1006 * @private 1007 * @param string $text 1008 * @return string 1009 */ 1010 public function doTableStuff( $text ) { 1011 wfProfileIn( __METHOD__ ); 1012 1013 $lines = StringUtils::explode( "\n", $text ); 1014 $out = ''; 1015 $td_history = array(); # Is currently a td tag open? 1016 $last_tag_history = array(); # Save history of last lag activated (td, th or caption) 1017 $tr_history = array(); # Is currently a tr tag open? 1018 $tr_attributes = array(); # history of tr attributes 1019 $has_opened_tr = array(); # Did this table open a <tr> element? 1020 $indent_level = 0; # indent level of the table 1021 1022 foreach ( $lines as $outLine ) { 1023 $line = trim( $outLine ); 1024 1025 if ( $line === '' ) { # empty line, go to next line 1026 $out .= $outLine . "\n"; 1027 continue; 1028 } 1029 1030 $first_character = $line[0]; 1031 $matches = array(); 1032 1033 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) { 1034 # First check if we are starting a new table 1035 $indent_level = strlen( $matches[1] ); 1036 1037 $attributes = $this->mStripState->unstripBoth( $matches[2] ); 1038 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' ); 1039 1040 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>"; 1041 array_push( $td_history, false ); 1042 array_push( $last_tag_history, '' ); 1043 array_push( $tr_history, false ); 1044 array_push( $tr_attributes, '' ); 1045 array_push( $has_opened_tr, false ); 1046 } elseif ( count( $td_history ) == 0 ) { 1047 # Don't do any of the following 1048 $out .= $outLine . "\n"; 1049 continue; 1050 } elseif ( substr( $line, 0, 2 ) === '|}' ) { 1051 # We are ending a table 1052 $line = '</table>' . substr( $line, 2 ); 1053 $last_tag = array_pop( $last_tag_history ); 1054 1055 if ( !array_pop( $has_opened_tr ) ) { 1056 $line = "<tr><td></td></tr>{$line}"; 1057 } 1058 1059 if ( array_pop( $tr_history ) ) { 1060 $line = "</tr>{$line}"; 1061 } 1062 1063 if ( array_pop( $td_history ) ) { 1064 $line = "</{$last_tag}>{$line}"; 1065 } 1066 array_pop( $tr_attributes ); 1067 $outLine = $line . str_repeat( '</dd></dl>', $indent_level ); 1068 } elseif ( substr( $line, 0, 2 ) === '|-' ) { 1069 # Now we have a table row 1070 $line = preg_replace( '#^\|-+#', '', $line ); 1071 1072 # Whats after the tag is now only attributes 1073 $attributes = $this->mStripState->unstripBoth( $line ); 1074 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' ); 1075 array_pop( $tr_attributes ); 1076 array_push( $tr_attributes, $attributes ); 1077 1078 $line = ''; 1079 $last_tag = array_pop( $last_tag_history ); 1080 array_pop( $has_opened_tr ); 1081 array_push( $has_opened_tr, true ); 1082 1083 if ( array_pop( $tr_history ) ) { 1084 $line = '</tr>'; 1085 } 1086 1087 if ( array_pop( $td_history ) ) { 1088 $line = "</{$last_tag}>{$line}"; 1089 } 1090 1091 $outLine = $line; 1092 array_push( $tr_history, false ); 1093 array_push( $td_history, false ); 1094 array_push( $last_tag_history, '' ); 1095 } elseif ( $first_character === '|' 1096 || $first_character === '!' 1097 || substr( $line, 0, 2 ) === '|+' 1098 ) { 1099 # This might be cell elements, td, th or captions 1100 if ( substr( $line, 0, 2 ) === '|+' ) { 1101 $first_character = '+'; 1102 $line = substr( $line, 1 ); 1103 } 1104 1105 $line = substr( $line, 1 ); 1106 1107 if ( $first_character === '!' ) { 1108 $line = str_replace( '!!', '||', $line ); 1109 } 1110 1111 # Split up multiple cells on the same line. 1112 # FIXME : This can result in improper nesting of tags processed 1113 # by earlier parser steps, but should avoid splitting up eg 1114 # attribute values containing literal "||". 1115 $cells = StringUtils::explodeMarkup( '||', $line ); 1116 1117 $outLine = ''; 1118 1119 # Loop through each table cell 1120 foreach ( $cells as $cell ) { 1121 $previous = ''; 1122 if ( $first_character !== '+' ) { 1123 $tr_after = array_pop( $tr_attributes ); 1124 if ( !array_pop( $tr_history ) ) { 1125 $previous = "<tr{$tr_after}>\n"; 1126 } 1127 array_push( $tr_history, true ); 1128 array_push( $tr_attributes, '' ); 1129 array_pop( $has_opened_tr ); 1130 array_push( $has_opened_tr, true ); 1131 } 1132 1133 $last_tag = array_pop( $last_tag_history ); 1134 1135 if ( array_pop( $td_history ) ) { 1136 $previous = "</{$last_tag}>\n{$previous}"; 1137 } 1138 1139 if ( $first_character === '|' ) { 1140 $last_tag = 'td'; 1141 } elseif ( $first_character === '!' ) { 1142 $last_tag = 'th'; 1143 } elseif ( $first_character === '+' ) { 1144 $last_tag = 'caption'; 1145 } else { 1146 $last_tag = ''; 1147 } 1148 1149 array_push( $last_tag_history, $last_tag ); 1150 1151 # A cell could contain both parameters and data 1152 $cell_data = explode( '|', $cell, 2 ); 1153 1154 # Bug 553: Note that a '|' inside an invalid link should not 1155 # be mistaken as delimiting cell parameters 1156 if ( strpos( $cell_data[0], '[[' ) !== false ) { 1157 $cell = "{$previous}<{$last_tag}>{$cell}"; 1158 } elseif ( count( $cell_data ) == 1 ) { 1159 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}"; 1160 } else { 1161 $attributes = $this->mStripState->unstripBoth( $cell_data[0] ); 1162 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag ); 1163 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}"; 1164 } 1165 1166 $outLine .= $cell; 1167 array_push( $td_history, true ); 1168 } 1169 } 1170 $out .= $outLine . "\n"; 1171 } 1172 1173 # Closing open td, tr && table 1174 while ( count( $td_history ) > 0 ) { 1175 if ( array_pop( $td_history ) ) { 1176 $out .= "</td>\n"; 1177 } 1178 if ( array_pop( $tr_history ) ) { 1179 $out .= "</tr>\n"; 1180 } 1181 if ( !array_pop( $has_opened_tr ) ) { 1182 $out .= "<tr><td></td></tr>\n"; 1183 } 1184 1185 $out .= "</table>\n"; 1186 } 1187 1188 # Remove trailing line-ending (b/c) 1189 if ( substr( $out, -1 ) === "\n" ) { 1190 $out = substr( $out, 0, -1 ); 1191 } 1192 1193 # special case: don't return empty table 1194 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) { 1195 $out = ''; 1196 } 1197 1198 wfProfileOut( __METHOD__ ); 1199 1200 return $out; 1201 } 1202 1203 /** 1204 * Helper function for parse() that transforms wiki markup into 1205 * HTML. Only called for $mOutputType == self::OT_HTML. 1206 * 1207 * @private 1208 * 1209 * @param string $text 1210 * @param bool $isMain 1211 * @param bool $frame 1212 * 1213 * @return string 1214 */ 1215 public function internalParse( $text, $isMain = true, $frame = false ) { 1216 wfProfileIn( __METHOD__ ); 1217 1218 $origText = $text; 1219 1220 # Hook to suspend the parser in this state 1221 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) { 1222 wfProfileOut( __METHOD__ ); 1223 return $text; 1224 } 1225 1226 # if $frame is provided, then use $frame for replacing any variables 1227 if ( $frame ) { 1228 # use frame depth to infer how include/noinclude tags should be handled 1229 # depth=0 means this is the top-level document; otherwise it's an included document 1230 if ( !$frame->depth ) { 1231 $flag = 0; 1232 } else { 1233 $flag = Parser::PTD_FOR_INCLUSION; 1234 } 1235 $dom = $this->preprocessToDom( $text, $flag ); 1236 $text = $frame->expand( $dom ); 1237 } else { 1238 # if $frame is not provided, then use old-style replaceVariables 1239 $text = $this->replaceVariables( $text ); 1240 } 1241 1242 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) ); 1243 $text = Sanitizer::removeHTMLtags( 1244 $text, 1245 array( &$this, 'attributeStripCallback' ), 1246 false, 1247 array_keys( $this->mTransparentTagHooks ) 1248 ); 1249 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) ); 1250 1251 # Tables need to come after variable replacement for things to work 1252 # properly; putting them before other transformations should keep 1253 # exciting things like link expansions from showing up in surprising 1254 # places. 1255 $text = $this->doTableStuff( $text ); 1256 1257 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text ); 1258 1259 $text = $this->doDoubleUnderscore( $text ); 1260 1261 $text = $this->doHeadings( $text ); 1262 $text = $this->replaceInternalLinks( $text ); 1263 $text = $this->doAllQuotes( $text ); 1264 $text = $this->replaceExternalLinks( $text ); 1265 1266 # replaceInternalLinks may sometimes leave behind 1267 # absolute URLs, which have to be masked to hide them from replaceExternalLinks 1268 $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text ); 1269 1270 $text = $this->doMagicLinks( $text ); 1271 $text = $this->formatHeadings( $text, $origText, $isMain ); 1272 1273 wfProfileOut( __METHOD__ ); 1274 return $text; 1275 } 1276 1277 /** 1278 * Replace special strings like "ISBN xxx" and "RFC xxx" with 1279 * magic external links. 1280 * 1281 * DML 1282 * @private 1283 * 1284 * @param string $text 1285 * 1286 * @return string 1287 */ 1288 public function doMagicLinks( $text ) { 1289 wfProfileIn( __METHOD__ ); 1290 $prots = wfUrlProtocolsWithoutProtRel(); 1291 $urlChar = self::EXT_LINK_URL_CLASS; 1292 $text = preg_replace_callback( 1293 '!(?: # Start cases 1294 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text 1295 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . " 1296 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . ' 1297 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number 1298 ISBN\s+(\b # m[5]: ISBN, capture number 1299 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix 1300 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters 1301 [0-9Xx] # check digit 1302 \b) 1303 )!xu', array( &$this, 'magicLinkCallback' ), $text ); 1304 wfProfileOut( __METHOD__ ); 1305 return $text; 1306 } 1307 1308 /** 1309 * @throws MWException 1310 * @param array $m 1311 * @return HTML|string 1312 */ 1313 public function magicLinkCallback( $m ) { 1314 if ( isset( $m[1] ) && $m[1] !== '' ) { 1315 # Skip anchor 1316 return $m[0]; 1317 } elseif ( isset( $m[2] ) && $m[2] !== '' ) { 1318 # Skip HTML element 1319 return $m[0]; 1320 } elseif ( isset( $m[3] ) && $m[3] !== '' ) { 1321 # Free external link 1322 return $this->makeFreeExternalLink( $m[0] ); 1323 } elseif ( isset( $m[4] ) && $m[4] !== '' ) { 1324 # RFC or PMID 1325 if ( substr( $m[0], 0, 3 ) === 'RFC' ) { 1326 $keyword = 'RFC'; 1327 $urlmsg = 'rfcurl'; 1328 $cssClass = 'mw-magiclink-rfc'; 1329 $id = $m[4]; 1330 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) { 1331 $keyword = 'PMID'; 1332 $urlmsg = 'pubmedurl'; 1333 $cssClass = 'mw-magiclink-pmid'; 1334 $id = $m[4]; 1335 } else { 1336 throw new MWException( __METHOD__ . ': unrecognised match type "' . 1337 substr( $m[0], 0, 20 ) . '"' ); 1338 } 1339 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text(); 1340 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass ); 1341 } elseif ( isset( $m[5] ) && $m[5] !== '' ) { 1342 # ISBN 1343 $isbn = $m[5]; 1344 $num = strtr( $isbn, array( 1345 '-' => '', 1346 ' ' => '', 1347 'x' => 'X', 1348 )); 1349 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num ); 1350 return '<a href="' . 1351 htmlspecialchars( $titleObj->getLocalURL() ) . 1352 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>"; 1353 } else { 1354 return $m[0]; 1355 } 1356 } 1357 1358 /** 1359 * Make a free external link, given a user-supplied URL 1360 * 1361 * @param string $url 1362 * 1363 * @return string HTML 1364 * @private 1365 */ 1366 public function makeFreeExternalLink( $url ) { 1367 wfProfileIn( __METHOD__ ); 1368 1369 $trail = ''; 1370 1371 # The characters '<' and '>' (which were escaped by 1372 # removeHTMLtags()) should not be included in 1373 # URLs, per RFC 2396. 1374 $m2 = array(); 1375 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) { 1376 $trail = substr( $url, $m2[0][1] ) . $trail; 1377 $url = substr( $url, 0, $m2[0][1] ); 1378 } 1379 1380 # Move trailing punctuation to $trail 1381 $sep = ',;\.:!?'; 1382 # If there is no left bracket, then consider right brackets fair game too 1383 if ( strpos( $url, '(' ) === false ) { 1384 $sep .= ')'; 1385 } 1386 1387 $numSepChars = strspn( strrev( $url ), $sep ); 1388 if ( $numSepChars ) { 1389 $trail = substr( $url, -$numSepChars ) . $trail; 1390 $url = substr( $url, 0, -$numSepChars ); 1391 } 1392 1393 $url = Sanitizer::cleanUrl( $url ); 1394 1395 # Is this an external image? 1396 $text = $this->maybeMakeExternalImage( $url ); 1397 if ( $text === false ) { 1398 # Not an image, make a link 1399 $text = Linker::makeExternalLink( $url, 1400 $this->getConverterLanguage()->markNoConversion( $url, true ), 1401 true, 'free', 1402 $this->getExternalLinkAttribs( $url ) ); 1403 # Register it in the output object... 1404 # Replace unnecessary URL escape codes with their equivalent characters 1405 $pasteurized = self::normalizeLinkUrl( $url ); 1406 $this->mOutput->addExternalLink( $pasteurized ); 1407 } 1408 wfProfileOut( __METHOD__ ); 1409 return $text . $trail; 1410 } 1411 1412 /** 1413 * Parse headers and return html 1414 * 1415 * @private 1416 * 1417 * @param string $text 1418 * 1419 * @return string 1420 */ 1421 public function doHeadings( $text ) { 1422 wfProfileIn( __METHOD__ ); 1423 for ( $i = 6; $i >= 1; --$i ) { 1424 $h = str_repeat( '=', $i ); 1425 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text ); 1426 } 1427 wfProfileOut( __METHOD__ ); 1428 return $text; 1429 } 1430 1431 /** 1432 * Replace single quotes with HTML markup 1433 * @private 1434 * 1435 * @param string $text 1436 * 1437 * @return string The altered text 1438 */ 1439 public function doAllQuotes( $text ) { 1440 wfProfileIn( __METHOD__ ); 1441 $outtext = ''; 1442 $lines = StringUtils::explode( "\n", $text ); 1443 foreach ( $lines as $line ) { 1444 $outtext .= $this->doQuotes( $line ) . "\n"; 1445 } 1446 $outtext = substr( $outtext, 0, -1 ); 1447 wfProfileOut( __METHOD__ ); 1448 return $outtext; 1449 } 1450 1451 /** 1452 * Helper function for doAllQuotes() 1453 * 1454 * @param string $text 1455 * 1456 * @return string 1457 */ 1458 public function doQuotes( $text ) { 1459 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE ); 1460 $countarr = count( $arr ); 1461 if ( $countarr == 1 ) { 1462 return $text; 1463 } 1464 1465 // First, do some preliminary work. This may shift some apostrophes from 1466 // being mark-up to being text. It also counts the number of occurrences 1467 // of bold and italics mark-ups. 1468 $numbold = 0; 1469 $numitalics = 0; 1470 for ( $i = 1; $i < $countarr; $i += 2 ) { 1471 $thislen = strlen( $arr[$i] ); 1472 // If there are ever four apostrophes, assume the first is supposed to 1473 // be text, and the remaining three constitute mark-up for bold text. 1474 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''') 1475 if ( $thislen == 4 ) { 1476 $arr[$i - 1] .= "'"; 1477 $arr[$i] = "'''"; 1478 $thislen = 3; 1479 } elseif ( $thislen > 5 ) { 1480 // If there are more than 5 apostrophes in a row, assume they're all 1481 // text except for the last 5. 1482 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''') 1483 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 ); 1484 $arr[$i] = "'''''"; 1485 $thislen = 5; 1486 } 1487 // Count the number of occurrences of bold and italics mark-ups. 1488 if ( $thislen == 2 ) { 1489 $numitalics++; 1490 } elseif ( $thislen == 3 ) { 1491 $numbold++; 1492 } elseif ( $thislen == 5 ) { 1493 $numitalics++; 1494 $numbold++; 1495 } 1496 } 1497 1498 // If there is an odd number of both bold and italics, it is likely 1499 // that one of the bold ones was meant to be an apostrophe followed 1500 // by italics. Which one we cannot know for certain, but it is more 1501 // likely to be one that has a single-letter word before it. 1502 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) { 1503 $firstsingleletterword = -1; 1504 $firstmultiletterword = -1; 1505 $firstspace = -1; 1506 for ( $i = 1; $i < $countarr; $i += 2 ) { 1507 if ( strlen( $arr[$i] ) == 3 ) { 1508 $x1 = substr( $arr[$i - 1], -1 ); 1509 $x2 = substr( $arr[$i - 1], -2, 1 ); 1510 if ( $x1 === ' ' ) { 1511 if ( $firstspace == -1 ) { 1512 $firstspace = $i; 1513 } 1514 } elseif ( $x2 === ' ' ) { 1515 if ( $firstsingleletterword == -1 ) { 1516 $firstsingleletterword = $i; 1517 // if $firstsingleletterword is set, we don't 1518 // look at the other options, so we can bail early. 1519 break; 1520 } 1521 } else { 1522 if ( $firstmultiletterword == -1 ) { 1523 $firstmultiletterword = $i; 1524 } 1525 } 1526 } 1527 } 1528 1529 // If there is a single-letter word, use it! 1530 if ( $firstsingleletterword > -1 ) { 1531 $arr[$firstsingleletterword] = "''"; 1532 $arr[$firstsingleletterword - 1] .= "'"; 1533 } elseif ( $firstmultiletterword > -1 ) { 1534 // If not, but there's a multi-letter word, use that one. 1535 $arr[$firstmultiletterword] = "''"; 1536 $arr[$firstmultiletterword - 1] .= "'"; 1537 } elseif ( $firstspace > -1 ) { 1538 // ... otherwise use the first one that has neither. 1539 // (notice that it is possible for all three to be -1 if, for example, 1540 // there is only one pentuple-apostrophe in the line) 1541 $arr[$firstspace] = "''"; 1542 $arr[$firstspace - 1] .= "'"; 1543 } 1544 } 1545 1546 // Now let's actually convert our apostrophic mush to HTML! 1547 $output = ''; 1548 $buffer = ''; 1549 $state = ''; 1550 $i = 0; 1551 foreach ( $arr as $r ) { 1552 if ( ( $i % 2 ) == 0 ) { 1553 if ( $state === 'both' ) { 1554 $buffer .= $r; 1555 } else { 1556 $output .= $r; 1557 } 1558 } else { 1559 $thislen = strlen( $r ); 1560 if ( $thislen == 2 ) { 1561 if ( $state === 'i' ) { 1562 $output .= '</i>'; 1563 $state = ''; 1564 } elseif ( $state === 'bi' ) { 1565 $output .= '</i>'; 1566 $state = 'b'; 1567 } elseif ( $state === 'ib' ) { 1568 $output .= '</b></i><b>'; 1569 $state = 'b'; 1570 } elseif ( $state === 'both' ) { 1571 $output .= '<b><i>' . $buffer . '</i>'; 1572 $state = 'b'; 1573 } else { // $state can be 'b' or '' 1574 $output .= '<i>'; 1575 $state .= 'i'; 1576 } 1577 } elseif ( $thislen == 3 ) { 1578 if ( $state === 'b' ) { 1579 $output .= '</b>'; 1580 $state = ''; 1581 } elseif ( $state === 'bi' ) { 1582 $output .= '</i></b><i>'; 1583 $state = 'i'; 1584 } elseif ( $state === 'ib' ) { 1585 $output .= '</b>'; 1586 $state = 'i'; 1587 } elseif ( $state === 'both' ) { 1588 $output .= '<i><b>' . $buffer . '</b>'; 1589 $state = 'i'; 1590 } else { // $state can be 'i' or '' 1591 $output .= '<b>'; 1592 $state .= 'b'; 1593 } 1594 } elseif ( $thislen == 5 ) { 1595 if ( $state === 'b' ) { 1596 $output .= '</b><i>'; 1597 $state = 'i'; 1598 } elseif ( $state === 'i' ) { 1599 $output .= '</i><b>'; 1600 $state = 'b'; 1601 } elseif ( $state === 'bi' ) { 1602 $output .= '</i></b>'; 1603 $state = ''; 1604 } elseif ( $state === 'ib' ) { 1605 $output .= '</b></i>'; 1606 $state = ''; 1607 } elseif ( $state === 'both' ) { 1608 $output .= '<i><b>' . $buffer . '</b></i>'; 1609 $state = ''; 1610 } else { // ($state == '') 1611 $buffer = ''; 1612 $state = 'both'; 1613 } 1614 } 1615 } 1616 $i++; 1617 } 1618 // Now close all remaining tags. Notice that the order is important. 1619 if ( $state === 'b' || $state === 'ib' ) { 1620 $output .= '</b>'; 1621 } 1622 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) { 1623 $output .= '</i>'; 1624 } 1625 if ( $state === 'bi' ) { 1626 $output .= '</b>'; 1627 } 1628 // There might be lonely ''''', so make sure we have a buffer 1629 if ( $state === 'both' && $buffer ) { 1630 $output .= '<b><i>' . $buffer . '</i></b>'; 1631 } 1632 return $output; 1633 } 1634 1635 /** 1636 * Replace external links (REL) 1637 * 1638 * Note: this is all very hackish and the order of execution matters a lot. 1639 * Make sure to run tests/parserTests.php if you change this code. 1640 * 1641 * @private 1642 * 1643 * @param string $text 1644 * 1645 * @throws MWException 1646 * @return string 1647 */ 1648 public function replaceExternalLinks( $text ) { 1649 wfProfileIn( __METHOD__ ); 1650 1651 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE ); 1652 if ( $bits === false ) { 1653 wfProfileOut( __METHOD__ ); 1654 throw new MWException( "PCRE needs to be compiled with " 1655 . "--enable-unicode-properties in order for MediaWiki to function" ); 1656 } 1657 $s = array_shift( $bits ); 1658 1659 $i = 0; 1660 while ( $i < count( $bits ) ) { 1661 $url = $bits[$i++]; 1662 $i++; // protocol 1663 $text = $bits[$i++]; 1664 $trail = $bits[$i++]; 1665 1666 # The characters '<' and '>' (which were escaped by 1667 # removeHTMLtags()) should not be included in 1668 # URLs, per RFC 2396. 1669 $m2 = array(); 1670 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) { 1671 $text = substr( $url, $m2[0][1] ) . ' ' . $text; 1672 $url = substr( $url, 0, $m2[0][1] ); 1673 } 1674 1675 # If the link text is an image URL, replace it with an <img> tag 1676 # This happened by accident in the original parser, but some people used it extensively 1677 $img = $this->maybeMakeExternalImage( $text ); 1678 if ( $img !== false ) { 1679 $text = $img; 1680 } 1681 1682 $dtrail = ''; 1683 1684 # Set linktype for CSS - if URL==text, link is essentially free 1685 $linktype = ( $text === $url ) ? 'free' : 'text'; 1686 1687 # No link text, e.g. [http://domain.tld/some.link] 1688 if ( $text == '' ) { 1689 # Autonumber 1690 $langObj = $this->getTargetLanguage(); 1691 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']'; 1692 $linktype = 'autonumber'; 1693 } else { 1694 # Have link text, e.g. [http://domain.tld/some.link text]s 1695 # Check for trail 1696 list( $dtrail, $trail ) = Linker::splitTrail( $trail ); 1697 } 1698 1699 $text = $this->getConverterLanguage()->markNoConversion( $text ); 1700 1701 $url = Sanitizer::cleanUrl( $url ); 1702 1703 # Use the encoded URL 1704 # This means that users can paste URLs directly into the text 1705 # Funny characters like ö aren't valid in URLs anyway 1706 # This was changed in August 2004 1707 $s .= Linker::makeExternalLink( $url, $text, false, $linktype, 1708 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail; 1709 1710 # Register link in the output object. 1711 # Replace unnecessary URL escape codes with the referenced character 1712 # This prevents spammers from hiding links from the filters 1713 $pasteurized = self::normalizeLinkUrl( $url ); 1714 $this->mOutput->addExternalLink( $pasteurized ); 1715 } 1716 1717 wfProfileOut( __METHOD__ ); 1718 return $s; 1719 } 1720 1721 /** 1722 * Get the rel attribute for a particular external link. 1723 * 1724 * @since 1.21 1725 * @param string|bool $url Optional URL, to extract the domain from for rel => 1726 * nofollow if appropriate 1727 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups 1728 * @return string|null Rel attribute for $url 1729 */ 1730 public static function getExternalLinkRel( $url = false, $title = null ) { 1731 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions; 1732 $ns = $title ? $title->getNamespace() : false; 1733 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) 1734 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) 1735 ) { 1736 return 'nofollow'; 1737 } 1738 return null; 1739 } 1740 1741 /** 1742 * Get an associative array of additional HTML attributes appropriate for a 1743 * particular external link. This currently may include rel => nofollow 1744 * (depending on configuration, namespace, and the URL's domain) and/or a 1745 * target attribute (depending on configuration). 1746 * 1747 * @param string|bool $url Optional URL, to extract the domain from for rel => 1748 * nofollow if appropriate 1749 * @return array Associative array of HTML attributes 1750 */ 1751 public function getExternalLinkAttribs( $url = false ) { 1752 $attribs = array(); 1753 $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle ); 1754 1755 if ( $this->mOptions->getExternalLinkTarget() ) { 1756 $attribs['target'] = $this->mOptions->getExternalLinkTarget(); 1757 } 1758 return $attribs; 1759 } 1760 1761 /** 1762 * Replace unusual escape codes in a URL with their equivalent characters 1763 * 1764 * @deprecated since 1.24, use normalizeLinkUrl 1765 * @param string $url 1766 * @return string 1767 */ 1768 public static function replaceUnusualEscapes( $url ) { 1769 wfDeprecated( __METHOD__, '1.24' ); 1770 return self::normalizeLinkUrl( $url ); 1771 } 1772 1773 /** 1774 * Replace unusual escape codes in a URL with their equivalent characters 1775 * 1776 * This generally follows the syntax defined in RFC 3986, with special 1777 * consideration for HTTP query strings. 1778 * 1779 * @param string $url 1780 * @return string 1781 */ 1782 public static function normalizeLinkUrl( $url ) { 1783 # First, make sure unsafe characters are encoded 1784 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/', 1785 function ( $m ) { 1786 return rawurlencode( $m[0] ); 1787 }, 1788 $url 1789 ); 1790 1791 $ret = ''; 1792 $end = strlen( $url ); 1793 1794 # Fragment part - 'fragment' 1795 $start = strpos( $url, '#' ); 1796 if ( $start !== false && $start < $end ) { 1797 $ret = self::normalizeUrlComponent( 1798 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret; 1799 $end = $start; 1800 } 1801 1802 # Query part - 'query' minus &=+; 1803 $start = strpos( $url, '?' ); 1804 if ( $start !== false && $start < $end ) { 1805 $ret = self::normalizeUrlComponent( 1806 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret; 1807 $end = $start; 1808 } 1809 1810 # Scheme and path part - 'pchar' 1811 # (we assume no userinfo or encoded colons in the host) 1812 $ret = self::normalizeUrlComponent( 1813 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret; 1814 1815 return $ret; 1816 } 1817 1818 private static function normalizeUrlComponent( $component, $unsafe ) { 1819 $callback = function ( $matches ) use ( $unsafe ) { 1820 $char = urldecode( $matches[0] ); 1821 $ord = ord( $char ); 1822 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) { 1823 # Unescape it 1824 return $char; 1825 } else { 1826 # Leave it escaped, but use uppercase for a-f 1827 return strtoupper( $matches[0] ); 1828 } 1829 }; 1830 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component ); 1831 } 1832 1833 /** 1834 * make an image if it's allowed, either through the global 1835 * option, through the exception, or through the on-wiki whitelist 1836 * 1837 * @param string $url 1838 * 1839 * @return string 1840 */ 1841 private function maybeMakeExternalImage( $url ) { 1842 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom(); 1843 $imagesexception = !empty( $imagesfrom ); 1844 $text = false; 1845 # $imagesfrom could be either a single string or an array of strings, parse out the latter 1846 if ( $imagesexception && is_array( $imagesfrom ) ) { 1847 $imagematch = false; 1848 foreach ( $imagesfrom as $match ) { 1849 if ( strpos( $url, $match ) === 0 ) { 1850 $imagematch = true; 1851 break; 1852 } 1853 } 1854 } elseif ( $imagesexception ) { 1855 $imagematch = ( strpos( $url, $imagesfrom ) === 0 ); 1856 } else { 1857 $imagematch = false; 1858 } 1859 1860 if ( $this->mOptions->getAllowExternalImages() 1861 || ( $imagesexception && $imagematch ) 1862 ) { 1863 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) { 1864 # Image found 1865 $text = Linker::makeExternalImage( $url ); 1866 } 1867 } 1868 if ( !$text && $this->mOptions->getEnableImageWhitelist() 1869 && preg_match( self::EXT_IMAGE_REGEX, $url ) 1870 ) { 1871 $whitelist = explode( 1872 "\n", 1873 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() 1874 ); 1875 1876 foreach ( $whitelist as $entry ) { 1877 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments 1878 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) { 1879 continue; 1880 } 1881 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) { 1882 # Image matches a whitelist entry 1883 $text = Linker::makeExternalImage( $url ); 1884 break; 1885 } 1886 } 1887 } 1888 return $text; 1889 } 1890 1891 /** 1892 * Process [[ ]] wikilinks 1893 * 1894 * @param string $s 1895 * 1896 * @return string Processed text 1897 * 1898 * @private 1899 */ 1900 public function replaceInternalLinks( $s ) { 1901 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) ); 1902 return $s; 1903 } 1904 1905 /** 1906 * Process [[ ]] wikilinks (RIL) 1907 * @param string $s 1908 * @throws MWException 1909 * @return LinkHolderArray 1910 * 1911 * @private 1912 */ 1913 public function replaceInternalLinks2( &$s ) { 1914 global $wgExtraInterlanguageLinkPrefixes; 1915 wfProfileIn( __METHOD__ ); 1916 1917 wfProfileIn( __METHOD__ . '-setup' ); 1918 static $tc = false, $e1, $e1_img; 1919 # the % is needed to support urlencoded titles as well 1920 if ( !$tc ) { 1921 $tc = Title::legalChars() . '#%'; 1922 # Match a link having the form [[namespace:link|alternate]]trail 1923 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; 1924 # Match cases where there is no "]]", which might still be images 1925 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; 1926 } 1927 1928 $holders = new LinkHolderArray( $this ); 1929 1930 # split the entire text string on occurrences of [[ 1931 $a = StringUtils::explode( '[[', ' ' . $s ); 1932 # get the first element (all text up to first [[), and remove the space we added 1933 $s = $a->current(); 1934 $a->next(); 1935 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void" 1936 $s = substr( $s, 1 ); 1937 1938 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension(); 1939 $e2 = null; 1940 if ( $useLinkPrefixExtension ) { 1941 # Match the end of a line for a word that's not followed by whitespace, 1942 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched 1943 global $wgContLang; 1944 $charset = $wgContLang->linkPrefixCharset(); 1945 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu"; 1946 } 1947 1948 if ( is_null( $this->mTitle ) ) { 1949 wfProfileOut( __METHOD__ . '-setup' ); 1950 wfProfileOut( __METHOD__ ); 1951 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" ); 1952 } 1953 $nottalk = !$this->mTitle->isTalkPage(); 1954 1955 if ( $useLinkPrefixExtension ) { 1956 $m = array(); 1957 if ( preg_match( $e2, $s, $m ) ) { 1958 $first_prefix = $m[2]; 1959 } else { 1960 $first_prefix = false; 1961 } 1962 } else { 1963 $prefix = ''; 1964 } 1965 1966 $useSubpages = $this->areSubpagesAllowed(); 1967 wfProfileOut( __METHOD__ . '-setup' ); 1968 1969 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect 1970 # Loop for each link 1971 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) { 1972 // @codingStandardsIgnoreStart 1973 1974 # Check for excessive memory usage 1975 if ( $holders->isBig() ) { 1976 # Too big 1977 # Do the existence check, replace the link holders and clear the array 1978 $holders->replace( $s ); 1979 $holders->clear(); 1980 } 1981 1982 if ( $useLinkPrefixExtension ) { 1983 wfProfileIn( __METHOD__ . '-prefixhandling' ); 1984 if ( preg_match( $e2, $s, $m ) ) { 1985 $prefix = $m[2]; 1986 $s = $m[1]; 1987 } else { 1988 $prefix = ''; 1989 } 1990 # first link 1991 if ( $first_prefix ) { 1992 $prefix = $first_prefix; 1993 $first_prefix = false; 1994 } 1995 wfProfileOut( __METHOD__ . '-prefixhandling' ); 1996 } 1997 1998 $might_be_img = false; 1999 2000 wfProfileIn( __METHOD__ . "-e1" ); 2001 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt 2002 $text = $m[2]; 2003 # If we get a ] at the beginning of $m[3] that means we have a link that's something like: 2004 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up, 2005 # the real problem is with the $e1 regex 2006 # See bug 1300. 2007 # 2008 # Still some problems for cases where the ] is meant to be outside punctuation, 2009 # and no image is in sight. See bug 2095. 2010 # 2011 if ( $text !== '' 2012 && substr( $m[3], 0, 1 ) === ']' 2013 && strpos( $text, '[' ) !== false 2014 ) { 2015 $text .= ']'; # so that replaceExternalLinks($text) works later 2016 $m[3] = substr( $m[3], 1 ); 2017 } 2018 # fix up urlencoded title texts 2019 if ( strpos( $m[1], '%' ) !== false ) { 2020 # Should anchors '#' also be rejected? 2021 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) ); 2022 } 2023 $trail = $m[3]; 2024 } elseif ( preg_match( $e1_img, $line, $m ) ) { 2025 # Invalid, but might be an image with a link in its caption 2026 $might_be_img = true; 2027 $text = $m[2]; 2028 if ( strpos( $m[1], '%' ) !== false ) { 2029 $m[1] = rawurldecode( $m[1] ); 2030 } 2031 $trail = ""; 2032 } else { # Invalid form; output directly 2033 $s .= $prefix . '[[' . $line; 2034 wfProfileOut( __METHOD__ . "-e1" ); 2035 continue; 2036 } 2037 wfProfileOut( __METHOD__ . "-e1" ); 2038 wfProfileIn( __METHOD__ . "-misc" ); 2039 2040 $origLink = $m[1]; 2041 2042 # Don't allow internal links to pages containing 2043 # PROTO: where PROTO is a valid URL protocol; these 2044 # should be external links. 2045 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) { 2046 $s .= $prefix . '[[' . $line; 2047 wfProfileOut( __METHOD__ . "-misc" ); 2048 continue; 2049 } 2050 2051 # Make subpage if necessary 2052 if ( $useSubpages ) { 2053 $link = $this->maybeDoSubpageLink( $origLink, $text ); 2054 } else { 2055 $link = $origLink; 2056 } 2057 2058 $noforce = ( substr( $origLink, 0, 1 ) !== ':' ); 2059 if ( !$noforce ) { 2060 # Strip off leading ':' 2061 $link = substr( $link, 1 ); 2062 } 2063 2064 wfProfileOut( __METHOD__ . "-misc" ); 2065 wfProfileIn( __METHOD__ . "-title" ); 2066 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) ); 2067 if ( $nt === null ) { 2068 $s .= $prefix . '[[' . $line; 2069 wfProfileOut( __METHOD__ . "-title" ); 2070 continue; 2071 } 2072 2073 $ns = $nt->getNamespace(); 2074 $iw = $nt->getInterwiki(); 2075 wfProfileOut( __METHOD__ . "-title" ); 2076 2077 if ( $might_be_img ) { # if this is actually an invalid link 2078 wfProfileIn( __METHOD__ . "-might_be_img" ); 2079 if ( $ns == NS_FILE && $noforce ) { # but might be an image 2080 $found = false; 2081 while ( true ) { 2082 # look at the next 'line' to see if we can close it there 2083 $a->next(); 2084 $next_line = $a->current(); 2085 if ( $next_line === false || $next_line === null ) { 2086 break; 2087 } 2088 $m = explode( ']]', $next_line, 3 ); 2089 if ( count( $m ) == 3 ) { 2090 # the first ]] closes the inner link, the second the image 2091 $found = true; 2092 $text .= "[[{$m[0]}]]{$m[1]}"; 2093 $trail = $m[2]; 2094 break; 2095 } elseif ( count( $m ) == 2 ) { 2096 # if there's exactly one ]] that's fine, we'll keep looking 2097 $text .= "[[{$m[0]}]]{$m[1]}"; 2098 } else { 2099 # if $next_line is invalid too, we need look no further 2100 $text .= '[[' . $next_line; 2101 break; 2102 } 2103 } 2104 if ( !$found ) { 2105 # we couldn't find the end of this imageLink, so output it raw 2106 # but don't ignore what might be perfectly normal links in the text we've examined 2107 $holders->merge( $this->replaceInternalLinks2( $text ) ); 2108 $s .= "{$prefix}[[$link|$text"; 2109 # note: no $trail, because without an end, there *is* no trail 2110 wfProfileOut( __METHOD__ . "-might_be_img" ); 2111 continue; 2112 } 2113 } else { # it's not an image, so output it raw 2114 $s .= "{$prefix}[[$link|$text"; 2115 # note: no $trail, because without an end, there *is* no trail 2116 wfProfileOut( __METHOD__ . "-might_be_img" ); 2117 continue; 2118 } 2119 wfProfileOut( __METHOD__ . "-might_be_img" ); 2120 } 2121 2122 $wasblank = ( $text == '' ); 2123 if ( $wasblank ) { 2124 $text = $link; 2125 } else { 2126 # Bug 4598 madness. Handle the quotes only if they come from the alternate part 2127 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a> 2128 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']] 2129 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a> 2130 $text = $this->doQuotes( $text ); 2131 } 2132 2133 # Link not escaped by : , create the various objects 2134 if ( $noforce && !$nt->wasLocalInterwiki() ) { 2135 # Interwikis 2136 wfProfileIn( __METHOD__ . "-interwiki" ); 2137 if ( 2138 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && ( 2139 Language::fetchLanguageName( $iw, null, 'mw' ) || 2140 in_array( $iw, $wgExtraInterlanguageLinkPrefixes ) 2141 ) 2142 ) { 2143 # Bug 24502: filter duplicates 2144 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) { 2145 $this->mLangLinkLanguages[$iw] = true; 2146 $this->mOutput->addLanguageLink( $nt->getFullText() ); 2147 } 2148 2149 $s = rtrim( $s . $prefix ); 2150 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail; 2151 wfProfileOut( __METHOD__ . "-interwiki" ); 2152 continue; 2153 } 2154 wfProfileOut( __METHOD__ . "-interwiki" ); 2155 2156 if ( $ns == NS_FILE ) { 2157 wfProfileIn( __METHOD__ . "-image" ); 2158 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) { 2159 if ( $wasblank ) { 2160 # if no parameters were passed, $text 2161 # becomes something like "File:Foo.png", 2162 # which we don't want to pass on to the 2163 # image generator 2164 $text = ''; 2165 } else { 2166 # recursively parse links inside the image caption 2167 # actually, this will parse them in any other parameters, too, 2168 # but it might be hard to fix that, and it doesn't matter ATM 2169 $text = $this->replaceExternalLinks( $text ); 2170 $holders->merge( $this->replaceInternalLinks2( $text ) ); 2171 } 2172 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them 2173 $s .= $prefix . $this->armorLinks( 2174 $this->makeImage( $nt, $text, $holders ) ) . $trail; 2175 } else { 2176 $s .= $prefix . $trail; 2177 } 2178 wfProfileOut( __METHOD__ . "-image" ); 2179 continue; 2180 } 2181 2182 if ( $ns == NS_CATEGORY ) { 2183 wfProfileIn( __METHOD__ . "-category" ); 2184 $s = rtrim( $s . "\n" ); # bug 87 2185 2186 if ( $wasblank ) { 2187 $sortkey = $this->getDefaultSort(); 2188 } else { 2189 $sortkey = $text; 2190 } 2191 $sortkey = Sanitizer::decodeCharReferences( $sortkey ); 2192 $sortkey = str_replace( "\n", '', $sortkey ); 2193 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey ); 2194 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey ); 2195 2196 /** 2197 * Strip the whitespace Category links produce, see bug 87 2198 */ 2199 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail; 2200 2201 wfProfileOut( __METHOD__ . "-category" ); 2202 continue; 2203 } 2204 } 2205 2206 # Self-link checking. For some languages, variants of the title are checked in 2207 # LinkHolderArray::doVariants() to allow batching the existence checks necessary 2208 # for linking to a different variant. 2209 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) { 2210 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail ); 2211 continue; 2212 } 2213 2214 # NS_MEDIA is a pseudo-namespace for linking directly to a file 2215 # @todo FIXME: Should do batch file existence checks, see comment below 2216 if ( $ns == NS_MEDIA ) { 2217 wfProfileIn( __METHOD__ . "-media" ); 2218 # Give extensions a chance to select the file revision for us 2219 $options = array(); 2220 $descQuery = false; 2221 wfRunHooks( 'BeforeParserFetchFileAndTitle', 2222 array( $this, $nt, &$options, &$descQuery ) ); 2223 # Fetch and register the file (file title may be different via hooks) 2224 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options ); 2225 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks 2226 $s .= $prefix . $this->armorLinks( 2227 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail; 2228 wfProfileOut( __METHOD__ . "-media" ); 2229 continue; 2230 } 2231 2232 wfProfileIn( __METHOD__ . "-always_known" ); 2233 # Some titles, such as valid special pages or files in foreign repos, should 2234 # be shown as bluelinks even though they're not included in the page table 2235 # 2236 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do 2237 # batch file existence checks for NS_FILE and NS_MEDIA 2238 if ( $iw == '' && $nt->isAlwaysKnown() ) { 2239 $this->mOutput->addLink( $nt ); 2240 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix ); 2241 } else { 2242 # Links will be added to the output link list after checking 2243 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix ); 2244 } 2245 wfProfileOut( __METHOD__ . "-always_known" ); 2246 } 2247 wfProfileOut( __METHOD__ ); 2248 return $holders; 2249 } 2250 2251 /** 2252 * Render a forced-blue link inline; protect against double expansion of 2253 * URLs if we're in a mode that prepends full URL prefixes to internal links. 2254 * Since this little disaster has to split off the trail text to avoid 2255 * breaking URLs in the following text without breaking trails on the 2256 * wiki links, it's been made into a horrible function. 2257 * 2258 * @param Title $nt 2259 * @param string $text 2260 * @param array|string $query 2261 * @param string $trail 2262 * @param string $prefix 2263 * @return string HTML-wikitext mix oh yuck 2264 */ 2265 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) { 2266 list( $inside, $trail ) = Linker::splitTrail( $trail ); 2267 2268 if ( is_string( $query ) ) { 2269 $query = wfCgiToArray( $query ); 2270 } 2271 if ( $text == '' ) { 2272 $text = htmlspecialchars( $nt->getPrefixedText() ); 2273 } 2274 2275 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query ); 2276 2277 return $this->armorLinks( $link ) . $trail; 2278 } 2279 2280 /** 2281 * Insert a NOPARSE hacky thing into any inline links in a chunk that's 2282 * going to go through further parsing steps before inline URL expansion. 2283 * 2284 * Not needed quite as much as it used to be since free links are a bit 2285 * more sensible these days. But bracketed links are still an issue. 2286 * 2287 * @param string $text More-or-less HTML 2288 * @return string Less-or-more HTML with NOPARSE bits 2289 */ 2290 public function armorLinks( $text ) { 2291 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/', 2292 "{$this->mUniqPrefix}NOPARSE$1", $text ); 2293 } 2294 2295 /** 2296 * Return true if subpage links should be expanded on this page. 2297 * @return bool 2298 */ 2299 public function areSubpagesAllowed() { 2300 # Some namespaces don't allow subpages 2301 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() ); 2302 } 2303 2304 /** 2305 * Handle link to subpage if necessary 2306 * 2307 * @param string $target The source of the link 2308 * @param string &$text The link text, modified as necessary 2309 * @return string The full name of the link 2310 * @private 2311 */ 2312 public function maybeDoSubpageLink( $target, &$text ) { 2313 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text ); 2314 } 2315 2316 /**#@+ 2317 * Used by doBlockLevels() 2318 * @private 2319 * 2320 * @return string 2321 */ 2322 public function closeParagraph() { 2323 $result = ''; 2324 if ( $this->mLastSection != '' ) { 2325 $result = '</' . $this->mLastSection . ">\n"; 2326 } 2327 $this->mInPre = false; 2328 $this->mLastSection = ''; 2329 return $result; 2330 } 2331 2332 /** 2333 * getCommon() returns the length of the longest common substring 2334 * of both arguments, starting at the beginning of both. 2335 * @private 2336 * 2337 * @param string $st1 2338 * @param string $st2 2339 * 2340 * @return int 2341 */ 2342 public function getCommon( $st1, $st2 ) { 2343 $fl = strlen( $st1 ); 2344 $shorter = strlen( $st2 ); 2345 if ( $fl < $shorter ) { 2346 $shorter = $fl; 2347 } 2348 2349 for ( $i = 0; $i < $shorter; ++$i ) { 2350 if ( $st1[$i] != $st2[$i] ) { 2351 break; 2352 } 2353 } 2354 return $i; 2355 } 2356 2357 /** 2358 * These next three functions open, continue, and close the list 2359 * element appropriate to the prefix character passed into them. 2360 * @private 2361 * 2362 * @param string $char 2363 * 2364 * @return string 2365 */ 2366 public function openList( $char ) { 2367 $result = $this->closeParagraph(); 2368 2369 if ( '*' === $char ) { 2370 $result .= "<ul><li>"; 2371 } elseif ( '#' === $char ) { 2372 $result .= "<ol><li>"; 2373 } elseif ( ':' === $char ) { 2374 $result .= "<dl><dd>"; 2375 } elseif ( ';' === $char ) { 2376 $result .= "<dl><dt>"; 2377 $this->mDTopen = true; 2378 } else { 2379 $result = '<!-- ERR 1 -->'; 2380 } 2381 2382 return $result; 2383 } 2384 2385 /** 2386 * TODO: document 2387 * @param string $char 2388 * @private 2389 * 2390 * @return string 2391 */ 2392 public function nextItem( $char ) { 2393 if ( '*' === $char || '#' === $char ) { 2394 return "</li>\n<li>"; 2395 } elseif ( ':' === $char || ';' === $char ) { 2396 $close = "</dd>\n"; 2397 if ( $this->mDTopen ) { 2398 $close = "</dt>\n"; 2399 } 2400 if ( ';' === $char ) { 2401 $this->mDTopen = true; 2402 return $close . '<dt>'; 2403 } else { 2404 $this->mDTopen = false; 2405 return $close . '<dd>'; 2406 } 2407 } 2408 return '<!-- ERR 2 -->'; 2409 } 2410 2411 /** 2412 * @todo Document 2413 * @param string $char 2414 * @private 2415 * 2416 * @return string 2417 */ 2418 public function closeList( $char ) { 2419 if ( '*' === $char ) { 2420 $text = "</li></ul>"; 2421 } elseif ( '#' === $char ) { 2422 $text = "</li></ol>"; 2423 } elseif ( ':' === $char ) { 2424 if ( $this->mDTopen ) { 2425 $this->mDTopen = false; 2426 $text = "</dt></dl>"; 2427 } else { 2428 $text = "</dd></dl>"; 2429 } 2430 } else { 2431 return '<!-- ERR 3 -->'; 2432 } 2433 return $text; 2434 } 2435 /**#@-*/ 2436 2437 /** 2438 * Make lists from lines starting with ':', '*', '#', etc. (DBL) 2439 * 2440 * @param string $text 2441 * @param bool $linestart Whether or not this is at the start of a line. 2442 * @private 2443 * @return string The lists rendered as HTML 2444 */ 2445 public function doBlockLevels( $text, $linestart ) { 2446 wfProfileIn( __METHOD__ ); 2447 2448 # Parsing through the text line by line. The main thing 2449 # happening here is handling of block-level elements p, pre, 2450 # and making lists from lines starting with * # : etc. 2451 # 2452 $textLines = StringUtils::explode( "\n", $text ); 2453 2454 $lastPrefix = $output = ''; 2455 $this->mDTopen = $inBlockElem = false; 2456 $prefixLength = 0; 2457 $paragraphStack = false; 2458 $inBlockquote = false; 2459 2460 foreach ( $textLines as $oLine ) { 2461 # Fix up $linestart 2462 if ( !$linestart ) { 2463 $output .= $oLine; 2464 $linestart = true; 2465 continue; 2466 } 2467 # * = ul 2468 # # = ol 2469 # ; = dt 2470 # : = dd 2471 2472 $lastPrefixLength = strlen( $lastPrefix ); 2473 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine ); 2474 $preOpenMatch = preg_match( '/<pre/i', $oLine ); 2475 # If not in a <pre> element, scan for and figure out what prefixes are there. 2476 if ( !$this->mInPre ) { 2477 # Multiple prefixes may abut each other for nested lists. 2478 $prefixLength = strspn( $oLine, '*#:;' ); 2479 $prefix = substr( $oLine, 0, $prefixLength ); 2480 2481 # eh? 2482 # ; and : are both from definition-lists, so they're equivalent 2483 # for the purposes of determining whether or not we need to open/close 2484 # elements. 2485 $prefix2 = str_replace( ';', ':', $prefix ); 2486 $t = substr( $oLine, $prefixLength ); 2487 $this->mInPre = (bool)$preOpenMatch; 2488 } else { 2489 # Don't interpret any other prefixes in preformatted text 2490 $prefixLength = 0; 2491 $prefix = $prefix2 = ''; 2492 $t = $oLine; 2493 } 2494 2495 # List generation 2496 if ( $prefixLength && $lastPrefix === $prefix2 ) { 2497 # Same as the last item, so no need to deal with nesting or opening stuff 2498 $output .= $this->nextItem( substr( $prefix, -1 ) ); 2499 $paragraphStack = false; 2500 2501 if ( substr( $prefix, -1 ) === ';' ) { 2502 # The one nasty exception: definition lists work like this: 2503 # ; title : definition text 2504 # So we check for : in the remainder text to split up the 2505 # title and definition, without b0rking links. 2506 $term = $t2 = ''; 2507 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) { 2508 $t = $t2; 2509 $output .= $term . $this->nextItem( ':' ); 2510 } 2511 } 2512 } elseif ( $prefixLength || $lastPrefixLength ) { 2513 # We need to open or close prefixes, or both. 2514 2515 # Either open or close a level... 2516 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix ); 2517 $paragraphStack = false; 2518 2519 # Close all the prefixes which aren't shared. 2520 while ( $commonPrefixLength < $lastPrefixLength ) { 2521 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] ); 2522 --$lastPrefixLength; 2523 } 2524 2525 # Continue the current prefix if appropriate. 2526 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) { 2527 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] ); 2528 } 2529 2530 # Open prefixes where appropriate. 2531 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) { 2532 $output .= "\n"; 2533 } 2534 while ( $prefixLength > $commonPrefixLength ) { 2535 $char = substr( $prefix, $commonPrefixLength, 1 ); 2536 $output .= $this->openList( $char ); 2537 2538 if ( ';' === $char ) { 2539 # @todo FIXME: This is dupe of code above 2540 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) { 2541 $t = $t2; 2542 $output .= $term . $this->nextItem( ':' ); 2543 } 2544 } 2545 ++$commonPrefixLength; 2546 } 2547 if ( !$prefixLength && $lastPrefix ) { 2548 $output .= "\n"; 2549 } 2550 $lastPrefix = $prefix2; 2551 } 2552 2553 # If we have no prefixes, go to paragraph mode. 2554 if ( 0 == $prefixLength ) { 2555 wfProfileIn( __METHOD__ . "-paragraph" ); 2556 # No prefix (not in list)--go to paragraph mode 2557 # XXX: use a stack for nestable elements like span, table and div 2558 $openmatch = preg_match( 2559 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|' 2560 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', 2561 $t 2562 ); 2563 $closematch = preg_match( 2564 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' 2565 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|' 2566 . $this->mUniqPrefix 2567 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', 2568 $t 2569 ); 2570 2571 if ( $openmatch or $closematch ) { 2572 $paragraphStack = false; 2573 # @todo bug 5718: paragraph closed 2574 $output .= $this->closeParagraph(); 2575 if ( $preOpenMatch and !$preCloseMatch ) { 2576 $this->mInPre = true; 2577 } 2578 $bqOffset = 0; 2579 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) { 2580 $inBlockquote = !$bqMatch[1][0]; // is this a close tag? 2581 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] ); 2582 } 2583 $inBlockElem = !$closematch; 2584 } elseif ( !$inBlockElem && !$this->mInPre ) { 2585 if ( ' ' == substr( $t, 0, 1 ) 2586 && ( $this->mLastSection === 'pre' || trim( $t ) != '' ) 2587 && !$inBlockquote 2588 ) { 2589 # pre 2590 if ( $this->mLastSection !== 'pre' ) { 2591 $paragraphStack = false; 2592 $output .= $this->closeParagraph() . '<pre>'; 2593 $this->mLastSection = 'pre'; 2594 } 2595 $t = substr( $t, 1 ); 2596 } else { 2597 # paragraph 2598 if ( trim( $t ) === '' ) { 2599 if ( $paragraphStack ) { 2600 $output .= $paragraphStack . '<br />'; 2601 $paragraphStack = false; 2602 $this->mLastSection = 'p'; 2603 } else { 2604 if ( $this->mLastSection !== 'p' ) { 2605 $output .= $this->closeParagraph(); 2606 $this->mLastSection = ''; 2607 $paragraphStack = '<p>'; 2608 } else { 2609 $paragraphStack = '</p><p>'; 2610 } 2611 } 2612 } else { 2613 if ( $paragraphStack ) { 2614 $output .= $paragraphStack; 2615 $paragraphStack = false; 2616 $this->mLastSection = 'p'; 2617 } elseif ( $this->mLastSection !== 'p' ) { 2618 $output .= $this->closeParagraph() . '<p>'; 2619 $this->mLastSection = 'p'; 2620 } 2621 } 2622 } 2623 } 2624 wfProfileOut( __METHOD__ . "-paragraph" ); 2625 } 2626 # somewhere above we forget to get out of pre block (bug 785) 2627 if ( $preCloseMatch && $this->mInPre ) { 2628 $this->mInPre = false; 2629 } 2630 if ( $paragraphStack === false ) { 2631 $output .= $t; 2632 if ( $prefixLength === 0 ) { 2633 $output .= "\n"; 2634 } 2635 } 2636 } 2637 while ( $prefixLength ) { 2638 $output .= $this->closeList( $prefix2[$prefixLength - 1] ); 2639 --$prefixLength; 2640 if ( !$prefixLength ) { 2641 $output .= "\n"; 2642 } 2643 } 2644 if ( $this->mLastSection != '' ) { 2645 $output .= '</' . $this->mLastSection . '>'; 2646 $this->mLastSection = ''; 2647 } 2648 2649 wfProfileOut( __METHOD__ ); 2650 return $output; 2651 } 2652 2653 /** 2654 * Split up a string on ':', ignoring any occurrences inside tags 2655 * to prevent illegal overlapping. 2656 * 2657 * @param string $str The string to split 2658 * @param string &$before Set to everything before the ':' 2659 * @param string &$after Set to everything after the ':' 2660 * @throws MWException 2661 * @return string The position of the ':', or false if none found 2662 */ 2663 public function findColonNoLinks( $str, &$before, &$after ) { 2664 wfProfileIn( __METHOD__ ); 2665 2666 $pos = strpos( $str, ':' ); 2667 if ( $pos === false ) { 2668 # Nothing to find! 2669 wfProfileOut( __METHOD__ ); 2670 return false; 2671 } 2672 2673 $lt = strpos( $str, '<' ); 2674 if ( $lt === false || $lt > $pos ) { 2675 # Easy; no tag nesting to worry about 2676 $before = substr( $str, 0, $pos ); 2677 $after = substr( $str, $pos + 1 ); 2678 wfProfileOut( __METHOD__ ); 2679 return $pos; 2680 } 2681 2682 # Ugly state machine to walk through avoiding tags. 2683 $state = self::COLON_STATE_TEXT; 2684 $stack = 0; 2685 $len = strlen( $str ); 2686 for ( $i = 0; $i < $len; $i++ ) { 2687 $c = $str[$i]; 2688 2689 switch ( $state ) { 2690 # (Using the number is a performance hack for common cases) 2691 case 0: # self::COLON_STATE_TEXT: 2692 switch ( $c ) { 2693 case "<": 2694 # Could be either a <start> tag or an </end> tag 2695 $state = self::COLON_STATE_TAGSTART; 2696 break; 2697 case ":": 2698 if ( $stack == 0 ) { 2699 # We found it! 2700 $before = substr( $str, 0, $i ); 2701 $after = substr( $str, $i + 1 ); 2702 wfProfileOut( __METHOD__ ); 2703 return $i; 2704 } 2705 # Embedded in a tag; don't break it. 2706 break; 2707 default: 2708 # Skip ahead looking for something interesting 2709 $colon = strpos( $str, ':', $i ); 2710 if ( $colon === false ) { 2711 # Nothing else interesting 2712 wfProfileOut( __METHOD__ ); 2713 return false; 2714 } 2715 $lt = strpos( $str, '<', $i ); 2716 if ( $stack === 0 ) { 2717 if ( $lt === false || $colon < $lt ) { 2718 # We found it! 2719 $before = substr( $str, 0, $colon ); 2720 $after = substr( $str, $colon + 1 ); 2721 wfProfileOut( __METHOD__ ); 2722 return $i; 2723 } 2724 } 2725 if ( $lt === false ) { 2726 # Nothing else interesting to find; abort! 2727 # We're nested, but there's no close tags left. Abort! 2728 break 2; 2729 } 2730 # Skip ahead to next tag start 2731 $i = $lt; 2732 $state = self::COLON_STATE_TAGSTART; 2733 } 2734 break; 2735 case 1: # self::COLON_STATE_TAG: 2736 # In a <tag> 2737 switch ( $c ) { 2738 case ">": 2739 $stack++; 2740 $state = self::COLON_STATE_TEXT; 2741 break; 2742 case "/": 2743 # Slash may be followed by >? 2744 $state = self::COLON_STATE_TAGSLASH; 2745 break; 2746 default: 2747 # ignore 2748 } 2749 break; 2750 case 2: # self::COLON_STATE_TAGSTART: 2751 switch ( $c ) { 2752 case "/": 2753 $state = self::COLON_STATE_CLOSETAG; 2754 break; 2755 case "!": 2756 $state = self::COLON_STATE_COMMENT; 2757 break; 2758 case ">": 2759 # Illegal early close? This shouldn't happen D: 2760 $state = self::COLON_STATE_TEXT; 2761 break; 2762 default: 2763 $state = self::COLON_STATE_TAG; 2764 } 2765 break; 2766 case 3: # self::COLON_STATE_CLOSETAG: 2767 # In a </tag> 2768 if ( $c === ">" ) { 2769 $stack--; 2770 if ( $stack < 0 ) { 2771 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" ); 2772 wfProfileOut( __METHOD__ ); 2773 return false; 2774 } 2775 $state = self::COLON_STATE_TEXT; 2776 } 2777 break; 2778 case self::COLON_STATE_TAGSLASH: 2779 if ( $c === ">" ) { 2780 # Yes, a self-closed tag <blah/> 2781 $state = self::COLON_STATE_TEXT; 2782 } else { 2783 # Probably we're jumping the gun, and this is an attribute 2784 $state = self::COLON_STATE_TAG; 2785 } 2786 break; 2787 case 5: # self::COLON_STATE_COMMENT: 2788 if ( $c === "-" ) { 2789 $state = self::COLON_STATE_COMMENTDASH; 2790 } 2791 break; 2792 case self::COLON_STATE_COMMENTDASH: 2793 if ( $c === "-" ) { 2794 $state = self::COLON_STATE_COMMENTDASHDASH; 2795 } else { 2796 $state = self::COLON_STATE_COMMENT; 2797 } 2798 break; 2799 case self::COLON_STATE_COMMENTDASHDASH: 2800 if ( $c === ">" ) { 2801 $state = self::COLON_STATE_TEXT; 2802 } else { 2803 $state = self::COLON_STATE_COMMENT; 2804 } 2805 break; 2806 default: 2807 wfProfileOut( __METHOD__ ); 2808 throw new MWException( "State machine error in " . __METHOD__ ); 2809 } 2810 } 2811 if ( $stack > 0 ) { 2812 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" ); 2813 wfProfileOut( __METHOD__ ); 2814 return false; 2815 } 2816 wfProfileOut( __METHOD__ ); 2817 return false; 2818 } 2819 2820 /** 2821 * Return value of a magic variable (like PAGENAME) 2822 * 2823 * @private 2824 * 2825 * @param int $index 2826 * @param bool|PPFrame $frame 2827 * 2828 * @throws MWException 2829 * @return string 2830 */ 2831 public function getVariableValue( $index, $frame = false ) { 2832 global $wgContLang, $wgSitename, $wgServer, $wgServerName; 2833 global $wgArticlePath, $wgScriptPath, $wgStylePath; 2834 2835 if ( is_null( $this->mTitle ) ) { 2836 // If no title set, bad things are going to happen 2837 // later. Title should always be set since this 2838 // should only be called in the middle of a parse 2839 // operation (but the unit-tests do funky stuff) 2840 throw new MWException( __METHOD__ . ' Should only be ' 2841 . ' called while parsing (no title set)' ); 2842 } 2843 2844 /** 2845 * Some of these require message or data lookups and can be 2846 * expensive to check many times. 2847 */ 2848 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) { 2849 if ( isset( $this->mVarCache[$index] ) ) { 2850 return $this->mVarCache[$index]; 2851 } 2852 } 2853 2854 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() ); 2855 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) ); 2856 2857 $pageLang = $this->getFunctionLang(); 2858 2859 switch ( $index ) { 2860 case '!': 2861 $value = '|'; 2862 break; 2863 case 'currentmonth': 2864 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) ); 2865 break; 2866 case 'currentmonth1': 2867 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) ); 2868 break; 2869 case 'currentmonthname': 2870 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) ); 2871 break; 2872 case 'currentmonthnamegen': 2873 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) ); 2874 break; 2875 case 'currentmonthabbrev': 2876 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) ); 2877 break; 2878 case 'currentday': 2879 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) ); 2880 break; 2881 case 'currentday2': 2882 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) ); 2883 break; 2884 case 'localmonth': 2885 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) ); 2886 break; 2887 case 'localmonth1': 2888 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) ); 2889 break; 2890 case 'localmonthname': 2891 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) ); 2892 break; 2893 case 'localmonthnamegen': 2894 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) ); 2895 break; 2896 case 'localmonthabbrev': 2897 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) ); 2898 break; 2899 case 'localday': 2900 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) ); 2901 break; 2902 case 'localday2': 2903 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) ); 2904 break; 2905 case 'pagename': 2906 $value = wfEscapeWikiText( $this->mTitle->getText() ); 2907 break; 2908 case 'pagenamee': 2909 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() ); 2910 break; 2911 case 'fullpagename': 2912 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() ); 2913 break; 2914 case 'fullpagenamee': 2915 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() ); 2916 break; 2917 case 'subpagename': 2918 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() ); 2919 break; 2920 case 'subpagenamee': 2921 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() ); 2922 break; 2923 case 'rootpagename': 2924 $value = wfEscapeWikiText( $this->mTitle->getRootText() ); 2925 break; 2926 case 'rootpagenamee': 2927 $value = wfEscapeWikiText( wfUrlEncode( str_replace( 2928 ' ', 2929 '_', 2930 $this->mTitle->getRootText() 2931 ) ) ); 2932 break; 2933 case 'basepagename': 2934 $value = wfEscapeWikiText( $this->mTitle->getBaseText() ); 2935 break; 2936 case 'basepagenamee': 2937 $value = wfEscapeWikiText( wfUrlEncode( str_replace( 2938 ' ', 2939 '_', 2940 $this->mTitle->getBaseText() 2941 ) ) ); 2942 break; 2943 case 'talkpagename': 2944 if ( $this->mTitle->canTalk() ) { 2945 $talkPage = $this->mTitle->getTalkPage(); 2946 $value = wfEscapeWikiText( $talkPage->getPrefixedText() ); 2947 } else { 2948 $value = ''; 2949 } 2950 break; 2951 case 'talkpagenamee': 2952 if ( $this->mTitle->canTalk() ) { 2953 $talkPage = $this->mTitle->getTalkPage(); 2954 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() ); 2955 } else { 2956 $value = ''; 2957 } 2958 break; 2959 case 'subjectpagename': 2960 $subjPage = $this->mTitle->getSubjectPage(); 2961 $value = wfEscapeWikiText( $subjPage->getPrefixedText() ); 2962 break; 2963 case 'subjectpagenamee': 2964 $subjPage = $this->mTitle->getSubjectPage(); 2965 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() ); 2966 break; 2967 case 'pageid': // requested in bug 23427 2968 $pageid = $this->getTitle()->getArticleID(); 2969 if ( $pageid == 0 ) { 2970 # 0 means the page doesn't exist in the database, 2971 # which means the user is previewing a new page. 2972 # The vary-revision flag must be set, because the magic word 2973 # will have a different value once the page is saved. 2974 $this->mOutput->setFlag( 'vary-revision' ); 2975 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" ); 2976 } 2977 $value = $pageid ? $pageid : null; 2978 break; 2979 case 'revisionid': 2980 # Let the edit saving system know we should parse the page 2981 # *after* a revision ID has been assigned. 2982 $this->mOutput->setFlag( 'vary-revision' ); 2983 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" ); 2984 $value = $this->mRevisionId; 2985 break; 2986 case 'revisionday': 2987 # Let the edit saving system know we should parse the page 2988 # *after* a revision ID has been assigned. This is for null edits. 2989 $this->mOutput->setFlag( 'vary-revision' ); 2990 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" ); 2991 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) ); 2992 break; 2993 case 'revisionday2': 2994 # Let the edit saving system know we should parse the page 2995 # *after* a revision ID has been assigned. This is for null edits. 2996 $this->mOutput->setFlag( 'vary-revision' ); 2997 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" ); 2998 $value = substr( $this->getRevisionTimestamp(), 6, 2 ); 2999 break; 3000 case 'revisionmonth': 3001 # Let the edit saving system know we should parse the page 3002 # *after* a revision ID has been assigned. This is for null edits. 3003 $this->mOutput->setFlag( 'vary-revision' ); 3004 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" ); 3005 $value = substr( $this->getRevisionTimestamp(), 4, 2 ); 3006 break; 3007 case 'revisionmonth1': 3008 # Let the edit saving system know we should parse the page 3009 # *after* a revision ID has been assigned. This is for null edits. 3010 $this->mOutput->setFlag( 'vary-revision' ); 3011 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" ); 3012 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) ); 3013 break; 3014 case 'revisionyear': 3015 # Let the edit saving system know we should parse the page 3016 # *after* a revision ID has been assigned. This is for null edits. 3017 $this->mOutput->setFlag( 'vary-revision' ); 3018 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" ); 3019 $value = substr( $this->getRevisionTimestamp(), 0, 4 ); 3020 break; 3021 case 'revisiontimestamp': 3022 # Let the edit saving system know we should parse the page 3023 # *after* a revision ID has been assigned. This is for null edits. 3024 $this->mOutput->setFlag( 'vary-revision' ); 3025 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" ); 3026 $value = $this->getRevisionTimestamp(); 3027 break; 3028 case 'revisionuser': 3029 # Let the edit saving system know we should parse the page 3030 # *after* a revision ID has been assigned. This is for null edits. 3031 $this->mOutput->setFlag( 'vary-revision' ); 3032 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" ); 3033 $value = $this->getRevisionUser(); 3034 break; 3035 case 'revisionsize': 3036 # Let the edit saving system know we should parse the page 3037 # *after* a revision ID has been assigned. This is for null edits. 3038 $this->mOutput->setFlag( 'vary-revision' ); 3039 wfDebug( __METHOD__ . ": {{REVISIONSIZE}} used, setting vary-revision...\n" ); 3040 $value = $this->getRevisionSize(); 3041 break; 3042 case 'namespace': 3043 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) ); 3044 break; 3045 case 'namespacee': 3046 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) ); 3047 break; 3048 case 'namespacenumber': 3049 $value = $this->mTitle->getNamespace(); 3050 break; 3051 case 'talkspace': 3052 $value = $this->mTitle->canTalk() 3053 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() ) 3054 : ''; 3055 break; 3056 case 'talkspacee': 3057 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : ''; 3058 break; 3059 case 'subjectspace': 3060 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() ); 3061 break; 3062 case 'subjectspacee': 3063 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) ); 3064 break; 3065 case 'currentdayname': 3066 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 ); 3067 break; 3068 case 'currentyear': 3069 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true ); 3070 break; 3071 case 'currenttime': 3072 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false ); 3073 break; 3074 case 'currenthour': 3075 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true ); 3076 break; 3077 case 'currentweek': 3078 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to 3079 # int to remove the padding 3080 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) ); 3081 break; 3082 case 'currentdow': 3083 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) ); 3084 break; 3085 case 'localdayname': 3086 $value = $pageLang->getWeekdayName( 3087 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1 3088 ); 3089 break; 3090 case 'localyear': 3091 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true ); 3092 break; 3093 case 'localtime': 3094 $value = $pageLang->time( 3095 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ), 3096 false, 3097 false 3098 ); 3099 break; 3100 case 'localhour': 3101 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true ); 3102 break; 3103 case 'localweek': 3104 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to 3105 # int to remove the padding 3106 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) ); 3107 break; 3108 case 'localdow': 3109 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) ); 3110 break; 3111 case 'numberofarticles': 3112 $value = $pageLang->formatNum( SiteStats::articles() ); 3113 break; 3114 case 'numberoffiles': 3115 $value = $pageLang->formatNum( SiteStats::images() ); 3116 break; 3117 case 'numberofusers': 3118 $value = $pageLang->formatNum( SiteStats::users() ); 3119 break; 3120 case 'numberofactiveusers': 3121 $value = $pageLang->formatNum( SiteStats::activeUsers() ); 3122 break; 3123 case 'numberofpages': 3124 $value = $pageLang->formatNum( SiteStats::pages() ); 3125 break; 3126 case 'numberofadmins': 3127 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) ); 3128 break; 3129 case 'numberofedits': 3130 $value = $pageLang->formatNum( SiteStats::edits() ); 3131 break; 3132 case 'numberofviews': 3133 global $wgDisableCounters; 3134 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : ''; 3135 break; 3136 case 'currenttimestamp': 3137 $value = wfTimestamp( TS_MW, $ts ); 3138 break; 3139 case 'localtimestamp': 3140 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ); 3141 break; 3142 case 'currentversion': 3143 $value = SpecialVersion::getVersion(); 3144 break; 3145 case 'articlepath': 3146 return $wgArticlePath; 3147 case 'sitename': 3148 return $wgSitename; 3149 case 'server': 3150 return $wgServer; 3151 case 'servername': 3152 return $wgServerName; 3153 case 'scriptpath': 3154 return $wgScriptPath; 3155 case 'stylepath': 3156 return $wgStylePath; 3157 case 'directionmark': 3158 return $pageLang->getDirMark(); 3159 case 'contentlanguage': 3160 global $wgLanguageCode; 3161 return $wgLanguageCode; 3162 case 'cascadingsources': 3163 $value = CoreParserFunctions::cascadingsources( $this ); 3164 break; 3165 default: 3166 $ret = null; 3167 wfRunHooks( 3168 'ParserGetVariableValueSwitch', 3169 array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) 3170 ); 3171 3172 return $ret; 3173 } 3174 3175 if ( $index ) { 3176 $this->mVarCache[$index] = $value; 3177 } 3178 3179 return $value; 3180 } 3181 3182 /** 3183 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers 3184 * 3185 * @private 3186 */ 3187 public function initialiseVariables() { 3188 wfProfileIn( __METHOD__ ); 3189 $variableIDs = MagicWord::getVariableIDs(); 3190 $substIDs = MagicWord::getSubstIDs(); 3191 3192 $this->mVariables = new MagicWordArray( $variableIDs ); 3193 $this->mSubstWords = new MagicWordArray( $substIDs ); 3194 wfProfileOut( __METHOD__ ); 3195 } 3196 3197 /** 3198 * Preprocess some wikitext and return the document tree. 3199 * This is the ghost of replace_variables(). 3200 * 3201 * @param string $text The text to parse 3202 * @param int $flags Bitwise combination of: 3203 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being 3204 * included. Default is to assume a direct page view. 3205 * 3206 * The generated DOM tree must depend only on the input text and the flags. 3207 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899. 3208 * 3209 * Any flag added to the $flags parameter here, or any other parameter liable to cause a 3210 * change in the DOM tree for a given text, must be passed through the section identifier 3211 * in the section edit link and thus back to extractSections(). 3212 * 3213 * The output of this function is currently only cached in process memory, but a persistent 3214 * cache may be implemented at a later date which takes further advantage of these strict 3215 * dependency requirements. 3216 * 3217 * @return PPNode 3218 */ 3219 public function preprocessToDom( $text, $flags = 0 ) { 3220 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags ); 3221 return $dom; 3222 } 3223 3224 /** 3225 * Return a three-element array: leading whitespace, string contents, trailing whitespace 3226 * 3227 * @param string $s 3228 * 3229 * @return array 3230 */ 3231 public static function splitWhitespace( $s ) { 3232 $ltrimmed = ltrim( $s ); 3233 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) ); 3234 $trimmed = rtrim( $ltrimmed ); 3235 $diff = strlen( $ltrimmed ) - strlen( $trimmed ); 3236 if ( $diff > 0 ) { 3237 $w2 = substr( $ltrimmed, -$diff ); 3238 } else { 3239 $w2 = ''; 3240 } 3241 return array( $w1, $trimmed, $w2 ); 3242 } 3243 3244 /** 3245 * Replace magic variables, templates, and template arguments 3246 * with the appropriate text. Templates are substituted recursively, 3247 * taking care to avoid infinite loops. 3248 * 3249 * Note that the substitution depends on value of $mOutputType: 3250 * self::OT_WIKI: only {{subst:}} templates 3251 * self::OT_PREPROCESS: templates but not extension tags 3252 * self::OT_HTML: all templates and extension tags 3253 * 3254 * @param string $text The text to transform 3255 * @param bool|PPFrame $frame Object describing the arguments passed to the 3256 * template. Arguments may also be provided as an associative array, as 3257 * was the usual case before MW1.12. Providing arguments this way may be 3258 * useful for extensions wishing to perform variable replacement 3259 * explicitly. 3260 * @param bool $argsOnly Only do argument (triple-brace) expansion, not 3261 * double-brace expansion. 3262 * @return string 3263 */ 3264 public function replaceVariables( $text, $frame = false, $argsOnly = false ) { 3265 # Is there any text? Also, Prevent too big inclusions! 3266 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) { 3267 return $text; 3268 } 3269 wfProfileIn( __METHOD__ ); 3270 3271 if ( $frame === false ) { 3272 $frame = $this->getPreprocessor()->newFrame(); 3273 } elseif ( !( $frame instanceof PPFrame ) ) { 3274 wfDebug( __METHOD__ . " called using plain parameters instead of " 3275 . "a PPFrame instance. Creating custom frame.\n" ); 3276 $frame = $this->getPreprocessor()->newCustomFrame( $frame ); 3277 } 3278 3279 $dom = $this->preprocessToDom( $text ); 3280 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0; 3281 $text = $frame->expand( $dom, $flags ); 3282 3283 wfProfileOut( __METHOD__ ); 3284 return $text; 3285 } 3286 3287 /** 3288 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too. 3289 * 3290 * @param array $args 3291 * 3292 * @return array 3293 */ 3294 public static function createAssocArgs( $args ) { 3295 $assocArgs = array(); 3296 $index = 1; 3297 foreach ( $args as $arg ) { 3298 $eqpos = strpos( $arg, '=' ); 3299 if ( $eqpos === false ) { 3300 $assocArgs[$index++] = $arg; 3301 } else { 3302 $name = trim( substr( $arg, 0, $eqpos ) ); 3303 $value = trim( substr( $arg, $eqpos + 1 ) ); 3304 if ( $value === false ) { 3305 $value = ''; 3306 } 3307 if ( $name !== false ) { 3308 $assocArgs[$name] = $value; 3309 } 3310 } 3311 } 3312 3313 return $assocArgs; 3314 } 3315 3316 /** 3317 * Warn the user when a parser limitation is reached 3318 * Will warn at most once the user per limitation type 3319 * 3320 * @param string $limitationType Should be one of: 3321 * 'expensive-parserfunction' (corresponding messages: 3322 * 'expensive-parserfunction-warning', 3323 * 'expensive-parserfunction-category') 3324 * 'post-expand-template-argument' (corresponding messages: 3325 * 'post-expand-template-argument-warning', 3326 * 'post-expand-template-argument-category') 3327 * 'post-expand-template-inclusion' (corresponding messages: 3328 * 'post-expand-template-inclusion-warning', 3329 * 'post-expand-template-inclusion-category') 3330 * 'node-count-exceeded' (corresponding messages: 3331 * 'node-count-exceeded-warning', 3332 * 'node-count-exceeded-category') 3333 * 'expansion-depth-exceeded' (corresponding messages: 3334 * 'expansion-depth-exceeded-warning', 3335 * 'expansion-depth-exceeded-category') 3336 * @param string|int|null $current Current value 3337 * @param string|int|null $max Maximum allowed, when an explicit limit has been 3338 * exceeded, provide the values (optional) 3339 */ 3340 public function limitationWarn( $limitationType, $current = '', $max = '' ) { 3341 # does no harm if $current and $max are present but are unnecessary for the message 3342 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max ) 3343 ->inLanguage( $this->mOptions->getUserLangObj() )->text(); 3344 $this->mOutput->addWarning( $warning ); 3345 $this->addTrackingCategory( "$limitationType-category" ); 3346 } 3347 3348 /** 3349 * Return the text of a template, after recursively 3350 * replacing any variables or templates within the template. 3351 * 3352 * @param array $piece The parts of the template 3353 * $piece['title']: the title, i.e. the part before the | 3354 * $piece['parts']: the parameter array 3355 * $piece['lineStart']: whether the brace was at the start of a line 3356 * @param PPFrame $frame The current frame, contains template arguments 3357 * @throws Exception 3358 * @return string The text of the template 3359 */ 3360 public function braceSubstitution( $piece, $frame ) { 3361 wfProfileIn( __METHOD__ ); 3362 wfProfileIn( __METHOD__ . '-setup' ); 3363 3364 // Flags 3365 3366 // $text has been filled 3367 $found = false; 3368 // wiki markup in $text should be escaped 3369 $nowiki = false; 3370 // $text is HTML, armour it against wikitext transformation 3371 $isHTML = false; 3372 // Force interwiki transclusion to be done in raw mode not rendered 3373 $forceRawInterwiki = false; 3374 // $text is a DOM node needing expansion in a child frame 3375 $isChildObj = false; 3376 // $text is a DOM node needing expansion in the current frame 3377 $isLocalObj = false; 3378 3379 # Title object, where $text came from 3380 $title = false; 3381 3382 # $part1 is the bit before the first |, and must contain only title characters. 3383 # Various prefixes will be stripped from it later. 3384 $titleWithSpaces = $frame->expand( $piece['title'] ); 3385 $part1 = trim( $titleWithSpaces ); 3386 $titleText = false; 3387 3388 # Original title text preserved for various purposes 3389 $originalTitle = $part1; 3390 3391 # $args is a list of argument nodes, starting from index 0, not including $part1 3392 # @todo FIXME: If piece['parts'] is null then the call to getLength() 3393 # below won't work b/c this $args isn't an object 3394 $args = ( null == $piece['parts'] ) ? array() : $piece['parts']; 3395 wfProfileOut( __METHOD__ . '-setup' ); 3396 3397 $titleProfileIn = null; // profile templates 3398 3399 # SUBST 3400 wfProfileIn( __METHOD__ . '-modifiers' ); 3401 if ( !$found ) { 3402 3403 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 ); 3404 3405 # Possibilities for substMatch: "subst", "safesubst" or FALSE 3406 # Decide whether to expand template or keep wikitext as-is. 3407 if ( $this->ot['wiki'] ) { 3408 if ( $substMatch === false ) { 3409 $literal = true; # literal when in PST with no prefix 3410 } else { 3411 $literal = false; # expand when in PST with subst: or safesubst: 3412 } 3413 } else { 3414 if ( $substMatch == 'subst' ) { 3415 $literal = true; # literal when not in PST with plain subst: 3416 } else { 3417 $literal = false; # expand when not in PST with safesubst: or no prefix 3418 } 3419 } 3420 if ( $literal ) { 3421 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args ); 3422 $isLocalObj = true; 3423 $found = true; 3424 } 3425 } 3426 3427 # Variables 3428 if ( !$found && $args->getLength() == 0 ) { 3429 $id = $this->mVariables->matchStartToEnd( $part1 ); 3430 if ( $id !== false ) { 3431 $text = $this->getVariableValue( $id, $frame ); 3432 if ( MagicWord::getCacheTTL( $id ) > -1 ) { 3433 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) ); 3434 } 3435 $found = true; 3436 } 3437 } 3438 3439 # MSG, MSGNW and RAW 3440 if ( !$found ) { 3441 # Check for MSGNW: 3442 $mwMsgnw = MagicWord::get( 'msgnw' ); 3443 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) { 3444 $nowiki = true; 3445 } else { 3446 # Remove obsolete MSG: 3447 $mwMsg = MagicWord::get( 'msg' ); 3448 $mwMsg->matchStartAndRemove( $part1 ); 3449 } 3450 3451 # Check for RAW: 3452 $mwRaw = MagicWord::get( 'raw' ); 3453 if ( $mwRaw->matchStartAndRemove( $part1 ) ) { 3454 $forceRawInterwiki = true; 3455 } 3456 } 3457 wfProfileOut( __METHOD__ . '-modifiers' ); 3458 3459 # Parser functions 3460 if ( !$found ) { 3461 wfProfileIn( __METHOD__ . '-pfunc' ); 3462 3463 $colonPos = strpos( $part1, ':' ); 3464 if ( $colonPos !== false ) { 3465 $func = substr( $part1, 0, $colonPos ); 3466 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) ); 3467 for ( $i = 0; $i < $args->getLength(); $i++ ) { 3468 $funcArgs[] = $args->item( $i ); 3469 } 3470 try { 3471 $result = $this->callParserFunction( $frame, $func, $funcArgs ); 3472 } catch ( Exception $ex ) { 3473 wfProfileOut( __METHOD__ . '-pfunc' ); 3474 wfProfileOut( __METHOD__ ); 3475 throw $ex; 3476 } 3477 3478 # The interface for parser functions allows for extracting 3479 # flags into the local scope. Extract any forwarded flags 3480 # here. 3481 extract( $result ); 3482 } 3483 wfProfileOut( __METHOD__ . '-pfunc' ); 3484 } 3485 3486 # Finish mangling title and then check for loops. 3487 # Set $title to a Title object and $titleText to the PDBK 3488 if ( !$found ) { 3489 $ns = NS_TEMPLATE; 3490 # Split the title into page and subpage 3491 $subpage = ''; 3492 $relative = $this->maybeDoSubpageLink( $part1, $subpage ); 3493 if ( $part1 !== $relative ) { 3494 $part1 = $relative; 3495 $ns = $this->mTitle->getNamespace(); 3496 } 3497 $title = Title::newFromText( $part1, $ns ); 3498 if ( $title ) { 3499 $titleText = $title->getPrefixedText(); 3500 # Check for language variants if the template is not found 3501 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) { 3502 $this->getConverterLanguage()->findVariantLink( $part1, $title, true ); 3503 } 3504 # Do recursion depth check 3505 $limit = $this->mOptions->getMaxTemplateDepth(); 3506 if ( $frame->depth >= $limit ) { 3507 $found = true; 3508 $text = '<span class="error">' 3509 . wfMessage( 'parser-template-recursion-depth-warning' ) 3510 ->numParams( $limit )->inContentLanguage()->text() 3511 . '</span>'; 3512 } 3513 } 3514 } 3515 3516 # Load from database 3517 if ( !$found && $title ) { 3518 if ( !Profiler::instance()->isPersistent() ) { 3519 # Too many unique items can kill profiling DBs/collectors 3520 $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey(); 3521 wfProfileIn( $titleProfileIn ); // template in 3522 } 3523 wfProfileIn( __METHOD__ . '-loadtpl' ); 3524 if ( !$title->isExternal() ) { 3525 if ( $title->isSpecialPage() 3526 && $this->mOptions->getAllowSpecialInclusion() 3527 && $this->ot['html'] 3528 ) { 3529 // Pass the template arguments as URL parameters. 3530 // "uselang" will have no effect since the Language object 3531 // is forced to the one defined in ParserOptions. 3532 $pageArgs = array(); 3533 $argsLength = $args->getLength(); 3534 for ( $i = 0; $i < $argsLength; $i++ ) { 3535 $bits = $args->item( $i )->splitArg(); 3536 if ( strval( $bits['index'] ) === '' ) { 3537 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) ); 3538 $value = trim( $frame->expand( $bits['value'] ) ); 3539 $pageArgs[$name] = $value; 3540 } 3541 } 3542 3543 // Create a new context to execute the special page 3544 $context = new RequestContext; 3545 $context->setTitle( $title ); 3546 $context->setRequest( new FauxRequest( $pageArgs ) ); 3547 $context->setUser( $this->getUser() ); 3548 $context->setLanguage( $this->mOptions->getUserLangObj() ); 3549 $ret = SpecialPageFactory::capturePath( $title, $context ); 3550 if ( $ret ) { 3551 $text = $context->getOutput()->getHTML(); 3552 $this->mOutput->addOutputPageMetadata( $context->getOutput() ); 3553 $found = true; 3554 $isHTML = true; 3555 $this->disableCache(); 3556 } 3557 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) { 3558 $found = false; # access denied 3559 wfDebug( __METHOD__ . ": template inclusion denied for " . 3560 $title->getPrefixedDBkey() . "\n" ); 3561 } else { 3562 list( $text, $title ) = $this->getTemplateDom( $title ); 3563 if ( $text !== false ) { 3564 $found = true; 3565 $isChildObj = true; 3566 } 3567 } 3568 3569 # If the title is valid but undisplayable, make a link to it 3570 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) { 3571 $text = "[[:$titleText]]"; 3572 $found = true; 3573 } 3574 } elseif ( $title->isTrans() ) { 3575 # Interwiki transclusion 3576 if ( $this->ot['html'] && !$forceRawInterwiki ) { 3577 $text = $this->interwikiTransclude( $title, 'render' ); 3578 $isHTML = true; 3579 } else { 3580 $text = $this->interwikiTransclude( $title, 'raw' ); 3581 # Preprocess it like a template 3582 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 3583 $isChildObj = true; 3584 } 3585 $found = true; 3586 } 3587 3588 # Do infinite loop check 3589 # This has to be done after redirect resolution to avoid infinite loops via redirects 3590 if ( !$frame->loopCheck( $title ) ) { 3591 $found = true; 3592 $text = '<span class="error">' 3593 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text() 3594 . '</span>'; 3595 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" ); 3596 } 3597 wfProfileOut( __METHOD__ . '-loadtpl' ); 3598 } 3599 3600 # If we haven't found text to substitute by now, we're done 3601 # Recover the source wikitext and return it 3602 if ( !$found ) { 3603 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args ); 3604 if ( $titleProfileIn ) { 3605 wfProfileOut( $titleProfileIn ); // template out 3606 } 3607 wfProfileOut( __METHOD__ ); 3608 return array( 'object' => $text ); 3609 } 3610 3611 # Expand DOM-style return values in a child frame 3612 if ( $isChildObj ) { 3613 # Clean up argument array 3614 $newFrame = $frame->newChild( $args, $title ); 3615 3616 if ( $nowiki ) { 3617 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG ); 3618 } elseif ( $titleText !== false && $newFrame->isEmpty() ) { 3619 # Expansion is eligible for the empty-frame cache 3620 $text = $newFrame->cachedExpand( $titleText, $text ); 3621 } else { 3622 # Uncached expansion 3623 $text = $newFrame->expand( $text ); 3624 } 3625 } 3626 if ( $isLocalObj && $nowiki ) { 3627 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG ); 3628 $isLocalObj = false; 3629 } 3630 3631 if ( $titleProfileIn ) { 3632 wfProfileOut( $titleProfileIn ); // template out 3633 } 3634 3635 # Replace raw HTML by a placeholder 3636 if ( $isHTML ) { 3637 $text = $this->insertStripItem( $text ); 3638 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) { 3639 # Escape nowiki-style return values 3640 $text = wfEscapeWikiText( $text ); 3641 } elseif ( is_string( $text ) 3642 && !$piece['lineStart'] 3643 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) 3644 ) { 3645 # Bug 529: if the template begins with a table or block-level 3646 # element, it should be treated as beginning a new line. 3647 # This behavior is somewhat controversial. 3648 $text = "\n" . $text; 3649 } 3650 3651 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) { 3652 # Error, oversize inclusion 3653 if ( $titleText !== false ) { 3654 # Make a working, properly escaped link if possible (bug 23588) 3655 $text = "[[:$titleText]]"; 3656 } else { 3657 # This will probably not be a working link, but at least it may 3658 # provide some hint of where the problem is 3659 preg_replace( '/^:/', '', $originalTitle ); 3660 $text = "[[:$originalTitle]]"; 3661 } 3662 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, ' 3663 . 'post-expand include size too large -->' ); 3664 $this->limitationWarn( 'post-expand-template-inclusion' ); 3665 } 3666 3667 if ( $isLocalObj ) { 3668 $ret = array( 'object' => $text ); 3669 } else { 3670 $ret = array( 'text' => $text ); 3671 } 3672 3673 wfProfileOut( __METHOD__ ); 3674 return $ret; 3675 } 3676 3677 /** 3678 * Call a parser function and return an array with text and flags. 3679 * 3680 * The returned array will always contain a boolean 'found', indicating 3681 * whether the parser function was found or not. It may also contain the 3682 * following: 3683 * text: string|object, resulting wikitext or PP DOM object 3684 * isHTML: bool, $text is HTML, armour it against wikitext transformation 3685 * isChildObj: bool, $text is a DOM node needing expansion in a child frame 3686 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame 3687 * nowiki: bool, wiki markup in $text should be escaped 3688 * 3689 * @since 1.21 3690 * @param PPFrame $frame The current frame, contains template arguments 3691 * @param string $function Function name 3692 * @param array $args Arguments to the function 3693 * @throws MWException 3694 * @return array 3695 */ 3696 public function callParserFunction( $frame, $function, array $args = array() ) { 3697 global $wgContLang; 3698 3699 wfProfileIn( __METHOD__ ); 3700 3701 # Case sensitive functions 3702 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) { 3703 $function = $this->mFunctionSynonyms[1][$function]; 3704 } else { 3705 # Case insensitive functions 3706 $function = $wgContLang->lc( $function ); 3707 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) { 3708 $function = $this->mFunctionSynonyms[0][$function]; 3709 } else { 3710 wfProfileOut( __METHOD__ ); 3711 return array( 'found' => false ); 3712 } 3713 } 3714 3715 wfProfileIn( __METHOD__ . '-pfunc-' . $function ); 3716 list( $callback, $flags ) = $this->mFunctionHooks[$function]; 3717 3718 # Workaround for PHP bug 35229 and similar 3719 if ( !is_callable( $callback ) ) { 3720 wfProfileOut( __METHOD__ . '-pfunc-' . $function ); 3721 wfProfileOut( __METHOD__ ); 3722 throw new MWException( "Tag hook for $function is not callable\n" ); 3723 } 3724 3725 $allArgs = array( &$this ); 3726 if ( $flags & SFH_OBJECT_ARGS ) { 3727 # Convert arguments to PPNodes and collect for appending to $allArgs 3728 $funcArgs = array(); 3729 foreach ( $args as $k => $v ) { 3730 if ( $v instanceof PPNode || $k === 0 ) { 3731 $funcArgs[] = $v; 3732 } else { 3733 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 ); 3734 } 3735 } 3736 3737 # Add a frame parameter, and pass the arguments as an array 3738 $allArgs[] = $frame; 3739 $allArgs[] = $funcArgs; 3740 } else { 3741 # Convert arguments to plain text and append to $allArgs 3742 foreach ( $args as $k => $v ) { 3743 if ( $v instanceof PPNode ) { 3744 $allArgs[] = trim( $frame->expand( $v ) ); 3745 } elseif ( is_int( $k ) && $k >= 0 ) { 3746 $allArgs[] = trim( $v ); 3747 } else { 3748 $allArgs[] = trim( "$k=$v" ); 3749 } 3750 } 3751 } 3752 3753 $result = call_user_func_array( $callback, $allArgs ); 3754 3755 # The interface for function hooks allows them to return a wikitext 3756 # string or an array containing the string and any flags. This mungs 3757 # things around to match what this method should return. 3758 if ( !is_array( $result ) ) { 3759 $result = array( 3760 'found' => true, 3761 'text' => $result, 3762 ); 3763 } else { 3764 if ( isset( $result[0] ) && !isset( $result['text'] ) ) { 3765 $result['text'] = $result[0]; 3766 } 3767 unset( $result[0] ); 3768 $result += array( 3769 'found' => true, 3770 ); 3771 } 3772 3773 $noparse = true; 3774 $preprocessFlags = 0; 3775 if ( isset( $result['noparse'] ) ) { 3776 $noparse = $result['noparse']; 3777 } 3778 if ( isset( $result['preprocessFlags'] ) ) { 3779 $preprocessFlags = $result['preprocessFlags']; 3780 } 3781 3782 if ( !$noparse ) { 3783 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags ); 3784 $result['isChildObj'] = true; 3785 } 3786 wfProfileOut( __METHOD__ . '-pfunc-' . $function ); 3787 wfProfileOut( __METHOD__ ); 3788 3789 return $result; 3790 } 3791 3792 /** 3793 * Get the semi-parsed DOM representation of a template with a given title, 3794 * and its redirect destination title. Cached. 3795 * 3796 * @param Title $title 3797 * 3798 * @return array 3799 */ 3800 public function getTemplateDom( $title ) { 3801 $cacheTitle = $title; 3802 $titleText = $title->getPrefixedDBkey(); 3803 3804 if ( isset( $this->mTplRedirCache[$titleText] ) ) { 3805 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText]; 3806 $title = Title::makeTitle( $ns, $dbk ); 3807 $titleText = $title->getPrefixedDBkey(); 3808 } 3809 if ( isset( $this->mTplDomCache[$titleText] ) ) { 3810 return array( $this->mTplDomCache[$titleText], $title ); 3811 } 3812 3813 # Cache miss, go to the database 3814 list( $text, $title ) = $this->fetchTemplateAndTitle( $title ); 3815 3816 if ( $text === false ) { 3817 $this->mTplDomCache[$titleText] = false; 3818 return array( false, $title ); 3819 } 3820 3821 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 3822 $this->mTplDomCache[$titleText] = $dom; 3823 3824 if ( !$title->equals( $cacheTitle ) ) { 3825 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] = 3826 array( $title->getNamespace(), $cdb = $title->getDBkey() ); 3827 } 3828 3829 return array( $dom, $title ); 3830 } 3831 3832 /** 3833 * Fetch the unparsed text of a template and register a reference to it. 3834 * @param Title $title 3835 * @return array ( string or false, Title ) 3836 */ 3837 public function fetchTemplateAndTitle( $title ) { 3838 // Defaults to Parser::statelessFetchTemplate() 3839 $templateCb = $this->mOptions->getTemplateCallback(); 3840 $stuff = call_user_func( $templateCb, $title, $this ); 3841 $text = $stuff['text']; 3842 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title; 3843 if ( isset( $stuff['deps'] ) ) { 3844 foreach ( $stuff['deps'] as $dep ) { 3845 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] ); 3846 if ( $dep['title']->equals( $this->getTitle() ) ) { 3847 // If we transclude ourselves, the final result 3848 // will change based on the new version of the page 3849 $this->mOutput->setFlag( 'vary-revision' ); 3850 } 3851 } 3852 } 3853 return array( $text, $finalTitle ); 3854 } 3855 3856 /** 3857 * Fetch the unparsed text of a template and register a reference to it. 3858 * @param Title $title 3859 * @return string|bool 3860 */ 3861 public function fetchTemplate( $title ) { 3862 $rv = $this->fetchTemplateAndTitle( $title ); 3863 return $rv[0]; 3864 } 3865 3866 /** 3867 * Static function to get a template 3868 * Can be overridden via ParserOptions::setTemplateCallback(). 3869 * 3870 * @param Title $title 3871 * @param bool|Parser $parser 3872 * 3873 * @return array 3874 */ 3875 public static function statelessFetchTemplate( $title, $parser = false ) { 3876 $text = $skip = false; 3877 $finalTitle = $title; 3878 $deps = array(); 3879 3880 # Loop to fetch the article, with up to 1 redirect 3881 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) { 3882 # Give extensions a chance to select the revision instead 3883 $id = false; # Assume current 3884 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', 3885 array( $parser, $title, &$skip, &$id ) ); 3886 3887 if ( $skip ) { 3888 $text = false; 3889 $deps[] = array( 3890 'title' => $title, 3891 'page_id' => $title->getArticleID(), 3892 'rev_id' => null 3893 ); 3894 break; 3895 } 3896 # Get the revision 3897 $rev = $id 3898 ? Revision::newFromId( $id ) 3899 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL ); 3900 $rev_id = $rev ? $rev->getId() : 0; 3901 # If there is no current revision, there is no page 3902 if ( $id === false && !$rev ) { 3903 $linkCache = LinkCache::singleton(); 3904 $linkCache->addBadLinkObj( $title ); 3905 } 3906 3907 $deps[] = array( 3908 'title' => $title, 3909 'page_id' => $title->getArticleID(), 3910 'rev_id' => $rev_id ); 3911 if ( $rev && !$title->equals( $rev->getTitle() ) ) { 3912 # We fetched a rev from a different title; register it too... 3913 $deps[] = array( 3914 'title' => $rev->getTitle(), 3915 'page_id' => $rev->getPage(), 3916 'rev_id' => $rev_id ); 3917 } 3918 3919 if ( $rev ) { 3920 $content = $rev->getContent(); 3921 $text = $content ? $content->getWikitextForTransclusion() : null; 3922 3923 if ( $text === false || $text === null ) { 3924 $text = false; 3925 break; 3926 } 3927 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) { 3928 global $wgContLang; 3929 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage(); 3930 if ( !$message->exists() ) { 3931 $text = false; 3932 break; 3933 } 3934 $content = $message->content(); 3935 $text = $message->plain(); 3936 } else { 3937 break; 3938 } 3939 if ( !$content ) { 3940 break; 3941 } 3942 # Redirect? 3943 $finalTitle = $title; 3944 $title = $content->getRedirectTarget(); 3945 } 3946 return array( 3947 'text' => $text, 3948 'finalTitle' => $finalTitle, 3949 'deps' => $deps ); 3950 } 3951 3952 /** 3953 * Fetch a file and its title and register a reference to it. 3954 * If 'broken' is a key in $options then the file will appear as a broken thumbnail. 3955 * @param Title $title 3956 * @param array $options Array of options to RepoGroup::findFile 3957 * @return File|bool 3958 */ 3959 public function fetchFile( $title, $options = array() ) { 3960 $res = $this->fetchFileAndTitle( $title, $options ); 3961 return $res[0]; 3962 } 3963 3964 /** 3965 * Fetch a file and its title and register a reference to it. 3966 * If 'broken' is a key in $options then the file will appear as a broken thumbnail. 3967 * @param Title $title 3968 * @param array $options Array of options to RepoGroup::findFile 3969 * @return array ( File or false, Title of file ) 3970 */ 3971 public function fetchFileAndTitle( $title, $options = array() ) { 3972 $file = $this->fetchFileNoRegister( $title, $options ); 3973 3974 $time = $file ? $file->getTimestamp() : false; 3975 $sha1 = $file ? $file->getSha1() : false; 3976 # Register the file as a dependency... 3977 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 ); 3978 if ( $file && !$title->equals( $file->getTitle() ) ) { 3979 # Update fetched file title 3980 $title = $file->getTitle(); 3981 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 ); 3982 } 3983 return array( $file, $title ); 3984 } 3985 3986 /** 3987 * Helper function for fetchFileAndTitle. 3988 * 3989 * Also useful if you need to fetch a file but not use it yet, 3990 * for example to get the file's handler. 3991 * 3992 * @param Title $title 3993 * @param array $options Array of options to RepoGroup::findFile 3994 * @return File|bool 3995 */ 3996 protected function fetchFileNoRegister( $title, $options = array() ) { 3997 if ( isset( $options['broken'] ) ) { 3998 $file = false; // broken thumbnail forced by hook 3999 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp) 4000 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options ); 4001 } else { // get by (name,timestamp) 4002 $file = wfFindFile( $title, $options ); 4003 } 4004 return $file; 4005 } 4006 4007 /** 4008 * Transclude an interwiki link. 4009 * 4010 * @param Title $title 4011 * @param string $action 4012 * 4013 * @return string 4014 */ 4015 public function interwikiTransclude( $title, $action ) { 4016 global $wgEnableScaryTranscluding; 4017 4018 if ( !$wgEnableScaryTranscluding ) { 4019 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text(); 4020 } 4021 4022 $url = $title->getFullURL( array( 'action' => $action ) ); 4023 4024 if ( strlen( $url ) > 255 ) { 4025 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text(); 4026 } 4027 return $this->fetchScaryTemplateMaybeFromCache( $url ); 4028 } 4029 4030 /** 4031 * @param string $url 4032 * @return mixed|string 4033 */ 4034 public function fetchScaryTemplateMaybeFromCache( $url ) { 4035 global $wgTranscludeCacheExpiry; 4036 $dbr = wfGetDB( DB_SLAVE ); 4037 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry ); 4038 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ), 4039 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) ); 4040 if ( $obj ) { 4041 return $obj->tc_contents; 4042 } 4043 4044 $req = MWHttpRequest::factory( $url ); 4045 $status = $req->execute(); // Status object 4046 if ( $status->isOK() ) { 4047 $text = $req->getContent(); 4048 } elseif ( $req->getStatus() != 200 ) { 4049 // Though we failed to fetch the content, this status is useless. 4050 return wfMessage( 'scarytranscludefailed-httpstatus' ) 4051 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text(); 4052 } else { 4053 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text(); 4054 } 4055 4056 $dbw = wfGetDB( DB_MASTER ); 4057 $dbw->replace( 'transcache', array( 'tc_url' ), array( 4058 'tc_url' => $url, 4059 'tc_time' => $dbw->timestamp( time() ), 4060 'tc_contents' => $text 4061 ) ); 4062 return $text; 4063 } 4064 4065 /** 4066 * Triple brace replacement -- used for template arguments 4067 * @private 4068 * 4069 * @param array $piece 4070 * @param PPFrame $frame 4071 * 4072 * @return array 4073 */ 4074 public function argSubstitution( $piece, $frame ) { 4075 wfProfileIn( __METHOD__ ); 4076 4077 $error = false; 4078 $parts = $piece['parts']; 4079 $nameWithSpaces = $frame->expand( $piece['title'] ); 4080 $argName = trim( $nameWithSpaces ); 4081 $object = false; 4082 $text = $frame->getArgument( $argName ); 4083 if ( $text === false && $parts->getLength() > 0 4084 && ( $this->ot['html'] 4085 || $this->ot['pre'] 4086 || ( $this->ot['wiki'] && $frame->isTemplate() ) 4087 ) 4088 ) { 4089 # No match in frame, use the supplied default 4090 $object = $parts->item( 0 )->getChildren(); 4091 } 4092 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) { 4093 $error = '<!-- WARNING: argument omitted, expansion size too large -->'; 4094 $this->limitationWarn( 'post-expand-template-argument' ); 4095 } 4096 4097 if ( $text === false && $object === false ) { 4098 # No match anywhere 4099 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts ); 4100 } 4101 if ( $error !== false ) { 4102 $text .= $error; 4103 } 4104 if ( $object !== false ) { 4105 $ret = array( 'object' => $object ); 4106 } else { 4107 $ret = array( 'text' => $text ); 4108 } 4109 4110 wfProfileOut( __METHOD__ ); 4111 return $ret; 4112 } 4113 4114 /** 4115 * Return the text to be used for a given extension tag. 4116 * This is the ghost of strip(). 4117 * 4118 * @param array $params Associative array of parameters: 4119 * name PPNode for the tag name 4120 * attr PPNode for unparsed text where tag attributes are thought to be 4121 * attributes Optional associative array of parsed attributes 4122 * inner Contents of extension element 4123 * noClose Original text did not have a close tag 4124 * @param PPFrame $frame 4125 * 4126 * @throws MWException 4127 * @return string 4128 */ 4129 public function extensionSubstitution( $params, $frame ) { 4130 $name = $frame->expand( $params['name'] ); 4131 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] ); 4132 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] ); 4133 $marker = "{$this->mUniqPrefix}-$name-" 4134 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX; 4135 4136 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) && 4137 ( $this->ot['html'] || $this->ot['pre'] ); 4138 if ( $isFunctionTag ) { 4139 $markerType = 'none'; 4140 } else { 4141 $markerType = 'general'; 4142 } 4143 if ( $this->ot['html'] || $isFunctionTag ) { 4144 $name = strtolower( $name ); 4145 $attributes = Sanitizer::decodeTagAttributes( $attrText ); 4146 if ( isset( $params['attributes'] ) ) { 4147 $attributes = $attributes + $params['attributes']; 4148 } 4149 4150 if ( isset( $this->mTagHooks[$name] ) ) { 4151 # Workaround for PHP bug 35229 and similar 4152 if ( !is_callable( $this->mTagHooks[$name] ) ) { 4153 throw new MWException( "Tag hook for $name is not callable\n" ); 4154 } 4155 $output = call_user_func_array( $this->mTagHooks[$name], 4156 array( $content, $attributes, $this, $frame ) ); 4157 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) { 4158 list( $callback, ) = $this->mFunctionTagHooks[$name]; 4159 if ( !is_callable( $callback ) ) { 4160 throw new MWException( "Tag hook for $name is not callable\n" ); 4161 } 4162 4163 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) ); 4164 } else { 4165 $output = '<span class="error">Invalid tag extension name: ' . 4166 htmlspecialchars( $name ) . '</span>'; 4167 } 4168 4169 if ( is_array( $output ) ) { 4170 # Extract flags to local scope (to override $markerType) 4171 $flags = $output; 4172 $output = $flags[0]; 4173 unset( $flags[0] ); 4174 extract( $flags ); 4175 } 4176 } else { 4177 if ( is_null( $attrText ) ) { 4178 $attrText = ''; 4179 } 4180 if ( isset( $params['attributes'] ) ) { 4181 foreach ( $params['attributes'] as $attrName => $attrValue ) { 4182 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' . 4183 htmlspecialchars( $attrValue ) . '"'; 4184 } 4185 } 4186 if ( $content === null ) { 4187 $output = "<$name$attrText/>"; 4188 } else { 4189 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] ); 4190 $output = "<$name$attrText>$content$close"; 4191 } 4192 } 4193 4194 if ( $markerType === 'none' ) { 4195 return $output; 4196 } elseif ( $markerType === 'nowiki' ) { 4197 $this->mStripState->addNoWiki( $marker, $output ); 4198 } elseif ( $markerType === 'general' ) { 4199 $this->mStripState->addGeneral( $marker, $output ); 4200 } else { 4201 throw new MWException( __METHOD__ . ': invalid marker type' ); 4202 } 4203 return $marker; 4204 } 4205 4206 /** 4207 * Increment an include size counter 4208 * 4209 * @param string $type The type of expansion 4210 * @param int $size The size of the text 4211 * @return bool False if this inclusion would take it over the maximum, true otherwise 4212 */ 4213 public function incrementIncludeSize( $type, $size ) { 4214 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) { 4215 return false; 4216 } else { 4217 $this->mIncludeSizes[$type] += $size; 4218 return true; 4219 } 4220 } 4221 4222 /** 4223 * Increment the expensive function count 4224 * 4225 * @return bool False if the limit has been exceeded 4226 */ 4227 public function incrementExpensiveFunctionCount() { 4228 $this->mExpensiveFunctionCount++; 4229 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit(); 4230 } 4231 4232 /** 4233 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__ 4234 * Fills $this->mDoubleUnderscores, returns the modified text 4235 * 4236 * @param string $text 4237 * 4238 * @return string 4239 */ 4240 public function doDoubleUnderscore( $text ) { 4241 wfProfileIn( __METHOD__ ); 4242 4243 # The position of __TOC__ needs to be recorded 4244 $mw = MagicWord::get( 'toc' ); 4245 if ( $mw->match( $text ) ) { 4246 $this->mShowToc = true; 4247 $this->mForceTocPosition = true; 4248 4249 # Set a placeholder. At the end we'll fill it in with the TOC. 4250 $text = $mw->replace( '<!--MWTOC-->', $text, 1 ); 4251 4252 # Only keep the first one. 4253 $text = $mw->replace( '', $text ); 4254 } 4255 4256 # Now match and remove the rest of them 4257 $mwa = MagicWord::getDoubleUnderscoreArray(); 4258 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text ); 4259 4260 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) { 4261 $this->mOutput->mNoGallery = true; 4262 } 4263 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) { 4264 $this->mShowToc = false; 4265 } 4266 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) 4267 && $this->mTitle->getNamespace() == NS_CATEGORY 4268 ) { 4269 $this->addTrackingCategory( 'hidden-category-category' ); 4270 } 4271 # (bug 8068) Allow control over whether robots index a page. 4272 # 4273 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This 4274 # is not desirable, the last one on the page should win. 4275 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) { 4276 $this->mOutput->setIndexPolicy( 'noindex' ); 4277 $this->addTrackingCategory( 'noindex-category' ); 4278 } 4279 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) { 4280 $this->mOutput->setIndexPolicy( 'index' ); 4281 $this->addTrackingCategory( 'index-category' ); 4282 } 4283 4284 # Cache all double underscores in the database 4285 foreach ( $this->mDoubleUnderscores as $key => $val ) { 4286 $this->mOutput->setProperty( $key, '' ); 4287 } 4288 4289 wfProfileOut( __METHOD__ ); 4290 return $text; 4291 } 4292 4293 /** 4294 * Add a tracking category, getting the title from a system message, 4295 * or print a debug message if the title is invalid. 4296 * 4297 * Please add any message that you use with this function to 4298 * $wgTrackingCategories. That way they will be listed on 4299 * Special:TrackingCategories. 4300 * 4301 * @param string $msg Message key 4302 * @return bool Whether the addition was successful 4303 */ 4304 public function addTrackingCategory( $msg ) { 4305 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) { 4306 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" ); 4307 return false; 4308 } 4309 // Important to parse with correct title (bug 31469) 4310 $cat = wfMessage( $msg ) 4311 ->title( $this->getTitle() ) 4312 ->inContentLanguage() 4313 ->text(); 4314 4315 # Allow tracking categories to be disabled by setting them to "-" 4316 if ( $cat === '-' ) { 4317 return false; 4318 } 4319 4320 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat ); 4321 if ( $containerCategory ) { 4322 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() ); 4323 return true; 4324 } else { 4325 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" ); 4326 return false; 4327 } 4328 } 4329 4330 /** 4331 * This function accomplishes several tasks: 4332 * 1) Auto-number headings if that option is enabled 4333 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page 4334 * 3) Add a Table of contents on the top for users who have enabled the option 4335 * 4) Auto-anchor headings 4336 * 4337 * It loops through all headlines, collects the necessary data, then splits up the 4338 * string and re-inserts the newly formatted headlines. 4339 * 4340 * @param string $text 4341 * @param string $origText Original, untouched wikitext 4342 * @param bool $isMain 4343 * @return mixed|string 4344 * @private 4345 */ 4346 public function formatHeadings( $text, $origText, $isMain = true ) { 4347 global $wgMaxTocLevel, $wgExperimentalHtmlIds; 4348 4349 # Inhibit editsection links if requested in the page 4350 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) { 4351 $maybeShowEditLink = $showEditLink = false; 4352 } else { 4353 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */ 4354 $showEditLink = $this->mOptions->getEditSection(); 4355 } 4356 if ( $showEditLink ) { 4357 $this->mOutput->setEditSectionTokens( true ); 4358 } 4359 4360 # Get all headlines for numbering them and adding funky stuff like [edit] 4361 # links - this is for later, but we need the number of headlines right now 4362 $matches = array(); 4363 $numMatches = preg_match_all( 4364 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', 4365 $text, 4366 $matches 4367 ); 4368 4369 # if there are fewer than 4 headlines in the article, do not show TOC 4370 # unless it's been explicitly enabled. 4371 $enoughToc = $this->mShowToc && 4372 ( ( $numMatches >= 4 ) || $this->mForceTocPosition ); 4373 4374 # Allow user to stipulate that a page should have a "new section" 4375 # link added via __NEWSECTIONLINK__ 4376 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) { 4377 $this->mOutput->setNewSection( true ); 4378 } 4379 4380 # Allow user to remove the "new section" 4381 # link via __NONEWSECTIONLINK__ 4382 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) { 4383 $this->mOutput->hideNewSection( true ); 4384 } 4385 4386 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML, 4387 # override above conditions and always show TOC above first header 4388 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) { 4389 $this->mShowToc = true; 4390 $enoughToc = true; 4391 } 4392 4393 # headline counter 4394 $headlineCount = 0; 4395 $numVisible = 0; 4396 4397 # Ugh .. the TOC should have neat indentation levels which can be 4398 # passed to the skin functions. These are determined here 4399 $toc = ''; 4400 $full = ''; 4401 $head = array(); 4402 $sublevelCount = array(); 4403 $levelCount = array(); 4404 $level = 0; 4405 $prevlevel = 0; 4406 $toclevel = 0; 4407 $prevtoclevel = 0; 4408 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX; 4409 $baseTitleText = $this->mTitle->getPrefixedDBkey(); 4410 $oldType = $this->mOutputType; 4411 $this->setOutputType( self::OT_WIKI ); 4412 $frame = $this->getPreprocessor()->newFrame(); 4413 $root = $this->preprocessToDom( $origText ); 4414 $node = $root->getFirstChild(); 4415 $byteOffset = 0; 4416 $tocraw = array(); 4417 $refers = array(); 4418 4419 foreach ( $matches[3] as $headline ) { 4420 $isTemplate = false; 4421 $titleText = false; 4422 $sectionIndex = false; 4423 $numbering = ''; 4424 $markerMatches = array(); 4425 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) { 4426 $serial = $markerMatches[1]; 4427 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial]; 4428 $isTemplate = ( $titleText != $baseTitleText ); 4429 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline ); 4430 } 4431 4432 if ( $toclevel ) { 4433 $prevlevel = $level; 4434 } 4435 $level = $matches[1][$headlineCount]; 4436 4437 if ( $level > $prevlevel ) { 4438 # Increase TOC level 4439 $toclevel++; 4440 $sublevelCount[$toclevel] = 0; 4441 if ( $toclevel < $wgMaxTocLevel ) { 4442 $prevtoclevel = $toclevel; 4443 $toc .= Linker::tocIndent(); 4444 $numVisible++; 4445 } 4446 } elseif ( $level < $prevlevel && $toclevel > 1 ) { 4447 # Decrease TOC level, find level to jump to 4448 4449 for ( $i = $toclevel; $i > 0; $i-- ) { 4450 if ( $levelCount[$i] == $level ) { 4451 # Found last matching level 4452 $toclevel = $i; 4453 break; 4454 } elseif ( $levelCount[$i] < $level ) { 4455 # Found first matching level below current level 4456 $toclevel = $i + 1; 4457 break; 4458 } 4459 } 4460 if ( $i == 0 ) { 4461 $toclevel = 1; 4462 } 4463 if ( $toclevel < $wgMaxTocLevel ) { 4464 if ( $prevtoclevel < $wgMaxTocLevel ) { 4465 # Unindent only if the previous toc level was shown :p 4466 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel ); 4467 $prevtoclevel = $toclevel; 4468 } else { 4469 $toc .= Linker::tocLineEnd(); 4470 } 4471 } 4472 } else { 4473 # No change in level, end TOC line 4474 if ( $toclevel < $wgMaxTocLevel ) { 4475 $toc .= Linker::tocLineEnd(); 4476 } 4477 } 4478 4479 $levelCount[$toclevel] = $level; 4480 4481 # count number of headlines for each level 4482 $sublevelCount[$toclevel]++; 4483 $dot = 0; 4484 for ( $i = 1; $i <= $toclevel; $i++ ) { 4485 if ( !empty( $sublevelCount[$i] ) ) { 4486 if ( $dot ) { 4487 $numbering .= '.'; 4488 } 4489 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] ); 4490 $dot = 1; 4491 } 4492 } 4493 4494 # The safe header is a version of the header text safe to use for links 4495 4496 # Remove link placeholders by the link text. 4497 # <!--LINK number--> 4498 # turns into 4499 # link text with suffix 4500 # Do this before unstrip since link text can contain strip markers 4501 $safeHeadline = $this->replaceLinkHoldersText( $headline ); 4502 4503 # Avoid insertion of weird stuff like <math> by expanding the relevant sections 4504 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline ); 4505 4506 # Strip out HTML (first regex removes any tag not allowed) 4507 # Allowed tags are: 4508 # * <sup> and <sub> (bug 8393) 4509 # * <i> (bug 26375) 4510 # * <b> (r105284) 4511 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167) 4512 # 4513 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>, 4514 # to allow setting directionality in toc items. 4515 $tocline = preg_replace( 4516 array( 4517 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', 4518 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' 4519 ), 4520 array( '', '<$1>' ), 4521 $safeHeadline 4522 ); 4523 $tocline = trim( $tocline ); 4524 4525 # For the anchor, strip out HTML-y stuff period 4526 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline ); 4527 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline ); 4528 4529 # Save headline for section edit hint before it's escaped 4530 $headlineHint = $safeHeadline; 4531 4532 if ( $wgExperimentalHtmlIds ) { 4533 # For reverse compatibility, provide an id that's 4534 # HTML4-compatible, like we used to. 4535 # 4536 # It may be worth noting, academically, that it's possible for 4537 # the legacy anchor to conflict with a non-legacy headline 4538 # anchor on the page. In this case likely the "correct" thing 4539 # would be to either drop the legacy anchors or make sure 4540 # they're numbered first. However, this would require people 4541 # to type in section names like "abc_.D7.93.D7.90.D7.A4" 4542 # manually, so let's not bother worrying about it. 4543 $legacyHeadline = Sanitizer::escapeId( $safeHeadline, 4544 array( 'noninitial', 'legacy' ) ); 4545 $safeHeadline = Sanitizer::escapeId( $safeHeadline ); 4546 4547 if ( $legacyHeadline == $safeHeadline ) { 4548 # No reason to have both (in fact, we can't) 4549 $legacyHeadline = false; 4550 } 4551 } else { 4552 $legacyHeadline = false; 4553 $safeHeadline = Sanitizer::escapeId( $safeHeadline, 4554 'noninitial' ); 4555 } 4556 4557 # HTML names must be case-insensitively unique (bug 10721). 4558 # This does not apply to Unicode characters per 4559 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison 4560 # @todo FIXME: We may be changing them depending on the current locale. 4561 $arrayKey = strtolower( $safeHeadline ); 4562 if ( $legacyHeadline === false ) { 4563 $legacyArrayKey = false; 4564 } else { 4565 $legacyArrayKey = strtolower( $legacyHeadline ); 4566 } 4567 4568 # count how many in assoc. array so we can track dupes in anchors 4569 if ( isset( $refers[$arrayKey] ) ) { 4570 $refers[$arrayKey]++; 4571 } else { 4572 $refers[$arrayKey] = 1; 4573 } 4574 if ( isset( $refers[$legacyArrayKey] ) ) { 4575 $refers[$legacyArrayKey]++; 4576 } else { 4577 $refers[$legacyArrayKey] = 1; 4578 } 4579 4580 # Don't number the heading if it is the only one (looks silly) 4581 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) { 4582 # the two are different if the line contains a link 4583 $headline = Html::element( 4584 'span', 4585 array( 'class' => 'mw-headline-number' ), 4586 $numbering 4587 ) . ' ' . $headline; 4588 } 4589 4590 # Create the anchor for linking from the TOC to the section 4591 $anchor = $safeHeadline; 4592 $legacyAnchor = $legacyHeadline; 4593 if ( $refers[$arrayKey] > 1 ) { 4594 $anchor .= '_' . $refers[$arrayKey]; 4595 } 4596 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) { 4597 $legacyAnchor .= '_' . $refers[$legacyArrayKey]; 4598 } 4599 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) { 4600 $toc .= Linker::tocLine( $anchor, $tocline, 4601 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) ); 4602 } 4603 4604 # Add the section to the section tree 4605 # Find the DOM node for this header 4606 $noOffset = ( $isTemplate || $sectionIndex === false ); 4607 while ( $node && !$noOffset ) { 4608 if ( $node->getName() === 'h' ) { 4609 $bits = $node->splitHeading(); 4610 if ( $bits['i'] == $sectionIndex ) { 4611 break; 4612 } 4613 } 4614 $byteOffset += mb_strlen( $this->mStripState->unstripBoth( 4615 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) ); 4616 $node = $node->getNextSibling(); 4617 } 4618 $tocraw[] = array( 4619 'toclevel' => $toclevel, 4620 'level' => $level, 4621 'line' => $tocline, 4622 'number' => $numbering, 4623 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex, 4624 'fromtitle' => $titleText, 4625 'byteoffset' => ( $noOffset ? null : $byteOffset ), 4626 'anchor' => $anchor, 4627 ); 4628 4629 # give headline the correct <h#> tag 4630 if ( $maybeShowEditLink && $sectionIndex !== false ) { 4631 // Output edit section links as markers with styles that can be customized by skins 4632 if ( $isTemplate ) { 4633 # Put a T flag in the section identifier, to indicate to extractSections() 4634 # that sections inside <includeonly> should be counted. 4635 $editsectionPage = $titleText; 4636 $editsectionSection = "T-$sectionIndex"; 4637 $editsectionContent = null; 4638 } else { 4639 $editsectionPage = $this->mTitle->getPrefixedText(); 4640 $editsectionSection = $sectionIndex; 4641 $editsectionContent = $headlineHint; 4642 } 4643 // We use a bit of pesudo-xml for editsection markers. The 4644 // language converter is run later on. Using a UNIQ style marker 4645 // leads to the converter screwing up the tokens when it 4646 // converts stuff. And trying to insert strip tags fails too. At 4647 // this point all real inputted tags have already been escaped, 4648 // so we don't have to worry about a user trying to input one of 4649 // these markers directly. We use a page and section attribute 4650 // to stop the language converter from converting these 4651 // important bits of data, but put the headline hint inside a 4652 // content block because the language converter is supposed to 4653 // be able to convert that piece of data. 4654 // Gets replaced with html in ParserOutput::getText 4655 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage ); 4656 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"'; 4657 if ( $editsectionContent !== null ) { 4658 $editlink .= '>' . $editsectionContent . '</mw:editsection>'; 4659 } else { 4660 $editlink .= '/>'; 4661 } 4662 } else { 4663 $editlink = ''; 4664 } 4665 $head[$headlineCount] = Linker::makeHeadline( $level, 4666 $matches['attrib'][$headlineCount], $anchor, $headline, 4667 $editlink, $legacyAnchor ); 4668 4669 $headlineCount++; 4670 } 4671 4672 $this->setOutputType( $oldType ); 4673 4674 # Never ever show TOC if no headers 4675 if ( $numVisible < 1 ) { 4676 $enoughToc = false; 4677 } 4678 4679 if ( $enoughToc ) { 4680 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) { 4681 $toc .= Linker::tocUnindent( $prevtoclevel - 1 ); 4682 } 4683 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() ); 4684 $this->mOutput->setTOCHTML( $toc ); 4685 $toc = self::TOC_START . $toc . self::TOC_END; 4686 $this->mOutput->addModules( 'mediawiki.toc' ); 4687 } 4688 4689 if ( $isMain ) { 4690 $this->mOutput->setSections( $tocraw ); 4691 } 4692 4693 # split up and insert constructed headlines 4694 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text ); 4695 $i = 0; 4696 4697 // build an array of document sections 4698 $sections = array(); 4699 foreach ( $blocks as $block ) { 4700 // $head is zero-based, sections aren't. 4701 if ( empty( $head[$i - 1] ) ) { 4702 $sections[$i] = $block; 4703 } else { 4704 $sections[$i] = $head[$i - 1] . $block; 4705 } 4706 4707 /** 4708 * Send a hook, one per section. 4709 * The idea here is to be able to make section-level DIVs, but to do so in a 4710 * lower-impact, more correct way than r50769 4711 * 4712 * $this : caller 4713 * $section : the section number 4714 * &$sectionContent : ref to the content of the section 4715 * $showEditLinks : boolean describing whether this section has an edit link 4716 */ 4717 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) ); 4718 4719 $i++; 4720 } 4721 4722 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) { 4723 // append the TOC at the beginning 4724 // Top anchor now in skin 4725 $sections[0] = $sections[0] . $toc . "\n"; 4726 } 4727 4728 $full .= join( '', $sections ); 4729 4730 if ( $this->mForceTocPosition ) { 4731 return str_replace( '<!--MWTOC-->', $toc, $full ); 4732 } else { 4733 return $full; 4734 } 4735 } 4736 4737 /** 4738 * Transform wiki markup when saving a page by doing "\r\n" -> "\n" 4739 * conversion, substitting signatures, {{subst:}} templates, etc. 4740 * 4741 * @param string $text The text to transform 4742 * @param Title $title The Title object for the current article 4743 * @param User $user The User object describing the current user 4744 * @param ParserOptions $options Parsing options 4745 * @param bool $clearState Whether to clear the parser state first 4746 * @return string The altered wiki markup 4747 */ 4748 public function preSaveTransform( $text, Title $title, User $user, 4749 ParserOptions $options, $clearState = true 4750 ) { 4751 if ( $clearState ) { 4752 $magicScopeVariable = $this->lock(); 4753 } 4754 $this->startParse( $title, $options, self::OT_WIKI, $clearState ); 4755 $this->setUser( $user ); 4756 4757 $pairs = array( 4758 "\r\n" => "\n", 4759 ); 4760 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text ); 4761 if ( $options->getPreSaveTransform() ) { 4762 $text = $this->pstPass2( $text, $user ); 4763 } 4764 $text = $this->mStripState->unstripBoth( $text ); 4765 4766 $this->setUser( null ); #Reset 4767 4768 return $text; 4769 } 4770 4771 /** 4772 * Pre-save transform helper function 4773 * 4774 * @param string $text 4775 * @param User $user 4776 * 4777 * @return string 4778 */ 4779 private function pstPass2( $text, $user ) { 4780 global $wgContLang; 4781 4782 # Note: This is the timestamp saved as hardcoded wikitext to 4783 # the database, we use $wgContLang here in order to give 4784 # everyone the same signature and use the default one rather 4785 # than the one selected in each user's preferences. 4786 # (see also bug 12815) 4787 $ts = $this->mOptions->getTimestamp(); 4788 $timestamp = MWTimestamp::getLocalInstance( $ts ); 4789 $ts = $timestamp->format( 'YmdHis' ); 4790 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover! 4791 4792 # Allow translation of timezones through wiki. format() can return 4793 # whatever crap the system uses, localised or not, so we cannot 4794 # ship premade translations. 4795 $key = 'timezone-' . strtolower( trim( $tzMsg ) ); 4796 $msg = wfMessage( $key )->inContentLanguage(); 4797 if ( $msg->exists() ) { 4798 $tzMsg = $msg->text(); 4799 } 4800 4801 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)"; 4802 4803 # Variable replacement 4804 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags 4805 $text = $this->replaceVariables( $text ); 4806 4807 # This works almost by chance, as the replaceVariables are done before the getUserSig(), 4808 # which may corrupt this parser instance via its wfMessage()->text() call- 4809 4810 # Signatures 4811 $sigText = $this->getUserSig( $user ); 4812 $text = strtr( $text, array( 4813 '~~~~~' => $d, 4814 '~~~~' => "$sigText $d", 4815 '~~~' => $sigText 4816 ) ); 4817 4818 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]] 4819 $tc = '[' . Title::legalChars() . ']'; 4820 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii! 4821 4822 // [[ns:page (context)|]] 4823 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; 4824 // [[ns:page(context)|]] (double-width brackets, added in r40257) 4825 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; 4826 // [[ns:page (context), context|]] (using either single or double-width comma) 4827 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; 4828 // [[|page]] (reverse pipe trick: add context from page title) 4829 $p2 = "/\[\[\\|($tc+)]]/"; 4830 4831 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]" 4832 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text ); 4833 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text ); 4834 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text ); 4835 4836 $t = $this->mTitle->getText(); 4837 $m = array(); 4838 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) { 4839 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text ); 4840 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) { 4841 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text ); 4842 } else { 4843 # if there's no context, don't bother duplicating the title 4844 $text = preg_replace( $p2, '[[\\1]]', $text ); 4845 } 4846 4847 # Trim trailing whitespace 4848 $text = rtrim( $text ); 4849 4850 return $text; 4851 } 4852 4853 /** 4854 * Fetch the user's signature text, if any, and normalize to 4855 * validated, ready-to-insert wikitext. 4856 * If you have pre-fetched the nickname or the fancySig option, you can 4857 * specify them here to save a database query. 4858 * Do not reuse this parser instance after calling getUserSig(), 4859 * as it may have changed if it's the $wgParser. 4860 * 4861 * @param User $user 4862 * @param string|bool $nickname Nickname to use or false to use user's default nickname 4863 * @param bool|null $fancySig whether the nicknname is the complete signature 4864 * or null to use default value 4865 * @return string 4866 */ 4867 public function getUserSig( &$user, $nickname = false, $fancySig = null ) { 4868 global $wgMaxSigChars; 4869 4870 $username = $user->getName(); 4871 4872 # If not given, retrieve from the user object. 4873 if ( $nickname === false ) { 4874 $nickname = $user->getOption( 'nickname' ); 4875 } 4876 4877 if ( is_null( $fancySig ) ) { 4878 $fancySig = $user->getBoolOption( 'fancysig' ); 4879 } 4880 4881 $nickname = $nickname == null ? $username : $nickname; 4882 4883 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) { 4884 $nickname = $username; 4885 wfDebug( __METHOD__ . ": $username has overlong signature.\n" ); 4886 } elseif ( $fancySig !== false ) { 4887 # Sig. might contain markup; validate this 4888 if ( $this->validateSig( $nickname ) !== false ) { 4889 # Validated; clean up (if needed) and return it 4890 return $this->cleanSig( $nickname, true ); 4891 } else { 4892 # Failed to validate; fall back to the default 4893 $nickname = $username; 4894 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" ); 4895 } 4896 } 4897 4898 # Make sure nickname doesnt get a sig in a sig 4899 $nickname = self::cleanSigInSig( $nickname ); 4900 4901 # If we're still here, make it a link to the user page 4902 $userText = wfEscapeWikiText( $username ); 4903 $nickText = wfEscapeWikiText( $nickname ); 4904 $msgName = $user->isAnon() ? 'signature-anon' : 'signature'; 4905 4906 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage() 4907 ->title( $this->getTitle() )->text(); 4908 } 4909 4910 /** 4911 * Check that the user's signature contains no bad XML 4912 * 4913 * @param string $text 4914 * @return string|bool An expanded string, or false if invalid. 4915 */ 4916 public function validateSig( $text ) { 4917 return Xml::isWellFormedXmlFragment( $text ) ? $text : false; 4918 } 4919 4920 /** 4921 * Clean up signature text 4922 * 4923 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig 4924 * 2) Substitute all transclusions 4925 * 4926 * @param string $text 4927 * @param bool $parsing Whether we're cleaning (preferences save) or parsing 4928 * @return string Signature text 4929 */ 4930 public function cleanSig( $text, $parsing = false ) { 4931 if ( !$parsing ) { 4932 global $wgTitle; 4933 $magicScopeVariable = $this->lock(); 4934 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true ); 4935 } 4936 4937 # Option to disable this feature 4938 if ( !$this->mOptions->getCleanSignatures() ) { 4939 return $text; 4940 } 4941 4942 # @todo FIXME: Regex doesn't respect extension tags or nowiki 4943 # => Move this logic to braceSubstitution() 4944 $substWord = MagicWord::get( 'subst' ); 4945 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase(); 4946 $substText = '{{' . $substWord->getSynonym( 0 ); 4947 4948 $text = preg_replace( $substRegex, $substText, $text ); 4949 $text = self::cleanSigInSig( $text ); 4950 $dom = $this->preprocessToDom( $text ); 4951 $frame = $this->getPreprocessor()->newFrame(); 4952 $text = $frame->expand( $dom ); 4953 4954 if ( !$parsing ) { 4955 $text = $this->mStripState->unstripBoth( $text ); 4956 } 4957 4958 return $text; 4959 } 4960 4961 /** 4962 * Strip ~~~, ~~~~ and ~~~~~ out of signatures 4963 * 4964 * @param string $text 4965 * @return string Signature text with /~{3,5}/ removed 4966 */ 4967 public static function cleanSigInSig( $text ) { 4968 $text = preg_replace( '/~{3,5}/', '', $text ); 4969 return $text; 4970 } 4971 4972 /** 4973 * Set up some variables which are usually set up in parse() 4974 * so that an external function can call some class members with confidence 4975 * 4976 * @param Title|null $title 4977 * @param ParserOptions $options 4978 * @param int $outputType 4979 * @param bool $clearState 4980 */ 4981 public function startExternalParse( Title $title = null, ParserOptions $options, 4982 $outputType, $clearState = true 4983 ) { 4984 $this->startParse( $title, $options, $outputType, $clearState ); 4985 } 4986 4987 /** 4988 * @param Title|null $title 4989 * @param ParserOptions $options 4990 * @param int $outputType 4991 * @param bool $clearState 4992 */ 4993 private function startParse( Title $title = null, ParserOptions $options, 4994 $outputType, $clearState = true 4995 ) { 4996 $this->setTitle( $title ); 4997 $this->mOptions = $options; 4998 $this->setOutputType( $outputType ); 4999 if ( $clearState ) { 5000 $this->clearState(); 5001 } 5002 } 5003 5004 /** 5005 * Wrapper for preprocess() 5006 * 5007 * @param string $text The text to preprocess 5008 * @param ParserOptions $options Options 5009 * @param Title|null $title Title object or null to use $wgTitle 5010 * @return string 5011 */ 5012 public function transformMsg( $text, $options, $title = null ) { 5013 static $executing = false; 5014 5015 # Guard against infinite recursion 5016 if ( $executing ) { 5017 return $text; 5018 } 5019 $executing = true; 5020 5021 wfProfileIn( __METHOD__ ); 5022 if ( !$title ) { 5023 global $wgTitle; 5024 $title = $wgTitle; 5025 } 5026 5027 $text = $this->preprocess( $text, $title, $options ); 5028 5029 $executing = false; 5030 wfProfileOut( __METHOD__ ); 5031 return $text; 5032 } 5033 5034 /** 5035 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>" 5036 * The callback should have the following form: 5037 * function myParserHook( $text, $params, $parser, $frame ) { ... } 5038 * 5039 * Transform and return $text. Use $parser for any required context, e.g. use 5040 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions 5041 * 5042 * Hooks may return extended information by returning an array, of which the 5043 * first numbered element (index 0) must be the return string, and all other 5044 * entries are extracted into local variables within an internal function 5045 * in the Parser class. 5046 * 5047 * This interface (introduced r61913) appears to be undocumented, but 5048 * 'markerName' is used by some core tag hooks to override which strip 5049 * array their results are placed in. **Use great caution if attempting 5050 * this interface, as it is not documented and injudicious use could smash 5051 * private variables.** 5052 * 5053 * @param string $tag The tag to use, e.g. 'hook' for "<hook>" 5054 * @param callable $callback The callback function (and object) to use for the tag 5055 * @throws MWException 5056 * @return callable|null The old value of the mTagHooks array associated with the hook 5057 */ 5058 public function setHook( $tag, $callback ) { 5059 $tag = strtolower( $tag ); 5060 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { 5061 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" ); 5062 } 5063 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null; 5064 $this->mTagHooks[$tag] = $callback; 5065 if ( !in_array( $tag, $this->mStripList ) ) { 5066 $this->mStripList[] = $tag; 5067 } 5068 5069 return $oldVal; 5070 } 5071 5072 /** 5073 * As setHook(), but letting the contents be parsed. 5074 * 5075 * Transparent tag hooks are like regular XML-style tag hooks, except they 5076 * operate late in the transformation sequence, on HTML instead of wikitext. 5077 * 5078 * This is probably obsoleted by things dealing with parser frames? 5079 * The only extension currently using it is geoserver. 5080 * 5081 * @since 1.10 5082 * @todo better document or deprecate this 5083 * 5084 * @param string $tag The tag to use, e.g. 'hook' for "<hook>" 5085 * @param callable $callback The callback function (and object) to use for the tag 5086 * @throws MWException 5087 * @return callable|null The old value of the mTagHooks array associated with the hook 5088 */ 5089 public function setTransparentTagHook( $tag, $callback ) { 5090 $tag = strtolower( $tag ); 5091 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { 5092 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" ); 5093 } 5094 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null; 5095 $this->mTransparentTagHooks[$tag] = $callback; 5096 5097 return $oldVal; 5098 } 5099 5100 /** 5101 * Remove all tag hooks 5102 */ 5103 public function clearTagHooks() { 5104 $this->mTagHooks = array(); 5105 $this->mFunctionTagHooks = array(); 5106 $this->mStripList = $this->mDefaultStripList; 5107 } 5108 5109 /** 5110 * Create a function, e.g. {{sum:1|2|3}} 5111 * The callback function should have the form: 5112 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... } 5113 * 5114 * Or with SFH_OBJECT_ARGS: 5115 * function myParserFunction( $parser, $frame, $args ) { ... } 5116 * 5117 * The callback may either return the text result of the function, or an array with the text 5118 * in element 0, and a number of flags in the other elements. The names of the flags are 5119 * specified in the keys. Valid flags are: 5120 * found The text returned is valid, stop processing the template. This 5121 * is on by default. 5122 * nowiki Wiki markup in the return value should be escaped 5123 * isHTML The returned text is HTML, armour it against wikitext transformation 5124 * 5125 * @param string $id The magic word ID 5126 * @param callable $callback The callback function (and object) to use 5127 * @param int $flags A combination of the following flags: 5128 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}} 5129 * 5130 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This 5131 * allows for conditional expansion of the parse tree, allowing you to eliminate dead 5132 * branches and thus speed up parsing. It is also possible to analyse the parse tree of 5133 * the arguments, and to control the way they are expanded. 5134 * 5135 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the 5136 * arguments, for instance: 5137 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : ''; 5138 * 5139 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in 5140 * future versions. Please call $frame->expand() on it anyway so that your code keeps 5141 * working if/when this is changed. 5142 * 5143 * If you want whitespace to be trimmed from $args, you need to do it yourself, post- 5144 * expansion. 5145 * 5146 * Please read the documentation in includes/parser/Preprocessor.php for more information 5147 * about the methods available in PPFrame and PPNode. 5148 * 5149 * @throws MWException 5150 * @return string|callable The old callback function for this name, if any 5151 */ 5152 public function setFunctionHook( $id, $callback, $flags = 0 ) { 5153 global $wgContLang; 5154 5155 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null; 5156 $this->mFunctionHooks[$id] = array( $callback, $flags ); 5157 5158 # Add to function cache 5159 $mw = MagicWord::get( $id ); 5160 if ( !$mw ) { 5161 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' ); 5162 } 5163 5164 $synonyms = $mw->getSynonyms(); 5165 $sensitive = intval( $mw->isCaseSensitive() ); 5166 5167 foreach ( $synonyms as $syn ) { 5168 # Case 5169 if ( !$sensitive ) { 5170 $syn = $wgContLang->lc( $syn ); 5171 } 5172 # Add leading hash 5173 if ( !( $flags & SFH_NO_HASH ) ) { 5174 $syn = '#' . $syn; 5175 } 5176 # Remove trailing colon 5177 if ( substr( $syn, -1, 1 ) === ':' ) { 5178 $syn = substr( $syn, 0, -1 ); 5179 } 5180 $this->mFunctionSynonyms[$sensitive][$syn] = $id; 5181 } 5182 return $oldVal; 5183 } 5184 5185 /** 5186 * Get all registered function hook identifiers 5187 * 5188 * @return array 5189 */ 5190 public function getFunctionHooks() { 5191 return array_keys( $this->mFunctionHooks ); 5192 } 5193 5194 /** 5195 * Create a tag function, e.g. "<test>some stuff</test>". 5196 * Unlike tag hooks, tag functions are parsed at preprocessor level. 5197 * Unlike parser functions, their content is not preprocessed. 5198 * @param string $tag 5199 * @param callable $callback 5200 * @param int $flags 5201 * @throws MWException 5202 * @return null 5203 */ 5204 public function setFunctionTagHook( $tag, $callback, $flags ) { 5205 $tag = strtolower( $tag ); 5206 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { 5207 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" ); 5208 } 5209 $old = isset( $this->mFunctionTagHooks[$tag] ) ? 5210 $this->mFunctionTagHooks[$tag] : null; 5211 $this->mFunctionTagHooks[$tag] = array( $callback, $flags ); 5212 5213 if ( !in_array( $tag, $this->mStripList ) ) { 5214 $this->mStripList[] = $tag; 5215 } 5216 5217 return $old; 5218 } 5219 5220 /** 5221 * @todo FIXME: Update documentation. makeLinkObj() is deprecated. 5222 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer 5223 * Placeholders created in Skin::makeLinkObj() 5224 * 5225 * @param string $text 5226 * @param int $options 5227 * 5228 * @return array Array of link CSS classes, indexed by PDBK. 5229 */ 5230 public function replaceLinkHolders( &$text, $options = 0 ) { 5231 return $this->mLinkHolders->replace( $text ); 5232 } 5233 5234 /** 5235 * Replace "<!--LINK-->" link placeholders with plain text of links 5236 * (not HTML-formatted). 5237 * 5238 * @param string $text 5239 * @return string 5240 */ 5241 public function replaceLinkHoldersText( $text ) { 5242 return $this->mLinkHolders->replaceText( $text ); 5243 } 5244 5245 /** 5246 * Renders an image gallery from a text with one line per image. 5247 * text labels may be given by using |-style alternative text. E.g. 5248 * Image:one.jpg|The number "1" 5249 * Image:tree.jpg|A tree 5250 * given as text will return the HTML of a gallery with two images, 5251 * labeled 'The number "1"' and 5252 * 'A tree'. 5253 * 5254 * @param string $text 5255 * @param array $params 5256 * @return string HTML 5257 */ 5258 public function renderImageGallery( $text, $params ) { 5259 wfProfileIn( __METHOD__ ); 5260 5261 $mode = false; 5262 if ( isset( $params['mode'] ) ) { 5263 $mode = $params['mode']; 5264 } 5265 5266 try { 5267 $ig = ImageGalleryBase::factory( $mode ); 5268 } catch ( MWException $e ) { 5269 // If invalid type set, fallback to default. 5270 $ig = ImageGalleryBase::factory( false ); 5271 } 5272 5273 $ig->setContextTitle( $this->mTitle ); 5274 $ig->setShowBytes( false ); 5275 $ig->setShowFilename( false ); 5276 $ig->setParser( $this ); 5277 $ig->setHideBadImages(); 5278 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) ); 5279 5280 if ( isset( $params['showfilename'] ) ) { 5281 $ig->setShowFilename( true ); 5282 } else { 5283 $ig->setShowFilename( false ); 5284 } 5285 if ( isset( $params['caption'] ) ) { 5286 $caption = $params['caption']; 5287 $caption = htmlspecialchars( $caption ); 5288 $caption = $this->replaceInternalLinks( $caption ); 5289 $ig->setCaptionHtml( $caption ); 5290 } 5291 if ( isset( $params['perrow'] ) ) { 5292 $ig->setPerRow( $params['perrow'] ); 5293 } 5294 if ( isset( $params['widths'] ) ) { 5295 $ig->setWidths( $params['widths'] ); 5296 } 5297 if ( isset( $params['heights'] ) ) { 5298 $ig->setHeights( $params['heights'] ); 5299 } 5300 $ig->setAdditionalOptions( $params ); 5301 5302 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) ); 5303 5304 $lines = StringUtils::explode( "\n", $text ); 5305 foreach ( $lines as $line ) { 5306 # match lines like these: 5307 # Image:someimage.jpg|This is some image 5308 $matches = array(); 5309 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches ); 5310 # Skip empty lines 5311 if ( count( $matches ) == 0 ) { 5312 continue; 5313 } 5314 5315 if ( strpos( $matches[0], '%' ) !== false ) { 5316 $matches[1] = rawurldecode( $matches[1] ); 5317 } 5318 $title = Title::newFromText( $matches[1], NS_FILE ); 5319 if ( is_null( $title ) ) { 5320 # Bogus title. Ignore these so we don't bomb out later. 5321 continue; 5322 } 5323 5324 # We need to get what handler the file uses, to figure out parameters. 5325 # Note, a hook can overide the file name, and chose an entirely different 5326 # file (which potentially could be of a different type and have different handler). 5327 $options = array(); 5328 $descQuery = false; 5329 wfRunHooks( 'BeforeParserFetchFileAndTitle', 5330 array( $this, $title, &$options, &$descQuery ) ); 5331 # Don't register it now, as ImageGallery does that later. 5332 $file = $this->fetchFileNoRegister( $title, $options ); 5333 $handler = $file ? $file->getHandler() : false; 5334 5335 wfProfileIn( __METHOD__ . '-getMagicWord' ); 5336 $paramMap = array( 5337 'img_alt' => 'gallery-internal-alt', 5338 'img_link' => 'gallery-internal-link', 5339 ); 5340 if ( $handler ) { 5341 $paramMap = $paramMap + $handler->getParamMap(); 5342 // We don't want people to specify per-image widths. 5343 // Additionally the width parameter would need special casing anyhow. 5344 unset( $paramMap['img_width'] ); 5345 } 5346 5347 $mwArray = new MagicWordArray( array_keys( $paramMap ) ); 5348 wfProfileOut( __METHOD__ . '-getMagicWord' ); 5349 5350 $label = ''; 5351 $alt = ''; 5352 $link = ''; 5353 $handlerOptions = array(); 5354 if ( isset( $matches[3] ) ) { 5355 // look for an |alt= definition while trying not to break existing 5356 // captions with multiple pipes (|) in it, until a more sensible grammar 5357 // is defined for images in galleries 5358 5359 // FIXME: Doing recursiveTagParse at this stage, and the trim before 5360 // splitting on '|' is a bit odd, and different from makeImage. 5361 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) ); 5362 $parameterMatches = StringUtils::explode( '|', $matches[3] ); 5363 5364 foreach ( $parameterMatches as $parameterMatch ) { 5365 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch ); 5366 if ( $magicName ) { 5367 $paramName = $paramMap[$magicName]; 5368 5369 switch ( $paramName ) { 5370 case 'gallery-internal-alt': 5371 $alt = $this->stripAltText( $match, false ); 5372 break; 5373 case 'gallery-internal-link': 5374 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) ); 5375 $chars = self::EXT_LINK_URL_CLASS; 5376 $prots = $this->mUrlProtocols; 5377 //check to see if link matches an absolute url, if not then it must be a wiki link. 5378 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) { 5379 $link = $linkValue; 5380 } else { 5381 $localLinkTitle = Title::newFromText( $linkValue ); 5382 if ( $localLinkTitle !== null ) { 5383 $link = $localLinkTitle->getLinkURL(); 5384 } 5385 } 5386 break; 5387 default: 5388 // Must be a handler specific parameter. 5389 if ( $handler->validateParam( $paramName, $match ) ) { 5390 $handlerOptions[$paramName] = $match; 5391 } else { 5392 // Guess not. Append it to the caption. 5393 wfDebug( "$parameterMatch failed parameter validation\n" ); 5394 $label .= '|' . $parameterMatch; 5395 } 5396 } 5397 5398 } else { 5399 // concatenate all other pipes 5400 $label .= '|' . $parameterMatch; 5401 } 5402 } 5403 // remove the first pipe 5404 $label = substr( $label, 1 ); 5405 } 5406 5407 $ig->add( $title, $label, $alt, $link, $handlerOptions ); 5408 } 5409 $html = $ig->toHTML(); 5410 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) ); 5411 wfProfileOut( __METHOD__ ); 5412 return $html; 5413 } 5414 5415 /** 5416 * @param string $handler 5417 * @return array 5418 */ 5419 public function getImageParams( $handler ) { 5420 if ( $handler ) { 5421 $handlerClass = get_class( $handler ); 5422 } else { 5423 $handlerClass = ''; 5424 } 5425 if ( !isset( $this->mImageParams[$handlerClass] ) ) { 5426 # Initialise static lists 5427 static $internalParamNames = array( 5428 'horizAlign' => array( 'left', 'right', 'center', 'none' ), 5429 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 5430 'bottom', 'text-bottom' ), 5431 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless', 5432 'upright', 'border', 'link', 'alt', 'class' ), 5433 ); 5434 static $internalParamMap; 5435 if ( !$internalParamMap ) { 5436 $internalParamMap = array(); 5437 foreach ( $internalParamNames as $type => $names ) { 5438 foreach ( $names as $name ) { 5439 $magicName = str_replace( '-', '_', "img_$name" ); 5440 $internalParamMap[$magicName] = array( $type, $name ); 5441 } 5442 } 5443 } 5444 5445 # Add handler params 5446 $paramMap = $internalParamMap; 5447 if ( $handler ) { 5448 $handlerParamMap = $handler->getParamMap(); 5449 foreach ( $handlerParamMap as $magic => $paramName ) { 5450 $paramMap[$magic] = array( 'handler', $paramName ); 5451 } 5452 } 5453 $this->mImageParams[$handlerClass] = $paramMap; 5454 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) ); 5455 } 5456 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ); 5457 } 5458 5459 /** 5460 * Parse image options text and use it to make an image 5461 * 5462 * @param Title $title 5463 * @param string $options 5464 * @param LinkHolderArray|bool $holders 5465 * @return string HTML 5466 */ 5467 public function makeImage( $title, $options, $holders = false ) { 5468 # Check if the options text is of the form "options|alt text" 5469 # Options are: 5470 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang 5471 # * left no resizing, just left align. label is used for alt= only 5472 # * right same, but right aligned 5473 # * none same, but not aligned 5474 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox 5475 # * center center the image 5476 # * frame Keep original image size, no magnify-button. 5477 # * framed Same as "frame" 5478 # * frameless like 'thumb' but without a frame. Keeps user preferences for width 5479 # * upright reduce width for upright images, rounded to full __0 px 5480 # * border draw a 1px border around the image 5481 # * alt Text for HTML alt attribute (defaults to empty) 5482 # * class Set a class for img node 5483 # * link Set the target of the image link. Can be external, interwiki, or local 5484 # vertical-align values (no % or length right now): 5485 # * baseline 5486 # * sub 5487 # * super 5488 # * top 5489 # * text-top 5490 # * middle 5491 # * bottom 5492 # * text-bottom 5493 5494 $parts = StringUtils::explode( "|", $options ); 5495 5496 # Give extensions a chance to select the file revision for us 5497 $options = array(); 5498 $descQuery = false; 5499 wfRunHooks( 'BeforeParserFetchFileAndTitle', 5500 array( $this, $title, &$options, &$descQuery ) ); 5501 # Fetch and register the file (file title may be different via hooks) 5502 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options ); 5503 5504 # Get parameter map 5505 $handler = $file ? $file->getHandler() : false; 5506 5507 list( $paramMap, $mwArray ) = $this->getImageParams( $handler ); 5508 5509 if ( !$file ) { 5510 $this->addTrackingCategory( 'broken-file-category' ); 5511 } 5512 5513 # Process the input parameters 5514 $caption = ''; 5515 $params = array( 'frame' => array(), 'handler' => array(), 5516 'horizAlign' => array(), 'vertAlign' => array() ); 5517 $seenformat = false; 5518 foreach ( $parts as $part ) { 5519 $part = trim( $part ); 5520 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part ); 5521 $validated = false; 5522 if ( isset( $paramMap[$magicName] ) ) { 5523 list( $type, $paramName ) = $paramMap[$magicName]; 5524 5525 # Special case; width and height come in one variable together 5526 if ( $type === 'handler' && $paramName === 'width' ) { 5527 $parsedWidthParam = $this->parseWidthParam( $value ); 5528 if ( isset( $parsedWidthParam['width'] ) ) { 5529 $width = $parsedWidthParam['width']; 5530 if ( $handler->validateParam( 'width', $width ) ) { 5531 $params[$type]['width'] = $width; 5532 $validated = true; 5533 } 5534 } 5535 if ( isset( $parsedWidthParam['height'] ) ) { 5536 $height = $parsedWidthParam['height']; 5537 if ( $handler->validateParam( 'height', $height ) ) { 5538 $params[$type]['height'] = $height; 5539 $validated = true; 5540 } 5541 } 5542 # else no validation -- bug 13436 5543 } else { 5544 if ( $type === 'handler' ) { 5545 # Validate handler parameter 5546 $validated = $handler->validateParam( $paramName, $value ); 5547 } else { 5548 # Validate internal parameters 5549 switch ( $paramName ) { 5550 case 'manualthumb': 5551 case 'alt': 5552 case 'class': 5553 # @todo FIXME: Possibly check validity here for 5554 # manualthumb? downstream behavior seems odd with 5555 # missing manual thumbs. 5556 $validated = true; 5557 $value = $this->stripAltText( $value, $holders ); 5558 break; 5559 case 'link': 5560 $chars = self::EXT_LINK_URL_CLASS; 5561 $prots = $this->mUrlProtocols; 5562 if ( $value === '' ) { 5563 $paramName = 'no-link'; 5564 $value = true; 5565 $validated = true; 5566 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) { 5567 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) { 5568 $paramName = 'link-url'; 5569 $this->mOutput->addExternalLink( $value ); 5570 if ( $this->mOptions->getExternalLinkTarget() ) { 5571 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget(); 5572 } 5573 $validated = true; 5574 } 5575 } else { 5576 $linkTitle = Title::newFromText( $value ); 5577 if ( $linkTitle ) { 5578 $paramName = 'link-title'; 5579 $value = $linkTitle; 5580 $this->mOutput->addLink( $linkTitle ); 5581 $validated = true; 5582 } 5583 } 5584 break; 5585 case 'frameless': 5586 case 'framed': 5587 case 'thumbnail': 5588 // use first appearing option, discard others. 5589 $validated = ! $seenformat; 5590 $seenformat = true; 5591 break; 5592 default: 5593 # Most other things appear to be empty or numeric... 5594 $validated = ( $value === false || is_numeric( trim( $value ) ) ); 5595 } 5596 } 5597 5598 if ( $validated ) { 5599 $params[$type][$paramName] = $value; 5600 } 5601 } 5602 } 5603 if ( !$validated ) { 5604 $caption = $part; 5605 } 5606 } 5607 5608 # Process alignment parameters 5609 if ( $params['horizAlign'] ) { 5610 $params['frame']['align'] = key( $params['horizAlign'] ); 5611 } 5612 if ( $params['vertAlign'] ) { 5613 $params['frame']['valign'] = key( $params['vertAlign'] ); 5614 } 5615 5616 $params['frame']['caption'] = $caption; 5617 5618 # Will the image be presented in a frame, with the caption below? 5619 $imageIsFramed = isset( $params['frame']['frame'] ) 5620 || isset( $params['frame']['framed'] ) 5621 || isset( $params['frame']['thumbnail'] ) 5622 || isset( $params['frame']['manualthumb'] ); 5623 5624 # In the old days, [[Image:Foo|text...]] would set alt text. Later it 5625 # came to also set the caption, ordinary text after the image -- which 5626 # makes no sense, because that just repeats the text multiple times in 5627 # screen readers. It *also* came to set the title attribute. 5628 # 5629 # Now that we have an alt attribute, we should not set the alt text to 5630 # equal the caption: that's worse than useless, it just repeats the 5631 # text. This is the framed/thumbnail case. If there's no caption, we 5632 # use the unnamed parameter for alt text as well, just for the time be- 5633 # ing, if the unnamed param is set and the alt param is not. 5634 # 5635 # For the future, we need to figure out if we want to tweak this more, 5636 # e.g., introducing a title= parameter for the title; ignoring the un- 5637 # named parameter entirely for images without a caption; adding an ex- 5638 # plicit caption= parameter and preserving the old magic unnamed para- 5639 # meter for BC; ... 5640 if ( $imageIsFramed ) { # Framed image 5641 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) { 5642 # No caption or alt text, add the filename as the alt text so 5643 # that screen readers at least get some description of the image 5644 $params['frame']['alt'] = $title->getText(); 5645 } 5646 # Do not set $params['frame']['title'] because tooltips don't make sense 5647 # for framed images 5648 } else { # Inline image 5649 if ( !isset( $params['frame']['alt'] ) ) { 5650 # No alt text, use the "caption" for the alt text 5651 if ( $caption !== '' ) { 5652 $params['frame']['alt'] = $this->stripAltText( $caption, $holders ); 5653 } else { 5654 # No caption, fall back to using the filename for the 5655 # alt text 5656 $params['frame']['alt'] = $title->getText(); 5657 } 5658 } 5659 # Use the "caption" for the tooltip text 5660 $params['frame']['title'] = $this->stripAltText( $caption, $holders ); 5661 } 5662 5663 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) ); 5664 5665 # Linker does the rest 5666 $time = isset( $options['time'] ) ? $options['time'] : false; 5667 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'], 5668 $time, $descQuery, $this->mOptions->getThumbSize() ); 5669 5670 # Give the handler a chance to modify the parser object 5671 if ( $handler ) { 5672 $handler->parserTransformHook( $this, $file ); 5673 } 5674 5675 return $ret; 5676 } 5677 5678 /** 5679 * @param string $caption 5680 * @param LinkHolderArray|bool $holders 5681 * @return mixed|string 5682 */ 5683 protected function stripAltText( $caption, $holders ) { 5684 # Strip bad stuff out of the title (tooltip). We can't just use 5685 # replaceLinkHoldersText() here, because if this function is called 5686 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date. 5687 if ( $holders ) { 5688 $tooltip = $holders->replaceText( $caption ); 5689 } else { 5690 $tooltip = $this->replaceLinkHoldersText( $caption ); 5691 } 5692 5693 # make sure there are no placeholders in thumbnail attributes 5694 # that are later expanded to html- so expand them now and 5695 # remove the tags 5696 $tooltip = $this->mStripState->unstripBoth( $tooltip ); 5697 $tooltip = Sanitizer::stripAllTags( $tooltip ); 5698 5699 return $tooltip; 5700 } 5701 5702 /** 5703 * Set a flag in the output object indicating that the content is dynamic and 5704 * shouldn't be cached. 5705 */ 5706 public function disableCache() { 5707 wfDebug( "Parser output marked as uncacheable.\n" ); 5708 if ( !$this->mOutput ) { 5709 throw new MWException( __METHOD__ . 5710 " can only be called when actually parsing something" ); 5711 } 5712 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility 5713 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency 5714 } 5715 5716 /** 5717 * Callback from the Sanitizer for expanding items found in HTML attribute 5718 * values, so they can be safely tested and escaped. 5719 * 5720 * @param string $text 5721 * @param bool|PPFrame $frame 5722 * @return string 5723 */ 5724 public function attributeStripCallback( &$text, $frame = false ) { 5725 $text = $this->replaceVariables( $text, $frame ); 5726 $text = $this->mStripState->unstripBoth( $text ); 5727 return $text; 5728 } 5729 5730 /** 5731 * Accessor 5732 * 5733 * @return array 5734 */ 5735 public function getTags() { 5736 return array_merge( 5737 array_keys( $this->mTransparentTagHooks ), 5738 array_keys( $this->mTagHooks ), 5739 array_keys( $this->mFunctionTagHooks ) 5740 ); 5741 } 5742 5743 /** 5744 * Replace transparent tags in $text with the values given by the callbacks. 5745 * 5746 * Transparent tag hooks are like regular XML-style tag hooks, except they 5747 * operate late in the transformation sequence, on HTML instead of wikitext. 5748 * 5749 * @param string $text 5750 * 5751 * @return string 5752 */ 5753 public function replaceTransparentTags( $text ) { 5754 $matches = array(); 5755 $elements = array_keys( $this->mTransparentTagHooks ); 5756 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix ); 5757 $replacements = array(); 5758 5759 foreach ( $matches as $marker => $data ) { 5760 list( $element, $content, $params, $tag ) = $data; 5761 $tagName = strtolower( $element ); 5762 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) { 5763 $output = call_user_func_array( 5764 $this->mTransparentTagHooks[$tagName], 5765 array( $content, $params, $this ) 5766 ); 5767 } else { 5768 $output = $tag; 5769 } 5770 $replacements[$marker] = $output; 5771 } 5772 return strtr( $text, $replacements ); 5773 } 5774 5775 /** 5776 * Break wikitext input into sections, and either pull or replace 5777 * some particular section's text. 5778 * 5779 * External callers should use the getSection and replaceSection methods. 5780 * 5781 * @param string $text Page wikitext 5782 * @param string|number $sectionId A section identifier string of the form: 5783 * "<flag1> - <flag2> - ... - <section number>" 5784 * 5785 * Currently the only recognised flag is "T", which means the target section number 5786 * was derived during a template inclusion parse, in other words this is a template 5787 * section edit link. If no flags are given, it was an ordinary section edit link. 5788 * This flag is required to avoid a section numbering mismatch when a section is 5789 * enclosed by "<includeonly>" (bug 6563). 5790 * 5791 * The section number 0 pulls the text before the first heading; other numbers will 5792 * pull the given section along with its lower-level subsections. If the section is 5793 * not found, $mode=get will return $newtext, and $mode=replace will return $text. 5794 * 5795 * Section 0 is always considered to exist, even if it only contains the empty 5796 * string. If $text is the empty string and section 0 is replaced, $newText is 5797 * returned. 5798 * 5799 * @param string $mode One of "get" or "replace" 5800 * @param string $newText Replacement text for section data. 5801 * @return string For "get", the extracted section text. 5802 * for "replace", the whole page with the section replaced. 5803 */ 5804 private function extractSections( $text, $sectionId, $mode, $newText = '' ) { 5805 global $wgTitle; # not generally used but removes an ugly failure mode 5806 5807 $magicScopeVariable = $this->lock(); 5808 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true ); 5809 $outText = ''; 5810 $frame = $this->getPreprocessor()->newFrame(); 5811 5812 # Process section extraction flags 5813 $flags = 0; 5814 $sectionParts = explode( '-', $sectionId ); 5815 $sectionIndex = array_pop( $sectionParts ); 5816 foreach ( $sectionParts as $part ) { 5817 if ( $part === 'T' ) { 5818 $flags |= self::PTD_FOR_INCLUSION; 5819 } 5820 } 5821 5822 # Check for empty input 5823 if ( strval( $text ) === '' ) { 5824 # Only sections 0 and T-0 exist in an empty document 5825 if ( $sectionIndex == 0 ) { 5826 if ( $mode === 'get' ) { 5827 return ''; 5828 } else { 5829 return $newText; 5830 } 5831 } else { 5832 if ( $mode === 'get' ) { 5833 return $newText; 5834 } else { 5835 return $text; 5836 } 5837 } 5838 } 5839 5840 # Preprocess the text 5841 $root = $this->preprocessToDom( $text, $flags ); 5842 5843 # <h> nodes indicate section breaks 5844 # They can only occur at the top level, so we can find them by iterating the root's children 5845 $node = $root->getFirstChild(); 5846 5847 # Find the target section 5848 if ( $sectionIndex == 0 ) { 5849 # Section zero doesn't nest, level=big 5850 $targetLevel = 1000; 5851 } else { 5852 while ( $node ) { 5853 if ( $node->getName() === 'h' ) { 5854 $bits = $node->splitHeading(); 5855 if ( $bits['i'] == $sectionIndex ) { 5856 $targetLevel = $bits['level']; 5857 break; 5858 } 5859 } 5860 if ( $mode === 'replace' ) { 5861 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 5862 } 5863 $node = $node->getNextSibling(); 5864 } 5865 } 5866 5867 if ( !$node ) { 5868 # Not found 5869 if ( $mode === 'get' ) { 5870 return $newText; 5871 } else { 5872 return $text; 5873 } 5874 } 5875 5876 # Find the end of the section, including nested sections 5877 do { 5878 if ( $node->getName() === 'h' ) { 5879 $bits = $node->splitHeading(); 5880 $curLevel = $bits['level']; 5881 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) { 5882 break; 5883 } 5884 } 5885 if ( $mode === 'get' ) { 5886 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 5887 } 5888 $node = $node->getNextSibling(); 5889 } while ( $node ); 5890 5891 # Write out the remainder (in replace mode only) 5892 if ( $mode === 'replace' ) { 5893 # Output the replacement text 5894 # Add two newlines on -- trailing whitespace in $newText is conventionally 5895 # stripped by the editor, so we need both newlines to restore the paragraph gap 5896 # Only add trailing whitespace if there is newText 5897 if ( $newText != "" ) { 5898 $outText .= $newText . "\n\n"; 5899 } 5900 5901 while ( $node ) { 5902 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 5903 $node = $node->getNextSibling(); 5904 } 5905 } 5906 5907 if ( is_string( $outText ) ) { 5908 # Re-insert stripped tags 5909 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) ); 5910 } 5911 5912 return $outText; 5913 } 5914 5915 /** 5916 * This function returns the text of a section, specified by a number ($section). 5917 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or 5918 * the first section before any such heading (section 0). 5919 * 5920 * If a section contains subsections, these are also returned. 5921 * 5922 * @param string $text Text to look in 5923 * @param string|number $sectionId Section identifier as a number or string 5924 * (e.g. 0, 1 or 'T-1'). 5925 * @param string $defaultText Default to return if section is not found 5926 * 5927 * @return string Text of the requested section 5928 */ 5929 public function getSection( $text, $sectionId, $defaultText = '' ) { 5930 return $this->extractSections( $text, $sectionId, 'get', $defaultText ); 5931 } 5932 5933 /** 5934 * This function returns $oldtext after the content of the section 5935 * specified by $section has been replaced with $text. If the target 5936 * section does not exist, $oldtext is returned unchanged. 5937 * 5938 * @param string $oldText Former text of the article 5939 * @param string|number $sectionId Section identifier as a number or string 5940 * (e.g. 0, 1 or 'T-1'). 5941 * @param string $newText Replacing text 5942 * 5943 * @return string Modified text 5944 */ 5945 public function replaceSection( $oldText, $sectionId, $newText ) { 5946 return $this->extractSections( $oldText, $sectionId, 'replace', $newText ); 5947 } 5948 5949 /** 5950 * Get the ID of the revision we are parsing 5951 * 5952 * @return int|null 5953 */ 5954 public function getRevisionId() { 5955 return $this->mRevisionId; 5956 } 5957 5958 /** 5959 * Get the revision object for $this->mRevisionId 5960 * 5961 * @return Revision|null Either a Revision object or null 5962 * @since 1.23 (public since 1.23) 5963 */ 5964 public function getRevisionObject() { 5965 if ( !is_null( $this->mRevisionObject ) ) { 5966 return $this->mRevisionObject; 5967 } 5968 if ( is_null( $this->mRevisionId ) ) { 5969 return null; 5970 } 5971 5972 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId ); 5973 return $this->mRevisionObject; 5974 } 5975 5976 /** 5977 * Get the timestamp associated with the current revision, adjusted for 5978 * the default server-local timestamp 5979 * @return string 5980 */ 5981 public function getRevisionTimestamp() { 5982 if ( is_null( $this->mRevisionTimestamp ) ) { 5983 wfProfileIn( __METHOD__ ); 5984 5985 global $wgContLang; 5986 5987 $revObject = $this->getRevisionObject(); 5988 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow(); 5989 5990 # The cryptic '' timezone parameter tells to use the site-default 5991 # timezone offset instead of the user settings. 5992 # 5993 # Since this value will be saved into the parser cache, served 5994 # to other users, and potentially even used inside links and such, 5995 # it needs to be consistent for all visitors. 5996 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' ); 5997 5998 wfProfileOut( __METHOD__ ); 5999 } 6000 return $this->mRevisionTimestamp; 6001 } 6002 6003 /** 6004 * Get the name of the user that edited the last revision 6005 * 6006 * @return string User name 6007 */ 6008 public function getRevisionUser() { 6009 if ( is_null( $this->mRevisionUser ) ) { 6010 $revObject = $this->getRevisionObject(); 6011 6012 # if this template is subst: the revision id will be blank, 6013 # so just use the current user's name 6014 if ( $revObject ) { 6015 $this->mRevisionUser = $revObject->getUserText(); 6016 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) { 6017 $this->mRevisionUser = $this->getUser()->getName(); 6018 } 6019 } 6020 return $this->mRevisionUser; 6021 } 6022 6023 /** 6024 * Get the size of the revision 6025 * 6026 * @return int|null Revision size 6027 */ 6028 public function getRevisionSize() { 6029 if ( is_null( $this->mRevisionSize ) ) { 6030 $revObject = $this->getRevisionObject(); 6031 6032 # if this variable is subst: the revision id will be blank, 6033 # so just use the parser input size, because the own substituation 6034 # will change the size. 6035 if ( $revObject ) { 6036 $this->mRevisionSize = $revObject->getSize(); 6037 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) { 6038 $this->mRevisionSize = $this->mInputSize; 6039 } 6040 } 6041 return $this->mRevisionSize; 6042 } 6043 6044 /** 6045 * Mutator for $mDefaultSort 6046 * 6047 * @param string $sort New value 6048 */ 6049 public function setDefaultSort( $sort ) { 6050 $this->mDefaultSort = $sort; 6051 $this->mOutput->setProperty( 'defaultsort', $sort ); 6052 } 6053 6054 /** 6055 * Accessor for $mDefaultSort 6056 * Will use the empty string if none is set. 6057 * 6058 * This value is treated as a prefix, so the 6059 * empty string is equivalent to sorting by 6060 * page name. 6061 * 6062 * @return string 6063 */ 6064 public function getDefaultSort() { 6065 if ( $this->mDefaultSort !== false ) { 6066 return $this->mDefaultSort; 6067 } else { 6068 return ''; 6069 } 6070 } 6071 6072 /** 6073 * Accessor for $mDefaultSort 6074 * Unlike getDefaultSort(), will return false if none is set 6075 * 6076 * @return string|bool 6077 */ 6078 public function getCustomDefaultSort() { 6079 return $this->mDefaultSort; 6080 } 6081 6082 /** 6083 * Try to guess the section anchor name based on a wikitext fragment 6084 * presumably extracted from a heading, for example "Header" from 6085 * "== Header ==". 6086 * 6087 * @param string $text 6088 * 6089 * @return string 6090 */ 6091 public function guessSectionNameFromWikiText( $text ) { 6092 # Strip out wikitext links(they break the anchor) 6093 $text = $this->stripSectionName( $text ); 6094 $text = Sanitizer::normalizeSectionNameWhitespace( $text ); 6095 return '#' . Sanitizer::escapeId( $text, 'noninitial' ); 6096 } 6097 6098 /** 6099 * Same as guessSectionNameFromWikiText(), but produces legacy anchors 6100 * instead. For use in redirects, since IE6 interprets Redirect: headers 6101 * as something other than UTF-8 (apparently?), resulting in breakage. 6102 * 6103 * @param string $text The section name 6104 * @return string An anchor 6105 */ 6106 public function guessLegacySectionNameFromWikiText( $text ) { 6107 # Strip out wikitext links(they break the anchor) 6108 $text = $this->stripSectionName( $text ); 6109 $text = Sanitizer::normalizeSectionNameWhitespace( $text ); 6110 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) ); 6111 } 6112 6113 /** 6114 * Strips a text string of wikitext for use in a section anchor 6115 * 6116 * Accepts a text string and then removes all wikitext from the 6117 * string and leaves only the resultant text (i.e. the result of 6118 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of 6119 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended 6120 * to create valid section anchors by mimicing the output of the 6121 * parser when headings are parsed. 6122 * 6123 * @param string $text Text string to be stripped of wikitext 6124 * for use in a Section anchor 6125 * @return string Filtered text string 6126 */ 6127 public function stripSectionName( $text ) { 6128 # Strip internal link markup 6129 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text ); 6130 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text ); 6131 6132 # Strip external link markup 6133 # @todo FIXME: Not tolerant to blank link text 6134 # I.E. [https://www.mediawiki.org] will render as [1] or something depending 6135 # on how many empty links there are on the page - need to figure that out. 6136 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text ); 6137 6138 # Parse wikitext quotes (italics & bold) 6139 $text = $this->doQuotes( $text ); 6140 6141 # Strip HTML tags 6142 $text = StringUtils::delimiterReplace( '<', '>', '', $text ); 6143 return $text; 6144 } 6145 6146 /** 6147 * strip/replaceVariables/unstrip for preprocessor regression testing 6148 * 6149 * @param string $text 6150 * @param Title $title 6151 * @param ParserOptions $options 6152 * @param int $outputType 6153 * 6154 * @return string 6155 */ 6156 public function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) { 6157 $magicScopeVariable = $this->lock(); 6158 $this->startParse( $title, $options, $outputType, true ); 6159 6160 $text = $this->replaceVariables( $text ); 6161 $text = $this->mStripState->unstripBoth( $text ); 6162 $text = Sanitizer::removeHTMLtags( $text ); 6163 return $text; 6164 } 6165 6166 /** 6167 * @param string $text 6168 * @param Title $title 6169 * @param ParserOptions $options 6170 * @return string 6171 */ 6172 public function testPst( $text, Title $title, ParserOptions $options ) { 6173 return $this->preSaveTransform( $text, $title, $options->getUser(), $options ); 6174 } 6175 6176 /** 6177 * @param string $text 6178 * @param Title $title 6179 * @param ParserOptions $options 6180 * @return string 6181 */ 6182 public function testPreprocess( $text, Title $title, ParserOptions $options ) { 6183 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS ); 6184 } 6185 6186 /** 6187 * Call a callback function on all regions of the given text that are not 6188 * inside strip markers, and replace those regions with the return value 6189 * of the callback. For example, with input: 6190 * 6191 * aaa<MARKER>bbb 6192 * 6193 * This will call the callback function twice, with 'aaa' and 'bbb'. Those 6194 * two strings will be replaced with the value returned by the callback in 6195 * each case. 6196 * 6197 * @param string $s 6198 * @param callable $callback 6199 * 6200 * @return string 6201 */ 6202 public function markerSkipCallback( $s, $callback ) { 6203 $i = 0; 6204 $out = ''; 6205 while ( $i < strlen( $s ) ) { 6206 $markerStart = strpos( $s, $this->mUniqPrefix, $i ); 6207 if ( $markerStart === false ) { 6208 $out .= call_user_func( $callback, substr( $s, $i ) ); 6209 break; 6210 } else { 6211 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) ); 6212 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart ); 6213 if ( $markerEnd === false ) { 6214 $out .= substr( $s, $markerStart ); 6215 break; 6216 } else { 6217 $markerEnd += strlen( self::MARKER_SUFFIX ); 6218 $out .= substr( $s, $markerStart, $markerEnd - $markerStart ); 6219 $i = $markerEnd; 6220 } 6221 } 6222 } 6223 return $out; 6224 } 6225 6226 /** 6227 * Remove any strip markers found in the given text. 6228 * 6229 * @param string $text Input string 6230 * @return string 6231 */ 6232 public function killMarkers( $text ) { 6233 return $this->mStripState->killMarkers( $text ); 6234 } 6235 6236 /** 6237 * Save the parser state required to convert the given half-parsed text to 6238 * HTML. "Half-parsed" in this context means the output of 6239 * recursiveTagParse() or internalParse(). This output has strip markers 6240 * from replaceVariables (extensionSubstitution() etc.), and link 6241 * placeholders from replaceLinkHolders(). 6242 * 6243 * Returns an array which can be serialized and stored persistently. This 6244 * array can later be loaded into another parser instance with 6245 * unserializeHalfParsedText(). The text can then be safely incorporated into 6246 * the return value of a parser hook. 6247 * 6248 * @param string $text 6249 * 6250 * @return array 6251 */ 6252 public function serializeHalfParsedText( $text ) { 6253 wfProfileIn( __METHOD__ ); 6254 $data = array( 6255 'text' => $text, 6256 'version' => self::HALF_PARSED_VERSION, 6257 'stripState' => $this->mStripState->getSubState( $text ), 6258 'linkHolders' => $this->mLinkHolders->getSubArray( $text ) 6259 ); 6260 wfProfileOut( __METHOD__ ); 6261 return $data; 6262 } 6263 6264 /** 6265 * Load the parser state given in the $data array, which is assumed to 6266 * have been generated by serializeHalfParsedText(). The text contents is 6267 * extracted from the array, and its markers are transformed into markers 6268 * appropriate for the current Parser instance. This transformed text is 6269 * returned, and can be safely included in the return value of a parser 6270 * hook. 6271 * 6272 * If the $data array has been stored persistently, the caller should first 6273 * check whether it is still valid, by calling isValidHalfParsedText(). 6274 * 6275 * @param array $data Serialized data 6276 * @throws MWException 6277 * @return string 6278 */ 6279 public function unserializeHalfParsedText( $data ) { 6280 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) { 6281 throw new MWException( __METHOD__ . ': invalid version' ); 6282 } 6283 6284 # First, extract the strip state. 6285 $texts = array( $data['text'] ); 6286 $texts = $this->mStripState->merge( $data['stripState'], $texts ); 6287 6288 # Now renumber links 6289 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts ); 6290 6291 # Should be good to go. 6292 return $texts[0]; 6293 } 6294 6295 /** 6296 * Returns true if the given array, presumed to be generated by 6297 * serializeHalfParsedText(), is compatible with the current version of the 6298 * parser. 6299 * 6300 * @param array $data 6301 * 6302 * @return bool 6303 */ 6304 public function isValidHalfParsedText( $data ) { 6305 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION; 6306 } 6307 6308 /** 6309 * Parsed a width param of imagelink like 300px or 200x300px 6310 * 6311 * @param string $value 6312 * 6313 * @return array 6314 * @since 1.20 6315 */ 6316 public function parseWidthParam( $value ) { 6317 $parsedWidthParam = array(); 6318 if ( $value === '' ) { 6319 return $parsedWidthParam; 6320 } 6321 $m = array(); 6322 # (bug 13500) In both cases (width/height and width only), 6323 # permit trailing "px" for backward compatibility. 6324 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) { 6325 $width = intval( $m[1] ); 6326 $height = intval( $m[2] ); 6327 $parsedWidthParam['width'] = $width; 6328 $parsedWidthParam['height'] = $height; 6329 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) { 6330 $width = intval( $value ); 6331 $parsedWidthParam['width'] = $width; 6332 } 6333 return $parsedWidthParam; 6334 } 6335 6336 /** 6337 * Lock the current instance of the parser. 6338 * 6339 * This is meant to stop someone from calling the parser 6340 * recursively and messing up all the strip state. 6341 * 6342 * @throws MWException If parser is in a parse 6343 * @return ScopedCallback The lock will be released once the return value goes out of scope. 6344 */ 6345 protected function lock() { 6346 if ( $this->mInParse ) { 6347 throw new MWException( "Parser state cleared while parsing. " 6348 . "Did you call Parser::parse recursively?" ); 6349 } 6350 $this->mInParse = true; 6351 6352 $that = $this; 6353 $recursiveCheck = new ScopedCallback( function() use ( $that ) { 6354 $that->mInParse = false; 6355 } ); 6356 6357 return $recursiveCheck; 6358 } 6359 6360 /** 6361 * Strip outer <p></p> tag from the HTML source of a single paragraph. 6362 * 6363 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag, 6364 * or if there is more than one <p/> tag in the input HTML. 6365 * 6366 * @param string $html 6367 * @return string 6368 * @since 1.24 6369 */ 6370 public static function stripOuterParagraph( $html ) { 6371 $m = array(); 6372 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) { 6373 if ( strpos( $m[1], '</p>' ) === false ) { 6374 $html = $m[1]; 6375 } 6376 } 6377 6378 return $html; 6379 } 6380 6381 /** 6382 * Return this parser if it is not doing anything, otherwise 6383 * get a fresh parser. You can use this method by doing 6384 * $myParser = $wgParser->getFreshParser(), or more simply 6385 * $wgParser->getFreshParser()->parse( ... ); 6386 * if you're unsure if $wgParser is safe to use. 6387 * 6388 * @since 1.24 6389 * @return Parser A parser object that is not parsing anything 6390 */ 6391 public function getFreshParser() { 6392 global $wgParserConf; 6393 if ( $this->mInParse ) { 6394 return new $wgParserConf['class']( $wgParserConf ); 6395 } else { 6396 return $this; 6397 } 6398 } 6399 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Fri Nov 28 14:03:12 2014 | Cross-referenced by PHPXref 0.7.1 |