MediaWiki
REL1_19
|
00001 <?php 00050 class Parser { 00056 const VERSION = '1.6.4'; 00057 00062 const HALF_PARSED_VERSION = 2; 00063 00064 # Flags for Parser::setFunctionHook 00065 # Also available as global constants from Defines.php 00066 const SFH_NO_HASH = 1; 00067 const SFH_OBJECT_ARGS = 2; 00068 00069 # Constants needed for external link processing 00070 # Everything except bracket, space, or control characters 00071 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20 00072 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052 00073 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]'; 00074 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+) 00075 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu'; 00076 00077 # State constants for the definition list colon extraction 00078 const COLON_STATE_TEXT = 0; 00079 const COLON_STATE_TAG = 1; 00080 const COLON_STATE_TAGSTART = 2; 00081 const COLON_STATE_CLOSETAG = 3; 00082 const COLON_STATE_TAGSLASH = 4; 00083 const COLON_STATE_COMMENT = 5; 00084 const COLON_STATE_COMMENTDASH = 6; 00085 const COLON_STATE_COMMENTDASHDASH = 7; 00086 00087 # Flags for preprocessToDom 00088 const PTD_FOR_INCLUSION = 1; 00089 00090 # Allowed values for $this->mOutputType 00091 # Parameter to startExternalParse(). 00092 const OT_HTML = 1; # like parse() 00093 const OT_WIKI = 2; # like preSaveTransform() 00094 const OT_PREPROCESS = 3; # like preprocess() 00095 const OT_MSG = 3; 00096 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged. 00097 00098 # Marker Suffix needs to be accessible staticly. 00099 const MARKER_SUFFIX = "-QINU\x7f"; 00100 00101 # Persistent: 00102 var $mTagHooks = array(); 00103 var $mTransparentTagHooks = array(); 00104 var $mFunctionHooks = array(); 00105 var $mFunctionSynonyms = array( 0 => array(), 1 => array() ); 00106 var $mFunctionTagHooks = array(); 00107 var $mStripList = array(); 00108 var $mDefaultStripList = array(); 00109 var $mVarCache = array(); 00110 var $mImageParams = array(); 00111 var $mImageParamsMagicArray = array(); 00112 var $mMarkerIndex = 0; 00113 var $mFirstCall = true; 00114 00115 # Initialised by initialiseVariables() 00116 00120 var $mVariables; 00121 00125 var $mSubstWords; 00126 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor 00127 00128 # Cleared with clearState(): 00129 00132 var $mOutput; 00133 var $mAutonumber, $mDTopen; 00134 00138 var $mStripState; 00139 00140 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre; 00144 var $mLinkHolders; 00145 00146 var $mLinkID; 00147 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort; 00148 var $mTplExpandCache; # empty-frame expansion cache 00149 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores; 00150 var $mExpensiveFunctionCount; # number of expensive parser function calls 00151 var $mShowToc, $mForceTocPosition; 00152 00156 var $mUser; # User object; only used when doing pre-save transform 00157 00158 # Temporary 00159 # These are variables reset at least once per parse regardless of $clearState 00160 00164 var $mOptions; 00165 00169 var $mTitle; # Title context, used for self-link rendering and similar things 00170 var $mOutputType; # Output type, one of the OT_xxx constants 00171 var $ot; # Shortcut alias, see setOutputType() 00172 var $mRevisionObject; # The revision object of the specified revision ID 00173 var $mRevisionId; # ID to display in {{REVISIONID}} tags 00174 var $mRevisionTimestamp; # The timestamp of the specified revision ID 00175 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag 00176 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp 00177 00181 var $mUniqPrefix; 00182 00188 public function __construct( $conf = array() ) { 00189 $this->mConf = $conf; 00190 $this->mUrlProtocols = wfUrlProtocols(); 00191 $this->mExtLinkBracketedRegex = '/\[((' . wfUrlProtocols() . ')'. 00192 self::EXT_LINK_URL_CLASS.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su'; 00193 if ( isset( $conf['preprocessorClass'] ) ) { 00194 $this->mPreprocessorClass = $conf['preprocessorClass']; 00195 } elseif ( defined( 'MW_COMPILED' ) ) { 00196 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode 00197 $this->mPreprocessorClass = 'Preprocessor_Hash'; 00198 } elseif ( extension_loaded( 'domxml' ) ) { 00199 # PECL extension that conflicts with the core DOM extension (bug 13770) 00200 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" ); 00201 $this->mPreprocessorClass = 'Preprocessor_Hash'; 00202 } elseif ( extension_loaded( 'dom' ) ) { 00203 $this->mPreprocessorClass = 'Preprocessor_DOM'; 00204 } else { 00205 $this->mPreprocessorClass = 'Preprocessor_Hash'; 00206 } 00207 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" ); 00208 } 00209 00213 function __destruct() { 00214 if ( isset( $this->mLinkHolders ) ) { 00215 unset( $this->mLinkHolders ); 00216 } 00217 foreach ( $this as $name => $value ) { 00218 unset( $this->$name ); 00219 } 00220 } 00221 00225 function firstCallInit() { 00226 if ( !$this->mFirstCall ) { 00227 return; 00228 } 00229 $this->mFirstCall = false; 00230 00231 wfProfileIn( __METHOD__ ); 00232 00233 CoreParserFunctions::register( $this ); 00234 CoreTagHooks::register( $this ); 00235 $this->initialiseVariables(); 00236 00237 wfRunHooks( 'ParserFirstCallInit', array( &$this ) ); 00238 wfProfileOut( __METHOD__ ); 00239 } 00240 00246 function clearState() { 00247 wfProfileIn( __METHOD__ ); 00248 if ( $this->mFirstCall ) { 00249 $this->firstCallInit(); 00250 } 00251 $this->mOutput = new ParserOutput; 00252 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) ); 00253 $this->mAutonumber = 0; 00254 $this->mLastSection = ''; 00255 $this->mDTopen = false; 00256 $this->mIncludeCount = array(); 00257 $this->mArgStack = false; 00258 $this->mInPre = false; 00259 $this->mLinkHolders = new LinkHolderArray( $this ); 00260 $this->mLinkID = 0; 00261 $this->mRevisionObject = $this->mRevisionTimestamp = 00262 $this->mRevisionId = $this->mRevisionUser = null; 00263 $this->mVarCache = array(); 00264 $this->mUser = null; 00265 00276 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString(); 00277 # Changed to \x7f to allow XML double-parsing -- TS 00278 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString(); 00279 $this->mStripState = new StripState( $this->mUniqPrefix ); 00280 00281 00282 # Clear these on every parse, bug 4549 00283 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array(); 00284 00285 $this->mShowToc = true; 00286 $this->mForceTocPosition = false; 00287 $this->mIncludeSizes = array( 00288 'post-expand' => 0, 00289 'arg' => 0, 00290 ); 00291 $this->mPPNodeCount = 0; 00292 $this->mDefaultSort = false; 00293 $this->mHeadings = array(); 00294 $this->mDoubleUnderscores = array(); 00295 $this->mExpensiveFunctionCount = 0; 00296 00297 # Fix cloning 00298 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) { 00299 $this->mPreprocessor = null; 00300 } 00301 00302 wfRunHooks( 'ParserClearState', array( &$this ) ); 00303 wfProfileOut( __METHOD__ ); 00304 } 00305 00318 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) { 00324 global $wgUseTidy, $wgAlwaysUseTidy, $wgDisableLangConversion, $wgDisableTitleConversion; 00325 $fname = __METHOD__.'-' . wfGetCaller(); 00326 wfProfileIn( __METHOD__ ); 00327 wfProfileIn( $fname ); 00328 00329 $this->startParse( $title, $options, self::OT_HTML, $clearState ); 00330 00331 $oldRevisionId = $this->mRevisionId; 00332 $oldRevisionObject = $this->mRevisionObject; 00333 $oldRevisionTimestamp = $this->mRevisionTimestamp; 00334 $oldRevisionUser = $this->mRevisionUser; 00335 if ( $revid !== null ) { 00336 $this->mRevisionId = $revid; 00337 $this->mRevisionObject = null; 00338 $this->mRevisionTimestamp = null; 00339 $this->mRevisionUser = null; 00340 } 00341 00342 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 00343 # No more strip! 00344 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 00345 $text = $this->internalParse( $text ); 00346 00347 $text = $this->mStripState->unstripGeneral( $text ); 00348 00349 # Clean up special characters, only run once, next-to-last before doBlockLevels 00350 $fixtags = array( 00351 # french spaces, last one Guillemet-left 00352 # only if there is something before the space 00353 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ', 00354 # french spaces, Guillemet-right 00355 '/(\\302\\253) /' => '\\1 ', 00356 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874. 00357 ); 00358 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text ); 00359 00360 $text = $this->doBlockLevels( $text, $linestart ); 00361 00362 $this->replaceLinkHolders( $text ); 00363 00371 if ( !( $wgDisableLangConversion 00372 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) 00373 || $this->mTitle->isConversionTable() ) ) 00374 { 00375 # Run convert unconditionally in 1.18-compatible mode 00376 global $wgBug34832TransitionalRollback; 00377 if ( $wgBug34832TransitionalRollback || !$this->mOptions->getInterfaceMessage() ) { 00378 # The position of the convert() call should not be changed. it 00379 # assumes that the links are all replaced and the only thing left 00380 # is the <nowiki> mark. 00381 $text = $this->getConverterLanguage()->convert( $text ); 00382 } 00383 } 00384 00392 if ( !( $wgDisableLangConversion 00393 || $wgDisableTitleConversion 00394 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) 00395 || isset( $this->mDoubleUnderscores['notitleconvert'] ) 00396 || $this->mOutput->getDisplayTitle() !== false ) ) 00397 { 00398 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle(); 00399 if ( $convruletitle ) { 00400 $this->mOutput->setTitleText( $convruletitle ); 00401 } else { 00402 $titleText = $this->getConverterLanguage()->convertTitle( $title ); 00403 $this->mOutput->setTitleText( $titleText ); 00404 } 00405 } 00406 00407 $text = $this->mStripState->unstripNoWiki( $text ); 00408 00409 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) ); 00410 00411 $text = $this->replaceTransparentTags( $text ); 00412 $text = $this->mStripState->unstripGeneral( $text ); 00413 00414 $text = Sanitizer::normalizeCharReferences( $text ); 00415 00416 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) { 00417 $text = MWTidy::tidy( $text ); 00418 } else { 00419 # attempt to sanitize at least some nesting problems 00420 # (bug #2702 and quite a few others) 00421 $tidyregs = array( 00422 # ''Something [http://www.cool.com cool''] --> 00423 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a> 00424 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' => 00425 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9', 00426 # fix up an anchor inside another anchor, only 00427 # at least for a single single nested link (bug 3695) 00428 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' => 00429 '\\1\\2</a>\\3</a>\\1\\4</a>', 00430 # fix div inside inline elements- doBlockLevels won't wrap a line which 00431 # contains a div, so fix it up here; replace 00432 # div with escaped text 00433 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' => 00434 '\\1\\3<div\\5>\\6</div>\\8\\9', 00435 # remove empty italic or bold tag pairs, some 00436 # introduced by rules above 00437 '/<([bi])><\/\\1>/' => '', 00438 ); 00439 00440 $text = preg_replace( 00441 array_keys( $tidyregs ), 00442 array_values( $tidyregs ), 00443 $text ); 00444 } 00445 global $wgExpensiveParserFunctionLimit; 00446 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) { 00447 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit ); 00448 } 00449 00450 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) ); 00451 00452 # Information on include size limits, for the benefit of users who try to skirt them 00453 if ( $this->mOptions->getEnableLimitReport() ) { 00454 $max = $this->mOptions->getMaxIncludeSize(); 00455 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n"; 00456 $limitReport = 00457 "NewPP limit report\n" . 00458 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" . 00459 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" . 00460 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n". 00461 $PFreport; 00462 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) ); 00463 00464 // Sanitize for comment. Note '‐' in the replacement is U+2010, 00465 // which looks much like the problematic '-'. 00466 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport ); 00467 00468 $text .= "\n<!-- \n$limitReport-->\n"; 00469 } 00470 $this->mOutput->setText( $text ); 00471 00472 $this->mRevisionId = $oldRevisionId; 00473 $this->mRevisionObject = $oldRevisionObject; 00474 $this->mRevisionTimestamp = $oldRevisionTimestamp; 00475 $this->mRevisionUser = $oldRevisionUser; 00476 wfProfileOut( $fname ); 00477 wfProfileOut( __METHOD__ ); 00478 00479 return $this->mOutput; 00480 } 00481 00493 function recursiveTagParse( $text, $frame=false ) { 00494 wfProfileIn( __METHOD__ ); 00495 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 00496 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 00497 $text = $this->internalParse( $text, false, $frame ); 00498 wfProfileOut( __METHOD__ ); 00499 return $text; 00500 } 00501 00506 function preprocess( $text, Title $title, ParserOptions $options, $revid = null ) { 00507 wfProfileIn( __METHOD__ ); 00508 $this->startParse( $title, $options, self::OT_PREPROCESS, true ); 00509 if ( $revid !== null ) { 00510 $this->mRevisionId = $revid; 00511 } 00512 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 00513 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 00514 $text = $this->replaceVariables( $text ); 00515 $text = $this->mStripState->unstripBoth( $text ); 00516 wfProfileOut( __METHOD__ ); 00517 return $text; 00518 } 00519 00529 public function recursivePreprocess( $text, $frame = false ) { 00530 wfProfileIn( __METHOD__ ); 00531 $text = $this->replaceVariables( $text, $frame ); 00532 $text = $this->mStripState->unstripBoth( $text ); 00533 wfProfileOut( __METHOD__ ); 00534 return $text; 00535 } 00536 00548 public function getPreloadText( $text, Title $title, ParserOptions $options ) { 00549 # Parser (re)initialisation 00550 $this->startParse( $title, $options, self::OT_PLAIN, true ); 00551 00552 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES; 00553 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 00554 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags ); 00555 $text = $this->mStripState->unstripBoth( $text ); 00556 return $text; 00557 } 00558 00564 static public function getRandomString() { 00565 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) ); 00566 } 00567 00574 function setUser( $user ) { 00575 $this->mUser = $user; 00576 } 00577 00583 public function uniqPrefix() { 00584 if ( !isset( $this->mUniqPrefix ) ) { 00585 # @todo FIXME: This is probably *horribly wrong* 00586 # LanguageConverter seems to want $wgParser's uniqPrefix, however 00587 # if this is called for a parser cache hit, the parser may not 00588 # have ever been initialized in the first place. 00589 # Not really sure what the heck is supposed to be going on here. 00590 return ''; 00591 # throw new MWException( "Accessing uninitialized mUniqPrefix" ); 00592 } 00593 return $this->mUniqPrefix; 00594 } 00595 00601 function setTitle( $t ) { 00602 if ( !$t || $t instanceof FakeTitle ) { 00603 $t = Title::newFromText( 'NO TITLE' ); 00604 } 00605 00606 if ( strval( $t->getFragment() ) !== '' ) { 00607 # Strip the fragment to avoid various odd effects 00608 $this->mTitle = clone $t; 00609 $this->mTitle->setFragment( '' ); 00610 } else { 00611 $this->mTitle = $t; 00612 } 00613 } 00614 00620 function getTitle() { 00621 return $this->mTitle; 00622 } 00623 00630 function Title( $x = null ) { 00631 return wfSetVar( $this->mTitle, $x ); 00632 } 00633 00639 function setOutputType( $ot ) { 00640 $this->mOutputType = $ot; 00641 # Shortcut alias 00642 $this->ot = array( 00643 'html' => $ot == self::OT_HTML, 00644 'wiki' => $ot == self::OT_WIKI, 00645 'pre' => $ot == self::OT_PREPROCESS, 00646 'plain' => $ot == self::OT_PLAIN, 00647 ); 00648 } 00649 00656 function OutputType( $x = null ) { 00657 return wfSetVar( $this->mOutputType, $x ); 00658 } 00659 00665 function getOutput() { 00666 return $this->mOutput; 00667 } 00668 00674 function getOptions() { 00675 return $this->mOptions; 00676 } 00677 00684 function Options( $x = null ) { 00685 return wfSetVar( $this->mOptions, $x ); 00686 } 00687 00691 function nextLinkID() { 00692 return $this->mLinkID++; 00693 } 00694 00698 function setLinkID( $id ) { 00699 $this->mLinkID = $id; 00700 } 00701 00706 function getFunctionLang() { 00707 return $this->getTargetLanguage(); 00708 } 00709 00714 function getTargetLanguage() { 00715 $target = $this->mOptions->getTargetLanguage(); 00716 if ( $target !== null ) { 00717 return $target; 00718 } elseif( $this->mOptions->getInterfaceMessage() ) { 00719 return $this->mOptions->getUserLangObj(); 00720 } elseif( is_null( $this->mTitle ) ) { 00721 throw new MWException( __METHOD__.': $this->mTitle is null' ); 00722 } 00723 return $this->mTitle->getPageLanguage(); 00724 } 00725 00729 function getConverterLanguage() { 00730 global $wgBug34832TransitionalRollback, $wgContLang; 00731 if ( $wgBug34832TransitionalRollback ) { 00732 return $wgContLang; 00733 } else { 00734 return $this->getTargetLanguage(); 00735 } 00736 } 00737 00744 function getUser() { 00745 if ( !is_null( $this->mUser ) ) { 00746 return $this->mUser; 00747 } 00748 return $this->mOptions->getUser(); 00749 } 00750 00756 function getPreprocessor() { 00757 if ( !isset( $this->mPreprocessor ) ) { 00758 $class = $this->mPreprocessorClass; 00759 $this->mPreprocessor = new $class( $this ); 00760 } 00761 return $this->mPreprocessor; 00762 } 00763 00781 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) { 00782 static $n = 1; 00783 $stripped = ''; 00784 $matches = array(); 00785 00786 $taglist = implode( '|', $elements ); 00787 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i"; 00788 00789 while ( $text != '' ) { 00790 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE ); 00791 $stripped .= $p[0]; 00792 if ( count( $p ) < 5 ) { 00793 break; 00794 } 00795 if ( count( $p ) > 5 ) { 00796 # comment 00797 $element = $p[4]; 00798 $attributes = ''; 00799 $close = ''; 00800 $inside = $p[5]; 00801 } else { 00802 # tag 00803 $element = $p[1]; 00804 $attributes = $p[2]; 00805 $close = $p[3]; 00806 $inside = $p[4]; 00807 } 00808 00809 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX; 00810 $stripped .= $marker; 00811 00812 if ( $close === '/>' ) { 00813 # Empty element tag, <tag /> 00814 $content = null; 00815 $text = $inside; 00816 $tail = null; 00817 } else { 00818 if ( $element === '!--' ) { 00819 $end = '/(-->)/'; 00820 } else { 00821 $end = "/(<\\/$element\\s*>)/i"; 00822 } 00823 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE ); 00824 $content = $q[0]; 00825 if ( count( $q ) < 3 ) { 00826 # No end tag -- let it run out to the end of the text. 00827 $tail = ''; 00828 $text = ''; 00829 } else { 00830 $tail = $q[1]; 00831 $text = $q[2]; 00832 } 00833 } 00834 00835 $matches[$marker] = array( $element, 00836 $content, 00837 Sanitizer::decodeTagAttributes( $attributes ), 00838 "<$element$attributes$close$content$tail" ); 00839 } 00840 return $stripped; 00841 } 00842 00848 function getStripList() { 00849 return $this->mStripList; 00850 } 00851 00861 function insertStripItem( $text ) { 00862 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX; 00863 $this->mMarkerIndex++; 00864 $this->mStripState->addGeneral( $rnd, $text ); 00865 return $rnd; 00866 } 00867 00873 function doTableStuff( $text ) { 00874 wfProfileIn( __METHOD__ ); 00875 00876 $lines = StringUtils::explode( "\n", $text ); 00877 $out = ''; 00878 $td_history = array(); # Is currently a td tag open? 00879 $last_tag_history = array(); # Save history of last lag activated (td, th or caption) 00880 $tr_history = array(); # Is currently a tr tag open? 00881 $tr_attributes = array(); # history of tr attributes 00882 $has_opened_tr = array(); # Did this table open a <tr> element? 00883 $indent_level = 0; # indent level of the table 00884 00885 foreach ( $lines as $outLine ) { 00886 $line = trim( $outLine ); 00887 00888 if ( $line === '' ) { # empty line, go to next line 00889 $out .= $outLine."\n"; 00890 continue; 00891 } 00892 00893 $first_character = $line[0]; 00894 $matches = array(); 00895 00896 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) { 00897 # First check if we are starting a new table 00898 $indent_level = strlen( $matches[1] ); 00899 00900 $attributes = $this->mStripState->unstripBoth( $matches[2] ); 00901 $attributes = Sanitizer::fixTagAttributes( $attributes , 'table' ); 00902 00903 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>"; 00904 array_push( $td_history , false ); 00905 array_push( $last_tag_history , '' ); 00906 array_push( $tr_history , false ); 00907 array_push( $tr_attributes , '' ); 00908 array_push( $has_opened_tr , false ); 00909 } elseif ( count( $td_history ) == 0 ) { 00910 # Don't do any of the following 00911 $out .= $outLine."\n"; 00912 continue; 00913 } elseif ( substr( $line , 0 , 2 ) === '|}' ) { 00914 # We are ending a table 00915 $line = '</table>' . substr( $line , 2 ); 00916 $last_tag = array_pop( $last_tag_history ); 00917 00918 if ( !array_pop( $has_opened_tr ) ) { 00919 $line = "<tr><td></td></tr>{$line}"; 00920 } 00921 00922 if ( array_pop( $tr_history ) ) { 00923 $line = "</tr>{$line}"; 00924 } 00925 00926 if ( array_pop( $td_history ) ) { 00927 $line = "</{$last_tag}>{$line}"; 00928 } 00929 array_pop( $tr_attributes ); 00930 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level ); 00931 } elseif ( substr( $line , 0 , 2 ) === '|-' ) { 00932 # Now we have a table row 00933 $line = preg_replace( '#^\|-+#', '', $line ); 00934 00935 # Whats after the tag is now only attributes 00936 $attributes = $this->mStripState->unstripBoth( $line ); 00937 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' ); 00938 array_pop( $tr_attributes ); 00939 array_push( $tr_attributes, $attributes ); 00940 00941 $line = ''; 00942 $last_tag = array_pop( $last_tag_history ); 00943 array_pop( $has_opened_tr ); 00944 array_push( $has_opened_tr , true ); 00945 00946 if ( array_pop( $tr_history ) ) { 00947 $line = '</tr>'; 00948 } 00949 00950 if ( array_pop( $td_history ) ) { 00951 $line = "</{$last_tag}>{$line}"; 00952 } 00953 00954 $outLine = $line; 00955 array_push( $tr_history , false ); 00956 array_push( $td_history , false ); 00957 array_push( $last_tag_history , '' ); 00958 } elseif ( $first_character === '|' || $first_character === '!' || substr( $line , 0 , 2 ) === '|+' ) { 00959 # This might be cell elements, td, th or captions 00960 if ( substr( $line , 0 , 2 ) === '|+' ) { 00961 $first_character = '+'; 00962 $line = substr( $line , 1 ); 00963 } 00964 00965 $line = substr( $line , 1 ); 00966 00967 if ( $first_character === '!' ) { 00968 $line = str_replace( '!!' , '||' , $line ); 00969 } 00970 00971 # Split up multiple cells on the same line. 00972 # FIXME : This can result in improper nesting of tags processed 00973 # by earlier parser steps, but should avoid splitting up eg 00974 # attribute values containing literal "||". 00975 $cells = StringUtils::explodeMarkup( '||' , $line ); 00976 00977 $outLine = ''; 00978 00979 # Loop through each table cell 00980 foreach ( $cells as $cell ) { 00981 $previous = ''; 00982 if ( $first_character !== '+' ) { 00983 $tr_after = array_pop( $tr_attributes ); 00984 if ( !array_pop( $tr_history ) ) { 00985 $previous = "<tr{$tr_after}>\n"; 00986 } 00987 array_push( $tr_history , true ); 00988 array_push( $tr_attributes , '' ); 00989 array_pop( $has_opened_tr ); 00990 array_push( $has_opened_tr , true ); 00991 } 00992 00993 $last_tag = array_pop( $last_tag_history ); 00994 00995 if ( array_pop( $td_history ) ) { 00996 $previous = "</{$last_tag}>\n{$previous}"; 00997 } 00998 00999 if ( $first_character === '|' ) { 01000 $last_tag = 'td'; 01001 } elseif ( $first_character === '!' ) { 01002 $last_tag = 'th'; 01003 } elseif ( $first_character === '+' ) { 01004 $last_tag = 'caption'; 01005 } else { 01006 $last_tag = ''; 01007 } 01008 01009 array_push( $last_tag_history , $last_tag ); 01010 01011 # A cell could contain both parameters and data 01012 $cell_data = explode( '|' , $cell , 2 ); 01013 01014 # Bug 553: Note that a '|' inside an invalid link should not 01015 # be mistaken as delimiting cell parameters 01016 if ( strpos( $cell_data[0], '[[' ) !== false ) { 01017 $cell = "{$previous}<{$last_tag}>{$cell}"; 01018 } elseif ( count( $cell_data ) == 1 ) { 01019 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}"; 01020 } else { 01021 $attributes = $this->mStripState->unstripBoth( $cell_data[0] ); 01022 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag ); 01023 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}"; 01024 } 01025 01026 $outLine .= $cell; 01027 array_push( $td_history , true ); 01028 } 01029 } 01030 $out .= $outLine . "\n"; 01031 } 01032 01033 # Closing open td, tr && table 01034 while ( count( $td_history ) > 0 ) { 01035 if ( array_pop( $td_history ) ) { 01036 $out .= "</td>\n"; 01037 } 01038 if ( array_pop( $tr_history ) ) { 01039 $out .= "</tr>\n"; 01040 } 01041 if ( !array_pop( $has_opened_tr ) ) { 01042 $out .= "<tr><td></td></tr>\n" ; 01043 } 01044 01045 $out .= "</table>\n"; 01046 } 01047 01048 # Remove trailing line-ending (b/c) 01049 if ( substr( $out, -1 ) === "\n" ) { 01050 $out = substr( $out, 0, -1 ); 01051 } 01052 01053 # special case: don't return empty table 01054 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) { 01055 $out = ''; 01056 } 01057 01058 wfProfileOut( __METHOD__ ); 01059 01060 return $out; 01061 } 01062 01075 function internalParse( $text, $isMain = true, $frame = false ) { 01076 wfProfileIn( __METHOD__ ); 01077 01078 $origText = $text; 01079 01080 # Hook to suspend the parser in this state 01081 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) { 01082 wfProfileOut( __METHOD__ ); 01083 return $text ; 01084 } 01085 01086 # if $frame is provided, then use $frame for replacing any variables 01087 if ( $frame ) { 01088 # use frame depth to infer how include/noinclude tags should be handled 01089 # depth=0 means this is the top-level document; otherwise it's an included document 01090 if ( !$frame->depth ) { 01091 $flag = 0; 01092 } else { 01093 $flag = Parser::PTD_FOR_INCLUSION; 01094 } 01095 $dom = $this->preprocessToDom( $text, $flag ); 01096 $text = $frame->expand( $dom ); 01097 } else { 01098 # if $frame is not provided, then use old-style replaceVariables 01099 $text = $this->replaceVariables( $text ); 01100 } 01101 01102 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) ); 01103 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) ); 01104 01105 # Tables need to come after variable replacement for things to work 01106 # properly; putting them before other transformations should keep 01107 # exciting things like link expansions from showing up in surprising 01108 # places. 01109 $text = $this->doTableStuff( $text ); 01110 01111 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text ); 01112 01113 $text = $this->doDoubleUnderscore( $text ); 01114 01115 $text = $this->doHeadings( $text ); 01116 if ( $this->mOptions->getUseDynamicDates() ) { 01117 $df = DateFormatter::getInstance(); 01118 $text = $df->reformat( $this->mOptions->getDateFormat(), $text ); 01119 } 01120 $text = $this->replaceInternalLinks( $text ); 01121 $text = $this->doAllQuotes( $text ); 01122 $text = $this->replaceExternalLinks( $text ); 01123 01124 # replaceInternalLinks may sometimes leave behind 01125 # absolute URLs, which have to be masked to hide them from replaceExternalLinks 01126 $text = str_replace( $this->mUniqPrefix.'NOPARSE', '', $text ); 01127 01128 $text = $this->doMagicLinks( $text ); 01129 $text = $this->formatHeadings( $text, $origText, $isMain ); 01130 01131 wfProfileOut( __METHOD__ ); 01132 return $text; 01133 } 01134 01146 function doMagicLinks( $text ) { 01147 wfProfileIn( __METHOD__ ); 01148 $prots = wfUrlProtocolsWithoutProtRel(); 01149 $urlChar = self::EXT_LINK_URL_CLASS; 01150 $text = preg_replace_callback( 01151 '!(?: # Start cases 01152 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text 01153 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . " 01154 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . ' 01155 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number 01156 ISBN\s+(\b # m[5]: ISBN, capture number 01157 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix 01158 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters 01159 [0-9Xx] # check digit 01160 \b) 01161 )!xu', array( &$this, 'magicLinkCallback' ), $text ); 01162 wfProfileOut( __METHOD__ ); 01163 return $text; 01164 } 01165 01171 function magicLinkCallback( $m ) { 01172 if ( isset( $m[1] ) && $m[1] !== '' ) { 01173 # Skip anchor 01174 return $m[0]; 01175 } elseif ( isset( $m[2] ) && $m[2] !== '' ) { 01176 # Skip HTML element 01177 return $m[0]; 01178 } elseif ( isset( $m[3] ) && $m[3] !== '' ) { 01179 # Free external link 01180 return $this->makeFreeExternalLink( $m[0] ); 01181 } elseif ( isset( $m[4] ) && $m[4] !== '' ) { 01182 # RFC or PMID 01183 if ( substr( $m[0], 0, 3 ) === 'RFC' ) { 01184 $keyword = 'RFC'; 01185 $urlmsg = 'rfcurl'; 01186 $CssClass = 'mw-magiclink-rfc'; 01187 $id = $m[4]; 01188 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) { 01189 $keyword = 'PMID'; 01190 $urlmsg = 'pubmedurl'; 01191 $CssClass = 'mw-magiclink-pmid'; 01192 $id = $m[4]; 01193 } else { 01194 throw new MWException( __METHOD__.': unrecognised match type "' . 01195 substr( $m[0], 0, 20 ) . '"' ); 01196 } 01197 $url = wfMsgForContent( $urlmsg, $id ); 01198 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass ); 01199 } elseif ( isset( $m[5] ) && $m[5] !== '' ) { 01200 # ISBN 01201 $isbn = $m[5]; 01202 $num = strtr( $isbn, array( 01203 '-' => '', 01204 ' ' => '', 01205 'x' => 'X', 01206 )); 01207 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num ); 01208 return'<a href="' . 01209 htmlspecialchars( $titleObj->getLocalUrl() ) . 01210 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>"; 01211 } else { 01212 return $m[0]; 01213 } 01214 } 01215 01224 function makeFreeExternalLink( $url ) { 01225 wfProfileIn( __METHOD__ ); 01226 01227 $trail = ''; 01228 01229 # The characters '<' and '>' (which were escaped by 01230 # removeHTMLtags()) should not be included in 01231 # URLs, per RFC 2396. 01232 $m2 = array(); 01233 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) { 01234 $trail = substr( $url, $m2[0][1] ) . $trail; 01235 $url = substr( $url, 0, $m2[0][1] ); 01236 } 01237 01238 # Move trailing punctuation to $trail 01239 $sep = ',;\.:!?'; 01240 # If there is no left bracket, then consider right brackets fair game too 01241 if ( strpos( $url, '(' ) === false ) { 01242 $sep .= ')'; 01243 } 01244 01245 $numSepChars = strspn( strrev( $url ), $sep ); 01246 if ( $numSepChars ) { 01247 $trail = substr( $url, -$numSepChars ) . $trail; 01248 $url = substr( $url, 0, -$numSepChars ); 01249 } 01250 01251 $url = Sanitizer::cleanUrl( $url ); 01252 01253 # Is this an external image? 01254 $text = $this->maybeMakeExternalImage( $url ); 01255 if ( $text === false ) { 01256 # Not an image, make a link 01257 $text = Linker::makeExternalLink( $url, 01258 $this->getConverterLanguage()->markNoConversion($url), true, 'free', 01259 $this->getExternalLinkAttribs( $url ) ); 01260 # Register it in the output object... 01261 # Replace unnecessary URL escape codes with their equivalent characters 01262 $pasteurized = self::replaceUnusualEscapes( $url ); 01263 $this->mOutput->addExternalLink( $pasteurized ); 01264 } 01265 wfProfileOut( __METHOD__ ); 01266 return $text . $trail; 01267 } 01268 01269 01279 function doHeadings( $text ) { 01280 wfProfileIn( __METHOD__ ); 01281 for ( $i = 6; $i >= 1; --$i ) { 01282 $h = str_repeat( '=', $i ); 01283 $text = preg_replace( "/^$h(.+)$h\\s*$/m", 01284 "<h$i>\\1</h$i>", $text ); 01285 } 01286 wfProfileOut( __METHOD__ ); 01287 return $text; 01288 } 01289 01298 function doAllQuotes( $text ) { 01299 wfProfileIn( __METHOD__ ); 01300 $outtext = ''; 01301 $lines = StringUtils::explode( "\n", $text ); 01302 foreach ( $lines as $line ) { 01303 $outtext .= $this->doQuotes( $line ) . "\n"; 01304 } 01305 $outtext = substr( $outtext, 0,-1 ); 01306 wfProfileOut( __METHOD__ ); 01307 return $outtext; 01308 } 01309 01317 public function doQuotes( $text ) { 01318 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE ); 01319 if ( count( $arr ) == 1 ) { 01320 return $text; 01321 } else { 01322 # First, do some preliminary work. This may shift some apostrophes from 01323 # being mark-up to being text. It also counts the number of occurrences 01324 # of bold and italics mark-ups. 01325 $numbold = 0; 01326 $numitalics = 0; 01327 for ( $i = 0; $i < count( $arr ); $i++ ) { 01328 if ( ( $i % 2 ) == 1 ) { 01329 # If there are ever four apostrophes, assume the first is supposed to 01330 # be text, and the remaining three constitute mark-up for bold text. 01331 if ( strlen( $arr[$i] ) == 4 ) { 01332 $arr[$i-1] .= "'"; 01333 $arr[$i] = "'''"; 01334 } elseif ( strlen( $arr[$i] ) > 5 ) { 01335 # If there are more than 5 apostrophes in a row, assume they're all 01336 # text except for the last 5. 01337 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 ); 01338 $arr[$i] = "'''''"; 01339 } 01340 # Count the number of occurrences of bold and italics mark-ups. 01341 # We are not counting sequences of five apostrophes. 01342 if ( strlen( $arr[$i] ) == 2 ) { 01343 $numitalics++; 01344 } elseif ( strlen( $arr[$i] ) == 3 ) { 01345 $numbold++; 01346 } elseif ( strlen( $arr[$i] ) == 5 ) { 01347 $numitalics++; 01348 $numbold++; 01349 } 01350 } 01351 } 01352 01353 # If there is an odd number of both bold and italics, it is likely 01354 # that one of the bold ones was meant to be an apostrophe followed 01355 # by italics. Which one we cannot know for certain, but it is more 01356 # likely to be one that has a single-letter word before it. 01357 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) { 01358 $i = 0; 01359 $firstsingleletterword = -1; 01360 $firstmultiletterword = -1; 01361 $firstspace = -1; 01362 foreach ( $arr as $r ) { 01363 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) { 01364 $x1 = substr( $arr[$i-1], -1 ); 01365 $x2 = substr( $arr[$i-1], -2, 1 ); 01366 if ( $x1 === ' ' ) { 01367 if ( $firstspace == -1 ) { 01368 $firstspace = $i; 01369 } 01370 } elseif ( $x2 === ' ') { 01371 if ( $firstsingleletterword == -1 ) { 01372 $firstsingleletterword = $i; 01373 } 01374 } else { 01375 if ( $firstmultiletterword == -1 ) { 01376 $firstmultiletterword = $i; 01377 } 01378 } 01379 } 01380 $i++; 01381 } 01382 01383 # If there is a single-letter word, use it! 01384 if ( $firstsingleletterword > -1 ) { 01385 $arr[$firstsingleletterword] = "''"; 01386 $arr[$firstsingleletterword-1] .= "'"; 01387 } elseif ( $firstmultiletterword > -1 ) { 01388 # If not, but there's a multi-letter word, use that one. 01389 $arr[$firstmultiletterword] = "''"; 01390 $arr[$firstmultiletterword-1] .= "'"; 01391 } elseif ( $firstspace > -1 ) { 01392 # ... otherwise use the first one that has neither. 01393 # (notice that it is possible for all three to be -1 if, for example, 01394 # there is only one pentuple-apostrophe in the line) 01395 $arr[$firstspace] = "''"; 01396 $arr[$firstspace-1] .= "'"; 01397 } 01398 } 01399 01400 # Now let's actually convert our apostrophic mush to HTML! 01401 $output = ''; 01402 $buffer = ''; 01403 $state = ''; 01404 $i = 0; 01405 foreach ( $arr as $r ) { 01406 if ( ( $i % 2 ) == 0 ) { 01407 if ( $state === 'both' ) { 01408 $buffer .= $r; 01409 } else { 01410 $output .= $r; 01411 } 01412 } else { 01413 if ( strlen( $r ) == 2 ) { 01414 if ( $state === 'i' ) { 01415 $output .= '</i>'; $state = ''; 01416 } elseif ( $state === 'bi' ) { 01417 $output .= '</i>'; $state = 'b'; 01418 } elseif ( $state === 'ib' ) { 01419 $output .= '</b></i><b>'; $state = 'b'; 01420 } elseif ( $state === 'both' ) { 01421 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; 01422 } else { # $state can be 'b' or '' 01423 $output .= '<i>'; $state .= 'i'; 01424 } 01425 } elseif ( strlen( $r ) == 3 ) { 01426 if ( $state === 'b' ) { 01427 $output .= '</b>'; $state = ''; 01428 } elseif ( $state === 'bi' ) { 01429 $output .= '</i></b><i>'; $state = 'i'; 01430 } elseif ( $state === 'ib' ) { 01431 $output .= '</b>'; $state = 'i'; 01432 } elseif ( $state === 'both' ) { 01433 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; 01434 } else { # $state can be 'i' or '' 01435 $output .= '<b>'; $state .= 'b'; 01436 } 01437 } elseif ( strlen( $r ) == 5 ) { 01438 if ( $state === 'b' ) { 01439 $output .= '</b><i>'; $state = 'i'; 01440 } elseif ( $state === 'i' ) { 01441 $output .= '</i><b>'; $state = 'b'; 01442 } elseif ( $state === 'bi' ) { 01443 $output .= '</i></b>'; $state = ''; 01444 } elseif ( $state === 'ib' ) { 01445 $output .= '</b></i>'; $state = ''; 01446 } elseif ( $state === 'both' ) { 01447 $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; 01448 } else { # ($state == '') 01449 $buffer = ''; $state = 'both'; 01450 } 01451 } 01452 } 01453 $i++; 01454 } 01455 # Now close all remaining tags. Notice that the order is important. 01456 if ( $state === 'b' || $state === 'ib' ) { 01457 $output .= '</b>'; 01458 } 01459 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) { 01460 $output .= '</i>'; 01461 } 01462 if ( $state === 'bi' ) { 01463 $output .= '</b>'; 01464 } 01465 # There might be lonely ''''', so make sure we have a buffer 01466 if ( $state === 'both' && $buffer ) { 01467 $output .= '<b><i>'.$buffer.'</i></b>'; 01468 } 01469 return $output; 01470 } 01471 } 01472 01485 function replaceExternalLinks( $text ) { 01486 wfProfileIn( __METHOD__ ); 01487 01488 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE ); 01489 if ( $bits === false ) { 01490 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" ); 01491 } 01492 $s = array_shift( $bits ); 01493 01494 $i = 0; 01495 while ( $i<count( $bits ) ) { 01496 $url = $bits[$i++]; 01497 $protocol = $bits[$i++]; 01498 $text = $bits[$i++]; 01499 $trail = $bits[$i++]; 01500 01501 # The characters '<' and '>' (which were escaped by 01502 # removeHTMLtags()) should not be included in 01503 # URLs, per RFC 2396. 01504 $m2 = array(); 01505 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) { 01506 $text = substr( $url, $m2[0][1] ) . ' ' . $text; 01507 $url = substr( $url, 0, $m2[0][1] ); 01508 } 01509 01510 # If the link text is an image URL, replace it with an <img> tag 01511 # This happened by accident in the original parser, but some people used it extensively 01512 $img = $this->maybeMakeExternalImage( $text ); 01513 if ( $img !== false ) { 01514 $text = $img; 01515 } 01516 01517 $dtrail = ''; 01518 01519 # Set linktype for CSS - if URL==text, link is essentially free 01520 $linktype = ( $text === $url ) ? 'free' : 'text'; 01521 01522 # No link text, e.g. [http://domain.tld/some.link] 01523 if ( $text == '' ) { 01524 # Autonumber 01525 $langObj = $this->getTargetLanguage(); 01526 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']'; 01527 $linktype = 'autonumber'; 01528 } else { 01529 # Have link text, e.g. [http://domain.tld/some.link text]s 01530 # Check for trail 01531 list( $dtrail, $trail ) = Linker::splitTrail( $trail ); 01532 } 01533 01534 $text = $this->getConverterLanguage()->markNoConversion( $text ); 01535 01536 $url = Sanitizer::cleanUrl( $url ); 01537 01538 # Use the encoded URL 01539 # This means that users can paste URLs directly into the text 01540 # Funny characters like ö aren't valid in URLs anyway 01541 # This was changed in August 2004 01542 $s .= Linker::makeExternalLink( $url, $text, false, $linktype, 01543 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail; 01544 01545 # Register link in the output object. 01546 # Replace unnecessary URL escape codes with the referenced character 01547 # This prevents spammers from hiding links from the filters 01548 $pasteurized = self::replaceUnusualEscapes( $url ); 01549 $this->mOutput->addExternalLink( $pasteurized ); 01550 } 01551 01552 wfProfileOut( __METHOD__ ); 01553 return $s; 01554 } 01555 01566 function getExternalLinkAttribs( $url = false ) { 01567 $attribs = array(); 01568 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions; 01569 $ns = $this->mTitle->getNamespace(); 01570 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) && 01571 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) ) 01572 { 01573 $attribs['rel'] = 'nofollow'; 01574 } 01575 if ( $this->mOptions->getExternalLinkTarget() ) { 01576 $attribs['target'] = $this->mOptions->getExternalLinkTarget(); 01577 } 01578 return $attribs; 01579 } 01580 01592 static function replaceUnusualEscapes( $url ) { 01593 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', 01594 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url ); 01595 } 01596 01605 private static function replaceUnusualEscapesCallback( $matches ) { 01606 $char = urldecode( $matches[0] ); 01607 $ord = ord( $char ); 01608 # Is it an unsafe or HTTP reserved character according to RFC 1738? 01609 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) { 01610 # No, shouldn't be escaped 01611 return $char; 01612 } else { 01613 # Yes, leave it escaped 01614 return $matches[0]; 01615 } 01616 } 01617 01627 function maybeMakeExternalImage( $url ) { 01628 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom(); 01629 $imagesexception = !empty( $imagesfrom ); 01630 $text = false; 01631 # $imagesfrom could be either a single string or an array of strings, parse out the latter 01632 if ( $imagesexception && is_array( $imagesfrom ) ) { 01633 $imagematch = false; 01634 foreach ( $imagesfrom as $match ) { 01635 if ( strpos( $url, $match ) === 0 ) { 01636 $imagematch = true; 01637 break; 01638 } 01639 } 01640 } elseif ( $imagesexception ) { 01641 $imagematch = ( strpos( $url, $imagesfrom ) === 0 ); 01642 } else { 01643 $imagematch = false; 01644 } 01645 if ( $this->mOptions->getAllowExternalImages() 01646 || ( $imagesexception && $imagematch ) ) { 01647 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) { 01648 # Image found 01649 $text = Linker::makeExternalImage( $url ); 01650 } 01651 } 01652 if ( !$text && $this->mOptions->getEnableImageWhitelist() 01653 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) { 01654 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) ); 01655 foreach ( $whitelist as $entry ) { 01656 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments 01657 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) { 01658 continue; 01659 } 01660 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) { 01661 # Image matches a whitelist entry 01662 $text = Linker::makeExternalImage( $url ); 01663 break; 01664 } 01665 } 01666 } 01667 return $text; 01668 } 01669 01679 function replaceInternalLinks( $s ) { 01680 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) ); 01681 return $s; 01682 } 01683 01690 function replaceInternalLinks2( &$s ) { 01691 wfProfileIn( __METHOD__ ); 01692 01693 wfProfileIn( __METHOD__.'-setup' ); 01694 static $tc = FALSE, $e1, $e1_img; 01695 # the % is needed to support urlencoded titles as well 01696 if ( !$tc ) { 01697 $tc = Title::legalChars() . '#%'; 01698 # Match a link having the form [[namespace:link|alternate]]trail 01699 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; 01700 # Match cases where there is no "]]", which might still be images 01701 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; 01702 } 01703 01704 $holders = new LinkHolderArray( $this ); 01705 01706 # split the entire text string on occurences of [[ 01707 $a = StringUtils::explode( '[[', ' ' . $s ); 01708 # get the first element (all text up to first [[), and remove the space we added 01709 $s = $a->current(); 01710 $a->next(); 01711 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void" 01712 $s = substr( $s, 1 ); 01713 01714 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension(); 01715 $e2 = null; 01716 if ( $useLinkPrefixExtension ) { 01717 # Match the end of a line for a word that's not followed by whitespace, 01718 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched 01719 $e2 = wfMsgForContent( 'linkprefix' ); 01720 } 01721 01722 if ( is_null( $this->mTitle ) ) { 01723 wfProfileOut( __METHOD__.'-setup' ); 01724 wfProfileOut( __METHOD__ ); 01725 throw new MWException( __METHOD__.": \$this->mTitle is null\n" ); 01726 } 01727 $nottalk = !$this->mTitle->isTalkPage(); 01728 01729 if ( $useLinkPrefixExtension ) { 01730 $m = array(); 01731 if ( preg_match( $e2, $s, $m ) ) { 01732 $first_prefix = $m[2]; 01733 } else { 01734 $first_prefix = false; 01735 } 01736 } else { 01737 $prefix = ''; 01738 } 01739 01740 if ( $this->getConverterLanguage()->hasVariants() ) { 01741 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants( 01742 $this->mTitle->getPrefixedText() ); 01743 } else { 01744 $selflink = array( $this->mTitle->getPrefixedText() ); 01745 } 01746 $useSubpages = $this->areSubpagesAllowed(); 01747 wfProfileOut( __METHOD__.'-setup' ); 01748 01749 # Loop for each link 01750 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) { 01751 # Check for excessive memory usage 01752 if ( $holders->isBig() ) { 01753 # Too big 01754 # Do the existence check, replace the link holders and clear the array 01755 $holders->replace( $s ); 01756 $holders->clear(); 01757 } 01758 01759 if ( $useLinkPrefixExtension ) { 01760 wfProfileIn( __METHOD__.'-prefixhandling' ); 01761 if ( preg_match( $e2, $s, $m ) ) { 01762 $prefix = $m[2]; 01763 $s = $m[1]; 01764 } else { 01765 $prefix=''; 01766 } 01767 # first link 01768 if ( $first_prefix ) { 01769 $prefix = $first_prefix; 01770 $first_prefix = false; 01771 } 01772 wfProfileOut( __METHOD__.'-prefixhandling' ); 01773 } 01774 01775 $might_be_img = false; 01776 01777 wfProfileIn( __METHOD__."-e1" ); 01778 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt 01779 $text = $m[2]; 01780 # If we get a ] at the beginning of $m[3] that means we have a link that's something like: 01781 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up, 01782 # the real problem is with the $e1 regex 01783 # See bug 1300. 01784 # 01785 # Still some problems for cases where the ] is meant to be outside punctuation, 01786 # and no image is in sight. See bug 2095. 01787 # 01788 if ( $text !== '' && 01789 substr( $m[3], 0, 1 ) === ']' && 01790 strpos( $text, '[' ) !== false 01791 ) 01792 { 01793 $text .= ']'; # so that replaceExternalLinks($text) works later 01794 $m[3] = substr( $m[3], 1 ); 01795 } 01796 # fix up urlencoded title texts 01797 if ( strpos( $m[1], '%' ) !== false ) { 01798 # Should anchors '#' also be rejected? 01799 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) ); 01800 } 01801 $trail = $m[3]; 01802 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption 01803 $might_be_img = true; 01804 $text = $m[2]; 01805 if ( strpos( $m[1], '%' ) !== false ) { 01806 $m[1] = rawurldecode( $m[1] ); 01807 } 01808 $trail = ""; 01809 } else { # Invalid form; output directly 01810 $s .= $prefix . '[[' . $line ; 01811 wfProfileOut( __METHOD__."-e1" ); 01812 continue; 01813 } 01814 wfProfileOut( __METHOD__."-e1" ); 01815 wfProfileIn( __METHOD__."-misc" ); 01816 01817 # Don't allow internal links to pages containing 01818 # PROTO: where PROTO is a valid URL protocol; these 01819 # should be external links. 01820 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $m[1] ) ) { 01821 $s .= $prefix . '[[' . $line ; 01822 wfProfileOut( __METHOD__."-misc" ); 01823 continue; 01824 } 01825 01826 # Make subpage if necessary 01827 if ( $useSubpages ) { 01828 $link = $this->maybeDoSubpageLink( $m[1], $text ); 01829 } else { 01830 $link = $m[1]; 01831 } 01832 01833 $noforce = ( substr( $m[1], 0, 1 ) !== ':' ); 01834 if ( !$noforce ) { 01835 # Strip off leading ':' 01836 $link = substr( $link, 1 ); 01837 } 01838 01839 wfProfileOut( __METHOD__."-misc" ); 01840 wfProfileIn( __METHOD__."-title" ); 01841 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) ); 01842 if ( $nt === null ) { 01843 $s .= $prefix . '[[' . $line; 01844 wfProfileOut( __METHOD__."-title" ); 01845 continue; 01846 } 01847 01848 $ns = $nt->getNamespace(); 01849 $iw = $nt->getInterWiki(); 01850 wfProfileOut( __METHOD__."-title" ); 01851 01852 if ( $might_be_img ) { # if this is actually an invalid link 01853 wfProfileIn( __METHOD__."-might_be_img" ); 01854 if ( $ns == NS_FILE && $noforce ) { # but might be an image 01855 $found = false; 01856 while ( true ) { 01857 # look at the next 'line' to see if we can close it there 01858 $a->next(); 01859 $next_line = $a->current(); 01860 if ( $next_line === false || $next_line === null ) { 01861 break; 01862 } 01863 $m = explode( ']]', $next_line, 3 ); 01864 if ( count( $m ) == 3 ) { 01865 # the first ]] closes the inner link, the second the image 01866 $found = true; 01867 $text .= "[[{$m[0]}]]{$m[1]}"; 01868 $trail = $m[2]; 01869 break; 01870 } elseif ( count( $m ) == 2 ) { 01871 # if there's exactly one ]] that's fine, we'll keep looking 01872 $text .= "[[{$m[0]}]]{$m[1]}"; 01873 } else { 01874 # if $next_line is invalid too, we need look no further 01875 $text .= '[[' . $next_line; 01876 break; 01877 } 01878 } 01879 if ( !$found ) { 01880 # we couldn't find the end of this imageLink, so output it raw 01881 # but don't ignore what might be perfectly normal links in the text we've examined 01882 $holders->merge( $this->replaceInternalLinks2( $text ) ); 01883 $s .= "{$prefix}[[$link|$text"; 01884 # note: no $trail, because without an end, there *is* no trail 01885 wfProfileOut( __METHOD__."-might_be_img" ); 01886 continue; 01887 } 01888 } else { # it's not an image, so output it raw 01889 $s .= "{$prefix}[[$link|$text"; 01890 # note: no $trail, because without an end, there *is* no trail 01891 wfProfileOut( __METHOD__."-might_be_img" ); 01892 continue; 01893 } 01894 wfProfileOut( __METHOD__."-might_be_img" ); 01895 } 01896 01897 $wasblank = ( $text == '' ); 01898 if ( $wasblank ) { 01899 $text = $link; 01900 } else { 01901 # Bug 4598 madness. Handle the quotes only if they come from the alternate part 01902 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a> 01903 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']] 01904 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a> 01905 $text = $this->doQuotes( $text ); 01906 } 01907 01908 # Link not escaped by : , create the various objects 01909 if ( $noforce ) { 01910 global $wgContLang; 01911 01912 # Interwikis 01913 wfProfileIn( __METHOD__."-interwiki" ); 01914 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) { 01915 $this->mOutput->addLanguageLink( $nt->getFullText() ); 01916 $s = rtrim( $s . $prefix ); 01917 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail; 01918 wfProfileOut( __METHOD__."-interwiki" ); 01919 continue; 01920 } 01921 wfProfileOut( __METHOD__."-interwiki" ); 01922 01923 if ( $ns == NS_FILE ) { 01924 wfProfileIn( __METHOD__."-image" ); 01925 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) { 01926 if ( $wasblank ) { 01927 # if no parameters were passed, $text 01928 # becomes something like "File:Foo.png", 01929 # which we don't want to pass on to the 01930 # image generator 01931 $text = ''; 01932 } else { 01933 # recursively parse links inside the image caption 01934 # actually, this will parse them in any other parameters, too, 01935 # but it might be hard to fix that, and it doesn't matter ATM 01936 $text = $this->replaceExternalLinks( $text ); 01937 $holders->merge( $this->replaceInternalLinks2( $text ) ); 01938 } 01939 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them 01940 $s .= $prefix . $this->armorLinks( 01941 $this->makeImage( $nt, $text, $holders ) ) . $trail; 01942 } else { 01943 $s .= $prefix . $trail; 01944 } 01945 wfProfileOut( __METHOD__."-image" ); 01946 continue; 01947 } 01948 01949 if ( $ns == NS_CATEGORY ) { 01950 wfProfileIn( __METHOD__."-category" ); 01951 $s = rtrim( $s . "\n" ); # bug 87 01952 01953 if ( $wasblank ) { 01954 $sortkey = $this->getDefaultSort(); 01955 } else { 01956 $sortkey = $text; 01957 } 01958 $sortkey = Sanitizer::decodeCharReferences( $sortkey ); 01959 $sortkey = str_replace( "\n", '', $sortkey ); 01960 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey ); 01961 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey ); 01962 01967 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail; 01968 01969 wfProfileOut( __METHOD__."-category" ); 01970 continue; 01971 } 01972 } 01973 01974 # Self-link checking 01975 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) { 01976 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) { 01977 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail ); 01978 continue; 01979 } 01980 } 01981 01982 # NS_MEDIA is a pseudo-namespace for linking directly to a file 01983 # @todo FIXME: Should do batch file existence checks, see comment below 01984 if ( $ns == NS_MEDIA ) { 01985 wfProfileIn( __METHOD__."-media" ); 01986 # Give extensions a chance to select the file revision for us 01987 $options = array(); 01988 $descQuery = false; 01989 wfRunHooks( 'BeforeParserFetchFileAndTitle', 01990 array( $this, $nt, &$options, &$descQuery ) ); 01991 # Fetch and register the file (file title may be different via hooks) 01992 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options ); 01993 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks 01994 $s .= $prefix . $this->armorLinks( 01995 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail; 01996 wfProfileOut( __METHOD__."-media" ); 01997 continue; 01998 } 01999 02000 wfProfileIn( __METHOD__."-always_known" ); 02001 # Some titles, such as valid special pages or files in foreign repos, should 02002 # be shown as bluelinks even though they're not included in the page table 02003 # 02004 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do 02005 # batch file existence checks for NS_FILE and NS_MEDIA 02006 if ( $iw == '' && $nt->isAlwaysKnown() ) { 02007 $this->mOutput->addLink( $nt ); 02008 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix ); 02009 } else { 02010 # Links will be added to the output link list after checking 02011 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix ); 02012 } 02013 wfProfileOut( __METHOD__."-always_known" ); 02014 } 02015 wfProfileOut( __METHOD__ ); 02016 return $holders; 02017 } 02018 02033 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) { 02034 list( $inside, $trail ) = Linker::splitTrail( $trail ); 02035 02036 if ( is_string( $query ) ) { 02037 $query = wfCgiToArray( $query ); 02038 } 02039 if ( $text == '' ) { 02040 $text = htmlspecialchars( $nt->getPrefixedText() ); 02041 } 02042 02043 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query ); 02044 02045 return $this->armorLinks( $link ) . $trail; 02046 } 02047 02058 function armorLinks( $text ) { 02059 return preg_replace( '/\b(' . wfUrlProtocols() . ')/', 02060 "{$this->mUniqPrefix}NOPARSE$1", $text ); 02061 } 02062 02067 function areSubpagesAllowed() { 02068 # Some namespaces don't allow subpages 02069 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() ); 02070 } 02071 02080 function maybeDoSubpageLink( $target, &$text ) { 02081 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text ); 02082 } 02083 02090 function closeParagraph() { 02091 $result = ''; 02092 if ( $this->mLastSection != '' ) { 02093 $result = '</' . $this->mLastSection . ">\n"; 02094 } 02095 $this->mInPre = false; 02096 $this->mLastSection = ''; 02097 return $result; 02098 } 02099 02110 function getCommon( $st1, $st2 ) { 02111 $fl = strlen( $st1 ); 02112 $shorter = strlen( $st2 ); 02113 if ( $fl < $shorter ) { 02114 $shorter = $fl; 02115 } 02116 02117 for ( $i = 0; $i < $shorter; ++$i ) { 02118 if ( $st1[$i] != $st2[$i] ) { 02119 break; 02120 } 02121 } 02122 return $i; 02123 } 02124 02134 function openList( $char ) { 02135 $result = $this->closeParagraph(); 02136 02137 if ( '*' === $char ) { 02138 $result .= '<ul><li>'; 02139 } elseif ( '#' === $char ) { 02140 $result .= '<ol><li>'; 02141 } elseif ( ':' === $char ) { 02142 $result .= '<dl><dd>'; 02143 } elseif ( ';' === $char ) { 02144 $result .= '<dl><dt>'; 02145 $this->mDTopen = true; 02146 } else { 02147 $result = '<!-- ERR 1 -->'; 02148 } 02149 02150 return $result; 02151 } 02152 02160 function nextItem( $char ) { 02161 if ( '*' === $char || '#' === $char ) { 02162 return '</li><li>'; 02163 } elseif ( ':' === $char || ';' === $char ) { 02164 $close = '</dd>'; 02165 if ( $this->mDTopen ) { 02166 $close = '</dt>'; 02167 } 02168 if ( ';' === $char ) { 02169 $this->mDTopen = true; 02170 return $close . '<dt>'; 02171 } else { 02172 $this->mDTopen = false; 02173 return $close . '<dd>'; 02174 } 02175 } 02176 return '<!-- ERR 2 -->'; 02177 } 02178 02186 function closeList( $char ) { 02187 if ( '*' === $char ) { 02188 $text = '</li></ul>'; 02189 } elseif ( '#' === $char ) { 02190 $text = '</li></ol>'; 02191 } elseif ( ':' === $char ) { 02192 if ( $this->mDTopen ) { 02193 $this->mDTopen = false; 02194 $text = '</dt></dl>'; 02195 } else { 02196 $text = '</dd></dl>'; 02197 } 02198 } else { 02199 return '<!-- ERR 3 -->'; 02200 } 02201 return $text."\n"; 02202 } 02213 function doBlockLevels( $text, $linestart ) { 02214 wfProfileIn( __METHOD__ ); 02215 02216 # Parsing through the text line by line. The main thing 02217 # happening here is handling of block-level elements p, pre, 02218 # and making lists from lines starting with * # : etc. 02219 # 02220 $textLines = StringUtils::explode( "\n", $text ); 02221 02222 $lastPrefix = $output = ''; 02223 $this->mDTopen = $inBlockElem = false; 02224 $prefixLength = 0; 02225 $paragraphStack = false; 02226 02227 foreach ( $textLines as $oLine ) { 02228 # Fix up $linestart 02229 if ( !$linestart ) { 02230 $output .= $oLine; 02231 $linestart = true; 02232 continue; 02233 } 02234 # * = ul 02235 # # = ol 02236 # ; = dt 02237 # : = dd 02238 02239 $lastPrefixLength = strlen( $lastPrefix ); 02240 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine ); 02241 $preOpenMatch = preg_match( '/<pre/i', $oLine ); 02242 # If not in a <pre> element, scan for and figure out what prefixes are there. 02243 if ( !$this->mInPre ) { 02244 # Multiple prefixes may abut each other for nested lists. 02245 $prefixLength = strspn( $oLine, '*#:;' ); 02246 $prefix = substr( $oLine, 0, $prefixLength ); 02247 02248 # eh? 02249 # ; and : are both from definition-lists, so they're equivalent 02250 # for the purposes of determining whether or not we need to open/close 02251 # elements. 02252 $prefix2 = str_replace( ';', ':', $prefix ); 02253 $t = substr( $oLine, $prefixLength ); 02254 $this->mInPre = (bool)$preOpenMatch; 02255 } else { 02256 # Don't interpret any other prefixes in preformatted text 02257 $prefixLength = 0; 02258 $prefix = $prefix2 = ''; 02259 $t = $oLine; 02260 } 02261 02262 # List generation 02263 if ( $prefixLength && $lastPrefix === $prefix2 ) { 02264 # Same as the last item, so no need to deal with nesting or opening stuff 02265 $output .= $this->nextItem( substr( $prefix, -1 ) ); 02266 $paragraphStack = false; 02267 02268 if ( substr( $prefix, -1 ) === ';') { 02269 # The one nasty exception: definition lists work like this: 02270 # ; title : definition text 02271 # So we check for : in the remainder text to split up the 02272 # title and definition, without b0rking links. 02273 $term = $t2 = ''; 02274 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) { 02275 $t = $t2; 02276 $output .= $term . $this->nextItem( ':' ); 02277 } 02278 } 02279 } elseif ( $prefixLength || $lastPrefixLength ) { 02280 # We need to open or close prefixes, or both. 02281 02282 # Either open or close a level... 02283 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix ); 02284 $paragraphStack = false; 02285 02286 # Close all the prefixes which aren't shared. 02287 while ( $commonPrefixLength < $lastPrefixLength ) { 02288 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] ); 02289 --$lastPrefixLength; 02290 } 02291 02292 # Continue the current prefix if appropriate. 02293 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) { 02294 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] ); 02295 } 02296 02297 # Open prefixes where appropriate. 02298 while ( $prefixLength > $commonPrefixLength ) { 02299 $char = substr( $prefix, $commonPrefixLength, 1 ); 02300 $output .= $this->openList( $char ); 02301 02302 if ( ';' === $char ) { 02303 # @todo FIXME: This is dupe of code above 02304 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) { 02305 $t = $t2; 02306 $output .= $term . $this->nextItem( ':' ); 02307 } 02308 } 02309 ++$commonPrefixLength; 02310 } 02311 $lastPrefix = $prefix2; 02312 } 02313 02314 # If we have no prefixes, go to paragraph mode. 02315 if ( 0 == $prefixLength ) { 02316 wfProfileIn( __METHOD__."-paragraph" ); 02317 # No prefix (not in list)--go to paragraph mode 02318 # XXX: use a stack for nestable elements like span, table and div 02319 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t ); 02320 $closematch = preg_match( 02321 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'. 02322 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t ); 02323 if ( $openmatch or $closematch ) { 02324 $paragraphStack = false; 02325 # TODO bug 5718: paragraph closed 02326 $output .= $this->closeParagraph(); 02327 if ( $preOpenMatch and !$preCloseMatch ) { 02328 $this->mInPre = true; 02329 } 02330 $inBlockElem = !$closematch; 02331 } elseif ( !$inBlockElem && !$this->mInPre ) { 02332 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) { 02333 # pre 02334 if ( $this->mLastSection !== 'pre' ) { 02335 $paragraphStack = false; 02336 $output .= $this->closeParagraph().'<pre>'; 02337 $this->mLastSection = 'pre'; 02338 } 02339 $t = substr( $t, 1 ); 02340 } else { 02341 # paragraph 02342 if ( trim( $t ) === '' ) { 02343 if ( $paragraphStack ) { 02344 $output .= $paragraphStack.'<br />'; 02345 $paragraphStack = false; 02346 $this->mLastSection = 'p'; 02347 } else { 02348 if ( $this->mLastSection !== 'p' ) { 02349 $output .= $this->closeParagraph(); 02350 $this->mLastSection = ''; 02351 $paragraphStack = '<p>'; 02352 } else { 02353 $paragraphStack = '</p><p>'; 02354 } 02355 } 02356 } else { 02357 if ( $paragraphStack ) { 02358 $output .= $paragraphStack; 02359 $paragraphStack = false; 02360 $this->mLastSection = 'p'; 02361 } elseif ( $this->mLastSection !== 'p' ) { 02362 $output .= $this->closeParagraph().'<p>'; 02363 $this->mLastSection = 'p'; 02364 } 02365 } 02366 } 02367 } 02368 wfProfileOut( __METHOD__."-paragraph" ); 02369 } 02370 # somewhere above we forget to get out of pre block (bug 785) 02371 if ( $preCloseMatch && $this->mInPre ) { 02372 $this->mInPre = false; 02373 } 02374 if ( $paragraphStack === false ) { 02375 $output .= $t."\n"; 02376 } 02377 } 02378 while ( $prefixLength ) { 02379 $output .= $this->closeList( $prefix2[$prefixLength-1] ); 02380 --$prefixLength; 02381 } 02382 if ( $this->mLastSection != '' ) { 02383 $output .= '</' . $this->mLastSection . '>'; 02384 $this->mLastSection = ''; 02385 } 02386 02387 wfProfileOut( __METHOD__ ); 02388 return $output; 02389 } 02390 02400 function findColonNoLinks( $str, &$before, &$after ) { 02401 wfProfileIn( __METHOD__ ); 02402 02403 $pos = strpos( $str, ':' ); 02404 if ( $pos === false ) { 02405 # Nothing to find! 02406 wfProfileOut( __METHOD__ ); 02407 return false; 02408 } 02409 02410 $lt = strpos( $str, '<' ); 02411 if ( $lt === false || $lt > $pos ) { 02412 # Easy; no tag nesting to worry about 02413 $before = substr( $str, 0, $pos ); 02414 $after = substr( $str, $pos+1 ); 02415 wfProfileOut( __METHOD__ ); 02416 return $pos; 02417 } 02418 02419 # Ugly state machine to walk through avoiding tags. 02420 $state = self::COLON_STATE_TEXT; 02421 $stack = 0; 02422 $len = strlen( $str ); 02423 for( $i = 0; $i < $len; $i++ ) { 02424 $c = $str[$i]; 02425 02426 switch( $state ) { 02427 # (Using the number is a performance hack for common cases) 02428 case 0: # self::COLON_STATE_TEXT: 02429 switch( $c ) { 02430 case "<": 02431 # Could be either a <start> tag or an </end> tag 02432 $state = self::COLON_STATE_TAGSTART; 02433 break; 02434 case ":": 02435 if ( $stack == 0 ) { 02436 # We found it! 02437 $before = substr( $str, 0, $i ); 02438 $after = substr( $str, $i + 1 ); 02439 wfProfileOut( __METHOD__ ); 02440 return $i; 02441 } 02442 # Embedded in a tag; don't break it. 02443 break; 02444 default: 02445 # Skip ahead looking for something interesting 02446 $colon = strpos( $str, ':', $i ); 02447 if ( $colon === false ) { 02448 # Nothing else interesting 02449 wfProfileOut( __METHOD__ ); 02450 return false; 02451 } 02452 $lt = strpos( $str, '<', $i ); 02453 if ( $stack === 0 ) { 02454 if ( $lt === false || $colon < $lt ) { 02455 # We found it! 02456 $before = substr( $str, 0, $colon ); 02457 $after = substr( $str, $colon + 1 ); 02458 wfProfileOut( __METHOD__ ); 02459 return $i; 02460 } 02461 } 02462 if ( $lt === false ) { 02463 # Nothing else interesting to find; abort! 02464 # We're nested, but there's no close tags left. Abort! 02465 break 2; 02466 } 02467 # Skip ahead to next tag start 02468 $i = $lt; 02469 $state = self::COLON_STATE_TAGSTART; 02470 } 02471 break; 02472 case 1: # self::COLON_STATE_TAG: 02473 # In a <tag> 02474 switch( $c ) { 02475 case ">": 02476 $stack++; 02477 $state = self::COLON_STATE_TEXT; 02478 break; 02479 case "/": 02480 # Slash may be followed by >? 02481 $state = self::COLON_STATE_TAGSLASH; 02482 break; 02483 default: 02484 # ignore 02485 } 02486 break; 02487 case 2: # self::COLON_STATE_TAGSTART: 02488 switch( $c ) { 02489 case "/": 02490 $state = self::COLON_STATE_CLOSETAG; 02491 break; 02492 case "!": 02493 $state = self::COLON_STATE_COMMENT; 02494 break; 02495 case ">": 02496 # Illegal early close? This shouldn't happen D: 02497 $state = self::COLON_STATE_TEXT; 02498 break; 02499 default: 02500 $state = self::COLON_STATE_TAG; 02501 } 02502 break; 02503 case 3: # self::COLON_STATE_CLOSETAG: 02504 # In a </tag> 02505 if ( $c === ">" ) { 02506 $stack--; 02507 if ( $stack < 0 ) { 02508 wfDebug( __METHOD__.": Invalid input; too many close tags\n" ); 02509 wfProfileOut( __METHOD__ ); 02510 return false; 02511 } 02512 $state = self::COLON_STATE_TEXT; 02513 } 02514 break; 02515 case self::COLON_STATE_TAGSLASH: 02516 if ( $c === ">" ) { 02517 # Yes, a self-closed tag <blah/> 02518 $state = self::COLON_STATE_TEXT; 02519 } else { 02520 # Probably we're jumping the gun, and this is an attribute 02521 $state = self::COLON_STATE_TAG; 02522 } 02523 break; 02524 case 5: # self::COLON_STATE_COMMENT: 02525 if ( $c === "-" ) { 02526 $state = self::COLON_STATE_COMMENTDASH; 02527 } 02528 break; 02529 case self::COLON_STATE_COMMENTDASH: 02530 if ( $c === "-" ) { 02531 $state = self::COLON_STATE_COMMENTDASHDASH; 02532 } else { 02533 $state = self::COLON_STATE_COMMENT; 02534 } 02535 break; 02536 case self::COLON_STATE_COMMENTDASHDASH: 02537 if ( $c === ">" ) { 02538 $state = self::COLON_STATE_TEXT; 02539 } else { 02540 $state = self::COLON_STATE_COMMENT; 02541 } 02542 break; 02543 default: 02544 throw new MWException( "State machine error in " . __METHOD__ ); 02545 } 02546 } 02547 if ( $stack > 0 ) { 02548 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" ); 02549 wfProfileOut( __METHOD__ ); 02550 return false; 02551 } 02552 wfProfileOut( __METHOD__ ); 02553 return false; 02554 } 02555 02566 function getVariableValue( $index, $frame = false ) { 02567 global $wgContLang, $wgSitename, $wgServer; 02568 global $wgArticlePath, $wgScriptPath, $wgStylePath; 02569 02570 if ( is_null( $this->mTitle ) ) { 02571 // If no title set, bad things are going to happen 02572 // later. Title should always be set since this 02573 // should only be called in the middle of a parse 02574 // operation (but the unit-tests do funky stuff) 02575 throw new MWException( __METHOD__ . ' Should only be ' 02576 . ' called while parsing (no title set)' ); 02577 } 02578 02583 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) { 02584 if ( isset( $this->mVarCache[$index] ) ) { 02585 return $this->mVarCache[$index]; 02586 } 02587 } 02588 02589 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() ); 02590 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) ); 02591 02592 # Use the time zone 02593 global $wgLocaltimezone; 02594 if ( isset( $wgLocaltimezone ) ) { 02595 $oldtz = date_default_timezone_get(); 02596 date_default_timezone_set( $wgLocaltimezone ); 02597 } 02598 02599 $localTimestamp = date( 'YmdHis', $ts ); 02600 $localMonth = date( 'm', $ts ); 02601 $localMonth1 = date( 'n', $ts ); 02602 $localMonthName = date( 'n', $ts ); 02603 $localDay = date( 'j', $ts ); 02604 $localDay2 = date( 'd', $ts ); 02605 $localDayOfWeek = date( 'w', $ts ); 02606 $localWeek = date( 'W', $ts ); 02607 $localYear = date( 'Y', $ts ); 02608 $localHour = date( 'H', $ts ); 02609 if ( isset( $wgLocaltimezone ) ) { 02610 date_default_timezone_set( $oldtz ); 02611 } 02612 02613 $pageLang = $this->getFunctionLang(); 02614 02615 switch ( $index ) { 02616 case 'currentmonth': 02617 $value = $pageLang->formatNum( gmdate( 'm', $ts ) ); 02618 break; 02619 case 'currentmonth1': 02620 $value = $pageLang->formatNum( gmdate( 'n', $ts ) ); 02621 break; 02622 case 'currentmonthname': 02623 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) ); 02624 break; 02625 case 'currentmonthnamegen': 02626 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) ); 02627 break; 02628 case 'currentmonthabbrev': 02629 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) ); 02630 break; 02631 case 'currentday': 02632 $value = $pageLang->formatNum( gmdate( 'j', $ts ) ); 02633 break; 02634 case 'currentday2': 02635 $value = $pageLang->formatNum( gmdate( 'd', $ts ) ); 02636 break; 02637 case 'localmonth': 02638 $value = $pageLang->formatNum( $localMonth ); 02639 break; 02640 case 'localmonth1': 02641 $value = $pageLang->formatNum( $localMonth1 ); 02642 break; 02643 case 'localmonthname': 02644 $value = $pageLang->getMonthName( $localMonthName ); 02645 break; 02646 case 'localmonthnamegen': 02647 $value = $pageLang->getMonthNameGen( $localMonthName ); 02648 break; 02649 case 'localmonthabbrev': 02650 $value = $pageLang->getMonthAbbreviation( $localMonthName ); 02651 break; 02652 case 'localday': 02653 $value = $pageLang->formatNum( $localDay ); 02654 break; 02655 case 'localday2': 02656 $value = $pageLang->formatNum( $localDay2 ); 02657 break; 02658 case 'pagename': 02659 $value = wfEscapeWikiText( $this->mTitle->getText() ); 02660 break; 02661 case 'pagenamee': 02662 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() ); 02663 break; 02664 case 'fullpagename': 02665 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() ); 02666 break; 02667 case 'fullpagenamee': 02668 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() ); 02669 break; 02670 case 'subpagename': 02671 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() ); 02672 break; 02673 case 'subpagenamee': 02674 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() ); 02675 break; 02676 case 'basepagename': 02677 $value = wfEscapeWikiText( $this->mTitle->getBaseText() ); 02678 break; 02679 case 'basepagenamee': 02680 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) ); 02681 break; 02682 case 'talkpagename': 02683 if ( $this->mTitle->canTalk() ) { 02684 $talkPage = $this->mTitle->getTalkPage(); 02685 $value = wfEscapeWikiText( $talkPage->getPrefixedText() ); 02686 } else { 02687 $value = ''; 02688 } 02689 break; 02690 case 'talkpagenamee': 02691 if ( $this->mTitle->canTalk() ) { 02692 $talkPage = $this->mTitle->getTalkPage(); 02693 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() ); 02694 } else { 02695 $value = ''; 02696 } 02697 break; 02698 case 'subjectpagename': 02699 $subjPage = $this->mTitle->getSubjectPage(); 02700 $value = wfEscapeWikiText( $subjPage->getPrefixedText() ); 02701 break; 02702 case 'subjectpagenamee': 02703 $subjPage = $this->mTitle->getSubjectPage(); 02704 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() ); 02705 break; 02706 case 'revisionid': 02707 # Let the edit saving system know we should parse the page 02708 # *after* a revision ID has been assigned. 02709 $this->mOutput->setFlag( 'vary-revision' ); 02710 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" ); 02711 $value = $this->mRevisionId; 02712 break; 02713 case 'revisionday': 02714 # Let the edit saving system know we should parse the page 02715 # *after* a revision ID has been assigned. This is for null edits. 02716 $this->mOutput->setFlag( 'vary-revision' ); 02717 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" ); 02718 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) ); 02719 break; 02720 case 'revisionday2': 02721 # Let the edit saving system know we should parse the page 02722 # *after* a revision ID has been assigned. This is for null edits. 02723 $this->mOutput->setFlag( 'vary-revision' ); 02724 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" ); 02725 $value = substr( $this->getRevisionTimestamp(), 6, 2 ); 02726 break; 02727 case 'revisionmonth': 02728 # Let the edit saving system know we should parse the page 02729 # *after* a revision ID has been assigned. This is for null edits. 02730 $this->mOutput->setFlag( 'vary-revision' ); 02731 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" ); 02732 $value = substr( $this->getRevisionTimestamp(), 4, 2 ); 02733 break; 02734 case 'revisionmonth1': 02735 # Let the edit saving system know we should parse the page 02736 # *after* a revision ID has been assigned. This is for null edits. 02737 $this->mOutput->setFlag( 'vary-revision' ); 02738 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" ); 02739 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) ); 02740 break; 02741 case 'revisionyear': 02742 # Let the edit saving system know we should parse the page 02743 # *after* a revision ID has been assigned. This is for null edits. 02744 $this->mOutput->setFlag( 'vary-revision' ); 02745 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" ); 02746 $value = substr( $this->getRevisionTimestamp(), 0, 4 ); 02747 break; 02748 case 'revisiontimestamp': 02749 # Let the edit saving system know we should parse the page 02750 # *after* a revision ID has been assigned. This is for null edits. 02751 $this->mOutput->setFlag( 'vary-revision' ); 02752 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" ); 02753 $value = $this->getRevisionTimestamp(); 02754 break; 02755 case 'revisionuser': 02756 # Let the edit saving system know we should parse the page 02757 # *after* a revision ID has been assigned. This is for null edits. 02758 $this->mOutput->setFlag( 'vary-revision' ); 02759 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" ); 02760 $value = $this->getRevisionUser(); 02761 break; 02762 case 'namespace': 02763 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) ); 02764 break; 02765 case 'namespacee': 02766 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) ); 02767 break; 02768 case 'talkspace': 02769 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : ''; 02770 break; 02771 case 'talkspacee': 02772 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : ''; 02773 break; 02774 case 'subjectspace': 02775 $value = $this->mTitle->getSubjectNsText(); 02776 break; 02777 case 'subjectspacee': 02778 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) ); 02779 break; 02780 case 'currentdayname': 02781 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) + 1 ); 02782 break; 02783 case 'currentyear': 02784 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true ); 02785 break; 02786 case 'currenttime': 02787 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false ); 02788 break; 02789 case 'currenthour': 02790 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true ); 02791 break; 02792 case 'currentweek': 02793 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to 02794 # int to remove the padding 02795 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) ); 02796 break; 02797 case 'currentdow': 02798 $value = $pageLang->formatNum( gmdate( 'w', $ts ) ); 02799 break; 02800 case 'localdayname': 02801 $value = $pageLang->getWeekdayName( $localDayOfWeek + 1 ); 02802 break; 02803 case 'localyear': 02804 $value = $pageLang->formatNum( $localYear, true ); 02805 break; 02806 case 'localtime': 02807 $value = $pageLang->time( $localTimestamp, false, false ); 02808 break; 02809 case 'localhour': 02810 $value = $pageLang->formatNum( $localHour, true ); 02811 break; 02812 case 'localweek': 02813 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to 02814 # int to remove the padding 02815 $value = $pageLang->formatNum( (int)$localWeek ); 02816 break; 02817 case 'localdow': 02818 $value = $pageLang->formatNum( $localDayOfWeek ); 02819 break; 02820 case 'numberofarticles': 02821 $value = $pageLang->formatNum( SiteStats::articles() ); 02822 break; 02823 case 'numberoffiles': 02824 $value = $pageLang->formatNum( SiteStats::images() ); 02825 break; 02826 case 'numberofusers': 02827 $value = $pageLang->formatNum( SiteStats::users() ); 02828 break; 02829 case 'numberofactiveusers': 02830 $value = $pageLang->formatNum( SiteStats::activeUsers() ); 02831 break; 02832 case 'numberofpages': 02833 $value = $pageLang->formatNum( SiteStats::pages() ); 02834 break; 02835 case 'numberofadmins': 02836 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) ); 02837 break; 02838 case 'numberofedits': 02839 $value = $pageLang->formatNum( SiteStats::edits() ); 02840 break; 02841 case 'numberofviews': 02842 $value = $pageLang->formatNum( SiteStats::views() ); 02843 break; 02844 case 'currenttimestamp': 02845 $value = wfTimestamp( TS_MW, $ts ); 02846 break; 02847 case 'localtimestamp': 02848 $value = $localTimestamp; 02849 break; 02850 case 'currentversion': 02851 $value = SpecialVersion::getVersion(); 02852 break; 02853 case 'articlepath': 02854 return $wgArticlePath; 02855 case 'sitename': 02856 return $wgSitename; 02857 case 'server': 02858 return $wgServer; 02859 case 'servername': 02860 $serverParts = wfParseUrl( $wgServer ); 02861 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer; 02862 case 'scriptpath': 02863 return $wgScriptPath; 02864 case 'stylepath': 02865 return $wgStylePath; 02866 case 'directionmark': 02867 return $pageLang->getDirMark(); 02868 case 'contentlanguage': 02869 global $wgLanguageCode; 02870 return $wgLanguageCode; 02871 default: 02872 $ret = null; 02873 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) { 02874 return $ret; 02875 } else { 02876 return null; 02877 } 02878 } 02879 02880 if ( $index ) { 02881 $this->mVarCache[$index] = $value; 02882 } 02883 02884 return $value; 02885 } 02886 02892 function initialiseVariables() { 02893 wfProfileIn( __METHOD__ ); 02894 $variableIDs = MagicWord::getVariableIDs(); 02895 $substIDs = MagicWord::getSubstIDs(); 02896 02897 $this->mVariables = new MagicWordArray( $variableIDs ); 02898 $this->mSubstWords = new MagicWordArray( $substIDs ); 02899 wfProfileOut( __METHOD__ ); 02900 } 02901 02926 function preprocessToDom( $text, $flags = 0 ) { 02927 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags ); 02928 return $dom; 02929 } 02930 02938 public static function splitWhitespace( $s ) { 02939 $ltrimmed = ltrim( $s ); 02940 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) ); 02941 $trimmed = rtrim( $ltrimmed ); 02942 $diff = strlen( $ltrimmed ) - strlen( $trimmed ); 02943 if ( $diff > 0 ) { 02944 $w2 = substr( $ltrimmed, -$diff ); 02945 } else { 02946 $w2 = ''; 02947 } 02948 return array( $w1, $trimmed, $w2 ); 02949 } 02950 02970 function replaceVariables( $text, $frame = false, $argsOnly = false ) { 02971 # Is there any text? Also, Prevent too big inclusions! 02972 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) { 02973 return $text; 02974 } 02975 wfProfileIn( __METHOD__ ); 02976 02977 if ( $frame === false ) { 02978 $frame = $this->getPreprocessor()->newFrame(); 02979 } elseif ( !( $frame instanceof PPFrame ) ) { 02980 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" ); 02981 $frame = $this->getPreprocessor()->newCustomFrame( $frame ); 02982 } 02983 02984 $dom = $this->preprocessToDom( $text ); 02985 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0; 02986 $text = $frame->expand( $dom, $flags ); 02987 02988 wfProfileOut( __METHOD__ ); 02989 return $text; 02990 } 02991 02999 static function createAssocArgs( $args ) { 03000 $assocArgs = array(); 03001 $index = 1; 03002 foreach ( $args as $arg ) { 03003 $eqpos = strpos( $arg, '=' ); 03004 if ( $eqpos === false ) { 03005 $assocArgs[$index++] = $arg; 03006 } else { 03007 $name = trim( substr( $arg, 0, $eqpos ) ); 03008 $value = trim( substr( $arg, $eqpos+1 ) ); 03009 if ( $value === false ) { 03010 $value = ''; 03011 } 03012 if ( $name !== false ) { 03013 $assocArgs[$name] = $value; 03014 } 03015 } 03016 } 03017 03018 return $assocArgs; 03019 } 03020 03039 function limitationWarn( $limitationType, $current=null, $max=null) { 03040 # does no harm if $current and $max are present but are unnecessary for the message 03041 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max ); 03042 $this->mOutput->addWarning( $warning ); 03043 $this->addTrackingCategory( "$limitationType-category" ); 03044 } 03045 03058 function braceSubstitution( $piece, $frame ) { 03059 global $wgNonincludableNamespaces, $wgContLang; 03060 wfProfileIn( __METHOD__ ); 03061 wfProfileIn( __METHOD__.'-setup' ); 03062 03063 # Flags 03064 $found = false; # $text has been filled 03065 $nowiki = false; # wiki markup in $text should be escaped 03066 $isHTML = false; # $text is HTML, armour it against wikitext transformation 03067 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered 03068 $isChildObj = false; # $text is a DOM node needing expansion in a child frame 03069 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame 03070 03071 # Title object, where $text came from 03072 $title = false; 03073 03074 # $part1 is the bit before the first |, and must contain only title characters. 03075 # Various prefixes will be stripped from it later. 03076 $titleWithSpaces = $frame->expand( $piece['title'] ); 03077 $part1 = trim( $titleWithSpaces ); 03078 $titleText = false; 03079 03080 # Original title text preserved for various purposes 03081 $originalTitle = $part1; 03082 03083 # $args is a list of argument nodes, starting from index 0, not including $part1 03084 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object 03085 $args = ( null == $piece['parts'] ) ? array() : $piece['parts']; 03086 wfProfileOut( __METHOD__.'-setup' ); 03087 03088 $titleProfileIn = null; // profile templates 03089 03090 # SUBST 03091 wfProfileIn( __METHOD__.'-modifiers' ); 03092 if ( !$found ) { 03093 03094 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 ); 03095 03096 # Possibilities for substMatch: "subst", "safesubst" or FALSE 03097 # Decide whether to expand template or keep wikitext as-is. 03098 if ( $this->ot['wiki'] ) { 03099 if ( $substMatch === false ) { 03100 $literal = true; # literal when in PST with no prefix 03101 } else { 03102 $literal = false; # expand when in PST with subst: or safesubst: 03103 } 03104 } else { 03105 if ( $substMatch == 'subst' ) { 03106 $literal = true; # literal when not in PST with plain subst: 03107 } else { 03108 $literal = false; # expand when not in PST with safesubst: or no prefix 03109 } 03110 } 03111 if ( $literal ) { 03112 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args ); 03113 $isLocalObj = true; 03114 $found = true; 03115 } 03116 } 03117 03118 # Variables 03119 if ( !$found && $args->getLength() == 0 ) { 03120 $id = $this->mVariables->matchStartToEnd( $part1 ); 03121 if ( $id !== false ) { 03122 $text = $this->getVariableValue( $id, $frame ); 03123 if ( MagicWord::getCacheTTL( $id ) > -1 ) { 03124 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) ); 03125 } 03126 $found = true; 03127 } 03128 } 03129 03130 # MSG, MSGNW and RAW 03131 if ( !$found ) { 03132 # Check for MSGNW: 03133 $mwMsgnw = MagicWord::get( 'msgnw' ); 03134 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) { 03135 $nowiki = true; 03136 } else { 03137 # Remove obsolete MSG: 03138 $mwMsg = MagicWord::get( 'msg' ); 03139 $mwMsg->matchStartAndRemove( $part1 ); 03140 } 03141 03142 # Check for RAW: 03143 $mwRaw = MagicWord::get( 'raw' ); 03144 if ( $mwRaw->matchStartAndRemove( $part1 ) ) { 03145 $forceRawInterwiki = true; 03146 } 03147 } 03148 wfProfileOut( __METHOD__.'-modifiers' ); 03149 03150 # Parser functions 03151 if ( !$found ) { 03152 wfProfileIn( __METHOD__ . '-pfunc' ); 03153 03154 $colonPos = strpos( $part1, ':' ); 03155 if ( $colonPos !== false ) { 03156 # Case sensitive functions 03157 $function = substr( $part1, 0, $colonPos ); 03158 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) { 03159 $function = $this->mFunctionSynonyms[1][$function]; 03160 } else { 03161 # Case insensitive functions 03162 $function = $wgContLang->lc( $function ); 03163 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) { 03164 $function = $this->mFunctionSynonyms[0][$function]; 03165 } else { 03166 $function = false; 03167 } 03168 } 03169 if ( $function ) { 03170 wfProfileIn( __METHOD__ . '-pfunc-' . $function ); 03171 list( $callback, $flags ) = $this->mFunctionHooks[$function]; 03172 $initialArgs = array( &$this ); 03173 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) ); 03174 if ( $flags & SFH_OBJECT_ARGS ) { 03175 # Add a frame parameter, and pass the arguments as an array 03176 $allArgs = $initialArgs; 03177 $allArgs[] = $frame; 03178 for ( $i = 0; $i < $args->getLength(); $i++ ) { 03179 $funcArgs[] = $args->item( $i ); 03180 } 03181 $allArgs[] = $funcArgs; 03182 } else { 03183 # Convert arguments to plain text 03184 for ( $i = 0; $i < $args->getLength(); $i++ ) { 03185 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) ); 03186 } 03187 $allArgs = array_merge( $initialArgs, $funcArgs ); 03188 } 03189 03190 # Workaround for PHP bug 35229 and similar 03191 if ( !is_callable( $callback ) ) { 03192 wfProfileOut( __METHOD__ . '-pfunc-' . $function ); 03193 wfProfileOut( __METHOD__ . '-pfunc' ); 03194 wfProfileOut( __METHOD__ ); 03195 throw new MWException( "Tag hook for $function is not callable\n" ); 03196 } 03197 $result = call_user_func_array( $callback, $allArgs ); 03198 $found = true; 03199 $noparse = true; 03200 $preprocessFlags = 0; 03201 03202 if ( is_array( $result ) ) { 03203 if ( isset( $result[0] ) ) { 03204 $text = $result[0]; 03205 unset( $result[0] ); 03206 } 03207 03208 # Extract flags into the local scope 03209 # This allows callers to set flags such as nowiki, found, etc. 03210 extract( $result ); 03211 } else { 03212 $text = $result; 03213 } 03214 if ( !$noparse ) { 03215 $text = $this->preprocessToDom( $text, $preprocessFlags ); 03216 $isChildObj = true; 03217 } 03218 wfProfileOut( __METHOD__ . '-pfunc-' . $function ); 03219 } 03220 } 03221 wfProfileOut( __METHOD__ . '-pfunc' ); 03222 } 03223 03224 # Finish mangling title and then check for loops. 03225 # Set $title to a Title object and $titleText to the PDBK 03226 if ( !$found ) { 03227 $ns = NS_TEMPLATE; 03228 # Split the title into page and subpage 03229 $subpage = ''; 03230 $part1 = $this->maybeDoSubpageLink( $part1, $subpage ); 03231 if ( $subpage !== '' ) { 03232 $ns = $this->mTitle->getNamespace(); 03233 } 03234 $title = Title::newFromText( $part1, $ns ); 03235 if ( $title ) { 03236 $titleText = $title->getPrefixedText(); 03237 # Check for language variants if the template is not found 03238 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) { 03239 $this->getConverterLanguage()->findVariantLink( $part1, $title, true ); 03240 } 03241 # Do recursion depth check 03242 $limit = $this->mOptions->getMaxTemplateDepth(); 03243 if ( $frame->depth >= $limit ) { 03244 $found = true; 03245 $text = '<span class="error">' 03246 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) 03247 . '</span>'; 03248 } 03249 } 03250 } 03251 03252 # Load from database 03253 if ( !$found && $title ) { 03254 $titleProfileIn = __METHOD__ . "-title-" . $title->getDBKey(); 03255 wfProfileIn( $titleProfileIn ); // template in 03256 wfProfileIn( __METHOD__ . '-loadtpl' ); 03257 if ( !$title->isExternal() ) { 03258 if ( $title->isSpecialPage() 03259 && $this->mOptions->getAllowSpecialInclusion() 03260 && $this->ot['html'] ) 03261 { 03262 // Pass the template arguments as URL parameters. 03263 // "uselang" will have no effect since the Language object 03264 // is forced to the one defined in ParserOptions. 03265 $pageArgs = array(); 03266 for ( $i = 0; $i < $args->getLength(); $i++ ) { 03267 $bits = $args->item( $i )->splitArg(); 03268 if ( strval( $bits['index'] ) === '' ) { 03269 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) ); 03270 $value = trim( $frame->expand( $bits['value'] ) ); 03271 $pageArgs[$name] = $value; 03272 } 03273 } 03274 03275 // Create a new context to execute the special page 03276 $context = new RequestContext; 03277 $context->setTitle( $title ); 03278 $context->setRequest( new FauxRequest( $pageArgs ) ); 03279 $context->setUser( $this->getUser() ); 03280 $context->setLanguage( $this->mOptions->getUserLangObj() ); 03281 $ret = SpecialPageFactory::capturePath( $title, $context ); 03282 if ( $ret ) { 03283 $text = $context->getOutput()->getHTML(); 03284 $this->mOutput->addOutputPageMetadata( $context->getOutput() ); 03285 $found = true; 03286 $isHTML = true; 03287 $this->disableCache(); 03288 } 03289 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) { 03290 $found = false; # access denied 03291 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() ); 03292 } else { 03293 list( $text, $title ) = $this->getTemplateDom( $title ); 03294 if ( $text !== false ) { 03295 $found = true; 03296 $isChildObj = true; 03297 } 03298 } 03299 03300 # If the title is valid but undisplayable, make a link to it 03301 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) { 03302 $text = "[[:$titleText]]"; 03303 $found = true; 03304 } 03305 } elseif ( $title->isTrans() ) { 03306 # Interwiki transclusion 03307 if ( $this->ot['html'] && !$forceRawInterwiki ) { 03308 $text = $this->interwikiTransclude( $title, 'render' ); 03309 $isHTML = true; 03310 } else { 03311 $text = $this->interwikiTransclude( $title, 'raw' ); 03312 # Preprocess it like a template 03313 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 03314 $isChildObj = true; 03315 } 03316 $found = true; 03317 } 03318 03319 # Do infinite loop check 03320 # This has to be done after redirect resolution to avoid infinite loops via redirects 03321 if ( !$frame->loopCheck( $title ) ) { 03322 $found = true; 03323 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>'; 03324 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" ); 03325 } 03326 wfProfileOut( __METHOD__ . '-loadtpl' ); 03327 } 03328 03329 # If we haven't found text to substitute by now, we're done 03330 # Recover the source wikitext and return it 03331 if ( !$found ) { 03332 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args ); 03333 if ( $titleProfileIn ) { 03334 wfProfileOut( $titleProfileIn ); // template out 03335 } 03336 wfProfileOut( __METHOD__ ); 03337 return array( 'object' => $text ); 03338 } 03339 03340 # Expand DOM-style return values in a child frame 03341 if ( $isChildObj ) { 03342 # Clean up argument array 03343 $newFrame = $frame->newChild( $args, $title ); 03344 03345 if ( $nowiki ) { 03346 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG ); 03347 } elseif ( $titleText !== false && $newFrame->isEmpty() ) { 03348 # Expansion is eligible for the empty-frame cache 03349 if ( isset( $this->mTplExpandCache[$titleText] ) ) { 03350 $text = $this->mTplExpandCache[$titleText]; 03351 } else { 03352 $text = $newFrame->expand( $text ); 03353 $this->mTplExpandCache[$titleText] = $text; 03354 } 03355 } else { 03356 # Uncached expansion 03357 $text = $newFrame->expand( $text ); 03358 } 03359 } 03360 if ( $isLocalObj && $nowiki ) { 03361 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG ); 03362 $isLocalObj = false; 03363 } 03364 03365 if ( $titleProfileIn ) { 03366 wfProfileOut( $titleProfileIn ); // template out 03367 } 03368 03369 # Replace raw HTML by a placeholder 03370 # Add a blank line preceding, to prevent it from mucking up 03371 # immediately preceding headings 03372 if ( $isHTML ) { 03373 $text = "\n\n" . $this->insertStripItem( $text ); 03374 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) { 03375 # Escape nowiki-style return values 03376 $text = wfEscapeWikiText( $text ); 03377 } elseif ( is_string( $text ) 03378 && !$piece['lineStart'] 03379 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) ) 03380 { 03381 # Bug 529: if the template begins with a table or block-level 03382 # element, it should be treated as beginning a new line. 03383 # This behaviour is somewhat controversial. 03384 $text = "\n" . $text; 03385 } 03386 03387 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) { 03388 # Error, oversize inclusion 03389 if ( $titleText !== false ) { 03390 # Make a working, properly escaped link if possible (bug 23588) 03391 $text = "[[:$titleText]]"; 03392 } else { 03393 # This will probably not be a working link, but at least it may 03394 # provide some hint of where the problem is 03395 preg_replace( '/^:/', '', $originalTitle ); 03396 $text = "[[:$originalTitle]]"; 03397 } 03398 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' ); 03399 $this->limitationWarn( 'post-expand-template-inclusion' ); 03400 } 03401 03402 if ( $isLocalObj ) { 03403 $ret = array( 'object' => $text ); 03404 } else { 03405 $ret = array( 'text' => $text ); 03406 } 03407 03408 wfProfileOut( __METHOD__ ); 03409 return $ret; 03410 } 03411 03420 function getTemplateDom( $title ) { 03421 $cacheTitle = $title; 03422 $titleText = $title->getPrefixedDBkey(); 03423 03424 if ( isset( $this->mTplRedirCache[$titleText] ) ) { 03425 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText]; 03426 $title = Title::makeTitle( $ns, $dbk ); 03427 $titleText = $title->getPrefixedDBkey(); 03428 } 03429 if ( isset( $this->mTplDomCache[$titleText] ) ) { 03430 return array( $this->mTplDomCache[$titleText], $title ); 03431 } 03432 03433 # Cache miss, go to the database 03434 list( $text, $title ) = $this->fetchTemplateAndTitle( $title ); 03435 03436 if ( $text === false ) { 03437 $this->mTplDomCache[$titleText] = false; 03438 return array( false, $title ); 03439 } 03440 03441 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 03442 $this->mTplDomCache[ $titleText ] = $dom; 03443 03444 if ( !$title->equals( $cacheTitle ) ) { 03445 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] = 03446 array( $title->getNamespace(), $cdb = $title->getDBkey() ); 03447 } 03448 03449 return array( $dom, $title ); 03450 } 03451 03457 function fetchTemplateAndTitle( $title ) { 03458 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate() 03459 $stuff = call_user_func( $templateCb, $title, $this ); 03460 $text = $stuff['text']; 03461 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title; 03462 if ( isset( $stuff['deps'] ) ) { 03463 foreach ( $stuff['deps'] as $dep ) { 03464 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] ); 03465 } 03466 } 03467 return array( $text, $finalTitle ); 03468 } 03469 03475 function fetchTemplate( $title ) { 03476 $rv = $this->fetchTemplateAndTitle( $title ); 03477 return $rv[0]; 03478 } 03479 03489 static function statelessFetchTemplate( $title, $parser = false ) { 03490 $text = $skip = false; 03491 $finalTitle = $title; 03492 $deps = array(); 03493 03494 # Loop to fetch the article, with up to 1 redirect 03495 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) { 03496 # Give extensions a chance to select the revision instead 03497 $id = false; # Assume current 03498 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', 03499 array( $parser, $title, &$skip, &$id ) ); 03500 03501 if ( $skip ) { 03502 $text = false; 03503 $deps[] = array( 03504 'title' => $title, 03505 'page_id' => $title->getArticleID(), 03506 'rev_id' => null 03507 ); 03508 break; 03509 } 03510 # Get the revision 03511 $rev = $id 03512 ? Revision::newFromId( $id ) 03513 : Revision::newFromTitle( $title ); 03514 $rev_id = $rev ? $rev->getId() : 0; 03515 # If there is no current revision, there is no page 03516 if ( $id === false && !$rev ) { 03517 $linkCache = LinkCache::singleton(); 03518 $linkCache->addBadLinkObj( $title ); 03519 } 03520 03521 $deps[] = array( 03522 'title' => $title, 03523 'page_id' => $title->getArticleID(), 03524 'rev_id' => $rev_id ); 03525 if ( $rev && !$title->equals( $rev->getTitle() ) ) { 03526 # We fetched a rev from a different title; register it too... 03527 $deps[] = array( 03528 'title' => $rev->getTitle(), 03529 'page_id' => $rev->getPage(), 03530 'rev_id' => $rev_id ); 03531 } 03532 03533 if ( $rev ) { 03534 $text = $rev->getText(); 03535 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) { 03536 global $wgContLang; 03537 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage(); 03538 if ( !$message->exists() ) { 03539 $text = false; 03540 break; 03541 } 03542 $text = $message->plain(); 03543 } else { 03544 break; 03545 } 03546 if ( $text === false ) { 03547 break; 03548 } 03549 # Redirect? 03550 $finalTitle = $title; 03551 $title = Title::newFromRedirect( $text ); 03552 } 03553 return array( 03554 'text' => $text, 03555 'finalTitle' => $finalTitle, 03556 'deps' => $deps ); 03557 } 03558 03566 function fetchFile( $title, $options = array() ) { 03567 $res = $this->fetchFileAndTitle( $title, $options ); 03568 return $res[0]; 03569 } 03570 03578 function fetchFileAndTitle( $title, $options = array() ) { 03579 if ( isset( $options['broken'] ) ) { 03580 $file = false; // broken thumbnail forced by hook 03581 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp) 03582 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options ); 03583 } else { // get by (name,timestamp) 03584 $file = wfFindFile( $title, $options ); 03585 } 03586 $time = $file ? $file->getTimestamp() : false; 03587 $sha1 = $file ? $file->getSha1() : false; 03588 # Register the file as a dependency... 03589 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 ); 03590 if ( $file && !$title->equals( $file->getTitle() ) ) { 03591 # Update fetched file title 03592 $title = $file->getTitle(); 03593 if ( is_null( $file->getRedirectedTitle() ) ) { 03594 # This file was not a redirect, but the title does not match. 03595 # Register under the new name because otherwise the link will 03596 # get lost. 03597 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 ); 03598 } 03599 } 03600 return array( $file, $title ); 03601 } 03602 03611 function interwikiTransclude( $title, $action ) { 03612 global $wgEnableScaryTranscluding; 03613 03614 if ( !$wgEnableScaryTranscluding ) { 03615 return wfMsgForContent('scarytranscludedisabled'); 03616 } 03617 03618 $url = $title->getFullUrl( "action=$action" ); 03619 03620 if ( strlen( $url ) > 255 ) { 03621 return wfMsgForContent( 'scarytranscludetoolong' ); 03622 } 03623 return $this->fetchScaryTemplateMaybeFromCache( $url ); 03624 } 03625 03630 function fetchScaryTemplateMaybeFromCache( $url ) { 03631 global $wgTranscludeCacheExpiry; 03632 $dbr = wfGetDB( DB_SLAVE ); 03633 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry ); 03634 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ), 03635 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) ); 03636 if ( $obj ) { 03637 return $obj->tc_contents; 03638 } 03639 03640 $text = Http::get( $url ); 03641 if ( !$text ) { 03642 return wfMsgForContent( 'scarytranscludefailed', $url ); 03643 } 03644 03645 $dbw = wfGetDB( DB_MASTER ); 03646 $dbw->replace( 'transcache', array('tc_url'), array( 03647 'tc_url' => $url, 03648 'tc_time' => $dbw->timestamp( time() ), 03649 'tc_contents' => $text) 03650 ); 03651 return $text; 03652 } 03653 03663 function argSubstitution( $piece, $frame ) { 03664 wfProfileIn( __METHOD__ ); 03665 03666 $error = false; 03667 $parts = $piece['parts']; 03668 $nameWithSpaces = $frame->expand( $piece['title'] ); 03669 $argName = trim( $nameWithSpaces ); 03670 $object = false; 03671 $text = $frame->getArgument( $argName ); 03672 if ( $text === false && $parts->getLength() > 0 03673 && ( 03674 $this->ot['html'] 03675 || $this->ot['pre'] 03676 || ( $this->ot['wiki'] && $frame->isTemplate() ) 03677 ) 03678 ) { 03679 # No match in frame, use the supplied default 03680 $object = $parts->item( 0 )->getChildren(); 03681 } 03682 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) { 03683 $error = '<!-- WARNING: argument omitted, expansion size too large -->'; 03684 $this->limitationWarn( 'post-expand-template-argument' ); 03685 } 03686 03687 if ( $text === false && $object === false ) { 03688 # No match anywhere 03689 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts ); 03690 } 03691 if ( $error !== false ) { 03692 $text .= $error; 03693 } 03694 if ( $object !== false ) { 03695 $ret = array( 'object' => $object ); 03696 } else { 03697 $ret = array( 'text' => $text ); 03698 } 03699 03700 wfProfileOut( __METHOD__ ); 03701 return $ret; 03702 } 03703 03718 function extensionSubstitution( $params, $frame ) { 03719 $name = $frame->expand( $params['name'] ); 03720 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] ); 03721 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] ); 03722 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX; 03723 03724 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) && 03725 ( $this->ot['html'] || $this->ot['pre'] ); 03726 if ( $isFunctionTag ) { 03727 $markerType = 'none'; 03728 } else { 03729 $markerType = 'general'; 03730 } 03731 if ( $this->ot['html'] || $isFunctionTag ) { 03732 $name = strtolower( $name ); 03733 $attributes = Sanitizer::decodeTagAttributes( $attrText ); 03734 if ( isset( $params['attributes'] ) ) { 03735 $attributes = $attributes + $params['attributes']; 03736 } 03737 03738 if ( isset( $this->mTagHooks[$name] ) ) { 03739 # Workaround for PHP bug 35229 and similar 03740 if ( !is_callable( $this->mTagHooks[$name] ) ) { 03741 throw new MWException( "Tag hook for $name is not callable\n" ); 03742 } 03743 $output = call_user_func_array( $this->mTagHooks[$name], 03744 array( $content, $attributes, $this, $frame ) ); 03745 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) { 03746 list( $callback, $flags ) = $this->mFunctionTagHooks[$name]; 03747 if ( !is_callable( $callback ) ) { 03748 throw new MWException( "Tag hook for $name is not callable\n" ); 03749 } 03750 03751 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) ); 03752 } else { 03753 $output = '<span class="error">Invalid tag extension name: ' . 03754 htmlspecialchars( $name ) . '</span>'; 03755 } 03756 03757 if ( is_array( $output ) ) { 03758 # Extract flags to local scope (to override $markerType) 03759 $flags = $output; 03760 $output = $flags[0]; 03761 unset( $flags[0] ); 03762 extract( $flags ); 03763 } 03764 } else { 03765 if ( is_null( $attrText ) ) { 03766 $attrText = ''; 03767 } 03768 if ( isset( $params['attributes'] ) ) { 03769 foreach ( $params['attributes'] as $attrName => $attrValue ) { 03770 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' . 03771 htmlspecialchars( $attrValue ) . '"'; 03772 } 03773 } 03774 if ( $content === null ) { 03775 $output = "<$name$attrText/>"; 03776 } else { 03777 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] ); 03778 $output = "<$name$attrText>$content$close"; 03779 } 03780 } 03781 03782 if ( $markerType === 'none' ) { 03783 return $output; 03784 } elseif ( $markerType === 'nowiki' ) { 03785 $this->mStripState->addNoWiki( $marker, $output ); 03786 } elseif ( $markerType === 'general' ) { 03787 $this->mStripState->addGeneral( $marker, $output ); 03788 } else { 03789 throw new MWException( __METHOD__.': invalid marker type' ); 03790 } 03791 return $marker; 03792 } 03793 03801 function incrementIncludeSize( $type, $size ) { 03802 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) { 03803 return false; 03804 } else { 03805 $this->mIncludeSizes[$type] += $size; 03806 return true; 03807 } 03808 } 03809 03815 function incrementExpensiveFunctionCount() { 03816 global $wgExpensiveParserFunctionLimit; 03817 $this->mExpensiveFunctionCount++; 03818 if ( $this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit ) { 03819 return true; 03820 } 03821 return false; 03822 } 03823 03832 function doDoubleUnderscore( $text ) { 03833 wfProfileIn( __METHOD__ ); 03834 03835 # The position of __TOC__ needs to be recorded 03836 $mw = MagicWord::get( 'toc' ); 03837 if ( $mw->match( $text ) ) { 03838 $this->mShowToc = true; 03839 $this->mForceTocPosition = true; 03840 03841 # Set a placeholder. At the end we'll fill it in with the TOC. 03842 $text = $mw->replace( '<!--MWTOC-->', $text, 1 ); 03843 03844 # Only keep the first one. 03845 $text = $mw->replace( '', $text ); 03846 } 03847 03848 # Now match and remove the rest of them 03849 $mwa = MagicWord::getDoubleUnderscoreArray(); 03850 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text ); 03851 03852 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) { 03853 $this->mOutput->mNoGallery = true; 03854 } 03855 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) { 03856 $this->mShowToc = false; 03857 } 03858 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) { 03859 $this->addTrackingCategory( 'hidden-category-category' ); 03860 } 03861 # (bug 8068) Allow control over whether robots index a page. 03862 # 03863 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This 03864 # is not desirable, the last one on the page should win. 03865 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) { 03866 $this->mOutput->setIndexPolicy( 'noindex' ); 03867 $this->addTrackingCategory( 'noindex-category' ); 03868 } 03869 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) { 03870 $this->mOutput->setIndexPolicy( 'index' ); 03871 $this->addTrackingCategory( 'index-category' ); 03872 } 03873 03874 # Cache all double underscores in the database 03875 foreach ( $this->mDoubleUnderscores as $key => $val ) { 03876 $this->mOutput->setProperty( $key, '' ); 03877 } 03878 03879 wfProfileOut( __METHOD__ ); 03880 return $text; 03881 } 03882 03890 public function addTrackingCategory( $msg ) { 03891 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) { 03892 wfDebug( __METHOD__.": Not adding tracking category $msg to special page!\n" ); 03893 return false; 03894 } 03895 // Important to parse with correct title (bug 31469) 03896 $cat = wfMessage( $msg ) 03897 ->title( $this->getTitle() ) 03898 ->inContentLanguage() 03899 ->text(); 03900 03901 # Allow tracking categories to be disabled by setting them to "-" 03902 if ( $cat === '-' ) { 03903 return false; 03904 } 03905 03906 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat ); 03907 if ( $containerCategory ) { 03908 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() ); 03909 return true; 03910 } else { 03911 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" ); 03912 return false; 03913 } 03914 } 03915 03931 function formatHeadings( $text, $origText, $isMain=true ) { 03932 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds; 03933 03934 # Inhibit editsection links if requested in the page 03935 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) { 03936 $maybeShowEditLink = $showEditLink = false; 03937 } else { 03938 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */ 03939 $showEditLink = $this->mOptions->getEditSection(); 03940 } 03941 if ( $showEditLink ) { 03942 $this->mOutput->setEditSectionTokens( true ); 03943 } 03944 03945 # Get all headlines for numbering them and adding funky stuff like [edit] 03946 # links - this is for later, but we need the number of headlines right now 03947 $matches = array(); 03948 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches ); 03949 03950 # if there are fewer than 4 headlines in the article, do not show TOC 03951 # unless it's been explicitly enabled. 03952 $enoughToc = $this->mShowToc && 03953 ( ( $numMatches >= 4 ) || $this->mForceTocPosition ); 03954 03955 # Allow user to stipulate that a page should have a "new section" 03956 # link added via __NEWSECTIONLINK__ 03957 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) { 03958 $this->mOutput->setNewSection( true ); 03959 } 03960 03961 # Allow user to remove the "new section" 03962 # link via __NONEWSECTIONLINK__ 03963 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) { 03964 $this->mOutput->hideNewSection( true ); 03965 } 03966 03967 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML, 03968 # override above conditions and always show TOC above first header 03969 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) { 03970 $this->mShowToc = true; 03971 $enoughToc = true; 03972 } 03973 03974 # headline counter 03975 $headlineCount = 0; 03976 $numVisible = 0; 03977 03978 # Ugh .. the TOC should have neat indentation levels which can be 03979 # passed to the skin functions. These are determined here 03980 $toc = ''; 03981 $full = ''; 03982 $head = array(); 03983 $sublevelCount = array(); 03984 $levelCount = array(); 03985 $level = 0; 03986 $prevlevel = 0; 03987 $toclevel = 0; 03988 $prevtoclevel = 0; 03989 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX; 03990 $baseTitleText = $this->mTitle->getPrefixedDBkey(); 03991 $oldType = $this->mOutputType; 03992 $this->setOutputType( self::OT_WIKI ); 03993 $frame = $this->getPreprocessor()->newFrame(); 03994 $root = $this->preprocessToDom( $origText ); 03995 $node = $root->getFirstChild(); 03996 $byteOffset = 0; 03997 $tocraw = array(); 03998 $refers = array(); 03999 04000 foreach ( $matches[3] as $headline ) { 04001 $isTemplate = false; 04002 $titleText = false; 04003 $sectionIndex = false; 04004 $numbering = ''; 04005 $markerMatches = array(); 04006 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) { 04007 $serial = $markerMatches[1]; 04008 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial]; 04009 $isTemplate = ( $titleText != $baseTitleText ); 04010 $headline = preg_replace( "/^$markerRegex/", "", $headline ); 04011 } 04012 04013 if ( $toclevel ) { 04014 $prevlevel = $level; 04015 } 04016 $level = $matches[1][$headlineCount]; 04017 04018 if ( $level > $prevlevel ) { 04019 # Increase TOC level 04020 $toclevel++; 04021 $sublevelCount[$toclevel] = 0; 04022 if ( $toclevel<$wgMaxTocLevel ) { 04023 $prevtoclevel = $toclevel; 04024 $toc .= Linker::tocIndent(); 04025 $numVisible++; 04026 } 04027 } elseif ( $level < $prevlevel && $toclevel > 1 ) { 04028 # Decrease TOC level, find level to jump to 04029 04030 for ( $i = $toclevel; $i > 0; $i-- ) { 04031 if ( $levelCount[$i] == $level ) { 04032 # Found last matching level 04033 $toclevel = $i; 04034 break; 04035 } elseif ( $levelCount[$i] < $level ) { 04036 # Found first matching level below current level 04037 $toclevel = $i + 1; 04038 break; 04039 } 04040 } 04041 if ( $i == 0 ) { 04042 $toclevel = 1; 04043 } 04044 if ( $toclevel<$wgMaxTocLevel ) { 04045 if ( $prevtoclevel < $wgMaxTocLevel ) { 04046 # Unindent only if the previous toc level was shown :p 04047 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel ); 04048 $prevtoclevel = $toclevel; 04049 } else { 04050 $toc .= Linker::tocLineEnd(); 04051 } 04052 } 04053 } else { 04054 # No change in level, end TOC line 04055 if ( $toclevel<$wgMaxTocLevel ) { 04056 $toc .= Linker::tocLineEnd(); 04057 } 04058 } 04059 04060 $levelCount[$toclevel] = $level; 04061 04062 # count number of headlines for each level 04063 @$sublevelCount[$toclevel]++; 04064 $dot = 0; 04065 for( $i = 1; $i <= $toclevel; $i++ ) { 04066 if ( !empty( $sublevelCount[$i] ) ) { 04067 if ( $dot ) { 04068 $numbering .= '.'; 04069 } 04070 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] ); 04071 $dot = 1; 04072 } 04073 } 04074 04075 # The safe header is a version of the header text safe to use for links 04076 04077 # Remove link placeholders by the link text. 04078 # <!--LINK number--> 04079 # turns into 04080 # link text with suffix 04081 # Do this before unstrip since link text can contain strip markers 04082 $safeHeadline = $this->replaceLinkHoldersText( $headline ); 04083 04084 # Avoid insertion of weird stuff like <math> by expanding the relevant sections 04085 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline ); 04086 04087 # Strip out HTML (first regex removes any tag not allowed) 04088 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284) 04089 # We strip any parameter from accepted tags (second regex) 04090 $tocline = preg_replace( 04091 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ), 04092 array( '', '<$1>' ), 04093 $safeHeadline 04094 ); 04095 $tocline = trim( $tocline ); 04096 04097 # For the anchor, strip out HTML-y stuff period 04098 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline ); 04099 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline ); 04100 04101 # Save headline for section edit hint before it's escaped 04102 $headlineHint = $safeHeadline; 04103 04104 if ( $wgHtml5 && $wgExperimentalHtmlIds ) { 04105 # For reverse compatibility, provide an id that's 04106 # HTML4-compatible, like we used to. 04107 # 04108 # It may be worth noting, academically, that it's possible for 04109 # the legacy anchor to conflict with a non-legacy headline 04110 # anchor on the page. In this case likely the "correct" thing 04111 # would be to either drop the legacy anchors or make sure 04112 # they're numbered first. However, this would require people 04113 # to type in section names like "abc_.D7.93.D7.90.D7.A4" 04114 # manually, so let's not bother worrying about it. 04115 $legacyHeadline = Sanitizer::escapeId( $safeHeadline, 04116 array( 'noninitial', 'legacy' ) ); 04117 $safeHeadline = Sanitizer::escapeId( $safeHeadline ); 04118 04119 if ( $legacyHeadline == $safeHeadline ) { 04120 # No reason to have both (in fact, we can't) 04121 $legacyHeadline = false; 04122 } 04123 } else { 04124 $legacyHeadline = false; 04125 $safeHeadline = Sanitizer::escapeId( $safeHeadline, 04126 'noninitial' ); 04127 } 04128 04129 # HTML names must be case-insensitively unique (bug 10721). 04130 # This does not apply to Unicode characters per 04131 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison 04132 # @todo FIXME: We may be changing them depending on the current locale. 04133 $arrayKey = strtolower( $safeHeadline ); 04134 if ( $legacyHeadline === false ) { 04135 $legacyArrayKey = false; 04136 } else { 04137 $legacyArrayKey = strtolower( $legacyHeadline ); 04138 } 04139 04140 # count how many in assoc. array so we can track dupes in anchors 04141 if ( isset( $refers[$arrayKey] ) ) { 04142 $refers[$arrayKey]++; 04143 } else { 04144 $refers[$arrayKey] = 1; 04145 } 04146 if ( isset( $refers[$legacyArrayKey] ) ) { 04147 $refers[$legacyArrayKey]++; 04148 } else { 04149 $refers[$legacyArrayKey] = 1; 04150 } 04151 04152 # Don't number the heading if it is the only one (looks silly) 04153 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) { 04154 # the two are different if the line contains a link 04155 $headline = $numbering . ' ' . $headline; 04156 } 04157 04158 # Create the anchor for linking from the TOC to the section 04159 $anchor = $safeHeadline; 04160 $legacyAnchor = $legacyHeadline; 04161 if ( $refers[$arrayKey] > 1 ) { 04162 $anchor .= '_' . $refers[$arrayKey]; 04163 } 04164 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) { 04165 $legacyAnchor .= '_' . $refers[$legacyArrayKey]; 04166 } 04167 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) { 04168 $toc .= Linker::tocLine( $anchor, $tocline, 04169 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) ); 04170 } 04171 04172 # Add the section to the section tree 04173 # Find the DOM node for this header 04174 while ( $node && !$isTemplate ) { 04175 if ( $node->getName() === 'h' ) { 04176 $bits = $node->splitHeading(); 04177 if ( $bits['i'] == $sectionIndex ) { 04178 break; 04179 } 04180 } 04181 $byteOffset += mb_strlen( $this->mStripState->unstripBoth( 04182 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) ); 04183 $node = $node->getNextSibling(); 04184 } 04185 $tocraw[] = array( 04186 'toclevel' => $toclevel, 04187 'level' => $level, 04188 'line' => $tocline, 04189 'number' => $numbering, 04190 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex, 04191 'fromtitle' => $titleText, 04192 'byteoffset' => ( $isTemplate ? null : $byteOffset ), 04193 'anchor' => $anchor, 04194 ); 04195 04196 # give headline the correct <h#> tag 04197 if ( $maybeShowEditLink && $sectionIndex !== false ) { 04198 // Output edit section links as markers with styles that can be customized by skins 04199 if ( $isTemplate ) { 04200 # Put a T flag in the section identifier, to indicate to extractSections() 04201 # that sections inside <includeonly> should be counted. 04202 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ ); 04203 } else { 04204 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint ); 04205 } 04206 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on 04207 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff 04208 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped 04209 // so we don't have to worry about a user trying to input one of these markers directly. 04210 // We use a page and section attribute to stop the language converter from converting these important bits 04211 // of data, but put the headline hint inside a content block because the language converter is supposed to 04212 // be able to convert that piece of data. 04213 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]); 04214 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"'; 04215 if ( isset($editlinkArgs[2]) ) { 04216 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>'; 04217 } else { 04218 $editlink .= '/>'; 04219 } 04220 } else { 04221 $editlink = ''; 04222 } 04223 $head[$headlineCount] = Linker::makeHeadline( $level, 04224 $matches['attrib'][$headlineCount], $anchor, $headline, 04225 $editlink, $legacyAnchor ); 04226 04227 $headlineCount++; 04228 } 04229 04230 $this->setOutputType( $oldType ); 04231 04232 # Never ever show TOC if no headers 04233 if ( $numVisible < 1 ) { 04234 $enoughToc = false; 04235 } 04236 04237 if ( $enoughToc ) { 04238 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) { 04239 $toc .= Linker::tocUnindent( $prevtoclevel - 1 ); 04240 } 04241 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() ); 04242 $this->mOutput->setTOCHTML( $toc ); 04243 } 04244 04245 if ( $isMain ) { 04246 $this->mOutput->setSections( $tocraw ); 04247 } 04248 04249 # split up and insert constructed headlines 04250 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text ); 04251 $i = 0; 04252 04253 // build an array of document sections 04254 $sections = array(); 04255 foreach ( $blocks as $block ) { 04256 // $head is zero-based, sections aren't. 04257 if ( empty( $head[$i - 1] ) ) { 04258 $sections[$i] = $block; 04259 } else { 04260 $sections[$i] = $head[$i - 1] . $block; 04261 } 04262 04273 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) ); 04274 04275 $i++; 04276 } 04277 04278 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) { 04279 // append the TOC at the beginning 04280 // Top anchor now in skin 04281 $sections[0] = $sections[0] . $toc . "\n"; 04282 } 04283 04284 $full .= join( '', $sections ); 04285 04286 if ( $this->mForceTocPosition ) { 04287 return str_replace( '<!--MWTOC-->', $toc, $full ); 04288 } else { 04289 return $full; 04290 } 04291 } 04292 04304 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) { 04305 $this->startParse( $title, $options, self::OT_WIKI, $clearState ); 04306 $this->setUser( $user ); 04307 04308 $pairs = array( 04309 "\r\n" => "\n", 04310 ); 04311 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text ); 04312 if( $options->getPreSaveTransform() ) { 04313 $text = $this->pstPass2( $text, $user ); 04314 } 04315 $text = $this->mStripState->unstripBoth( $text ); 04316 04317 $this->setUser( null ); #Reset 04318 04319 return $text; 04320 } 04321 04331 function pstPass2( $text, $user ) { 04332 global $wgContLang, $wgLocaltimezone; 04333 04334 # Note: This is the timestamp saved as hardcoded wikitext to 04335 # the database, we use $wgContLang here in order to give 04336 # everyone the same signature and use the default one rather 04337 # than the one selected in each user's preferences. 04338 # (see also bug 12815) 04339 $ts = $this->mOptions->getTimestamp(); 04340 if ( isset( $wgLocaltimezone ) ) { 04341 $tz = $wgLocaltimezone; 04342 } else { 04343 $tz = date_default_timezone_get(); 04344 } 04345 04346 $unixts = wfTimestamp( TS_UNIX, $ts ); 04347 $oldtz = date_default_timezone_get(); 04348 date_default_timezone_set( $tz ); 04349 $ts = date( 'YmdHis', $unixts ); 04350 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover! 04351 04352 # Allow translation of timezones through wiki. date() can return 04353 # whatever crap the system uses, localised or not, so we cannot 04354 # ship premade translations. 04355 $key = 'timezone-' . strtolower( trim( $tzMsg ) ); 04356 $msg = wfMessage( $key )->inContentLanguage(); 04357 if ( $msg->exists() ) { 04358 $tzMsg = $msg->text(); 04359 } 04360 04361 date_default_timezone_set( $oldtz ); 04362 04363 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)"; 04364 04365 # Variable replacement 04366 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags 04367 $text = $this->replaceVariables( $text ); 04368 04369 # This works almost by chance, as the replaceVariables are done before the getUserSig(), 04370 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call- 04371 04372 # Signatures 04373 $sigText = $this->getUserSig( $user ); 04374 $text = strtr( $text, array( 04375 '~~~~~' => $d, 04376 '~~~~' => "$sigText $d", 04377 '~~~' => $sigText 04378 ) ); 04379 04380 # Context links: [[|name]] and [[name (context)|]] 04381 global $wgLegalTitleChars; 04382 $tc = "[$wgLegalTitleChars]"; 04383 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii! 04384 04385 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]] 04386 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] 04387 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]] 04388 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] 04389 04390 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]" 04391 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text ); 04392 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text ); 04393 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text ); 04394 04395 $t = $this->mTitle->getText(); 04396 $m = array(); 04397 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) { 04398 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text ); 04399 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) { 04400 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text ); 04401 } else { 04402 # if there's no context, don't bother duplicating the title 04403 $text = preg_replace( $p2, '[[\\1]]', $text ); 04404 } 04405 04406 # Trim trailing whitespace 04407 $text = rtrim( $text ); 04408 04409 return $text; 04410 } 04411 04426 function getUserSig( &$user, $nickname = false, $fancySig = null ) { 04427 global $wgMaxSigChars; 04428 04429 $username = $user->getName(); 04430 04431 # If not given, retrieve from the user object. 04432 if ( $nickname === false ) 04433 $nickname = $user->getOption( 'nickname' ); 04434 04435 if ( is_null( $fancySig ) ) { 04436 $fancySig = $user->getBoolOption( 'fancysig' ); 04437 } 04438 04439 $nickname = $nickname == null ? $username : $nickname; 04440 04441 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) { 04442 $nickname = $username; 04443 wfDebug( __METHOD__ . ": $username has overlong signature.\n" ); 04444 } elseif ( $fancySig !== false ) { 04445 # Sig. might contain markup; validate this 04446 if ( $this->validateSig( $nickname ) !== false ) { 04447 # Validated; clean up (if needed) and return it 04448 return $this->cleanSig( $nickname, true ); 04449 } else { 04450 # Failed to validate; fall back to the default 04451 $nickname = $username; 04452 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" ); 04453 } 04454 } 04455 04456 # Make sure nickname doesnt get a sig in a sig 04457 $nickname = self::cleanSigInSig( $nickname ); 04458 04459 # If we're still here, make it a link to the user page 04460 $userText = wfEscapeWikiText( $username ); 04461 $nickText = wfEscapeWikiText( $nickname ); 04462 $msgName = $user->isAnon() ? 'signature-anon' : 'signature'; 04463 04464 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text(); 04465 } 04466 04473 function validateSig( $text ) { 04474 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false ); 04475 } 04476 04487 public function cleanSig( $text, $parsing = false ) { 04488 if ( !$parsing ) { 04489 global $wgTitle; 04490 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true ); 04491 } 04492 04493 # Option to disable this feature 04494 if ( !$this->mOptions->getCleanSignatures() ) { 04495 return $text; 04496 } 04497 04498 # @todo FIXME: Regex doesn't respect extension tags or nowiki 04499 # => Move this logic to braceSubstitution() 04500 $substWord = MagicWord::get( 'subst' ); 04501 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase(); 04502 $substText = '{{' . $substWord->getSynonym( 0 ); 04503 04504 $text = preg_replace( $substRegex, $substText, $text ); 04505 $text = self::cleanSigInSig( $text ); 04506 $dom = $this->preprocessToDom( $text ); 04507 $frame = $this->getPreprocessor()->newFrame(); 04508 $text = $frame->expand( $dom ); 04509 04510 if ( !$parsing ) { 04511 $text = $this->mStripState->unstripBoth( $text ); 04512 } 04513 04514 return $text; 04515 } 04516 04523 public static function cleanSigInSig( $text ) { 04524 $text = preg_replace( '/~{3,5}/', '', $text ); 04525 return $text; 04526 } 04527 04537 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) { 04538 $this->startParse( $title, $options, $outputType, $clearState ); 04539 } 04540 04547 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) { 04548 $this->setTitle( $title ); 04549 $this->mOptions = $options; 04550 $this->setOutputType( $outputType ); 04551 if ( $clearState ) { 04552 $this->clearState(); 04553 } 04554 } 04555 04564 public function transformMsg( $text, $options, $title = null ) { 04565 static $executing = false; 04566 04567 # Guard against infinite recursion 04568 if ( $executing ) { 04569 return $text; 04570 } 04571 $executing = true; 04572 04573 wfProfileIn( __METHOD__ ); 04574 if ( !$title ) { 04575 global $wgTitle; 04576 $title = $wgTitle; 04577 } 04578 if ( !$title ) { 04579 # It's not uncommon having a null $wgTitle in scripts. See r80898 04580 # Create a ghost title in such case 04581 $title = Title::newFromText( 'Dwimmerlaik' ); 04582 } 04583 $text = $this->preprocess( $text, $title, $options ); 04584 04585 $executing = false; 04586 wfProfileOut( __METHOD__ ); 04587 return $text; 04588 } 04589 04613 public function setHook( $tag, $callback ) { 04614 $tag = strtolower( $tag ); 04615 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" ); 04616 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null; 04617 $this->mTagHooks[$tag] = $callback; 04618 if ( !in_array( $tag, $this->mStripList ) ) { 04619 $this->mStripList[] = $tag; 04620 } 04621 04622 return $oldVal; 04623 } 04624 04641 function setTransparentTagHook( $tag, $callback ) { 04642 $tag = strtolower( $tag ); 04643 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" ); 04644 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null; 04645 $this->mTransparentTagHooks[$tag] = $callback; 04646 04647 return $oldVal; 04648 } 04649 04653 function clearTagHooks() { 04654 $this->mTagHooks = array(); 04655 $this->mFunctionTagHooks = array(); 04656 $this->mStripList = $this->mDefaultStripList; 04657 } 04658 04701 public function setFunctionHook( $id, $callback, $flags = 0 ) { 04702 global $wgContLang; 04703 04704 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null; 04705 $this->mFunctionHooks[$id] = array( $callback, $flags ); 04706 04707 # Add to function cache 04708 $mw = MagicWord::get( $id ); 04709 if ( !$mw ) 04710 throw new MWException( __METHOD__.'() expecting a magic word identifier.' ); 04711 04712 $synonyms = $mw->getSynonyms(); 04713 $sensitive = intval( $mw->isCaseSensitive() ); 04714 04715 foreach ( $synonyms as $syn ) { 04716 # Case 04717 if ( !$sensitive ) { 04718 $syn = $wgContLang->lc( $syn ); 04719 } 04720 # Add leading hash 04721 if ( !( $flags & SFH_NO_HASH ) ) { 04722 $syn = '#' . $syn; 04723 } 04724 # Remove trailing colon 04725 if ( substr( $syn, -1, 1 ) === ':' ) { 04726 $syn = substr( $syn, 0, -1 ); 04727 } 04728 $this->mFunctionSynonyms[$sensitive][$syn] = $id; 04729 } 04730 return $oldVal; 04731 } 04732 04738 function getFunctionHooks() { 04739 return array_keys( $this->mFunctionHooks ); 04740 } 04741 04747 function setFunctionTagHook( $tag, $callback, $flags ) { 04748 $tag = strtolower( $tag ); 04749 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" ); 04750 $old = isset( $this->mFunctionTagHooks[$tag] ) ? 04751 $this->mFunctionTagHooks[$tag] : null; 04752 $this->mFunctionTagHooks[$tag] = array( $callback, $flags ); 04753 04754 if ( !in_array( $tag, $this->mStripList ) ) { 04755 $this->mStripList[] = $tag; 04756 } 04757 04758 return $old; 04759 } 04760 04771 function replaceLinkHolders( &$text, $options = 0 ) { 04772 return $this->mLinkHolders->replace( $text ); 04773 } 04774 04782 function replaceLinkHoldersText( $text ) { 04783 return $this->mLinkHolders->replaceText( $text ); 04784 } 04785 04799 function renderImageGallery( $text, $params ) { 04800 $ig = new ImageGallery(); 04801 $ig->setContextTitle( $this->mTitle ); 04802 $ig->setShowBytes( false ); 04803 $ig->setShowFilename( false ); 04804 $ig->setParser( $this ); 04805 $ig->setHideBadImages(); 04806 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) ); 04807 04808 if ( isset( $params['showfilename'] ) ) { 04809 $ig->setShowFilename( true ); 04810 } else { 04811 $ig->setShowFilename( false ); 04812 } 04813 if ( isset( $params['caption'] ) ) { 04814 $caption = $params['caption']; 04815 $caption = htmlspecialchars( $caption ); 04816 $caption = $this->replaceInternalLinks( $caption ); 04817 $ig->setCaptionHtml( $caption ); 04818 } 04819 if ( isset( $params['perrow'] ) ) { 04820 $ig->setPerRow( $params['perrow'] ); 04821 } 04822 if ( isset( $params['widths'] ) ) { 04823 $ig->setWidths( $params['widths'] ); 04824 } 04825 if ( isset( $params['heights'] ) ) { 04826 $ig->setHeights( $params['heights'] ); 04827 } 04828 04829 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) ); 04830 04831 $lines = StringUtils::explode( "\n", $text ); 04832 foreach ( $lines as $line ) { 04833 # match lines like these: 04834 # Image:someimage.jpg|This is some image 04835 $matches = array(); 04836 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches ); 04837 # Skip empty lines 04838 if ( count( $matches ) == 0 ) { 04839 continue; 04840 } 04841 04842 if ( strpos( $matches[0], '%' ) !== false ) { 04843 $matches[1] = rawurldecode( $matches[1] ); 04844 } 04845 $title = Title::newFromText( $matches[1], NS_FILE ); 04846 if ( is_null( $title ) ) { 04847 # Bogus title. Ignore these so we don't bomb out later. 04848 continue; 04849 } 04850 04851 $label = ''; 04852 $alt = ''; 04853 if ( isset( $matches[3] ) ) { 04854 // look for an |alt= definition while trying not to break existing 04855 // captions with multiple pipes (|) in it, until a more sensible grammar 04856 // is defined for images in galleries 04857 04858 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) ); 04859 $altmatches = StringUtils::explode('|', $matches[3]); 04860 $magicWordAlt = MagicWord::get( 'img_alt' ); 04861 04862 foreach ( $altmatches as $altmatch ) { 04863 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch ); 04864 if ( $match ) { 04865 $alt = $this->stripAltText( $match, false ); 04866 } 04867 else { 04868 // concatenate all other pipes 04869 $label .= '|' . $altmatch; 04870 } 04871 } 04872 // remove the first pipe 04873 $label = substr( $label, 1 ); 04874 } 04875 04876 $ig->add( $title, $label, $alt ); 04877 } 04878 return $ig->toHTML(); 04879 } 04880 04885 function getImageParams( $handler ) { 04886 if ( $handler ) { 04887 $handlerClass = get_class( $handler ); 04888 } else { 04889 $handlerClass = ''; 04890 } 04891 if ( !isset( $this->mImageParams[$handlerClass] ) ) { 04892 # Initialise static lists 04893 static $internalParamNames = array( 04894 'horizAlign' => array( 'left', 'right', 'center', 'none' ), 04895 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 04896 'bottom', 'text-bottom' ), 04897 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless', 04898 'upright', 'border', 'link', 'alt' ), 04899 ); 04900 static $internalParamMap; 04901 if ( !$internalParamMap ) { 04902 $internalParamMap = array(); 04903 foreach ( $internalParamNames as $type => $names ) { 04904 foreach ( $names as $name ) { 04905 $magicName = str_replace( '-', '_', "img_$name" ); 04906 $internalParamMap[$magicName] = array( $type, $name ); 04907 } 04908 } 04909 } 04910 04911 # Add handler params 04912 $paramMap = $internalParamMap; 04913 if ( $handler ) { 04914 $handlerParamMap = $handler->getParamMap(); 04915 foreach ( $handlerParamMap as $magic => $paramName ) { 04916 $paramMap[$magic] = array( 'handler', $paramName ); 04917 } 04918 } 04919 $this->mImageParams[$handlerClass] = $paramMap; 04920 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) ); 04921 } 04922 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ); 04923 } 04924 04933 function makeImage( $title, $options, $holders = false ) { 04934 # Check if the options text is of the form "options|alt text" 04935 # Options are: 04936 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang 04937 # * left no resizing, just left align. label is used for alt= only 04938 # * right same, but right aligned 04939 # * none same, but not aligned 04940 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox 04941 # * center center the image 04942 # * frame Keep original image size, no magnify-button. 04943 # * framed Same as "frame" 04944 # * frameless like 'thumb' but without a frame. Keeps user preferences for width 04945 # * upright reduce width for upright images, rounded to full __0 px 04946 # * border draw a 1px border around the image 04947 # * alt Text for HTML alt attribute (defaults to empty) 04948 # * link Set the target of the image link. Can be external, interwiki, or local 04949 # vertical-align values (no % or length right now): 04950 # * baseline 04951 # * sub 04952 # * super 04953 # * top 04954 # * text-top 04955 # * middle 04956 # * bottom 04957 # * text-bottom 04958 04959 $parts = StringUtils::explode( "|", $options ); 04960 04961 # Give extensions a chance to select the file revision for us 04962 $options = array(); 04963 $descQuery = false; 04964 wfRunHooks( 'BeforeParserFetchFileAndTitle', 04965 array( $this, $title, &$options, &$descQuery ) ); 04966 # Fetch and register the file (file title may be different via hooks) 04967 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options ); 04968 04969 # Get parameter map 04970 $handler = $file ? $file->getHandler() : false; 04971 04972 list( $paramMap, $mwArray ) = $this->getImageParams( $handler ); 04973 04974 if ( !$file ) { 04975 $this->addTrackingCategory( 'broken-file-category' ); 04976 } 04977 04978 # Process the input parameters 04979 $caption = ''; 04980 $params = array( 'frame' => array(), 'handler' => array(), 04981 'horizAlign' => array(), 'vertAlign' => array() ); 04982 foreach ( $parts as $part ) { 04983 $part = trim( $part ); 04984 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part ); 04985 $validated = false; 04986 if ( isset( $paramMap[$magicName] ) ) { 04987 list( $type, $paramName ) = $paramMap[$magicName]; 04988 04989 # Special case; width and height come in one variable together 04990 if ( $type === 'handler' && $paramName === 'width' ) { 04991 $m = array(); 04992 # (bug 13500) In both cases (width/height and width only), 04993 # permit trailing "px" for backward compatibility. 04994 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) { 04995 $width = intval( $m[1] ); 04996 $height = intval( $m[2] ); 04997 if ( $handler->validateParam( 'width', $width ) ) { 04998 $params[$type]['width'] = $width; 04999 $validated = true; 05000 } 05001 if ( $handler->validateParam( 'height', $height ) ) { 05002 $params[$type]['height'] = $height; 05003 $validated = true; 05004 } 05005 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) { 05006 $width = intval( $value ); 05007 if ( $handler->validateParam( 'width', $width ) ) { 05008 $params[$type]['width'] = $width; 05009 $validated = true; 05010 } 05011 } # else no validation -- bug 13436 05012 } else { 05013 if ( $type === 'handler' ) { 05014 # Validate handler parameter 05015 $validated = $handler->validateParam( $paramName, $value ); 05016 } else { 05017 # Validate internal parameters 05018 switch( $paramName ) { 05019 case 'manualthumb': 05020 case 'alt': 05021 # @todo FIXME: Possibly check validity here for 05022 # manualthumb? downstream behavior seems odd with 05023 # missing manual thumbs. 05024 $validated = true; 05025 $value = $this->stripAltText( $value, $holders ); 05026 break; 05027 case 'link': 05028 $chars = self::EXT_LINK_URL_CLASS; 05029 $prots = $this->mUrlProtocols; 05030 if ( $value === '' ) { 05031 $paramName = 'no-link'; 05032 $value = true; 05033 $validated = true; 05034 } elseif ( preg_match( "/^$prots/", $value ) ) { 05035 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) { 05036 $paramName = 'link-url'; 05037 $this->mOutput->addExternalLink( $value ); 05038 if ( $this->mOptions->getExternalLinkTarget() ) { 05039 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget(); 05040 } 05041 $validated = true; 05042 } 05043 } else { 05044 $linkTitle = Title::newFromText( $value ); 05045 if ( $linkTitle ) { 05046 $paramName = 'link-title'; 05047 $value = $linkTitle; 05048 $this->mOutput->addLink( $linkTitle ); 05049 $validated = true; 05050 } 05051 } 05052 break; 05053 default: 05054 # Most other things appear to be empty or numeric... 05055 $validated = ( $value === false || is_numeric( trim( $value ) ) ); 05056 } 05057 } 05058 05059 if ( $validated ) { 05060 $params[$type][$paramName] = $value; 05061 } 05062 } 05063 } 05064 if ( !$validated ) { 05065 $caption = $part; 05066 } 05067 } 05068 05069 # Process alignment parameters 05070 if ( $params['horizAlign'] ) { 05071 $params['frame']['align'] = key( $params['horizAlign'] ); 05072 } 05073 if ( $params['vertAlign'] ) { 05074 $params['frame']['valign'] = key( $params['vertAlign'] ); 05075 } 05076 05077 $params['frame']['caption'] = $caption; 05078 05079 # Will the image be presented in a frame, with the caption below? 05080 $imageIsFramed = isset( $params['frame']['frame'] ) || 05081 isset( $params['frame']['framed'] ) || 05082 isset( $params['frame']['thumbnail'] ) || 05083 isset( $params['frame']['manualthumb'] ); 05084 05085 # In the old days, [[Image:Foo|text...]] would set alt text. Later it 05086 # came to also set the caption, ordinary text after the image -- which 05087 # makes no sense, because that just repeats the text multiple times in 05088 # screen readers. It *also* came to set the title attribute. 05089 # 05090 # Now that we have an alt attribute, we should not set the alt text to 05091 # equal the caption: that's worse than useless, it just repeats the 05092 # text. This is the framed/thumbnail case. If there's no caption, we 05093 # use the unnamed parameter for alt text as well, just for the time be- 05094 # ing, if the unnamed param is set and the alt param is not. 05095 # 05096 # For the future, we need to figure out if we want to tweak this more, 05097 # e.g., introducing a title= parameter for the title; ignoring the un- 05098 # named parameter entirely for images without a caption; adding an ex- 05099 # plicit caption= parameter and preserving the old magic unnamed para- 05100 # meter for BC; ... 05101 if ( $imageIsFramed ) { # Framed image 05102 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) { 05103 # No caption or alt text, add the filename as the alt text so 05104 # that screen readers at least get some description of the image 05105 $params['frame']['alt'] = $title->getText(); 05106 } 05107 # Do not set $params['frame']['title'] because tooltips don't make sense 05108 # for framed images 05109 } else { # Inline image 05110 if ( !isset( $params['frame']['alt'] ) ) { 05111 # No alt text, use the "caption" for the alt text 05112 if ( $caption !== '') { 05113 $params['frame']['alt'] = $this->stripAltText( $caption, $holders ); 05114 } else { 05115 # No caption, fall back to using the filename for the 05116 # alt text 05117 $params['frame']['alt'] = $title->getText(); 05118 } 05119 } 05120 # Use the "caption" for the tooltip text 05121 $params['frame']['title'] = $this->stripAltText( $caption, $holders ); 05122 } 05123 05124 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) ); 05125 05126 # Linker does the rest 05127 $time = isset( $options['time'] ) ? $options['time'] : false; 05128 $ret = Linker::makeImageLink2( $title, $file, $params['frame'], $params['handler'], 05129 $time, $descQuery, $this->mOptions->getThumbSize() ); 05130 05131 # Give the handler a chance to modify the parser object 05132 if ( $handler ) { 05133 $handler->parserTransformHook( $this, $file ); 05134 } 05135 05136 return $ret; 05137 } 05138 05144 protected function stripAltText( $caption, $holders ) { 05145 # Strip bad stuff out of the title (tooltip). We can't just use 05146 # replaceLinkHoldersText() here, because if this function is called 05147 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date. 05148 if ( $holders ) { 05149 $tooltip = $holders->replaceText( $caption ); 05150 } else { 05151 $tooltip = $this->replaceLinkHoldersText( $caption ); 05152 } 05153 05154 # make sure there are no placeholders in thumbnail attributes 05155 # that are later expanded to html- so expand them now and 05156 # remove the tags 05157 $tooltip = $this->mStripState->unstripBoth( $tooltip ); 05158 $tooltip = Sanitizer::stripAllTags( $tooltip ); 05159 05160 return $tooltip; 05161 } 05162 05167 function disableCache() { 05168 wfDebug( "Parser output marked as uncacheable.\n" ); 05169 if ( !$this->mOutput ) { 05170 throw new MWException( __METHOD__ . 05171 " can only be called when actually parsing something" ); 05172 } 05173 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility 05174 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency 05175 } 05176 05185 function attributeStripCallback( &$text, $frame = false ) { 05186 $text = $this->replaceVariables( $text, $frame ); 05187 $text = $this->mStripState->unstripBoth( $text ); 05188 return $text; 05189 } 05190 05196 function getTags() { 05197 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) ); 05198 } 05199 05210 function replaceTransparentTags( $text ) { 05211 $matches = array(); 05212 $elements = array_keys( $this->mTransparentTagHooks ); 05213 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix ); 05214 $replacements = array(); 05215 05216 foreach ( $matches as $marker => $data ) { 05217 list( $element, $content, $params, $tag ) = $data; 05218 $tagName = strtolower( $element ); 05219 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) { 05220 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) ); 05221 } else { 05222 $output = $tag; 05223 } 05224 $replacements[$marker] = $output; 05225 } 05226 return strtr( $text, $replacements ); 05227 } 05228 05258 private function extractSections( $text, $section, $mode, $newText='' ) { 05259 global $wgTitle; # not generally used but removes an ugly failure mode 05260 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true ); 05261 $outText = ''; 05262 $frame = $this->getPreprocessor()->newFrame(); 05263 05264 # Process section extraction flags 05265 $flags = 0; 05266 $sectionParts = explode( '-', $section ); 05267 $sectionIndex = array_pop( $sectionParts ); 05268 foreach ( $sectionParts as $part ) { 05269 if ( $part === 'T' ) { 05270 $flags |= self::PTD_FOR_INCLUSION; 05271 } 05272 } 05273 05274 # Check for empty input 05275 if ( strval( $text ) === '' ) { 05276 # Only sections 0 and T-0 exist in an empty document 05277 if ( $sectionIndex == 0 ) { 05278 if ( $mode === 'get' ) { 05279 return ''; 05280 } else { 05281 return $newText; 05282 } 05283 } else { 05284 if ( $mode === 'get' ) { 05285 return $newText; 05286 } else { 05287 return $text; 05288 } 05289 } 05290 } 05291 05292 # Preprocess the text 05293 $root = $this->preprocessToDom( $text, $flags ); 05294 05295 # <h> nodes indicate section breaks 05296 # They can only occur at the top level, so we can find them by iterating the root's children 05297 $node = $root->getFirstChild(); 05298 05299 # Find the target section 05300 if ( $sectionIndex == 0 ) { 05301 # Section zero doesn't nest, level=big 05302 $targetLevel = 1000; 05303 } else { 05304 while ( $node ) { 05305 if ( $node->getName() === 'h' ) { 05306 $bits = $node->splitHeading(); 05307 if ( $bits['i'] == $sectionIndex ) { 05308 $targetLevel = $bits['level']; 05309 break; 05310 } 05311 } 05312 if ( $mode === 'replace' ) { 05313 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 05314 } 05315 $node = $node->getNextSibling(); 05316 } 05317 } 05318 05319 if ( !$node ) { 05320 # Not found 05321 if ( $mode === 'get' ) { 05322 return $newText; 05323 } else { 05324 return $text; 05325 } 05326 } 05327 05328 # Find the end of the section, including nested sections 05329 do { 05330 if ( $node->getName() === 'h' ) { 05331 $bits = $node->splitHeading(); 05332 $curLevel = $bits['level']; 05333 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) { 05334 break; 05335 } 05336 } 05337 if ( $mode === 'get' ) { 05338 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 05339 } 05340 $node = $node->getNextSibling(); 05341 } while ( $node ); 05342 05343 # Write out the remainder (in replace mode only) 05344 if ( $mode === 'replace' ) { 05345 # Output the replacement text 05346 # Add two newlines on -- trailing whitespace in $newText is conventionally 05347 # stripped by the editor, so we need both newlines to restore the paragraph gap 05348 # Only add trailing whitespace if there is newText 05349 if ( $newText != "" ) { 05350 $outText .= $newText . "\n\n"; 05351 } 05352 05353 while ( $node ) { 05354 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 05355 $node = $node->getNextSibling(); 05356 } 05357 } 05358 05359 if ( is_string( $outText ) ) { 05360 # Re-insert stripped tags 05361 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) ); 05362 } 05363 05364 return $outText; 05365 } 05366 05379 public function getSection( $text, $section, $deftext='' ) { 05380 return $this->extractSections( $text, $section, "get", $deftext ); 05381 } 05382 05393 public function replaceSection( $oldtext, $section, $text ) { 05394 return $this->extractSections( $oldtext, $section, "replace", $text ); 05395 } 05396 05402 function getRevisionId() { 05403 return $this->mRevisionId; 05404 } 05405 05411 protected function getRevisionObject() { 05412 if ( !is_null( $this->mRevisionObject ) ) { 05413 return $this->mRevisionObject; 05414 } 05415 if ( is_null( $this->mRevisionId ) ) { 05416 return null; 05417 } 05418 05419 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId ); 05420 return $this->mRevisionObject; 05421 } 05422 05427 function getRevisionTimestamp() { 05428 if ( is_null( $this->mRevisionTimestamp ) ) { 05429 wfProfileIn( __METHOD__ ); 05430 05431 global $wgContLang; 05432 05433 $revObject = $this->getRevisionObject(); 05434 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow(); 05435 05436 # The cryptic '' timezone parameter tells to use the site-default 05437 # timezone offset instead of the user settings. 05438 # 05439 # Since this value will be saved into the parser cache, served 05440 # to other users, and potentially even used inside links and such, 05441 # it needs to be consistent for all visitors. 05442 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' ); 05443 05444 wfProfileOut( __METHOD__ ); 05445 } 05446 return $this->mRevisionTimestamp; 05447 } 05448 05454 function getRevisionUser() { 05455 if( is_null( $this->mRevisionUser ) ) { 05456 $revObject = $this->getRevisionObject(); 05457 05458 # if this template is subst: the revision id will be blank, 05459 # so just use the current user's name 05460 if( $revObject ) { 05461 $this->mRevisionUser = $revObject->getUserText(); 05462 } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) { 05463 $this->mRevisionUser = $this->getUser()->getName(); 05464 } 05465 } 05466 return $this->mRevisionUser; 05467 } 05468 05474 public function setDefaultSort( $sort ) { 05475 $this->mDefaultSort = $sort; 05476 $this->mOutput->setProperty( 'defaultsort', $sort ); 05477 } 05478 05489 public function getDefaultSort() { 05490 if ( $this->mDefaultSort !== false ) { 05491 return $this->mDefaultSort; 05492 } else { 05493 return ''; 05494 } 05495 } 05496 05503 public function getCustomDefaultSort() { 05504 return $this->mDefaultSort; 05505 } 05506 05516 public function guessSectionNameFromWikiText( $text ) { 05517 # Strip out wikitext links(they break the anchor) 05518 $text = $this->stripSectionName( $text ); 05519 $text = Sanitizer::normalizeSectionNameWhitespace( $text ); 05520 return '#' . Sanitizer::escapeId( $text, 'noninitial' ); 05521 } 05522 05531 public function guessLegacySectionNameFromWikiText( $text ) { 05532 # Strip out wikitext links(they break the anchor) 05533 $text = $this->stripSectionName( $text ); 05534 $text = Sanitizer::normalizeSectionNameWhitespace( $text ); 05535 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) ); 05536 } 05537 05552 public function stripSectionName( $text ) { 05553 # Strip internal link markup 05554 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text ); 05555 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text ); 05556 05557 # Strip external link markup 05558 # @todo FIXME: Not tolerant to blank link text 05559 # I.E. [http://www.mediawiki.org] will render as [1] or something depending 05560 # on how many empty links there are on the page - need to figure that out. 05561 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text ); 05562 05563 # Parse wikitext quotes (italics & bold) 05564 $text = $this->doQuotes( $text ); 05565 05566 # Strip HTML tags 05567 $text = StringUtils::delimiterReplace( '<', '>', '', $text ); 05568 return $text; 05569 } 05570 05581 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) { 05582 $this->startParse( $title, $options, $outputType, true ); 05583 05584 $text = $this->replaceVariables( $text ); 05585 $text = $this->mStripState->unstripBoth( $text ); 05586 $text = Sanitizer::removeHTMLtags( $text ); 05587 return $text; 05588 } 05589 05596 function testPst( $text, Title $title, ParserOptions $options ) { 05597 return $this->preSaveTransform( $text, $title, $options->getUser(), $options ); 05598 } 05599 05606 function testPreprocess( $text, Title $title, ParserOptions $options ) { 05607 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS ); 05608 } 05609 05626 function markerSkipCallback( $s, $callback ) { 05627 $i = 0; 05628 $out = ''; 05629 while ( $i < strlen( $s ) ) { 05630 $markerStart = strpos( $s, $this->mUniqPrefix, $i ); 05631 if ( $markerStart === false ) { 05632 $out .= call_user_func( $callback, substr( $s, $i ) ); 05633 break; 05634 } else { 05635 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) ); 05636 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart ); 05637 if ( $markerEnd === false ) { 05638 $out .= substr( $s, $markerStart ); 05639 break; 05640 } else { 05641 $markerEnd += strlen( self::MARKER_SUFFIX ); 05642 $out .= substr( $s, $markerStart, $markerEnd - $markerStart ); 05643 $i = $markerEnd; 05644 } 05645 } 05646 } 05647 return $out; 05648 } 05649 05656 function killMarkers( $text ) { 05657 return $this->mStripState->killMarkers( $text ); 05658 } 05659 05676 function serializeHalfParsedText( $text ) { 05677 wfProfileIn( __METHOD__ ); 05678 $data = array( 05679 'text' => $text, 05680 'version' => self::HALF_PARSED_VERSION, 05681 'stripState' => $this->mStripState->getSubState( $text ), 05682 'linkHolders' => $this->mLinkHolders->getSubArray( $text ) 05683 ); 05684 wfProfileOut( __METHOD__ ); 05685 return $data; 05686 } 05687 05702 function unserializeHalfParsedText( $data ) { 05703 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) { 05704 throw new MWException( __METHOD__.': invalid version' ); 05705 } 05706 05707 # First, extract the strip state. 05708 $texts = array( $data['text'] ); 05709 $texts = $this->mStripState->merge( $data['stripState'], $texts ); 05710 05711 # Now renumber links 05712 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts ); 05713 05714 # Should be good to go. 05715 return $texts[0]; 05716 } 05717 05727 function isValidHalfParsedText( $data ) { 05728 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION; 05729 } 05730 }