MediaWiki  master
Parser.php
Go to the documentation of this file.
00001 <?php
00067 class Parser {
00073     const VERSION = '1.6.4';
00074 
00079     const HALF_PARSED_VERSION = 2;
00080 
00081     # Flags for Parser::setFunctionHook
00082     # Also available as global constants from Defines.php
00083     const SFH_NO_HASH = 1;
00084     const SFH_OBJECT_ARGS = 2;
00085 
00086     # Constants needed for external link processing
00087     # Everything except bracket, space, or control characters
00088     # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
00089     # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
00090     const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
00091     const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
00092         \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
00093 
00094     # State constants for the definition list colon extraction
00095     const COLON_STATE_TEXT = 0;
00096     const COLON_STATE_TAG = 1;
00097     const COLON_STATE_TAGSTART = 2;
00098     const COLON_STATE_CLOSETAG = 3;
00099     const COLON_STATE_TAGSLASH = 4;
00100     const COLON_STATE_COMMENT = 5;
00101     const COLON_STATE_COMMENTDASH = 6;
00102     const COLON_STATE_COMMENTDASHDASH = 7;
00103 
00104     # Flags for preprocessToDom
00105     const PTD_FOR_INCLUSION = 1;
00106 
00107     # Allowed values for $this->mOutputType
00108     # Parameter to startExternalParse().
00109     const OT_HTML = 1; # like parse()
00110     const OT_WIKI = 2; # like preSaveTransform()
00111     const OT_PREPROCESS = 3; # like preprocess()
00112     const OT_MSG = 3;
00113     const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
00114 
00115     # Marker Suffix needs to be accessible staticly.
00116     const MARKER_SUFFIX = "-QINU\x7f";
00117 
00118     # Markers used for wrapping the table of contents
00119     const TOC_START = '<mw:toc>';
00120     const TOC_END = '</mw:toc>';
00121 
00122     # Persistent:
00123     var $mTagHooks = array();
00124     var $mTransparentTagHooks = array();
00125     var $mFunctionHooks = array();
00126     var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
00127     var $mFunctionTagHooks = array();
00128     var $mStripList = array();
00129     var $mDefaultStripList = array();
00130     var $mVarCache = array();
00131     var $mImageParams = array();
00132     var $mImageParamsMagicArray = array();
00133     var $mMarkerIndex = 0;
00134     var $mFirstCall = true;
00135 
00136     # Initialised by initialiseVariables()
00137 
00141     var $mVariables;
00142 
00146     var $mSubstWords;
00147     var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
00148 
00149     # Cleared with clearState():
00150 
00153     var $mOutput;
00154     var $mAutonumber, $mDTopen;
00155 
00159     var $mStripState;
00160 
00161     var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
00165     var $mLinkHolders;
00166 
00167     var $mLinkID;
00168     var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
00169     var $mDefaultSort;
00170     var $mTplExpandCache; # empty-frame expansion cache
00171     var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
00172     var $mExpensiveFunctionCount; # number of expensive parser function calls
00173     var $mShowToc, $mForceTocPosition;
00174 
00178     var $mUser; # User object; only used when doing pre-save transform
00179 
00180     # Temporary
00181     # These are variables reset at least once per parse regardless of $clearState
00182 
00186     var $mOptions;
00187 
00191     var $mTitle;        # Title context, used for self-link rendering and similar things
00192     var $mOutputType;   # Output type, one of the OT_xxx constants
00193     var $ot;            # Shortcut alias, see setOutputType()
00194     var $mRevisionObject; # The revision object of the specified revision ID
00195     var $mRevisionId;   # ID to display in {{REVISIONID}} tags
00196     var $mRevisionTimestamp; # The timestamp of the specified revision ID
00197     var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
00198     var $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
00199     var $mRevIdForTs;   # The revision ID which was used to fetch the timestamp
00200     var $mInputSize = false; # For {{PAGESIZE}} on current page.
00201 
00205     var $mUniqPrefix;
00206 
00212     var $mLangLinkLanguages;
00213 
00219     public function __construct( $conf = array() ) {
00220         $this->mConf = $conf;
00221         $this->mUrlProtocols = wfUrlProtocols();
00222         $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
00223             self::EXT_LINK_URL_CLASS . '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
00224         if ( isset( $conf['preprocessorClass'] ) ) {
00225             $this->mPreprocessorClass = $conf['preprocessorClass'];
00226         } elseif ( defined( 'HPHP_VERSION' ) ) {
00227             # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
00228             $this->mPreprocessorClass = 'Preprocessor_Hash';
00229         } elseif ( extension_loaded( 'domxml' ) ) {
00230             # PECL extension that conflicts with the core DOM extension (bug 13770)
00231             wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
00232             $this->mPreprocessorClass = 'Preprocessor_Hash';
00233         } elseif ( extension_loaded( 'dom' ) ) {
00234             $this->mPreprocessorClass = 'Preprocessor_DOM';
00235         } else {
00236             $this->mPreprocessorClass = 'Preprocessor_Hash';
00237         }
00238         wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
00239     }
00240 
00244     function __destruct() {
00245         if ( isset( $this->mLinkHolders ) ) {
00246             unset( $this->mLinkHolders );
00247         }
00248         foreach ( $this as $name => $value ) {
00249             unset( $this->$name );
00250         }
00251     }
00252 
00256     function __clone() {
00257         wfRunHooks( 'ParserCloned', array( $this ) );
00258     }
00259 
00263     function firstCallInit() {
00264         if ( !$this->mFirstCall ) {
00265             return;
00266         }
00267         $this->mFirstCall = false;
00268 
00269         wfProfileIn( __METHOD__ );
00270 
00271         CoreParserFunctions::register( $this );
00272         CoreTagHooks::register( $this );
00273         $this->initialiseVariables();
00274 
00275         wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
00276         wfProfileOut( __METHOD__ );
00277     }
00278 
00284     function clearState() {
00285         wfProfileIn( __METHOD__ );
00286         if ( $this->mFirstCall ) {
00287             $this->firstCallInit();
00288         }
00289         $this->mOutput = new ParserOutput;
00290         $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
00291         $this->mAutonumber = 0;
00292         $this->mLastSection = '';
00293         $this->mDTopen = false;
00294         $this->mIncludeCount = array();
00295         $this->mArgStack = false;
00296         $this->mInPre = false;
00297         $this->mLinkHolders = new LinkHolderArray( $this );
00298         $this->mLinkID = 0;
00299         $this->mRevisionObject = $this->mRevisionTimestamp =
00300             $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
00301         $this->mVarCache = array();
00302         $this->mUser = null;
00303         $this->mLangLinkLanguages = array();
00304 
00315         $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
00316         $this->mStripState = new StripState( $this->mUniqPrefix );
00317 
00318         # Clear these on every parse, bug 4549
00319         $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
00320 
00321         $this->mShowToc = true;
00322         $this->mForceTocPosition = false;
00323         $this->mIncludeSizes = array(
00324             'post-expand' => 0,
00325             'arg' => 0,
00326         );
00327         $this->mPPNodeCount = 0;
00328         $this->mGeneratedPPNodeCount = 0;
00329         $this->mHighestExpansionDepth = 0;
00330         $this->mDefaultSort = false;
00331         $this->mHeadings = array();
00332         $this->mDoubleUnderscores = array();
00333         $this->mExpensiveFunctionCount = 0;
00334 
00335         # Fix cloning
00336         if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
00337             $this->mPreprocessor = null;
00338         }
00339 
00340         wfRunHooks( 'ParserClearState', array( &$this ) );
00341         wfProfileOut( __METHOD__ );
00342     }
00343 
00356     public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
00362         global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
00363         $fname = __METHOD__ . '-' . wfGetCaller();
00364         wfProfileIn( __METHOD__ );
00365         wfProfileIn( $fname );
00366 
00367         $this->startParse( $title, $options, self::OT_HTML, $clearState );
00368 
00369         $this->mInputSize = strlen( $text );
00370         if ( $this->mOptions->getEnableLimitReport() ) {
00371             $this->mOutput->resetParseStartTime();
00372         }
00373 
00374         # Remove the strip marker tag prefix from the input, if present.
00375         if ( $clearState ) {
00376             $text = str_replace( $this->mUniqPrefix, '', $text );
00377         }
00378 
00379         $oldRevisionId = $this->mRevisionId;
00380         $oldRevisionObject = $this->mRevisionObject;
00381         $oldRevisionTimestamp = $this->mRevisionTimestamp;
00382         $oldRevisionUser = $this->mRevisionUser;
00383         $oldRevisionSize = $this->mRevisionSize;
00384         if ( $revid !== null ) {
00385             $this->mRevisionId = $revid;
00386             $this->mRevisionObject = null;
00387             $this->mRevisionTimestamp = null;
00388             $this->mRevisionUser = null;
00389             $this->mRevisionSize = null;
00390         }
00391 
00392         wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
00393         # No more strip!
00394         wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
00395         $text = $this->internalParse( $text );
00396         wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
00397 
00398         $text = $this->mStripState->unstripGeneral( $text );
00399 
00400         # Clean up special characters, only run once, next-to-last before doBlockLevels
00401         $fixtags = array(
00402             # french spaces, last one Guillemet-left
00403             # only if there is something before the space
00404             '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
00405             # french spaces, Guillemet-right
00406             '/(\\302\\253) /' => '\\1&#160;',
00407             '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
00408         );
00409         $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
00410 
00411         $text = $this->doBlockLevels( $text, $linestart );
00412 
00413         $this->replaceLinkHolders( $text );
00414 
00422         if ( !( $options->getDisableContentConversion()
00423             || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
00424         ) {
00425             if ( !$this->mOptions->getInterfaceMessage() ) {
00426                 # The position of the convert() call should not be changed. it
00427                 # assumes that the links are all replaced and the only thing left
00428                 # is the <nowiki> mark.
00429                 $text = $this->getConverterLanguage()->convert( $text );
00430             }
00431         }
00432 
00440         if ( !( $options->getDisableTitleConversion()
00441             || isset( $this->mDoubleUnderscores['nocontentconvert'] )
00442             || isset( $this->mDoubleUnderscores['notitleconvert'] )
00443             || $this->mOutput->getDisplayTitle() !== false )
00444         ) {
00445             $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
00446             if ( $convruletitle ) {
00447                 $this->mOutput->setTitleText( $convruletitle );
00448             } else {
00449                 $titleText = $this->getConverterLanguage()->convertTitle( $title );
00450                 $this->mOutput->setTitleText( $titleText );
00451             }
00452         }
00453 
00454         $text = $this->mStripState->unstripNoWiki( $text );
00455 
00456         wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
00457 
00458         $text = $this->replaceTransparentTags( $text );
00459         $text = $this->mStripState->unstripGeneral( $text );
00460 
00461         $text = Sanitizer::normalizeCharReferences( $text );
00462 
00463         if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
00464             $text = MWTidy::tidy( $text );
00465         } else {
00466             # attempt to sanitize at least some nesting problems
00467             # (bug #2702 and quite a few others)
00468             $tidyregs = array(
00469                 # ''Something [http://www.cool.com cool''] -->
00470                 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
00471                 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
00472                 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
00473                 # fix up an anchor inside another anchor, only
00474                 # at least for a single single nested link (bug 3695)
00475                 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
00476                 '\\1\\2</a>\\3</a>\\1\\4</a>',
00477                 # fix div inside inline elements- doBlockLevels won't wrap a line which
00478                 # contains a div, so fix it up here; replace
00479                 # div with escaped text
00480                 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
00481                 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
00482                 # remove empty italic or bold tag pairs, some
00483                 # introduced by rules above
00484                 '/<([bi])><\/\\1>/' => '',
00485             );
00486 
00487             $text = preg_replace(
00488                 array_keys( $tidyregs ),
00489                 array_values( $tidyregs ),
00490                 $text );
00491         }
00492 
00493         if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
00494             $this->limitationWarn( 'expensive-parserfunction',
00495                 $this->mExpensiveFunctionCount,
00496                 $this->mOptions->getExpensiveParserFunctionLimit()
00497             );
00498         }
00499 
00500         wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
00501 
00502         # Information on include size limits, for the benefit of users who try to skirt them
00503         if ( $this->mOptions->getEnableLimitReport() ) {
00504             $max = $this->mOptions->getMaxIncludeSize();
00505 
00506             $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
00507             if ( $cpuTime !== null ) {
00508                 $this->mOutput->setLimitReportData( 'limitreport-cputime',
00509                     sprintf( "%.3f", $cpuTime )
00510                 );
00511             }
00512 
00513             $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
00514             $this->mOutput->setLimitReportData( 'limitreport-walltime',
00515                 sprintf( "%.3f", $wallTime )
00516             );
00517 
00518             $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
00519                 array( $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() )
00520             );
00521             $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
00522                 array( $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() )
00523             );
00524             $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
00525                 array( $this->mIncludeSizes['post-expand'], $max )
00526             );
00527             $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
00528                 array( $this->mIncludeSizes['arg'], $max )
00529             );
00530             $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
00531                 array( $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() )
00532             );
00533             $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
00534                 array( $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() )
00535             );
00536             wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput ) );
00537 
00538             $limitReport = "NewPP limit report\n";
00539             if ( $wgShowHostnames ) {
00540                 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
00541             }
00542             foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
00543                 if ( wfRunHooks( 'ParserLimitReportFormat',
00544                     array( $key, &$value, &$limitReport, false, false )
00545                 ) ) {
00546                     $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
00547                     $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
00548                         ->inLanguage( 'en' )->useDatabase( false );
00549                     if ( !$valueMsg->exists() ) {
00550                         $valueMsg = new RawMessage( '$1' );
00551                     }
00552                     if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
00553                         $valueMsg->params( $value );
00554                         $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
00555                     }
00556                 }
00557             }
00558             // Since we're not really outputting HTML, decode the entities and
00559             // then re-encode the things that need hiding inside HTML comments.
00560             $limitReport = htmlspecialchars_decode( $limitReport );
00561             wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
00562 
00563             // Sanitize for comment. Note '‐' in the replacement is U+2010,
00564             // which looks much like the problematic '-'.
00565             $limitReport = str_replace( array( '-', '&' ), array( '‐', '&amp;' ), $limitReport );
00566             $text .= "\n<!-- \n$limitReport-->\n";
00567 
00568             if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
00569                 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
00570                     $this->mTitle->getPrefixedDBkey() );
00571             }
00572         }
00573         $this->mOutput->setText( $text );
00574 
00575         $this->mRevisionId = $oldRevisionId;
00576         $this->mRevisionObject = $oldRevisionObject;
00577         $this->mRevisionTimestamp = $oldRevisionTimestamp;
00578         $this->mRevisionUser = $oldRevisionUser;
00579         $this->mRevisionSize = $oldRevisionSize;
00580         $this->mInputSize = false;
00581         wfProfileOut( $fname );
00582         wfProfileOut( __METHOD__ );
00583 
00584         return $this->mOutput;
00585     }
00586 
00598     function recursiveTagParse( $text, $frame = false ) {
00599         wfProfileIn( __METHOD__ );
00600         wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
00601         wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
00602         $text = $this->internalParse( $text, false, $frame );
00603         wfProfileOut( __METHOD__ );
00604         return $text;
00605     }
00606 
00616     function preprocess( $text, Title $title = null, ParserOptions $options, $revid = null ) {
00617         wfProfileIn( __METHOD__ );
00618         $this->startParse( $title, $options, self::OT_PREPROCESS, true );
00619         if ( $revid !== null ) {
00620             $this->mRevisionId = $revid;
00621         }
00622         wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
00623         wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
00624         $text = $this->replaceVariables( $text );
00625         $text = $this->mStripState->unstripBoth( $text );
00626         wfProfileOut( __METHOD__ );
00627         return $text;
00628     }
00629 
00639     public function recursivePreprocess( $text, $frame = false ) {
00640         wfProfileIn( __METHOD__ );
00641         $text = $this->replaceVariables( $text, $frame );
00642         $text = $this->mStripState->unstripBoth( $text );
00643         wfProfileOut( __METHOD__ );
00644         return $text;
00645     }
00646 
00660     public function getPreloadText( $text, Title $title, ParserOptions $options, $params = array() ) {
00661         $msg = new RawMessage( $text );
00662         $text = $msg->params( $params )->plain();
00663 
00664         # Parser (re)initialisation
00665         $this->startParse( $title, $options, self::OT_PLAIN, true );
00666 
00667         $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
00668         $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
00669         $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
00670         $text = $this->mStripState->unstripBoth( $text );
00671         return $text;
00672     }
00673 
00679     public static function getRandomString() {
00680         return wfRandomString( 16 );
00681     }
00682 
00689     function setUser( $user ) {
00690         $this->mUser = $user;
00691     }
00692 
00698     public function uniqPrefix() {
00699         if ( !isset( $this->mUniqPrefix ) ) {
00700             # @todo FIXME: This is probably *horribly wrong*
00701             # LanguageConverter seems to want $wgParser's uniqPrefix, however
00702             # if this is called for a parser cache hit, the parser may not
00703             # have ever been initialized in the first place.
00704             # Not really sure what the heck is supposed to be going on here.
00705             return '';
00706             # throw new MWException( "Accessing uninitialized mUniqPrefix" );
00707         }
00708         return $this->mUniqPrefix;
00709     }
00710 
00716     function setTitle( $t ) {
00717         if ( !$t ) {
00718             $t = Title::newFromText( 'NO TITLE' );
00719         }
00720 
00721         if ( $t->hasFragment() ) {
00722             # Strip the fragment to avoid various odd effects
00723             $this->mTitle = clone $t;
00724             $this->mTitle->setFragment( '' );
00725         } else {
00726             $this->mTitle = $t;
00727         }
00728     }
00729 
00735     function getTitle() {
00736         return $this->mTitle;
00737     }
00738 
00745     function Title( $x = null ) {
00746         return wfSetVar( $this->mTitle, $x );
00747     }
00748 
00754     function setOutputType( $ot ) {
00755         $this->mOutputType = $ot;
00756         # Shortcut alias
00757         $this->ot = array(
00758             'html' => $ot == self::OT_HTML,
00759             'wiki' => $ot == self::OT_WIKI,
00760             'pre' => $ot == self::OT_PREPROCESS,
00761             'plain' => $ot == self::OT_PLAIN,
00762         );
00763     }
00764 
00771     function OutputType( $x = null ) {
00772         return wfSetVar( $this->mOutputType, $x );
00773     }
00774 
00780     function getOutput() {
00781         return $this->mOutput;
00782     }
00783 
00789     function getOptions() {
00790         return $this->mOptions;
00791     }
00792 
00799     function Options( $x = null ) {
00800         return wfSetVar( $this->mOptions, $x );
00801     }
00802 
00806     function nextLinkID() {
00807         return $this->mLinkID++;
00808     }
00809 
00813     function setLinkID( $id ) {
00814         $this->mLinkID = $id;
00815     }
00816 
00821     function getFunctionLang() {
00822         return $this->getTargetLanguage();
00823     }
00824 
00834     public function getTargetLanguage() {
00835         $target = $this->mOptions->getTargetLanguage();
00836 
00837         if ( $target !== null ) {
00838             return $target;
00839         } elseif ( $this->mOptions->getInterfaceMessage() ) {
00840             return $this->mOptions->getUserLangObj();
00841         } elseif ( is_null( $this->mTitle ) ) {
00842             throw new MWException( __METHOD__ . ': $this->mTitle is null' );
00843         }
00844 
00845         return $this->mTitle->getPageLanguage();
00846     }
00847 
00852     function getConverterLanguage() {
00853         return $this->getTargetLanguage();
00854     }
00855 
00862     function getUser() {
00863         if ( !is_null( $this->mUser ) ) {
00864             return $this->mUser;
00865         }
00866         return $this->mOptions->getUser();
00867     }
00868 
00874     function getPreprocessor() {
00875         if ( !isset( $this->mPreprocessor ) ) {
00876             $class = $this->mPreprocessorClass;
00877             $this->mPreprocessor = new $class( $this );
00878         }
00879         return $this->mPreprocessor;
00880     }
00881 
00902     public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
00903         static $n = 1;
00904         $stripped = '';
00905         $matches = array();
00906 
00907         $taglist = implode( '|', $elements );
00908         $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
00909 
00910         while ( $text != '' ) {
00911             $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
00912             $stripped .= $p[0];
00913             if ( count( $p ) < 5 ) {
00914                 break;
00915             }
00916             if ( count( $p ) > 5 ) {
00917                 # comment
00918                 $element = $p[4];
00919                 $attributes = '';
00920                 $close = '';
00921                 $inside = $p[5];
00922             } else {
00923                 # tag
00924                 $element = $p[1];
00925                 $attributes = $p[2];
00926                 $close = $p[3];
00927                 $inside = $p[4];
00928             }
00929 
00930             $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
00931             $stripped .= $marker;
00932 
00933             if ( $close === '/>' ) {
00934                 # Empty element tag, <tag />
00935                 $content = null;
00936                 $text = $inside;
00937                 $tail = null;
00938             } else {
00939                 if ( $element === '!--' ) {
00940                     $end = '/(-->)/';
00941                 } else {
00942                     $end = "/(<\\/$element\\s*>)/i";
00943                 }
00944                 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
00945                 $content = $q[0];
00946                 if ( count( $q ) < 3 ) {
00947                     # No end tag -- let it run out to the end of the text.
00948                     $tail = '';
00949                     $text = '';
00950                 } else {
00951                     $tail = $q[1];
00952                     $text = $q[2];
00953                 }
00954             }
00955 
00956             $matches[$marker] = array( $element,
00957                 $content,
00958                 Sanitizer::decodeTagAttributes( $attributes ),
00959                 "<$element$attributes$close$content$tail" );
00960         }
00961         return $stripped;
00962     }
00963 
00969     function getStripList() {
00970         return $this->mStripList;
00971     }
00972 
00982     function insertStripItem( $text ) {
00983         $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
00984         $this->mMarkerIndex++;
00985         $this->mStripState->addGeneral( $rnd, $text );
00986         return $rnd;
00987     }
00988 
00996     function doTableStuff( $text ) {
00997         wfProfileIn( __METHOD__ );
00998 
00999         $lines = StringUtils::explode( "\n", $text );
01000         $out = '';
01001         $td_history = array(); # Is currently a td tag open?
01002         $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
01003         $tr_history = array(); # Is currently a tr tag open?
01004         $tr_attributes = array(); # history of tr attributes
01005         $has_opened_tr = array(); # Did this table open a <tr> element?
01006         $indent_level = 0; # indent level of the table
01007 
01008         foreach ( $lines as $outLine ) {
01009             $line = trim( $outLine );
01010 
01011             if ( $line === '' ) { # empty line, go to next line
01012                 $out .= $outLine . "\n";
01013                 continue;
01014             }
01015 
01016             $first_character = $line[0];
01017             $matches = array();
01018 
01019             if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
01020                 # First check if we are starting a new table
01021                 $indent_level = strlen( $matches[1] );
01022 
01023                 $attributes = $this->mStripState->unstripBoth( $matches[2] );
01024                 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
01025 
01026                 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
01027                 array_push( $td_history, false );
01028                 array_push( $last_tag_history, '' );
01029                 array_push( $tr_history, false );
01030                 array_push( $tr_attributes, '' );
01031                 array_push( $has_opened_tr, false );
01032             } elseif ( count( $td_history ) == 0 ) {
01033                 # Don't do any of the following
01034                 $out .= $outLine . "\n";
01035                 continue;
01036             } elseif ( substr( $line, 0, 2 ) === '|}' ) {
01037                 # We are ending a table
01038                 $line = '</table>' . substr( $line, 2 );
01039                 $last_tag = array_pop( $last_tag_history );
01040 
01041                 if ( !array_pop( $has_opened_tr ) ) {
01042                     $line = "<tr><td></td></tr>{$line}";
01043                 }
01044 
01045                 if ( array_pop( $tr_history ) ) {
01046                     $line = "</tr>{$line}";
01047                 }
01048 
01049                 if ( array_pop( $td_history ) ) {
01050                     $line = "</{$last_tag}>{$line}";
01051                 }
01052                 array_pop( $tr_attributes );
01053                 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
01054             } elseif ( substr( $line, 0, 2 ) === '|-' ) {
01055                 # Now we have a table row
01056                 $line = preg_replace( '#^\|-+#', '', $line );
01057 
01058                 # Whats after the tag is now only attributes
01059                 $attributes = $this->mStripState->unstripBoth( $line );
01060                 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
01061                 array_pop( $tr_attributes );
01062                 array_push( $tr_attributes, $attributes );
01063 
01064                 $line = '';
01065                 $last_tag = array_pop( $last_tag_history );
01066                 array_pop( $has_opened_tr );
01067                 array_push( $has_opened_tr, true );
01068 
01069                 if ( array_pop( $tr_history ) ) {
01070                     $line = '</tr>';
01071                 }
01072 
01073                 if ( array_pop( $td_history ) ) {
01074                     $line = "</{$last_tag}>{$line}";
01075                 }
01076 
01077                 $outLine = $line;
01078                 array_push( $tr_history, false );
01079                 array_push( $td_history, false );
01080                 array_push( $last_tag_history, '' );
01081             } elseif ( $first_character === '|' || $first_character === '!' || substr( $line, 0, 2 ) === '|+' ) {
01082                 # This might be cell elements, td, th or captions
01083                 if ( substr( $line, 0, 2 ) === '|+' ) {
01084                     $first_character = '+';
01085                     $line = substr( $line, 1 );
01086                 }
01087 
01088                 $line = substr( $line, 1 );
01089 
01090                 if ( $first_character === '!' ) {
01091                     $line = str_replace( '!!', '||', $line );
01092                 }
01093 
01094                 # Split up multiple cells on the same line.
01095                 # FIXME : This can result in improper nesting of tags processed
01096                 # by earlier parser steps, but should avoid splitting up eg
01097                 # attribute values containing literal "||".
01098                 $cells = StringUtils::explodeMarkup( '||', $line );
01099 
01100                 $outLine = '';
01101 
01102                 # Loop through each table cell
01103                 foreach ( $cells as $cell ) {
01104                     $previous = '';
01105                     if ( $first_character !== '+' ) {
01106                         $tr_after = array_pop( $tr_attributes );
01107                         if ( !array_pop( $tr_history ) ) {
01108                             $previous = "<tr{$tr_after}>\n";
01109                         }
01110                         array_push( $tr_history, true );
01111                         array_push( $tr_attributes, '' );
01112                         array_pop( $has_opened_tr );
01113                         array_push( $has_opened_tr, true );
01114                     }
01115 
01116                     $last_tag = array_pop( $last_tag_history );
01117 
01118                     if ( array_pop( $td_history ) ) {
01119                         $previous = "</{$last_tag}>\n{$previous}";
01120                     }
01121 
01122                     if ( $first_character === '|' ) {
01123                         $last_tag = 'td';
01124                     } elseif ( $first_character === '!' ) {
01125                         $last_tag = 'th';
01126                     } elseif ( $first_character === '+' ) {
01127                         $last_tag = 'caption';
01128                     } else {
01129                         $last_tag = '';
01130                     }
01131 
01132                     array_push( $last_tag_history, $last_tag );
01133 
01134                     # A cell could contain both parameters and data
01135                     $cell_data = explode( '|', $cell, 2 );
01136 
01137                     # Bug 553: Note that a '|' inside an invalid link should not
01138                     # be mistaken as delimiting cell parameters
01139                     if ( strpos( $cell_data[0], '[[' ) !== false ) {
01140                         $cell = "{$previous}<{$last_tag}>{$cell}";
01141                     } elseif ( count( $cell_data ) == 1 ) {
01142                         $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
01143                     } else {
01144                         $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
01145                         $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
01146                         $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
01147                     }
01148 
01149                     $outLine .= $cell;
01150                     array_push( $td_history, true );
01151                 }
01152             }
01153             $out .= $outLine . "\n";
01154         }
01155 
01156         # Closing open td, tr && table
01157         while ( count( $td_history ) > 0 ) {
01158             if ( array_pop( $td_history ) ) {
01159                 $out .= "</td>\n";
01160             }
01161             if ( array_pop( $tr_history ) ) {
01162                 $out .= "</tr>\n";
01163             }
01164             if ( !array_pop( $has_opened_tr ) ) {
01165                 $out .= "<tr><td></td></tr>\n";
01166             }
01167 
01168             $out .= "</table>\n";
01169         }
01170 
01171         # Remove trailing line-ending (b/c)
01172         if ( substr( $out, -1 ) === "\n" ) {
01173             $out = substr( $out, 0, -1 );
01174         }
01175 
01176         # special case: don't return empty table
01177         if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
01178             $out = '';
01179         }
01180 
01181         wfProfileOut( __METHOD__ );
01182 
01183         return $out;
01184     }
01185 
01198     function internalParse( $text, $isMain = true, $frame = false ) {
01199         wfProfileIn( __METHOD__ );
01200 
01201         $origText = $text;
01202 
01203         # Hook to suspend the parser in this state
01204         if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
01205             wfProfileOut( __METHOD__ );
01206             return $text;
01207         }
01208 
01209         # if $frame is provided, then use $frame for replacing any variables
01210         if ( $frame ) {
01211             # use frame depth to infer how include/noinclude tags should be handled
01212             # depth=0 means this is the top-level document; otherwise it's an included document
01213             if ( !$frame->depth ) {
01214                 $flag = 0;
01215             } else {
01216                 $flag = Parser::PTD_FOR_INCLUSION;
01217             }
01218             $dom = $this->preprocessToDom( $text, $flag );
01219             $text = $frame->expand( $dom );
01220         } else {
01221             # if $frame is not provided, then use old-style replaceVariables
01222             $text = $this->replaceVariables( $text );
01223         }
01224 
01225         wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
01226         $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
01227         wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
01228 
01229         # Tables need to come after variable replacement for things to work
01230         # properly; putting them before other transformations should keep
01231         # exciting things like link expansions from showing up in surprising
01232         # places.
01233         $text = $this->doTableStuff( $text );
01234 
01235         $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
01236 
01237         $text = $this->doDoubleUnderscore( $text );
01238 
01239         $text = $this->doHeadings( $text );
01240         $text = $this->replaceInternalLinks( $text );
01241         $text = $this->doAllQuotes( $text );
01242         $text = $this->replaceExternalLinks( $text );
01243 
01244         # replaceInternalLinks may sometimes leave behind
01245         # absolute URLs, which have to be masked to hide them from replaceExternalLinks
01246         $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text );
01247 
01248         $text = $this->doMagicLinks( $text );
01249         $text = $this->formatHeadings( $text, $origText, $isMain );
01250 
01251         wfProfileOut( __METHOD__ );
01252         return $text;
01253     }
01254 
01266     function doMagicLinks( $text ) {
01267         wfProfileIn( __METHOD__ );
01268         $prots = wfUrlProtocolsWithoutProtRel();
01269         $urlChar = self::EXT_LINK_URL_CLASS;
01270         $text = preg_replace_callback(
01271             '!(?:                           # Start cases
01272                 (<a[ \t\r\n>].*?</a>) |     # m[1]: Skip link text
01273                 (<.*?>) |                   # m[2]: Skip stuff inside HTML elements' . "
01274                 (\\b(?i:$prots)$urlChar+) |  # m[3]: Free external links" . '
01275                 (?:RFC|PMID)\s+([0-9]+) |   # m[4]: RFC or PMID, capture number
01276                 ISBN\s+(\b                  # m[5]: ISBN, capture number
01277                     (?: 97[89] [\ \-]? )?   # optional 13-digit ISBN prefix
01278                     (?: [0-9]  [\ \-]? ){9} # 9 digits with opt. delimiters
01279                     [0-9Xx]                 # check digit
01280                     \b)
01281             )!xu', array( &$this, 'magicLinkCallback' ), $text );
01282         wfProfileOut( __METHOD__ );
01283         return $text;
01284     }
01285 
01291     function magicLinkCallback( $m ) {
01292         if ( isset( $m[1] ) && $m[1] !== '' ) {
01293             # Skip anchor
01294             return $m[0];
01295         } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
01296             # Skip HTML element
01297             return $m[0];
01298         } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
01299             # Free external link
01300             return $this->makeFreeExternalLink( $m[0] );
01301         } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
01302             # RFC or PMID
01303             if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
01304                 $keyword = 'RFC';
01305                 $urlmsg = 'rfcurl';
01306                 $cssClass = 'mw-magiclink-rfc';
01307                 $id = $m[4];
01308             } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
01309                 $keyword = 'PMID';
01310                 $urlmsg = 'pubmedurl';
01311                 $cssClass = 'mw-magiclink-pmid';
01312                 $id = $m[4];
01313             } else {
01314                 throw new MWException( __METHOD__ . ': unrecognised match type "' .
01315                     substr( $m[0], 0, 20 ) . '"' );
01316             }
01317             $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
01318             return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
01319         } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
01320             # ISBN
01321             $isbn = $m[5];
01322             $num = strtr( $isbn, array(
01323                 '-' => '',
01324                 ' ' => '',
01325                 'x' => 'X',
01326             ));
01327             $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
01328             return '<a href="' .
01329                 htmlspecialchars( $titleObj->getLocalURL() ) .
01330                 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
01331         } else {
01332             return $m[0];
01333         }
01334     }
01335 
01344     function makeFreeExternalLink( $url ) {
01345         wfProfileIn( __METHOD__ );
01346 
01347         $trail = '';
01348 
01349         # The characters '<' and '>' (which were escaped by
01350         # removeHTMLtags()) should not be included in
01351         # URLs, per RFC 2396.
01352         $m2 = array();
01353         if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
01354             $trail = substr( $url, $m2[0][1] ) . $trail;
01355             $url = substr( $url, 0, $m2[0][1] );
01356         }
01357 
01358         # Move trailing punctuation to $trail
01359         $sep = ',;\.:!?';
01360         # If there is no left bracket, then consider right brackets fair game too
01361         if ( strpos( $url, '(' ) === false ) {
01362             $sep .= ')';
01363         }
01364 
01365         $numSepChars = strspn( strrev( $url ), $sep );
01366         if ( $numSepChars ) {
01367             $trail = substr( $url, -$numSepChars ) . $trail;
01368             $url = substr( $url, 0, -$numSepChars );
01369         }
01370 
01371         $url = Sanitizer::cleanUrl( $url );
01372 
01373         # Is this an external image?
01374         $text = $this->maybeMakeExternalImage( $url );
01375         if ( $text === false ) {
01376             # Not an image, make a link
01377             $text = Linker::makeExternalLink( $url,
01378                 $this->getConverterLanguage()->markNoConversion( $url, true ),
01379                 true, 'free',
01380                 $this->getExternalLinkAttribs( $url ) );
01381             # Register it in the output object...
01382             # Replace unnecessary URL escape codes with their equivalent characters
01383             $pasteurized = self::replaceUnusualEscapes( $url );
01384             $this->mOutput->addExternalLink( $pasteurized );
01385         }
01386         wfProfileOut( __METHOD__ );
01387         return $text . $trail;
01388     }
01389 
01399     function doHeadings( $text ) {
01400         wfProfileIn( __METHOD__ );
01401         for ( $i = 6; $i >= 1; --$i ) {
01402             $h = str_repeat( '=', $i );
01403             $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
01404         }
01405         wfProfileOut( __METHOD__ );
01406         return $text;
01407     }
01408 
01417     function doAllQuotes( $text ) {
01418         wfProfileIn( __METHOD__ );
01419         $outtext = '';
01420         $lines = StringUtils::explode( "\n", $text );
01421         foreach ( $lines as $line ) {
01422             $outtext .= $this->doQuotes( $line ) . "\n";
01423         }
01424         $outtext = substr( $outtext, 0, -1 );
01425         wfProfileOut( __METHOD__ );
01426         return $outtext;
01427     }
01428 
01436     public function doQuotes( $text ) {
01437         $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
01438         $countarr = count( $arr );
01439         if ( $countarr == 1 ) {
01440             return $text;
01441         }
01442 
01443         // First, do some preliminary work. This may shift some apostrophes from
01444         // being mark-up to being text. It also counts the number of occurrences
01445         // of bold and italics mark-ups.
01446         $numbold = 0;
01447         $numitalics = 0;
01448         for ( $i = 1; $i < $countarr; $i += 2 ) {
01449             $thislen = strlen( $arr[$i] );
01450             // If there are ever four apostrophes, assume the first is supposed to
01451             // be text, and the remaining three constitute mark-up for bold text.
01452             // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
01453             if ( $thislen == 4 ) {
01454                 $arr[$i - 1] .= "'";
01455                 $arr[$i] = "'''";
01456                 $thislen = 3;
01457             } elseif ( $thislen > 5 ) {
01458                 // If there are more than 5 apostrophes in a row, assume they're all
01459                 // text except for the last 5.
01460                 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
01461                 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
01462                 $arr[$i] = "'''''";
01463                 $thislen = 5;
01464             }
01465             // Count the number of occurrences of bold and italics mark-ups.
01466             if ( $thislen == 2 ) {
01467                 $numitalics++;
01468             } elseif ( $thislen == 3 ) {
01469                 $numbold++;
01470             } elseif ( $thislen == 5 ) {
01471                 $numitalics++;
01472                 $numbold++;
01473             }
01474         }
01475 
01476         // If there is an odd number of both bold and italics, it is likely
01477         // that one of the bold ones was meant to be an apostrophe followed
01478         // by italics. Which one we cannot know for certain, but it is more
01479         // likely to be one that has a single-letter word before it.
01480         if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
01481             $firstsingleletterword = -1;
01482             $firstmultiletterword = -1;
01483             $firstspace = -1;
01484             for ( $i = 1; $i < $countarr; $i += 2 ) {
01485                 if ( strlen( $arr[$i] ) == 3 ) {
01486                     $x1 = substr( $arr[$i - 1], -1 );
01487                     $x2 = substr( $arr[$i - 1], -2, 1 );
01488                     if ( $x1 === ' ' ) {
01489                         if ( $firstspace == -1 ) {
01490                             $firstspace = $i;
01491                         }
01492                     } elseif ( $x2 === ' ' ) {
01493                         if ( $firstsingleletterword == -1 ) {
01494                             $firstsingleletterword = $i;
01495                             // if $firstsingleletterword is set, we don't
01496                             // look at the other options, so we can bail early.
01497                             break;
01498                         }
01499                     } else {
01500                         if ( $firstmultiletterword == -1 ) {
01501                             $firstmultiletterword = $i;
01502                         }
01503                     }
01504                 }
01505             }
01506 
01507             // If there is a single-letter word, use it!
01508             if ( $firstsingleletterword > -1 ) {
01509                 $arr[$firstsingleletterword] = "''";
01510                 $arr[$firstsingleletterword - 1] .= "'";
01511             } elseif ( $firstmultiletterword > -1 ) {
01512                 // If not, but there's a multi-letter word, use that one.
01513                 $arr[$firstmultiletterword] = "''";
01514                 $arr[$firstmultiletterword - 1] .= "'";
01515             } elseif ( $firstspace > -1 ) {
01516                 // ... otherwise use the first one that has neither.
01517                 // (notice that it is possible for all three to be -1 if, for example,
01518                 // there is only one pentuple-apostrophe in the line)
01519                 $arr[$firstspace] = "''";
01520                 $arr[$firstspace - 1] .= "'";
01521             }
01522         }
01523 
01524         // Now let's actually convert our apostrophic mush to HTML!
01525         $output = '';
01526         $buffer = '';
01527         $state = '';
01528         $i = 0;
01529         foreach ( $arr as $r ) {
01530             if ( ( $i % 2 ) == 0 ) {
01531                 if ( $state === 'both' ) {
01532                     $buffer .= $r;
01533                 } else {
01534                     $output .= $r;
01535                 }
01536             } else {
01537                 $thislen = strlen( $r );
01538                 if ( $thislen == 2 ) {
01539                     if ( $state === 'i' ) {
01540                         $output .= '</i>';
01541                         $state = '';
01542                     } elseif ( $state === 'bi' ) {
01543                         $output .= '</i>';
01544                         $state = 'b';
01545                     } elseif ( $state === 'ib' ) {
01546                         $output .= '</b></i><b>';
01547                         $state = 'b';
01548                     } elseif ( $state === 'both' ) {
01549                         $output .= '<b><i>' . $buffer . '</i>';
01550                         $state = 'b';
01551                     } else { // $state can be 'b' or ''
01552                         $output .= '<i>';
01553                         $state .= 'i';
01554                     }
01555                 } elseif ( $thislen == 3 ) {
01556                     if ( $state === 'b' ) {
01557                         $output .= '</b>';
01558                         $state = '';
01559                     } elseif ( $state === 'bi' ) {
01560                         $output .= '</i></b><i>';
01561                         $state = 'i';
01562                     } elseif ( $state === 'ib' ) {
01563                         $output .= '</b>';
01564                         $state = 'i';
01565                     } elseif ( $state === 'both' ) {
01566                         $output .= '<i><b>' . $buffer . '</b>';
01567                         $state = 'i';
01568                     } else { // $state can be 'i' or ''
01569                         $output .= '<b>';
01570                         $state .= 'b';
01571                     }
01572                 } elseif ( $thislen == 5 ) {
01573                     if ( $state === 'b' ) {
01574                         $output .= '</b><i>';
01575                         $state = 'i';
01576                     } elseif ( $state === 'i' ) {
01577                         $output .= '</i><b>';
01578                         $state = 'b';
01579                     } elseif ( $state === 'bi' ) {
01580                         $output .= '</i></b>';
01581                         $state = '';
01582                     } elseif ( $state === 'ib' ) {
01583                         $output .= '</b></i>';
01584                         $state = '';
01585                     } elseif ( $state === 'both' ) {
01586                         $output .= '<i><b>' . $buffer . '</b></i>';
01587                         $state = '';
01588                     } else { // ($state == '')
01589                         $buffer = '';
01590                         $state = 'both';
01591                     }
01592                 }
01593             }
01594             $i++;
01595         }
01596         // Now close all remaining tags.  Notice that the order is important.
01597         if ( $state === 'b' || $state === 'ib' ) {
01598             $output .= '</b>';
01599         }
01600         if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
01601             $output .= '</i>';
01602         }
01603         if ( $state === 'bi' ) {
01604             $output .= '</b>';
01605         }
01606         // There might be lonely ''''', so make sure we have a buffer
01607         if ( $state === 'both' && $buffer ) {
01608             $output .= '<b><i>' . $buffer . '</i></b>';
01609         }
01610         return $output;
01611     }
01612 
01626     function replaceExternalLinks( $text ) {
01627         wfProfileIn( __METHOD__ );
01628 
01629         $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
01630         if ( $bits === false ) {
01631             wfProfileOut( __METHOD__ );
01632             throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
01633         }
01634         $s = array_shift( $bits );
01635 
01636         $i = 0;
01637         while ( $i < count( $bits ) ) {
01638             $url = $bits[$i++];
01639             $i++; // protocol
01640             $text = $bits[$i++];
01641             $trail = $bits[$i++];
01642 
01643             # The characters '<' and '>' (which were escaped by
01644             # removeHTMLtags()) should not be included in
01645             # URLs, per RFC 2396.
01646             $m2 = array();
01647             if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
01648                 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
01649                 $url = substr( $url, 0, $m2[0][1] );
01650             }
01651 
01652             # If the link text is an image URL, replace it with an <img> tag
01653             # This happened by accident in the original parser, but some people used it extensively
01654             $img = $this->maybeMakeExternalImage( $text );
01655             if ( $img !== false ) {
01656                 $text = $img;
01657             }
01658 
01659             $dtrail = '';
01660 
01661             # Set linktype for CSS - if URL==text, link is essentially free
01662             $linktype = ( $text === $url ) ? 'free' : 'text';
01663 
01664             # No link text, e.g. [http://domain.tld/some.link]
01665             if ( $text == '' ) {
01666                 # Autonumber
01667                 $langObj = $this->getTargetLanguage();
01668                 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
01669                 $linktype = 'autonumber';
01670             } else {
01671                 # Have link text, e.g. [http://domain.tld/some.link text]s
01672                 # Check for trail
01673                 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
01674             }
01675 
01676             $text = $this->getConverterLanguage()->markNoConversion( $text );
01677 
01678             $url = Sanitizer::cleanUrl( $url );
01679 
01680             # Use the encoded URL
01681             # This means that users can paste URLs directly into the text
01682             # Funny characters like ö aren't valid in URLs anyway
01683             # This was changed in August 2004
01684             $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
01685                 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
01686 
01687             # Register link in the output object.
01688             # Replace unnecessary URL escape codes with the referenced character
01689             # This prevents spammers from hiding links from the filters
01690             $pasteurized = self::replaceUnusualEscapes( $url );
01691             $this->mOutput->addExternalLink( $pasteurized );
01692         }
01693 
01694         wfProfileOut( __METHOD__ );
01695         return $s;
01696     }
01697 
01707     public static function getExternalLinkRel( $url = false, $title = null ) {
01708         global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
01709         $ns = $title ? $title->getNamespace() : false;
01710         if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
01711             && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
01712         ) {
01713             return 'nofollow';
01714         }
01715         return null;
01716     }
01717 
01728     function getExternalLinkAttribs( $url = false ) {
01729         $attribs = array();
01730         $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle );
01731 
01732         if ( $this->mOptions->getExternalLinkTarget() ) {
01733             $attribs['target'] = $this->mOptions->getExternalLinkTarget();
01734         }
01735         return $attribs;
01736     }
01737 
01749     static function replaceUnusualEscapes( $url ) {
01750         return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
01751             array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
01752     }
01753 
01762     private static function replaceUnusualEscapesCallback( $matches ) {
01763         $char = urldecode( $matches[0] );
01764         $ord = ord( $char );
01765         # Is it an unsafe or HTTP reserved character according to RFC 1738?
01766         if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
01767             # No, shouldn't be escaped
01768             return $char;
01769         } else {
01770             # Yes, leave it escaped
01771             return $matches[0];
01772         }
01773     }
01774 
01784     function maybeMakeExternalImage( $url ) {
01785         $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
01786         $imagesexception = !empty( $imagesfrom );
01787         $text = false;
01788         # $imagesfrom could be either a single string or an array of strings, parse out the latter
01789         if ( $imagesexception && is_array( $imagesfrom ) ) {
01790             $imagematch = false;
01791             foreach ( $imagesfrom as $match ) {
01792                 if ( strpos( $url, $match ) === 0 ) {
01793                     $imagematch = true;
01794                     break;
01795                 }
01796             }
01797         } elseif ( $imagesexception ) {
01798             $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
01799         } else {
01800             $imagematch = false;
01801         }
01802         if ( $this->mOptions->getAllowExternalImages()
01803             || ( $imagesexception && $imagematch ) ) {
01804             if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
01805                 # Image found
01806                 $text = Linker::makeExternalImage( $url );
01807             }
01808         }
01809         if ( !$text && $this->mOptions->getEnableImageWhitelist()
01810             && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
01811             $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
01812             foreach ( $whitelist as $entry ) {
01813                 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
01814                 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
01815                     continue;
01816                 }
01817                 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
01818                     # Image matches a whitelist entry
01819                     $text = Linker::makeExternalImage( $url );
01820                     break;
01821                 }
01822             }
01823         }
01824         return $text;
01825     }
01826 
01836     function replaceInternalLinks( $s ) {
01837         $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
01838         return $s;
01839     }
01840 
01849     function replaceInternalLinks2( &$s ) {
01850         wfProfileIn( __METHOD__ );
01851 
01852         wfProfileIn( __METHOD__ . '-setup' );
01853         static $tc = false, $e1, $e1_img;
01854         # the % is needed to support urlencoded titles as well
01855         if ( !$tc ) {
01856             $tc = Title::legalChars() . '#%';
01857             # Match a link having the form [[namespace:link|alternate]]trail
01858             $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
01859             # Match cases where there is no "]]", which might still be images
01860             $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
01861         }
01862 
01863         $holders = new LinkHolderArray( $this );
01864 
01865         # split the entire text string on occurrences of [[
01866         $a = StringUtils::explode( '[[', ' ' . $s );
01867         # get the first element (all text up to first [[), and remove the space we added
01868         $s = $a->current();
01869         $a->next();
01870         $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
01871         $s = substr( $s, 1 );
01872 
01873         $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
01874         $e2 = null;
01875         if ( $useLinkPrefixExtension ) {
01876             # Match the end of a line for a word that's not followed by whitespace,
01877             # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
01878             global $wgContLang;
01879             $charset = $wgContLang->linkPrefixCharset();
01880             $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
01881         }
01882 
01883         if ( is_null( $this->mTitle ) ) {
01884             wfProfileOut( __METHOD__ . '-setup' );
01885             wfProfileOut( __METHOD__ );
01886             throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
01887         }
01888         $nottalk = !$this->mTitle->isTalkPage();
01889 
01890         if ( $useLinkPrefixExtension ) {
01891             $m = array();
01892             if ( preg_match( $e2, $s, $m ) ) {
01893                 $first_prefix = $m[2];
01894             } else {
01895                 $first_prefix = false;
01896             }
01897         } else {
01898             $prefix = '';
01899         }
01900 
01901         $useSubpages = $this->areSubpagesAllowed();
01902         wfProfileOut( __METHOD__ . '-setup' );
01903 
01904         # Loop for each link
01905         for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
01906             # Check for excessive memory usage
01907             if ( $holders->isBig() ) {
01908                 # Too big
01909                 # Do the existence check, replace the link holders and clear the array
01910                 $holders->replace( $s );
01911                 $holders->clear();
01912             }
01913 
01914             if ( $useLinkPrefixExtension ) {
01915                 wfProfileIn( __METHOD__ . '-prefixhandling' );
01916                 if ( preg_match( $e2, $s, $m ) ) {
01917                     $prefix = $m[2];
01918                     $s = $m[1];
01919                 } else {
01920                     $prefix = '';
01921                 }
01922                 # first link
01923                 if ( $first_prefix ) {
01924                     $prefix = $first_prefix;
01925                     $first_prefix = false;
01926                 }
01927                 wfProfileOut( __METHOD__ . '-prefixhandling' );
01928             }
01929 
01930             $might_be_img = false;
01931 
01932             wfProfileIn( __METHOD__ . "-e1" );
01933             if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
01934                 $text = $m[2];
01935                 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
01936                 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
01937                 # the real problem is with the $e1 regex
01938                 # See bug 1300.
01939                 #
01940                 # Still some problems for cases where the ] is meant to be outside punctuation,
01941                 # and no image is in sight. See bug 2095.
01942                 #
01943                 if ( $text !== ''
01944                     && substr( $m[3], 0, 1 ) === ']'
01945                     && strpos( $text, '[' ) !== false
01946                 ) {
01947                     $text .= ']'; # so that replaceExternalLinks($text) works later
01948                     $m[3] = substr( $m[3], 1 );
01949                 }
01950                 # fix up urlencoded title texts
01951                 if ( strpos( $m[1], '%' ) !== false ) {
01952                     # Should anchors '#' also be rejected?
01953                     $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
01954                 }
01955                 $trail = $m[3];
01956             } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
01957                 $might_be_img = true;
01958                 $text = $m[2];
01959                 if ( strpos( $m[1], '%' ) !== false ) {
01960                     $m[1] = rawurldecode( $m[1] );
01961                 }
01962                 $trail = "";
01963             } else { # Invalid form; output directly
01964                 $s .= $prefix . '[[' . $line;
01965                 wfProfileOut( __METHOD__ . "-e1" );
01966                 continue;
01967             }
01968             wfProfileOut( __METHOD__ . "-e1" );
01969             wfProfileIn( __METHOD__ . "-misc" );
01970 
01971             # Don't allow internal links to pages containing
01972             # PROTO: where PROTO is a valid URL protocol; these
01973             # should be external links.
01974             if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
01975                 $s .= $prefix . '[[' . $line;
01976                 wfProfileOut( __METHOD__ . "-misc" );
01977                 continue;
01978             }
01979 
01980             # Make subpage if necessary
01981             if ( $useSubpages ) {
01982                 $link = $this->maybeDoSubpageLink( $m[1], $text );
01983             } else {
01984                 $link = $m[1];
01985             }
01986 
01987             $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
01988             if ( !$noforce ) {
01989                 # Strip off leading ':'
01990                 $link = substr( $link, 1 );
01991             }
01992 
01993             wfProfileOut( __METHOD__ . "-misc" );
01994             wfProfileIn( __METHOD__ . "-title" );
01995             $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
01996             if ( $nt === null ) {
01997                 $s .= $prefix . '[[' . $line;
01998                 wfProfileOut( __METHOD__ . "-title" );
01999                 continue;
02000             }
02001 
02002             $ns = $nt->getNamespace();
02003             $iw = $nt->getInterwiki();
02004             wfProfileOut( __METHOD__ . "-title" );
02005 
02006             if ( $might_be_img ) { # if this is actually an invalid link
02007                 wfProfileIn( __METHOD__ . "-might_be_img" );
02008                 if ( $ns == NS_FILE && $noforce ) { # but might be an image
02009                     $found = false;
02010                     while ( true ) {
02011                         # look at the next 'line' to see if we can close it there
02012                         $a->next();
02013                         $next_line = $a->current();
02014                         if ( $next_line === false || $next_line === null ) {
02015                             break;
02016                         }
02017                         $m = explode( ']]', $next_line, 3 );
02018                         if ( count( $m ) == 3 ) {
02019                             # the first ]] closes the inner link, the second the image
02020                             $found = true;
02021                             $text .= "[[{$m[0]}]]{$m[1]}";
02022                             $trail = $m[2];
02023                             break;
02024                         } elseif ( count( $m ) == 2 ) {
02025                             # if there's exactly one ]] that's fine, we'll keep looking
02026                             $text .= "[[{$m[0]}]]{$m[1]}";
02027                         } else {
02028                             # if $next_line is invalid too, we need look no further
02029                             $text .= '[[' . $next_line;
02030                             break;
02031                         }
02032                     }
02033                     if ( !$found ) {
02034                         # we couldn't find the end of this imageLink, so output it raw
02035                         # but don't ignore what might be perfectly normal links in the text we've examined
02036                         $holders->merge( $this->replaceInternalLinks2( $text ) );
02037                         $s .= "{$prefix}[[$link|$text";
02038                         # note: no $trail, because without an end, there *is* no trail
02039                         wfProfileOut( __METHOD__ . "-might_be_img" );
02040                         continue;
02041                     }
02042                 } else { # it's not an image, so output it raw
02043                     $s .= "{$prefix}[[$link|$text";
02044                     # note: no $trail, because without an end, there *is* no trail
02045                     wfProfileOut( __METHOD__ . "-might_be_img" );
02046                     continue;
02047                 }
02048                 wfProfileOut( __METHOD__ . "-might_be_img" );
02049             }
02050 
02051             $wasblank = ( $text == '' );
02052             if ( $wasblank ) {
02053                 $text = $link;
02054             } else {
02055                 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
02056                 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
02057                 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
02058                 #    -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
02059                 $text = $this->doQuotes( $text );
02060             }
02061 
02062             # Link not escaped by : , create the various objects
02063             if ( $noforce ) {
02064                 # Interwikis
02065                 wfProfileIn( __METHOD__ . "-interwiki" );
02066                 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) {
02067                     // XXX: the above check prevents links to sites with identifiers that are not language codes
02068 
02069                     # Bug 24502: filter duplicates
02070                     if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
02071                         $this->mLangLinkLanguages[$iw] = true;
02072                         $this->mOutput->addLanguageLink( $nt->getFullText() );
02073                     }
02074 
02075                     $s = rtrim( $s . $prefix );
02076                     $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
02077                     wfProfileOut( __METHOD__ . "-interwiki" );
02078                     continue;
02079                 }
02080                 wfProfileOut( __METHOD__ . "-interwiki" );
02081 
02082                 if ( $ns == NS_FILE ) {
02083                     wfProfileIn( __METHOD__ . "-image" );
02084                     if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
02085                         if ( $wasblank ) {
02086                             # if no parameters were passed, $text
02087                             # becomes something like "File:Foo.png",
02088                             # which we don't want to pass on to the
02089                             # image generator
02090                             $text = '';
02091                         } else {
02092                             # recursively parse links inside the image caption
02093                             # actually, this will parse them in any other parameters, too,
02094                             # but it might be hard to fix that, and it doesn't matter ATM
02095                             $text = $this->replaceExternalLinks( $text );
02096                             $holders->merge( $this->replaceInternalLinks2( $text ) );
02097                         }
02098                         # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
02099                         $s .= $prefix . $this->armorLinks(
02100                             $this->makeImage( $nt, $text, $holders ) ) . $trail;
02101                     } else {
02102                         $s .= $prefix . $trail;
02103                     }
02104                     wfProfileOut( __METHOD__ . "-image" );
02105                     continue;
02106                 }
02107 
02108                 if ( $ns == NS_CATEGORY ) {
02109                     wfProfileIn( __METHOD__ . "-category" );
02110                     $s = rtrim( $s . "\n" ); # bug 87
02111 
02112                     if ( $wasblank ) {
02113                         $sortkey = $this->getDefaultSort();
02114                     } else {
02115                         $sortkey = $text;
02116                     }
02117                     $sortkey = Sanitizer::decodeCharReferences( $sortkey );
02118                     $sortkey = str_replace( "\n", '', $sortkey );
02119                     $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
02120                     $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
02121 
02125                     $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
02126 
02127                     wfProfileOut( __METHOD__ . "-category" );
02128                     continue;
02129                 }
02130             }
02131 
02132             # Self-link checking. For some languages, variants of the title are checked in
02133             # LinkHolderArray::doVariants() to allow batching the existence checks necessary
02134             # for linking to a different variant.
02135             if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
02136                 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
02137                 continue;
02138             }
02139 
02140             # NS_MEDIA is a pseudo-namespace for linking directly to a file
02141             # @todo FIXME: Should do batch file existence checks, see comment below
02142             if ( $ns == NS_MEDIA ) {
02143                 wfProfileIn( __METHOD__ . "-media" );
02144                 # Give extensions a chance to select the file revision for us
02145                 $options = array();
02146                 $descQuery = false;
02147                 wfRunHooks( 'BeforeParserFetchFileAndTitle',
02148                     array( $this, $nt, &$options, &$descQuery ) );
02149                 # Fetch and register the file (file title may be different via hooks)
02150                 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
02151                 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
02152                 $s .= $prefix . $this->armorLinks(
02153                     Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
02154                 wfProfileOut( __METHOD__ . "-media" );
02155                 continue;
02156             }
02157 
02158             wfProfileIn( __METHOD__ . "-always_known" );
02159             # Some titles, such as valid special pages or files in foreign repos, should
02160             # be shown as bluelinks even though they're not included in the page table
02161             #
02162             # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
02163             # batch file existence checks for NS_FILE and NS_MEDIA
02164             if ( $iw == '' && $nt->isAlwaysKnown() ) {
02165                 $this->mOutput->addLink( $nt );
02166                 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
02167             } else {
02168                 # Links will be added to the output link list after checking
02169                 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
02170             }
02171             wfProfileOut( __METHOD__ . "-always_known" );
02172         }
02173         wfProfileOut( __METHOD__ );
02174         return $holders;
02175     }
02176 
02191     function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
02192         list( $inside, $trail ) = Linker::splitTrail( $trail );
02193 
02194         if ( is_string( $query ) ) {
02195             $query = wfCgiToArray( $query );
02196         }
02197         if ( $text == '' ) {
02198             $text = htmlspecialchars( $nt->getPrefixedText() );
02199         }
02200 
02201         $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
02202 
02203         return $this->armorLinks( $link ) . $trail;
02204     }
02205 
02216     function armorLinks( $text ) {
02217         return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
02218             "{$this->mUniqPrefix}NOPARSE$1", $text );
02219     }
02220 
02225     function areSubpagesAllowed() {
02226         # Some namespaces don't allow subpages
02227         return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
02228     }
02229 
02238     function maybeDoSubpageLink( $target, &$text ) {
02239         return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
02240     }
02241 
02248     function closeParagraph() {
02249         $result = '';
02250         if ( $this->mLastSection != '' ) {
02251             $result = '</' . $this->mLastSection . ">\n";
02252         }
02253         $this->mInPre = false;
02254         $this->mLastSection = '';
02255         return $result;
02256     }
02257 
02268     function getCommon( $st1, $st2 ) {
02269         $fl = strlen( $st1 );
02270         $shorter = strlen( $st2 );
02271         if ( $fl < $shorter ) {
02272             $shorter = $fl;
02273         }
02274 
02275         for ( $i = 0; $i < $shorter; ++$i ) {
02276             if ( $st1[$i] != $st2[$i] ) {
02277                 break;
02278             }
02279         }
02280         return $i;
02281     }
02282 
02292     function openList( $char ) {
02293         $result = $this->closeParagraph();
02294 
02295         if ( '*' === $char ) {
02296             $result .= "<ul>\n<li>";
02297         } elseif ( '#' === $char ) {
02298             $result .= "<ol>\n<li>";
02299         } elseif ( ':' === $char ) {
02300             $result .= "<dl>\n<dd>";
02301         } elseif ( ';' === $char ) {
02302             $result .= "<dl>\n<dt>";
02303             $this->mDTopen = true;
02304         } else {
02305             $result = '<!-- ERR 1 -->';
02306         }
02307 
02308         return $result;
02309     }
02310 
02318     function nextItem( $char ) {
02319         if ( '*' === $char || '#' === $char ) {
02320             return "</li>\n<li>";
02321         } elseif ( ':' === $char || ';' === $char ) {
02322             $close = "</dd>\n";
02323             if ( $this->mDTopen ) {
02324                 $close = "</dt>\n";
02325             }
02326             if ( ';' === $char ) {
02327                 $this->mDTopen = true;
02328                 return $close . '<dt>';
02329             } else {
02330                 $this->mDTopen = false;
02331                 return $close . '<dd>';
02332             }
02333         }
02334         return '<!-- ERR 2 -->';
02335     }
02336 
02344     function closeList( $char ) {
02345         if ( '*' === $char ) {
02346             $text = "</li>\n</ul>";
02347         } elseif ( '#' === $char ) {
02348             $text = "</li>\n</ol>";
02349         } elseif ( ':' === $char ) {
02350             if ( $this->mDTopen ) {
02351                 $this->mDTopen = false;
02352                 $text = "</dt>\n</dl>";
02353             } else {
02354                 $text = "</dd>\n</dl>";
02355             }
02356         } else {
02357             return '<!-- ERR 3 -->';
02358         }
02359         return $text . "\n";
02360     }
02371     function doBlockLevels( $text, $linestart ) {
02372         wfProfileIn( __METHOD__ );
02373 
02374         # Parsing through the text line by line.  The main thing
02375         # happening here is handling of block-level elements p, pre,
02376         # and making lists from lines starting with * # : etc.
02377         #
02378         $textLines = StringUtils::explode( "\n", $text );
02379 
02380         $lastPrefix = $output = '';
02381         $this->mDTopen = $inBlockElem = false;
02382         $prefixLength = 0;
02383         $paragraphStack = false;
02384         $inBlockquote = false;
02385 
02386         foreach ( $textLines as $oLine ) {
02387             # Fix up $linestart
02388             if ( !$linestart ) {
02389                 $output .= $oLine;
02390                 $linestart = true;
02391                 continue;
02392             }
02393             # * = ul
02394             # # = ol
02395             # ; = dt
02396             # : = dd
02397 
02398             $lastPrefixLength = strlen( $lastPrefix );
02399             $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
02400             $preOpenMatch = preg_match( '/<pre/i', $oLine );
02401             # If not in a <pre> element, scan for and figure out what prefixes are there.
02402             if ( !$this->mInPre ) {
02403                 # Multiple prefixes may abut each other for nested lists.
02404                 $prefixLength = strspn( $oLine, '*#:;' );
02405                 $prefix = substr( $oLine, 0, $prefixLength );
02406 
02407                 # eh?
02408                 # ; and : are both from definition-lists, so they're equivalent
02409                 #  for the purposes of determining whether or not we need to open/close
02410                 #  elements.
02411                 $prefix2 = str_replace( ';', ':', $prefix );
02412                 $t = substr( $oLine, $prefixLength );
02413                 $this->mInPre = (bool)$preOpenMatch;
02414             } else {
02415                 # Don't interpret any other prefixes in preformatted text
02416                 $prefixLength = 0;
02417                 $prefix = $prefix2 = '';
02418                 $t = $oLine;
02419             }
02420 
02421             # List generation
02422             if ( $prefixLength && $lastPrefix === $prefix2 ) {
02423                 # Same as the last item, so no need to deal with nesting or opening stuff
02424                 $output .= $this->nextItem( substr( $prefix, -1 ) );
02425                 $paragraphStack = false;
02426 
02427                 if ( substr( $prefix, -1 ) === ';' ) {
02428                     # The one nasty exception: definition lists work like this:
02429                     # ; title : definition text
02430                     # So we check for : in the remainder text to split up the
02431                     # title and definition, without b0rking links.
02432                     $term = $t2 = '';
02433                     if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
02434                         $t = $t2;
02435                         $output .= $term . $this->nextItem( ':' );
02436                     }
02437                 }
02438             } elseif ( $prefixLength || $lastPrefixLength ) {
02439                 # We need to open or close prefixes, or both.
02440 
02441                 # Either open or close a level...
02442                 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
02443                 $paragraphStack = false;
02444 
02445                 # Close all the prefixes which aren't shared.
02446                 while ( $commonPrefixLength < $lastPrefixLength ) {
02447                     $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
02448                     --$lastPrefixLength;
02449                 }
02450 
02451                 # Continue the current prefix if appropriate.
02452                 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
02453                     $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
02454                 }
02455 
02456                 # Open prefixes where appropriate.
02457                 while ( $prefixLength > $commonPrefixLength ) {
02458                     $char = substr( $prefix, $commonPrefixLength, 1 );
02459                     $output .= $this->openList( $char );
02460 
02461                     if ( ';' === $char ) {
02462                         # @todo FIXME: This is dupe of code above
02463                         if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
02464                             $t = $t2;
02465                             $output .= $term . $this->nextItem( ':' );
02466                         }
02467                     }
02468                     ++$commonPrefixLength;
02469                 }
02470                 $lastPrefix = $prefix2;
02471             }
02472 
02473             # If we have no prefixes, go to paragraph mode.
02474             if ( 0 == $prefixLength ) {
02475                 wfProfileIn( __METHOD__ . "-paragraph" );
02476                 # No prefix (not in list)--go to paragraph mode
02477                 # XXX: use a stack for nestable elements like span, table and div
02478                 $openmatch = preg_match( '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
02479                 $closematch = preg_match(
02480                     '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
02481                     '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|' . $this->mUniqPrefix . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
02482                 if ( $openmatch or $closematch ) {
02483                     $paragraphStack = false;
02484                     # TODO bug 5718: paragraph closed
02485                     $output .= $this->closeParagraph();
02486                     if ( $preOpenMatch and !$preCloseMatch ) {
02487                         $this->mInPre = true;
02488                     }
02489                     $bqOffset = 0;
02490                     while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) {
02491                         $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
02492                         $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
02493                     }
02494                     $inBlockElem = !$closematch;
02495                 } elseif ( !$inBlockElem && !$this->mInPre ) {
02496                     if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) and !$inBlockquote ) {
02497                         # pre
02498                         if ( $this->mLastSection !== 'pre' ) {
02499                             $paragraphStack = false;
02500                             $output .= $this->closeParagraph() . '<pre>';
02501                             $this->mLastSection = 'pre';
02502                         }
02503                         $t = substr( $t, 1 );
02504                     } else {
02505                         # paragraph
02506                         if ( trim( $t ) === '' ) {
02507                             if ( $paragraphStack ) {
02508                                 $output .= $paragraphStack . '<br />';
02509                                 $paragraphStack = false;
02510                                 $this->mLastSection = 'p';
02511                             } else {
02512                                 if ( $this->mLastSection !== 'p' ) {
02513                                     $output .= $this->closeParagraph();
02514                                     $this->mLastSection = '';
02515                                     $paragraphStack = '<p>';
02516                                 } else {
02517                                     $paragraphStack = '</p><p>';
02518                                 }
02519                             }
02520                         } else {
02521                             if ( $paragraphStack ) {
02522                                 $output .= $paragraphStack;
02523                                 $paragraphStack = false;
02524                                 $this->mLastSection = 'p';
02525                             } elseif ( $this->mLastSection !== 'p' ) {
02526                                 $output .= $this->closeParagraph() . '<p>';
02527                                 $this->mLastSection = 'p';
02528                             }
02529                         }
02530                     }
02531                 }
02532                 wfProfileOut( __METHOD__ . "-paragraph" );
02533             }
02534             # somewhere above we forget to get out of pre block (bug 785)
02535             if ( $preCloseMatch && $this->mInPre ) {
02536                 $this->mInPre = false;
02537             }
02538             if ( $paragraphStack === false ) {
02539                 $output .= $t . "\n";
02540             }
02541         }
02542         while ( $prefixLength ) {
02543             $output .= $this->closeList( $prefix2[$prefixLength - 1] );
02544             --$prefixLength;
02545         }
02546         if ( $this->mLastSection != '' ) {
02547             $output .= '</' . $this->mLastSection . '>';
02548             $this->mLastSection = '';
02549         }
02550 
02551         wfProfileOut( __METHOD__ );
02552         return $output;
02553     }
02554 
02565     function findColonNoLinks( $str, &$before, &$after ) {
02566         wfProfileIn( __METHOD__ );
02567 
02568         $pos = strpos( $str, ':' );
02569         if ( $pos === false ) {
02570             # Nothing to find!
02571             wfProfileOut( __METHOD__ );
02572             return false;
02573         }
02574 
02575         $lt = strpos( $str, '<' );
02576         if ( $lt === false || $lt > $pos ) {
02577             # Easy; no tag nesting to worry about
02578             $before = substr( $str, 0, $pos );
02579             $after = substr( $str, $pos + 1 );
02580             wfProfileOut( __METHOD__ );
02581             return $pos;
02582         }
02583 
02584         # Ugly state machine to walk through avoiding tags.
02585         $state = self::COLON_STATE_TEXT;
02586         $stack = 0;
02587         $len = strlen( $str );
02588         for ( $i = 0; $i < $len; $i++ ) {
02589             $c = $str[$i];
02590 
02591             switch ( $state ) {
02592             # (Using the number is a performance hack for common cases)
02593             case 0: # self::COLON_STATE_TEXT:
02594                 switch ( $c ) {
02595                 case "<":
02596                     # Could be either a <start> tag or an </end> tag
02597                     $state = self::COLON_STATE_TAGSTART;
02598                     break;
02599                 case ":":
02600                     if ( $stack == 0 ) {
02601                         # We found it!
02602                         $before = substr( $str, 0, $i );
02603                         $after = substr( $str, $i + 1 );
02604                         wfProfileOut( __METHOD__ );
02605                         return $i;
02606                     }
02607                     # Embedded in a tag; don't break it.
02608                     break;
02609                 default:
02610                     # Skip ahead looking for something interesting
02611                     $colon = strpos( $str, ':', $i );
02612                     if ( $colon === false ) {
02613                         # Nothing else interesting
02614                         wfProfileOut( __METHOD__ );
02615                         return false;
02616                     }
02617                     $lt = strpos( $str, '<', $i );
02618                     if ( $stack === 0 ) {
02619                         if ( $lt === false || $colon < $lt ) {
02620                             # We found it!
02621                             $before = substr( $str, 0, $colon );
02622                             $after = substr( $str, $colon + 1 );
02623                             wfProfileOut( __METHOD__ );
02624                             return $i;
02625                         }
02626                     }
02627                     if ( $lt === false ) {
02628                         # Nothing else interesting to find; abort!
02629                         # We're nested, but there's no close tags left. Abort!
02630                         break 2;
02631                     }
02632                     # Skip ahead to next tag start
02633                     $i = $lt;
02634                     $state = self::COLON_STATE_TAGSTART;
02635                 }
02636                 break;
02637             case 1: # self::COLON_STATE_TAG:
02638                 # In a <tag>
02639                 switch ( $c ) {
02640                 case ">":
02641                     $stack++;
02642                     $state = self::COLON_STATE_TEXT;
02643                     break;
02644                 case "/":
02645                     # Slash may be followed by >?
02646                     $state = self::COLON_STATE_TAGSLASH;
02647                     break;
02648                 default:
02649                     # ignore
02650                 }
02651                 break;
02652             case 2: # self::COLON_STATE_TAGSTART:
02653                 switch ( $c ) {
02654                 case "/":
02655                     $state = self::COLON_STATE_CLOSETAG;
02656                     break;
02657                 case "!":
02658                     $state = self::COLON_STATE_COMMENT;
02659                     break;
02660                 case ">":
02661                     # Illegal early close? This shouldn't happen D:
02662                     $state = self::COLON_STATE_TEXT;
02663                     break;
02664                 default:
02665                     $state = self::COLON_STATE_TAG;
02666                 }
02667                 break;
02668             case 3: # self::COLON_STATE_CLOSETAG:
02669                 # In a </tag>
02670                 if ( $c === ">" ) {
02671                     $stack--;
02672                     if ( $stack < 0 ) {
02673                         wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
02674                         wfProfileOut( __METHOD__ );
02675                         return false;
02676                     }
02677                     $state = self::COLON_STATE_TEXT;
02678                 }
02679                 break;
02680             case self::COLON_STATE_TAGSLASH:
02681                 if ( $c === ">" ) {
02682                     # Yes, a self-closed tag <blah/>
02683                     $state = self::COLON_STATE_TEXT;
02684                 } else {
02685                     # Probably we're jumping the gun, and this is an attribute
02686                     $state = self::COLON_STATE_TAG;
02687                 }
02688                 break;
02689             case 5: # self::COLON_STATE_COMMENT:
02690                 if ( $c === "-" ) {
02691                     $state = self::COLON_STATE_COMMENTDASH;
02692                 }
02693                 break;
02694             case self::COLON_STATE_COMMENTDASH:
02695                 if ( $c === "-" ) {
02696                     $state = self::COLON_STATE_COMMENTDASHDASH;
02697                 } else {
02698                     $state = self::COLON_STATE_COMMENT;
02699                 }
02700                 break;
02701             case self::COLON_STATE_COMMENTDASHDASH:
02702                 if ( $c === ">" ) {
02703                     $state = self::COLON_STATE_TEXT;
02704                 } else {
02705                     $state = self::COLON_STATE_COMMENT;
02706                 }
02707                 break;
02708             default:
02709                 wfProfileOut( __METHOD__ );
02710                 throw new MWException( "State machine error in " . __METHOD__ );
02711             }
02712         }
02713         if ( $stack > 0 ) {
02714             wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
02715             wfProfileOut( __METHOD__ );
02716             return false;
02717         }
02718         wfProfileOut( __METHOD__ );
02719         return false;
02720     }
02721 
02733     function getVariableValue( $index, $frame = false ) {
02734         global $wgContLang, $wgSitename, $wgServer;
02735         global $wgArticlePath, $wgScriptPath, $wgStylePath;
02736 
02737         if ( is_null( $this->mTitle ) ) {
02738             // If no title set, bad things are going to happen
02739             // later. Title should always be set since this
02740             // should only be called in the middle of a parse
02741             // operation (but the unit-tests do funky stuff)
02742             throw new MWException( __METHOD__ . ' Should only be '
02743                 . ' called while parsing (no title set)' );
02744         }
02745 
02750         if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
02751             if ( isset( $this->mVarCache[$index] ) ) {
02752                 return $this->mVarCache[$index];
02753             }
02754         }
02755 
02756         $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
02757         wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
02758 
02759         $pageLang = $this->getFunctionLang();
02760 
02761         switch ( $index ) {
02762             case 'currentmonth':
02763                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
02764                 break;
02765             case 'currentmonth1':
02766                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
02767                 break;
02768             case 'currentmonthname':
02769                 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
02770                 break;
02771             case 'currentmonthnamegen':
02772                 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
02773                 break;
02774             case 'currentmonthabbrev':
02775                 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
02776                 break;
02777             case 'currentday':
02778                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
02779                 break;
02780             case 'currentday2':
02781                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
02782                 break;
02783             case 'localmonth':
02784                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
02785                 break;
02786             case 'localmonth1':
02787                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
02788                 break;
02789             case 'localmonthname':
02790                 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
02791                 break;
02792             case 'localmonthnamegen':
02793                 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
02794                 break;
02795             case 'localmonthabbrev':
02796                 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
02797                 break;
02798             case 'localday':
02799                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
02800                 break;
02801             case 'localday2':
02802                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
02803                 break;
02804             case 'pagename':
02805                 $value = wfEscapeWikiText( $this->mTitle->getText() );
02806                 break;
02807             case 'pagenamee':
02808                 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
02809                 break;
02810             case 'fullpagename':
02811                 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
02812                 break;
02813             case 'fullpagenamee':
02814                 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
02815                 break;
02816             case 'subpagename':
02817                 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
02818                 break;
02819             case 'subpagenamee':
02820                 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
02821                 break;
02822             case 'rootpagename':
02823                 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
02824                 break;
02825             case 'rootpagenamee':
02826                 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getRootText() ) ) );
02827                 break;
02828             case 'basepagename':
02829                 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
02830                 break;
02831             case 'basepagenamee':
02832                 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) );
02833                 break;
02834             case 'talkpagename':
02835                 if ( $this->mTitle->canTalk() ) {
02836                     $talkPage = $this->mTitle->getTalkPage();
02837                     $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
02838                 } else {
02839                     $value = '';
02840                 }
02841                 break;
02842             case 'talkpagenamee':
02843                 if ( $this->mTitle->canTalk() ) {
02844                     $talkPage = $this->mTitle->getTalkPage();
02845                     $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
02846                 } else {
02847                     $value = '';
02848                 }
02849                 break;
02850             case 'subjectpagename':
02851                 $subjPage = $this->mTitle->getSubjectPage();
02852                 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
02853                 break;
02854             case 'subjectpagenamee':
02855                 $subjPage = $this->mTitle->getSubjectPage();
02856                 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
02857                 break;
02858             case 'pageid': // requested in bug 23427
02859                 $pageid = $this->getTitle()->getArticleID();
02860                 if ( $pageid == 0 ) {
02861                     # 0 means the page doesn't exist in the database,
02862                     # which means the user is previewing a new page.
02863                     # The vary-revision flag must be set, because the magic word
02864                     # will have a different value once the page is saved.
02865                     $this->mOutput->setFlag( 'vary-revision' );
02866                     wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
02867                 }
02868                 $value = $pageid ? $pageid : null;
02869                 break;
02870             case 'revisionid':
02871                 # Let the edit saving system know we should parse the page
02872                 # *after* a revision ID has been assigned.
02873                 $this->mOutput->setFlag( 'vary-revision' );
02874                 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
02875                 $value = $this->mRevisionId;
02876                 break;
02877             case 'revisionday':
02878                 # Let the edit saving system know we should parse the page
02879                 # *after* a revision ID has been assigned. This is for null edits.
02880                 $this->mOutput->setFlag( 'vary-revision' );
02881                 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
02882                 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
02883                 break;
02884             case 'revisionday2':
02885                 # Let the edit saving system know we should parse the page
02886                 # *after* a revision ID has been assigned. This is for null edits.
02887                 $this->mOutput->setFlag( 'vary-revision' );
02888                 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
02889                 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
02890                 break;
02891             case 'revisionmonth':
02892                 # Let the edit saving system know we should parse the page
02893                 # *after* a revision ID has been assigned. This is for null edits.
02894                 $this->mOutput->setFlag( 'vary-revision' );
02895                 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
02896                 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
02897                 break;
02898             case 'revisionmonth1':
02899                 # Let the edit saving system know we should parse the page
02900                 # *after* a revision ID has been assigned. This is for null edits.
02901                 $this->mOutput->setFlag( 'vary-revision' );
02902                 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
02903                 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
02904                 break;
02905             case 'revisionyear':
02906                 # Let the edit saving system know we should parse the page
02907                 # *after* a revision ID has been assigned. This is for null edits.
02908                 $this->mOutput->setFlag( 'vary-revision' );
02909                 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
02910                 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
02911                 break;
02912             case 'revisiontimestamp':
02913                 # Let the edit saving system know we should parse the page
02914                 # *after* a revision ID has been assigned. This is for null edits.
02915                 $this->mOutput->setFlag( 'vary-revision' );
02916                 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
02917                 $value = $this->getRevisionTimestamp();
02918                 break;
02919             case 'revisionuser':
02920                 # Let the edit saving system know we should parse the page
02921                 # *after* a revision ID has been assigned. This is for null edits.
02922                 $this->mOutput->setFlag( 'vary-revision' );
02923                 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
02924                 $value = $this->getRevisionUser();
02925                 break;
02926             case 'revisionsize':
02927                 # Let the edit saving system know we should parse the page
02928                 # *after* a revision ID has been assigned. This is for null edits.
02929                 $this->mOutput->setFlag( 'vary-revision' );
02930                 wfDebug( __METHOD__ . ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
02931                 $value = $this->getRevisionSize();
02932                 break;
02933             case 'namespace':
02934                 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
02935                 break;
02936             case 'namespacee':
02937                 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
02938                 break;
02939             case 'namespacenumber':
02940                 $value = $this->mTitle->getNamespace();
02941                 break;
02942             case 'talkspace':
02943                 $value = $this->mTitle->canTalk() ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() ) : '';
02944                 break;
02945             case 'talkspacee':
02946                 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
02947                 break;
02948             case 'subjectspace':
02949                 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
02950                 break;
02951             case 'subjectspacee':
02952                 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
02953                 break;
02954             case 'currentdayname':
02955                 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
02956                 break;
02957             case 'currentyear':
02958                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
02959                 break;
02960             case 'currenttime':
02961                 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
02962                 break;
02963             case 'currenthour':
02964                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
02965                 break;
02966             case 'currentweek':
02967                 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
02968                 # int to remove the padding
02969                 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
02970                 break;
02971             case 'currentdow':
02972                 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
02973                 break;
02974             case 'localdayname':
02975                 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1 );
02976                 break;
02977             case 'localyear':
02978                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
02979                 break;
02980             case 'localtime':
02981                 $value = $pageLang->time( MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
02982                 break;
02983             case 'localhour':
02984                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
02985                 break;
02986             case 'localweek':
02987                 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
02988                 # int to remove the padding
02989                 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
02990                 break;
02991             case 'localdow':
02992                 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
02993                 break;
02994             case 'numberofarticles':
02995                 $value = $pageLang->formatNum( SiteStats::articles() );
02996                 break;
02997             case 'numberoffiles':
02998                 $value = $pageLang->formatNum( SiteStats::images() );
02999                 break;
03000             case 'numberofusers':
03001                 $value = $pageLang->formatNum( SiteStats::users() );
03002                 break;
03003             case 'numberofactiveusers':
03004                 $value = $pageLang->formatNum( SiteStats::activeUsers() );
03005                 break;
03006             case 'numberofpages':
03007                 $value = $pageLang->formatNum( SiteStats::pages() );
03008                 break;
03009             case 'numberofadmins':
03010                 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
03011                 break;
03012             case 'numberofedits':
03013                 $value = $pageLang->formatNum( SiteStats::edits() );
03014                 break;
03015             case 'numberofviews':
03016                 global $wgDisableCounters;
03017                 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
03018                 break;
03019             case 'currenttimestamp':
03020                 $value = wfTimestamp( TS_MW, $ts );
03021                 break;
03022             case 'localtimestamp':
03023                 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
03024                 break;
03025             case 'currentversion':
03026                 $value = SpecialVersion::getVersion();
03027                 break;
03028             case 'articlepath':
03029                 return $wgArticlePath;
03030             case 'sitename':
03031                 return $wgSitename;
03032             case 'server':
03033                 return $wgServer;
03034             case 'servername':
03035                 $serverParts = wfParseUrl( $wgServer );
03036                 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer;
03037             case 'scriptpath':
03038                 return $wgScriptPath;
03039             case 'stylepath':
03040                 return $wgStylePath;
03041             case 'directionmark':
03042                 return $pageLang->getDirMark();
03043             case 'contentlanguage':
03044                 global $wgLanguageCode;
03045                 return $wgLanguageCode;
03046             case 'cascadingsources':
03047                 $value = CoreParserFunctions::cascadingsources( $this );
03048                 break;
03049             default:
03050                 $ret = null;
03051                 wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) );
03052                 return $ret;
03053         }
03054 
03055         if ( $index ) {
03056             $this->mVarCache[$index] = $value;
03057         }
03058 
03059         return $value;
03060     }
03061 
03067     function initialiseVariables() {
03068         wfProfileIn( __METHOD__ );
03069         $variableIDs = MagicWord::getVariableIDs();
03070         $substIDs = MagicWord::getSubstIDs();
03071 
03072         $this->mVariables = new MagicWordArray( $variableIDs );
03073         $this->mSubstWords = new MagicWordArray( $substIDs );
03074         wfProfileOut( __METHOD__ );
03075     }
03076 
03099     function preprocessToDom( $text, $flags = 0 ) {
03100         $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
03101         return $dom;
03102     }
03103 
03111     public static function splitWhitespace( $s ) {
03112         $ltrimmed = ltrim( $s );
03113         $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
03114         $trimmed = rtrim( $ltrimmed );
03115         $diff = strlen( $ltrimmed ) - strlen( $trimmed );
03116         if ( $diff > 0 ) {
03117             $w2 = substr( $ltrimmed, -$diff );
03118         } else {
03119             $w2 = '';
03120         }
03121         return array( $w1, $trimmed, $w2 );
03122     }
03123 
03143     function replaceVariables( $text, $frame = false, $argsOnly = false ) {
03144         # Is there any text? Also, Prevent too big inclusions!
03145         if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
03146             return $text;
03147         }
03148         wfProfileIn( __METHOD__ );
03149 
03150         if ( $frame === false ) {
03151             $frame = $this->getPreprocessor()->newFrame();
03152         } elseif ( !( $frame instanceof PPFrame ) ) {
03153             wfDebug( __METHOD__ . " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
03154             $frame = $this->getPreprocessor()->newCustomFrame( $frame );
03155         }
03156 
03157         $dom = $this->preprocessToDom( $text );
03158         $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
03159         $text = $frame->expand( $dom, $flags );
03160 
03161         wfProfileOut( __METHOD__ );
03162         return $text;
03163     }
03164 
03172     static function createAssocArgs( $args ) {
03173         $assocArgs = array();
03174         $index = 1;
03175         foreach ( $args as $arg ) {
03176             $eqpos = strpos( $arg, '=' );
03177             if ( $eqpos === false ) {
03178                 $assocArgs[$index++] = $arg;
03179             } else {
03180                 $name = trim( substr( $arg, 0, $eqpos ) );
03181                 $value = trim( substr( $arg, $eqpos + 1 ) );
03182                 if ( $value === false ) {
03183                     $value = '';
03184                 }
03185                 if ( $name !== false ) {
03186                     $assocArgs[$name] = $value;
03187                 }
03188             }
03189         }
03190 
03191         return $assocArgs;
03192     }
03193 
03218     function limitationWarn( $limitationType, $current = '', $max = '' ) {
03219         # does no harm if $current and $max are present but are unnecessary for the message
03220         $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
03221             ->inLanguage( $this->mOptions->getUserLangObj() )->text();
03222         $this->mOutput->addWarning( $warning );
03223         $this->addTrackingCategory( "$limitationType-category" );
03224     }
03225 
03239     function braceSubstitution( $piece, $frame ) {
03240         wfProfileIn( __METHOD__ );
03241         wfProfileIn( __METHOD__ . '-setup' );
03242 
03243         # Flags
03244         $found = false;             # $text has been filled
03245         $nowiki = false;            # wiki markup in $text should be escaped
03246         $isHTML = false;            # $text is HTML, armour it against wikitext transformation
03247         $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
03248         $isChildObj = false;        # $text is a DOM node needing expansion in a child frame
03249         $isLocalObj = false;        # $text is a DOM node needing expansion in the current frame
03250 
03251         # Title object, where $text came from
03252         $title = false;
03253 
03254         # $part1 is the bit before the first |, and must contain only title characters.
03255         # Various prefixes will be stripped from it later.
03256         $titleWithSpaces = $frame->expand( $piece['title'] );
03257         $part1 = trim( $titleWithSpaces );
03258         $titleText = false;
03259 
03260         # Original title text preserved for various purposes
03261         $originalTitle = $part1;
03262 
03263         # $args is a list of argument nodes, starting from index 0, not including $part1
03264         # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
03265         $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
03266         wfProfileOut( __METHOD__ . '-setup' );
03267 
03268         $titleProfileIn = null; // profile templates
03269 
03270         # SUBST
03271         wfProfileIn( __METHOD__ . '-modifiers' );
03272         if ( !$found ) {
03273 
03274             $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
03275 
03276             # Possibilities for substMatch: "subst", "safesubst" or FALSE
03277             # Decide whether to expand template or keep wikitext as-is.
03278             if ( $this->ot['wiki'] ) {
03279                 if ( $substMatch === false ) {
03280                     $literal = true;  # literal when in PST with no prefix
03281                 } else {
03282                     $literal = false; # expand when in PST with subst: or safesubst:
03283                 }
03284             } else {
03285                 if ( $substMatch == 'subst' ) {
03286                     $literal = true;  # literal when not in PST with plain subst:
03287                 } else {
03288                     $literal = false; # expand when not in PST with safesubst: or no prefix
03289                 }
03290             }
03291             if ( $literal ) {
03292                 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
03293                 $isLocalObj = true;
03294                 $found = true;
03295             }
03296         }
03297 
03298         # Variables
03299         if ( !$found && $args->getLength() == 0 ) {
03300             $id = $this->mVariables->matchStartToEnd( $part1 );
03301             if ( $id !== false ) {
03302                 $text = $this->getVariableValue( $id, $frame );
03303                 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
03304                     $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
03305                 }
03306                 $found = true;
03307             }
03308         }
03309 
03310         # MSG, MSGNW and RAW
03311         if ( !$found ) {
03312             # Check for MSGNW:
03313             $mwMsgnw = MagicWord::get( 'msgnw' );
03314             if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
03315                 $nowiki = true;
03316             } else {
03317                 # Remove obsolete MSG:
03318                 $mwMsg = MagicWord::get( 'msg' );
03319                 $mwMsg->matchStartAndRemove( $part1 );
03320             }
03321 
03322             # Check for RAW:
03323             $mwRaw = MagicWord::get( 'raw' );
03324             if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
03325                 $forceRawInterwiki = true;
03326             }
03327         }
03328         wfProfileOut( __METHOD__ . '-modifiers' );
03329 
03330         # Parser functions
03331         if ( !$found ) {
03332             wfProfileIn( __METHOD__ . '-pfunc' );
03333 
03334             $colonPos = strpos( $part1, ':' );
03335             if ( $colonPos !== false ) {
03336                 $func = substr( $part1, 0, $colonPos );
03337                 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
03338                 for ( $i = 0; $i < $args->getLength(); $i++ ) {
03339                     $funcArgs[] = $args->item( $i );
03340                 }
03341                 try {
03342                     $result = $this->callParserFunction( $frame, $func, $funcArgs );
03343                 } catch ( Exception $ex ) {
03344                     wfProfileOut( __METHOD__ . '-pfunc' );
03345                     wfProfileOut( __METHOD__ );
03346                     throw $ex;
03347                 }
03348 
03349                 # The interface for parser functions allows for extracting
03350                 # flags into the local scope. Extract any forwarded flags
03351                 # here.
03352                 extract( $result );
03353             }
03354             wfProfileOut( __METHOD__ . '-pfunc' );
03355         }
03356 
03357         # Finish mangling title and then check for loops.
03358         # Set $title to a Title object and $titleText to the PDBK
03359         if ( !$found ) {
03360             $ns = NS_TEMPLATE;
03361             # Split the title into page and subpage
03362             $subpage = '';
03363             $relative = $this->maybeDoSubpageLink( $part1, $subpage );
03364             if ( $part1 !== $relative ) {
03365                 $part1 = $relative;
03366                 $ns = $this->mTitle->getNamespace();
03367             }
03368             $title = Title::newFromText( $part1, $ns );
03369             if ( $title ) {
03370                 $titleText = $title->getPrefixedText();
03371                 # Check for language variants if the template is not found
03372                 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
03373                     $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
03374                 }
03375                 # Do recursion depth check
03376                 $limit = $this->mOptions->getMaxTemplateDepth();
03377                 if ( $frame->depth >= $limit ) {
03378                     $found = true;
03379                     $text = '<span class="error">'
03380                         . wfMessage( 'parser-template-recursion-depth-warning' )
03381                             ->numParams( $limit )->inContentLanguage()->text()
03382                         . '</span>';
03383                 }
03384             }
03385         }
03386 
03387         # Load from database
03388         if ( !$found && $title ) {
03389             if ( !Profiler::instance()->isPersistent() ) {
03390                 # Too many unique items can kill profiling DBs/collectors
03391                 $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey();
03392                 wfProfileIn( $titleProfileIn ); // template in
03393             }
03394             wfProfileIn( __METHOD__ . '-loadtpl' );
03395             if ( !$title->isExternal() ) {
03396                 if ( $title->isSpecialPage()
03397                     && $this->mOptions->getAllowSpecialInclusion()
03398                     && $this->ot['html']
03399                 ) {
03400                     // Pass the template arguments as URL parameters.
03401                     // "uselang" will have no effect since the Language object
03402                     // is forced to the one defined in ParserOptions.
03403                     $pageArgs = array();
03404                     for ( $i = 0; $i < $args->getLength(); $i++ ) {
03405                         $bits = $args->item( $i )->splitArg();
03406                         if ( strval( $bits['index'] ) === '' ) {
03407                             $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
03408                             $value = trim( $frame->expand( $bits['value'] ) );
03409                             $pageArgs[$name] = $value;
03410                         }
03411                     }
03412 
03413                     // Create a new context to execute the special page
03414                     $context = new RequestContext;
03415                     $context->setTitle( $title );
03416                     $context->setRequest( new FauxRequest( $pageArgs ) );
03417                     $context->setUser( $this->getUser() );
03418                     $context->setLanguage( $this->mOptions->getUserLangObj() );
03419                     $ret = SpecialPageFactory::capturePath( $title, $context );
03420                     if ( $ret ) {
03421                         $text = $context->getOutput()->getHTML();
03422                         $this->mOutput->addOutputPageMetadata( $context->getOutput() );
03423                         $found = true;
03424                         $isHTML = true;
03425                         $this->disableCache();
03426                     }
03427                 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
03428                     $found = false; # access denied
03429                     wfDebug( __METHOD__ . ": template inclusion denied for " .
03430                         $title->getPrefixedDBkey() . "\n" );
03431                 } else {
03432                     list( $text, $title ) = $this->getTemplateDom( $title );
03433                     if ( $text !== false ) {
03434                         $found = true;
03435                         $isChildObj = true;
03436                     }
03437                 }
03438 
03439                 # If the title is valid but undisplayable, make a link to it
03440                 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
03441                     $text = "[[:$titleText]]";
03442                     $found = true;
03443                 }
03444             } elseif ( $title->isTrans() ) {
03445                 # Interwiki transclusion
03446                 if ( $this->ot['html'] && !$forceRawInterwiki ) {
03447                     $text = $this->interwikiTransclude( $title, 'render' );
03448                     $isHTML = true;
03449                 } else {
03450                     $text = $this->interwikiTransclude( $title, 'raw' );
03451                     # Preprocess it like a template
03452                     $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
03453                     $isChildObj = true;
03454                 }
03455                 $found = true;
03456             }
03457 
03458             # Do infinite loop check
03459             # This has to be done after redirect resolution to avoid infinite loops via redirects
03460             if ( !$frame->loopCheck( $title ) ) {
03461                 $found = true;
03462                 $text = '<span class="error">'
03463                     . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
03464                     . '</span>';
03465                 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
03466             }
03467             wfProfileOut( __METHOD__ . '-loadtpl' );
03468         }
03469 
03470         # If we haven't found text to substitute by now, we're done
03471         # Recover the source wikitext and return it
03472         if ( !$found ) {
03473             $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
03474             if ( $titleProfileIn ) {
03475                 wfProfileOut( $titleProfileIn ); // template out
03476             }
03477             wfProfileOut( __METHOD__ );
03478             return array( 'object' => $text );
03479         }
03480 
03481         # Expand DOM-style return values in a child frame
03482         if ( $isChildObj ) {
03483             # Clean up argument array
03484             $newFrame = $frame->newChild( $args, $title );
03485 
03486             if ( $nowiki ) {
03487                 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
03488             } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
03489                 # Expansion is eligible for the empty-frame cache
03490                 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
03491                     $text = $this->mTplExpandCache[$titleText];
03492                 } else {
03493                     $text = $newFrame->expand( $text );
03494                     $this->mTplExpandCache[$titleText] = $text;
03495                 }
03496             } else {
03497                 # Uncached expansion
03498                 $text = $newFrame->expand( $text );
03499             }
03500         }
03501         if ( $isLocalObj && $nowiki ) {
03502             $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
03503             $isLocalObj = false;
03504         }
03505 
03506         if ( $titleProfileIn ) {
03507             wfProfileOut( $titleProfileIn ); // template out
03508         }
03509 
03510         # Replace raw HTML by a placeholder
03511         if ( $isHTML ) {
03512             $text = $this->insertStripItem( $text );
03513         } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
03514             # Escape nowiki-style return values
03515             $text = wfEscapeWikiText( $text );
03516         } elseif ( is_string( $text )
03517             && !$piece['lineStart']
03518             && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
03519         ) {
03520             # Bug 529: if the template begins with a table or block-level
03521             # element, it should be treated as beginning a new line.
03522             # This behavior is somewhat controversial.
03523             $text = "\n" . $text;
03524         }
03525 
03526         if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
03527             # Error, oversize inclusion
03528             if ( $titleText !== false ) {
03529                 # Make a working, properly escaped link if possible (bug 23588)
03530                 $text = "[[:$titleText]]";
03531             } else {
03532                 # This will probably not be a working link, but at least it may
03533                 # provide some hint of where the problem is
03534                 preg_replace( '/^:/', '', $originalTitle );
03535                 $text = "[[:$originalTitle]]";
03536             }
03537             $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
03538             $this->limitationWarn( 'post-expand-template-inclusion' );
03539         }
03540 
03541         if ( $isLocalObj ) {
03542             $ret = array( 'object' => $text );
03543         } else {
03544             $ret = array( 'text' => $text );
03545         }
03546 
03547         wfProfileOut( __METHOD__ );
03548         return $ret;
03549     }
03550 
03569     public function callParserFunction( $frame, $function, array $args = array() ) {
03570         global $wgContLang;
03571 
03572         wfProfileIn( __METHOD__ );
03573 
03574         # Case sensitive functions
03575         if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
03576             $function = $this->mFunctionSynonyms[1][$function];
03577         } else {
03578             # Case insensitive functions
03579             $function = $wgContLang->lc( $function );
03580             if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
03581                 $function = $this->mFunctionSynonyms[0][$function];
03582             } else {
03583                 wfProfileOut( __METHOD__ );
03584                 return array( 'found' => false );
03585             }
03586         }
03587 
03588         wfProfileIn( __METHOD__ . '-pfunc-' . $function );
03589         list( $callback, $flags ) = $this->mFunctionHooks[$function];
03590 
03591         # Workaround for PHP bug 35229 and similar
03592         if ( !is_callable( $callback ) ) {
03593             wfProfileOut( __METHOD__ . '-pfunc-' . $function );
03594             wfProfileOut( __METHOD__ );
03595             throw new MWException( "Tag hook for $function is not callable\n" );
03596         }
03597 
03598         $allArgs = array( &$this );
03599         if ( $flags & SFH_OBJECT_ARGS ) {
03600             # Convert arguments to PPNodes and collect for appending to $allArgs
03601             $funcArgs = array();
03602             foreach ( $args as $k => $v ) {
03603                 if ( $v instanceof PPNode || $k === 0 ) {
03604                     $funcArgs[] = $v;
03605                 } else {
03606                     $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
03607                 }
03608             }
03609 
03610             # Add a frame parameter, and pass the arguments as an array
03611             $allArgs[] = $frame;
03612             $allArgs[] = $funcArgs;
03613         } else {
03614             # Convert arguments to plain text and append to $allArgs
03615             foreach ( $args as $k => $v ) {
03616                 if ( $v instanceof PPNode ) {
03617                     $allArgs[] = trim( $frame->expand( $v ) );
03618                 } elseif ( is_int( $k ) && $k >= 0 ) {
03619                     $allArgs[] = trim( $v );
03620                 } else {
03621                     $allArgs[] = trim( "$k=$v" );
03622                 }
03623             }
03624         }
03625 
03626         $result = call_user_func_array( $callback, $allArgs );
03627 
03628         # The interface for function hooks allows them to return a wikitext
03629         # string or an array containing the string and any flags. This mungs
03630         # things around to match what this method should return.
03631         if ( !is_array( $result ) ) {
03632             $result = array(
03633                 'found' => true,
03634                 'text' => $result,
03635             );
03636         } else {
03637             if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
03638                 $result['text'] = $result[0];
03639             }
03640             unset( $result[0] );
03641             $result += array(
03642                 'found' => true,
03643             );
03644         }
03645 
03646         $noparse = true;
03647         $preprocessFlags = 0;
03648         if ( isset( $result['noparse'] ) ) {
03649             $noparse = $result['noparse'];
03650         }
03651         if ( isset( $result['preprocessFlags'] ) ) {
03652             $preprocessFlags = $result['preprocessFlags'];
03653         }
03654 
03655         if ( !$noparse ) {
03656             $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
03657             $result['isChildObj'] = true;
03658         }
03659         wfProfileOut( __METHOD__ . '-pfunc-' . $function );
03660         wfProfileOut( __METHOD__ );
03661 
03662         return $result;
03663     }
03664 
03673     function getTemplateDom( $title ) {
03674         $cacheTitle = $title;
03675         $titleText = $title->getPrefixedDBkey();
03676 
03677         if ( isset( $this->mTplRedirCache[$titleText] ) ) {
03678             list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
03679             $title = Title::makeTitle( $ns, $dbk );
03680             $titleText = $title->getPrefixedDBkey();
03681         }
03682         if ( isset( $this->mTplDomCache[$titleText] ) ) {
03683             return array( $this->mTplDomCache[$titleText], $title );
03684         }
03685 
03686         # Cache miss, go to the database
03687         list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
03688 
03689         if ( $text === false ) {
03690             $this->mTplDomCache[$titleText] = false;
03691             return array( false, $title );
03692         }
03693 
03694         $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
03695         $this->mTplDomCache[$titleText] = $dom;
03696 
03697         if ( !$title->equals( $cacheTitle ) ) {
03698             $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
03699                 array( $title->getNamespace(), $cdb = $title->getDBkey() );
03700         }
03701 
03702         return array( $dom, $title );
03703     }
03704 
03710     function fetchTemplateAndTitle( $title ) {
03711         $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
03712         $stuff = call_user_func( $templateCb, $title, $this );
03713         $text = $stuff['text'];
03714         $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
03715         if ( isset( $stuff['deps'] ) ) {
03716             foreach ( $stuff['deps'] as $dep ) {
03717                 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
03718                 if ( $dep['title']->equals( $this->getTitle() ) ) {
03719                     // If we transclude ourselves, the final result
03720                     // will change based on the new version of the page
03721                     $this->mOutput->setFlag( 'vary-revision' );
03722                 }
03723             }
03724         }
03725         return array( $text, $finalTitle );
03726     }
03727 
03733     function fetchTemplate( $title ) {
03734         $rv = $this->fetchTemplateAndTitle( $title );
03735         return $rv[0];
03736     }
03737 
03747     static function statelessFetchTemplate( $title, $parser = false ) {
03748         $text = $skip = false;
03749         $finalTitle = $title;
03750         $deps = array();
03751 
03752         # Loop to fetch the article, with up to 1 redirect
03753         for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
03754             # Give extensions a chance to select the revision instead
03755             $id = false; # Assume current
03756             wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
03757                 array( $parser, $title, &$skip, &$id ) );
03758 
03759             if ( $skip ) {
03760                 $text = false;
03761                 $deps[] = array(
03762                     'title' => $title,
03763                     'page_id' => $title->getArticleID(),
03764                     'rev_id' => null
03765                 );
03766                 break;
03767             }
03768             # Get the revision
03769             $rev = $id
03770                 ? Revision::newFromId( $id )
03771                 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
03772             $rev_id = $rev ? $rev->getId() : 0;
03773             # If there is no current revision, there is no page
03774             if ( $id === false && !$rev ) {
03775                 $linkCache = LinkCache::singleton();
03776                 $linkCache->addBadLinkObj( $title );
03777             }
03778 
03779             $deps[] = array(
03780                 'title' => $title,
03781                 'page_id' => $title->getArticleID(),
03782                 'rev_id' => $rev_id );
03783             if ( $rev && !$title->equals( $rev->getTitle() ) ) {
03784                 # We fetched a rev from a different title; register it too...
03785                 $deps[] = array(
03786                     'title' => $rev->getTitle(),
03787                     'page_id' => $rev->getPage(),
03788                     'rev_id' => $rev_id );
03789             }
03790 
03791             if ( $rev ) {
03792                 $content = $rev->getContent();
03793                 $text = $content ? $content->getWikitextForTransclusion() : null;
03794 
03795                 if ( $text === false || $text === null ) {
03796                     $text = false;
03797                     break;
03798                 }
03799             } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
03800                 global $wgContLang;
03801                 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
03802                 if ( !$message->exists() ) {
03803                     $text = false;
03804                     break;
03805                 }
03806                 $content = $message->content();
03807                 $text = $message->plain();
03808             } else {
03809                 break;
03810             }
03811             if ( !$content ) {
03812                 break;
03813             }
03814             # Redirect?
03815             $finalTitle = $title;
03816             $title = $content->getRedirectTarget();
03817         }
03818         return array(
03819             'text' => $text,
03820             'finalTitle' => $finalTitle,
03821             'deps' => $deps );
03822     }
03823 
03831     function fetchFile( $title, $options = array() ) {
03832         $res = $this->fetchFileAndTitle( $title, $options );
03833         return $res[0];
03834     }
03835 
03843     function fetchFileAndTitle( $title, $options = array() ) {
03844         $file = $this->fetchFileNoRegister( $title, $options );
03845 
03846         $time = $file ? $file->getTimestamp() : false;
03847         $sha1 = $file ? $file->getSha1() : false;
03848         # Register the file as a dependency...
03849         $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
03850         if ( $file && !$title->equals( $file->getTitle() ) ) {
03851             # Update fetched file title
03852             $title = $file->getTitle();
03853             $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
03854         }
03855         return array( $file, $title );
03856     }
03857 
03868     protected function fetchFileNoRegister( $title, $options = array() ) {
03869         if ( isset( $options['broken'] ) ) {
03870             $file = false; // broken thumbnail forced by hook
03871         } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
03872             $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
03873         } else { // get by (name,timestamp)
03874             $file = wfFindFile( $title, $options );
03875         }
03876         return $file;
03877     }
03878 
03887     function interwikiTransclude( $title, $action ) {
03888         global $wgEnableScaryTranscluding;
03889 
03890         if ( !$wgEnableScaryTranscluding ) {
03891             return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
03892         }
03893 
03894         $url = $title->getFullURL( array( 'action' => $action ) );
03895 
03896         if ( strlen( $url ) > 255 ) {
03897             return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
03898         }
03899         return $this->fetchScaryTemplateMaybeFromCache( $url );
03900     }
03901 
03906     function fetchScaryTemplateMaybeFromCache( $url ) {
03907         global $wgTranscludeCacheExpiry;
03908         $dbr = wfGetDB( DB_SLAVE );
03909         $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
03910         $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
03911                 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
03912         if ( $obj ) {
03913             return $obj->tc_contents;
03914         }
03915 
03916         $req = MWHttpRequest::factory( $url );
03917         $status = $req->execute(); // Status object
03918         if ( $status->isOK() ) {
03919             $text = $req->getContent();
03920         } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
03921             return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
03922         } else {
03923             return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
03924         }
03925 
03926         $dbw = wfGetDB( DB_MASTER );
03927         $dbw->replace( 'transcache', array( 'tc_url' ), array(
03928             'tc_url' => $url,
03929             'tc_time' => $dbw->timestamp( time() ),
03930             'tc_contents' => $text
03931         ) );
03932         return $text;
03933     }
03934 
03944     function argSubstitution( $piece, $frame ) {
03945         wfProfileIn( __METHOD__ );
03946 
03947         $error = false;
03948         $parts = $piece['parts'];
03949         $nameWithSpaces = $frame->expand( $piece['title'] );
03950         $argName = trim( $nameWithSpaces );
03951         $object = false;
03952         $text = $frame->getArgument( $argName );
03953         if ( $text === false && $parts->getLength() > 0
03954             && ( $this->ot['html']
03955                 || $this->ot['pre']
03956                 || ( $this->ot['wiki'] && $frame->isTemplate() )
03957             )
03958         ) {
03959             # No match in frame, use the supplied default
03960             $object = $parts->item( 0 )->getChildren();
03961         }
03962         if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
03963             $error = '<!-- WARNING: argument omitted, expansion size too large -->';
03964             $this->limitationWarn( 'post-expand-template-argument' );
03965         }
03966 
03967         if ( $text === false && $object === false ) {
03968             # No match anywhere
03969             $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
03970         }
03971         if ( $error !== false ) {
03972             $text .= $error;
03973         }
03974         if ( $object !== false ) {
03975             $ret = array( 'object' => $object );
03976         } else {
03977             $ret = array( 'text' => $text );
03978         }
03979 
03980         wfProfileOut( __METHOD__ );
03981         return $ret;
03982     }
03983 
03999     function extensionSubstitution( $params, $frame ) {
04000         $name = $frame->expand( $params['name'] );
04001         $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
04002         $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
04003         $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
04004 
04005         $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
04006             ( $this->ot['html'] || $this->ot['pre'] );
04007         if ( $isFunctionTag ) {
04008             $markerType = 'none';
04009         } else {
04010             $markerType = 'general';
04011         }
04012         if ( $this->ot['html'] || $isFunctionTag ) {
04013             $name = strtolower( $name );
04014             $attributes = Sanitizer::decodeTagAttributes( $attrText );
04015             if ( isset( $params['attributes'] ) ) {
04016                 $attributes = $attributes + $params['attributes'];
04017             }
04018 
04019             if ( isset( $this->mTagHooks[$name] ) ) {
04020                 # Workaround for PHP bug 35229 and similar
04021                 if ( !is_callable( $this->mTagHooks[$name] ) ) {
04022                     throw new MWException( "Tag hook for $name is not callable\n" );
04023                 }
04024                 $output = call_user_func_array( $this->mTagHooks[$name],
04025                     array( $content, $attributes, $this, $frame ) );
04026             } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
04027                 list( $callback, ) = $this->mFunctionTagHooks[$name];
04028                 if ( !is_callable( $callback ) ) {
04029                     throw new MWException( "Tag hook for $name is not callable\n" );
04030                 }
04031 
04032                 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
04033             } else {
04034                 $output = '<span class="error">Invalid tag extension name: ' .
04035                     htmlspecialchars( $name ) . '</span>';
04036             }
04037 
04038             if ( is_array( $output ) ) {
04039                 # Extract flags to local scope (to override $markerType)
04040                 $flags = $output;
04041                 $output = $flags[0];
04042                 unset( $flags[0] );
04043                 extract( $flags );
04044             }
04045         } else {
04046             if ( is_null( $attrText ) ) {
04047                 $attrText = '';
04048             }
04049             if ( isset( $params['attributes'] ) ) {
04050                 foreach ( $params['attributes'] as $attrName => $attrValue ) {
04051                     $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
04052                         htmlspecialchars( $attrValue ) . '"';
04053                 }
04054             }
04055             if ( $content === null ) {
04056                 $output = "<$name$attrText/>";
04057             } else {
04058                 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
04059                 $output = "<$name$attrText>$content$close";
04060             }
04061         }
04062 
04063         if ( $markerType === 'none' ) {
04064             return $output;
04065         } elseif ( $markerType === 'nowiki' ) {
04066             $this->mStripState->addNoWiki( $marker, $output );
04067         } elseif ( $markerType === 'general' ) {
04068             $this->mStripState->addGeneral( $marker, $output );
04069         } else {
04070             throw new MWException( __METHOD__ . ': invalid marker type' );
04071         }
04072         return $marker;
04073     }
04074 
04082     function incrementIncludeSize( $type, $size ) {
04083         if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
04084             return false;
04085         } else {
04086             $this->mIncludeSizes[$type] += $size;
04087             return true;
04088         }
04089     }
04090 
04096     function incrementExpensiveFunctionCount() {
04097         $this->mExpensiveFunctionCount++;
04098         return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
04099     }
04100 
04109     function doDoubleUnderscore( $text ) {
04110         wfProfileIn( __METHOD__ );
04111 
04112         # The position of __TOC__ needs to be recorded
04113         $mw = MagicWord::get( 'toc' );
04114         if ( $mw->match( $text ) ) {
04115             $this->mShowToc = true;
04116             $this->mForceTocPosition = true;
04117 
04118             # Set a placeholder. At the end we'll fill it in with the TOC.
04119             $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
04120 
04121             # Only keep the first one.
04122             $text = $mw->replace( '', $text );
04123         }
04124 
04125         # Now match and remove the rest of them
04126         $mwa = MagicWord::getDoubleUnderscoreArray();
04127         $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
04128 
04129         if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
04130             $this->mOutput->mNoGallery = true;
04131         }
04132         if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
04133             $this->mShowToc = false;
04134         }
04135         if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
04136             $this->addTrackingCategory( 'hidden-category-category' );
04137         }
04138         # (bug 8068) Allow control over whether robots index a page.
04139         #
04140         # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here!  This
04141         # is not desirable, the last one on the page should win.
04142         if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
04143             $this->mOutput->setIndexPolicy( 'noindex' );
04144             $this->addTrackingCategory( 'noindex-category' );
04145         }
04146         if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
04147             $this->mOutput->setIndexPolicy( 'index' );
04148             $this->addTrackingCategory( 'index-category' );
04149         }
04150 
04151         # Cache all double underscores in the database
04152         foreach ( $this->mDoubleUnderscores as $key => $val ) {
04153             $this->mOutput->setProperty( $key, '' );
04154         }
04155 
04156         wfProfileOut( __METHOD__ );
04157         return $text;
04158     }
04159 
04171     public function addTrackingCategory( $msg ) {
04172         if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
04173             wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
04174             return false;
04175         }
04176         // Important to parse with correct title (bug 31469)
04177         $cat = wfMessage( $msg )
04178             ->title( $this->getTitle() )
04179             ->inContentLanguage()
04180             ->text();
04181 
04182         # Allow tracking categories to be disabled by setting them to "-"
04183         if ( $cat === '-' ) {
04184             return false;
04185         }
04186 
04187         $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
04188         if ( $containerCategory ) {
04189             $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
04190             return true;
04191         } else {
04192             wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
04193             return false;
04194         }
04195     }
04196 
04213     function formatHeadings( $text, $origText, $isMain = true ) {
04214         global $wgMaxTocLevel, $wgExperimentalHtmlIds;
04215 
04216         # Inhibit editsection links if requested in the page
04217         if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
04218             $maybeShowEditLink = $showEditLink = false;
04219         } else {
04220             $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
04221             $showEditLink = $this->mOptions->getEditSection();
04222         }
04223         if ( $showEditLink ) {
04224             $this->mOutput->setEditSectionTokens( true );
04225         }
04226 
04227         # Get all headlines for numbering them and adding funky stuff like [edit]
04228         # links - this is for later, but we need the number of headlines right now
04229         $matches = array();
04230         $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
04231 
04232         # if there are fewer than 4 headlines in the article, do not show TOC
04233         # unless it's been explicitly enabled.
04234         $enoughToc = $this->mShowToc &&
04235             ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
04236 
04237         # Allow user to stipulate that a page should have a "new section"
04238         # link added via __NEWSECTIONLINK__
04239         if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
04240             $this->mOutput->setNewSection( true );
04241         }
04242 
04243         # Allow user to remove the "new section"
04244         # link via __NONEWSECTIONLINK__
04245         if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
04246             $this->mOutput->hideNewSection( true );
04247         }
04248 
04249         # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
04250         # override above conditions and always show TOC above first header
04251         if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
04252             $this->mShowToc = true;
04253             $enoughToc = true;
04254         }
04255 
04256         # headline counter
04257         $headlineCount = 0;
04258         $numVisible = 0;
04259 
04260         # Ugh .. the TOC should have neat indentation levels which can be
04261         # passed to the skin functions. These are determined here
04262         $toc = '';
04263         $full = '';
04264         $head = array();
04265         $sublevelCount = array();
04266         $levelCount = array();
04267         $level = 0;
04268         $prevlevel = 0;
04269         $toclevel = 0;
04270         $prevtoclevel = 0;
04271         $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
04272         $baseTitleText = $this->mTitle->getPrefixedDBkey();
04273         $oldType = $this->mOutputType;
04274         $this->setOutputType( self::OT_WIKI );
04275         $frame = $this->getPreprocessor()->newFrame();
04276         $root = $this->preprocessToDom( $origText );
04277         $node = $root->getFirstChild();
04278         $byteOffset = 0;
04279         $tocraw = array();
04280         $refers = array();
04281 
04282         foreach ( $matches[3] as $headline ) {
04283             $isTemplate = false;
04284             $titleText = false;
04285             $sectionIndex = false;
04286             $numbering = '';
04287             $markerMatches = array();
04288             if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
04289                 $serial = $markerMatches[1];
04290                 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
04291                 $isTemplate = ( $titleText != $baseTitleText );
04292                 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
04293             }
04294 
04295             if ( $toclevel ) {
04296                 $prevlevel = $level;
04297             }
04298             $level = $matches[1][$headlineCount];
04299 
04300             if ( $level > $prevlevel ) {
04301                 # Increase TOC level
04302                 $toclevel++;
04303                 $sublevelCount[$toclevel] = 0;
04304                 if ( $toclevel < $wgMaxTocLevel ) {
04305                     $prevtoclevel = $toclevel;
04306                     $toc .= Linker::tocIndent();
04307                     $numVisible++;
04308                 }
04309             } elseif ( $level < $prevlevel && $toclevel > 1 ) {
04310                 # Decrease TOC level, find level to jump to
04311 
04312                 for ( $i = $toclevel; $i > 0; $i-- ) {
04313                     if ( $levelCount[$i] == $level ) {
04314                         # Found last matching level
04315                         $toclevel = $i;
04316                         break;
04317                     } elseif ( $levelCount[$i] < $level ) {
04318                         # Found first matching level below current level
04319                         $toclevel = $i + 1;
04320                         break;
04321                     }
04322                 }
04323                 if ( $i == 0 ) {
04324                     $toclevel = 1;
04325                 }
04326                 if ( $toclevel < $wgMaxTocLevel ) {
04327                     if ( $prevtoclevel < $wgMaxTocLevel ) {
04328                         # Unindent only if the previous toc level was shown :p
04329                         $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
04330                         $prevtoclevel = $toclevel;
04331                     } else {
04332                         $toc .= Linker::tocLineEnd();
04333                     }
04334                 }
04335             } else {
04336                 # No change in level, end TOC line
04337                 if ( $toclevel < $wgMaxTocLevel ) {
04338                     $toc .= Linker::tocLineEnd();
04339                 }
04340             }
04341 
04342             $levelCount[$toclevel] = $level;
04343 
04344             # count number of headlines for each level
04345             $sublevelCount[$toclevel]++;
04346             $dot = 0;
04347             for ( $i = 1; $i <= $toclevel; $i++ ) {
04348                 if ( !empty( $sublevelCount[$i] ) ) {
04349                     if ( $dot ) {
04350                         $numbering .= '.';
04351                     }
04352                     $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
04353                     $dot = 1;
04354                 }
04355             }
04356 
04357             # The safe header is a version of the header text safe to use for links
04358 
04359             # Remove link placeholders by the link text.
04360             #     <!--LINK number-->
04361             # turns into
04362             #     link text with suffix
04363             # Do this before unstrip since link text can contain strip markers
04364             $safeHeadline = $this->replaceLinkHoldersText( $headline );
04365 
04366             # Avoid insertion of weird stuff like <math> by expanding the relevant sections
04367             $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
04368 
04369             # Strip out HTML (first regex removes any tag not allowed)
04370             # Allowed tags are:
04371             # * <sup> and <sub> (bug 8393)
04372             # * <i> (bug 26375)
04373             # * <b> (r105284)
04374             # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
04375             #
04376             # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
04377             # to allow setting directionality in toc items.
04378             $tocline = preg_replace(
04379                 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
04380                 array( '', '<$1>' ),
04381                 $safeHeadline
04382             );
04383             $tocline = trim( $tocline );
04384 
04385             # For the anchor, strip out HTML-y stuff period
04386             $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
04387             $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
04388 
04389             # Save headline for section edit hint before it's escaped
04390             $headlineHint = $safeHeadline;
04391 
04392             if ( $wgExperimentalHtmlIds ) {
04393                 # For reverse compatibility, provide an id that's
04394                 # HTML4-compatible, like we used to.
04395                 #
04396                 # It may be worth noting, academically, that it's possible for
04397                 # the legacy anchor to conflict with a non-legacy headline
04398                 # anchor on the page.  In this case likely the "correct" thing
04399                 # would be to either drop the legacy anchors or make sure
04400                 # they're numbered first.  However, this would require people
04401                 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
04402                 # manually, so let's not bother worrying about it.
04403                 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
04404                     array( 'noninitial', 'legacy' ) );
04405                 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
04406 
04407                 if ( $legacyHeadline == $safeHeadline ) {
04408                     # No reason to have both (in fact, we can't)
04409                     $legacyHeadline = false;
04410                 }
04411             } else {
04412                 $legacyHeadline = false;
04413                 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
04414                     'noninitial' );
04415             }
04416 
04417             # HTML names must be case-insensitively unique (bug 10721).
04418             # This does not apply to Unicode characters per
04419             # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
04420             # @todo FIXME: We may be changing them depending on the current locale.
04421             $arrayKey = strtolower( $safeHeadline );
04422             if ( $legacyHeadline === false ) {
04423                 $legacyArrayKey = false;
04424             } else {
04425                 $legacyArrayKey = strtolower( $legacyHeadline );
04426             }
04427 
04428             # count how many in assoc. array so we can track dupes in anchors
04429             if ( isset( $refers[$arrayKey] ) ) {
04430                 $refers[$arrayKey]++;
04431             } else {
04432                 $refers[$arrayKey] = 1;
04433             }
04434             if ( isset( $refers[$legacyArrayKey] ) ) {
04435                 $refers[$legacyArrayKey]++;
04436             } else {
04437                 $refers[$legacyArrayKey] = 1;
04438             }
04439 
04440             # Don't number the heading if it is the only one (looks silly)
04441             if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
04442                 # the two are different if the line contains a link
04443                 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
04444             }
04445 
04446             # Create the anchor for linking from the TOC to the section
04447             $anchor = $safeHeadline;
04448             $legacyAnchor = $legacyHeadline;
04449             if ( $refers[$arrayKey] > 1 ) {
04450                 $anchor .= '_' . $refers[$arrayKey];
04451             }
04452             if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
04453                 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
04454             }
04455             if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
04456                 $toc .= Linker::tocLine( $anchor, $tocline,
04457                     $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
04458             }
04459 
04460             # Add the section to the section tree
04461             # Find the DOM node for this header
04462             $noOffset = ( $isTemplate || $sectionIndex === false );
04463             while ( $node && !$noOffset ) {
04464                 if ( $node->getName() === 'h' ) {
04465                     $bits = $node->splitHeading();
04466                     if ( $bits['i'] == $sectionIndex ) {
04467                         break;
04468                     }
04469                 }
04470                 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
04471                     $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
04472                 $node = $node->getNextSibling();
04473             }
04474             $tocraw[] = array(
04475                 'toclevel' => $toclevel,
04476                 'level' => $level,
04477                 'line' => $tocline,
04478                 'number' => $numbering,
04479                 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
04480                 'fromtitle' => $titleText,
04481                 'byteoffset' => ( $noOffset ? null : $byteOffset ),
04482                 'anchor' => $anchor,
04483             );
04484 
04485             # give headline the correct <h#> tag
04486             if ( $maybeShowEditLink && $sectionIndex !== false ) {
04487                 // Output edit section links as markers with styles that can be customized by skins
04488                 if ( $isTemplate ) {
04489                     # Put a T flag in the section identifier, to indicate to extractSections()
04490                     # that sections inside <includeonly> should be counted.
04491                     $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
04492                 } else {
04493                     $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
04494                 }
04495                 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
04496                 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
04497                 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
04498                 // so we don't have to worry about a user trying to input one of these markers directly.
04499                 // We use a page and section attribute to stop the language converter from converting these important bits
04500                 // of data, but put the headline hint inside a content block because the language converter is supposed to
04501                 // be able to convert that piece of data.
04502                 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
04503                 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
04504                 if ( isset( $editlinkArgs[2] ) ) {
04505                     $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
04506                 } else {
04507                     $editlink .= '/>';
04508                 }
04509             } else {
04510                 $editlink = '';
04511             }
04512             $head[$headlineCount] = Linker::makeHeadline( $level,
04513                 $matches['attrib'][$headlineCount], $anchor, $headline,
04514                 $editlink, $legacyAnchor );
04515 
04516             $headlineCount++;
04517         }
04518 
04519         $this->setOutputType( $oldType );
04520 
04521         # Never ever show TOC if no headers
04522         if ( $numVisible < 1 ) {
04523             $enoughToc = false;
04524         }
04525 
04526         if ( $enoughToc ) {
04527             if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
04528                 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
04529             }
04530             $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
04531             $this->mOutput->setTOCHTML( $toc );
04532             $toc = self::TOC_START . $toc . self::TOC_END;
04533             $this->mOutput->addModules( 'mediawiki.toc' );
04534         }
04535 
04536         if ( $isMain ) {
04537             $this->mOutput->setSections( $tocraw );
04538         }
04539 
04540         # split up and insert constructed headlines
04541         $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
04542         $i = 0;
04543 
04544         // build an array of document sections
04545         $sections = array();
04546         foreach ( $blocks as $block ) {
04547             // $head is zero-based, sections aren't.
04548             if ( empty( $head[$i - 1] ) ) {
04549                 $sections[$i] = $block;
04550             } else {
04551                 $sections[$i] = $head[$i - 1] . $block;
04552             }
04553 
04564             wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
04565 
04566             $i++;
04567         }
04568 
04569         if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
04570             // append the TOC at the beginning
04571             // Top anchor now in skin
04572             $sections[0] = $sections[0] . $toc . "\n";
04573         }
04574 
04575         $full .= join( '', $sections );
04576 
04577         if ( $this->mForceTocPosition ) {
04578             return str_replace( '<!--MWTOC-->', $toc, $full );
04579         } else {
04580             return $full;
04581         }
04582     }
04583 
04595     public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
04596         $this->startParse( $title, $options, self::OT_WIKI, $clearState );
04597         $this->setUser( $user );
04598 
04599         $pairs = array(
04600             "\r\n" => "\n",
04601         );
04602         $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
04603         if ( $options->getPreSaveTransform() ) {
04604             $text = $this->pstPass2( $text, $user );
04605         }
04606         $text = $this->mStripState->unstripBoth( $text );
04607 
04608         $this->setUser( null ); #Reset
04609 
04610         return $text;
04611     }
04612 
04621     private function pstPass2( $text, $user ) {
04622         global $wgContLang;
04623 
04624         # Note: This is the timestamp saved as hardcoded wikitext to
04625         # the database, we use $wgContLang here in order to give
04626         # everyone the same signature and use the default one rather
04627         # than the one selected in each user's preferences.
04628         # (see also bug 12815)
04629         $ts = $this->mOptions->getTimestamp();
04630         $timestamp = MWTimestamp::getLocalInstance( $ts );
04631         $ts = $timestamp->format( 'YmdHis' );
04632         $tzMsg = $timestamp->format( 'T' );  # might vary on DST changeover!
04633 
04634         # Allow translation of timezones through wiki. format() can return
04635         # whatever crap the system uses, localised or not, so we cannot
04636         # ship premade translations.
04637         $key = 'timezone-' . strtolower( trim( $tzMsg ) );
04638         $msg = wfMessage( $key )->inContentLanguage();
04639         if ( $msg->exists() ) {
04640             $tzMsg = $msg->text();
04641         }
04642 
04643         $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
04644 
04645         # Variable replacement
04646         # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
04647         $text = $this->replaceVariables( $text );
04648 
04649         # This works almost by chance, as the replaceVariables are done before the getUserSig(),
04650         # which may corrupt this parser instance via its wfMessage()->text() call-
04651 
04652         # Signatures
04653         $sigText = $this->getUserSig( $user );
04654         $text = strtr( $text, array(
04655             '~~~~~' => $d,
04656             '~~~~' => "$sigText $d",
04657             '~~~' => $sigText
04658         ) );
04659 
04660         # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
04661         $tc = '[' . Title::legalChars() . ']';
04662         $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
04663 
04664         $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";                   # [[ns:page (context)|]]
04665         $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";                       # [[ns:page(context)|]] (double-width brackets, added in r40257)
04666         $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";     # [[ns:page (context), context|]] (using either single or double-width comma)
04667         $p2 = "/\[\[\\|($tc+)]]/";                                              # [[|page]] (reverse pipe trick: add context from page title)
04668 
04669         # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
04670         $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
04671         $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
04672         $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
04673 
04674         $t = $this->mTitle->getText();
04675         $m = array();
04676         if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
04677             $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
04678         } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
04679             $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
04680         } else {
04681             # if there's no context, don't bother duplicating the title
04682             $text = preg_replace( $p2, '[[\\1]]', $text );
04683         }
04684 
04685         # Trim trailing whitespace
04686         $text = rtrim( $text );
04687 
04688         return $text;
04689     }
04690 
04705     function getUserSig( &$user, $nickname = false, $fancySig = null ) {
04706         global $wgMaxSigChars;
04707 
04708         $username = $user->getName();
04709 
04710         # If not given, retrieve from the user object.
04711         if ( $nickname === false ) {
04712             $nickname = $user->getOption( 'nickname' );
04713         }
04714 
04715         if ( is_null( $fancySig ) ) {
04716             $fancySig = $user->getBoolOption( 'fancysig' );
04717         }
04718 
04719         $nickname = $nickname == null ? $username : $nickname;
04720 
04721         if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
04722             $nickname = $username;
04723             wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
04724         } elseif ( $fancySig !== false ) {
04725             # Sig. might contain markup; validate this
04726             if ( $this->validateSig( $nickname ) !== false ) {
04727                 # Validated; clean up (if needed) and return it
04728                 return $this->cleanSig( $nickname, true );
04729             } else {
04730                 # Failed to validate; fall back to the default
04731                 $nickname = $username;
04732                 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
04733             }
04734         }
04735 
04736         # Make sure nickname doesnt get a sig in a sig
04737         $nickname = self::cleanSigInSig( $nickname );
04738 
04739         # If we're still here, make it a link to the user page
04740         $userText = wfEscapeWikiText( $username );
04741         $nickText = wfEscapeWikiText( $nickname );
04742         $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
04743 
04744         return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
04745     }
04746 
04753     function validateSig( $text ) {
04754         return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
04755     }
04756 
04767     public function cleanSig( $text, $parsing = false ) {
04768         if ( !$parsing ) {
04769             global $wgTitle;
04770             $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
04771         }
04772 
04773         # Option to disable this feature
04774         if ( !$this->mOptions->getCleanSignatures() ) {
04775             return $text;
04776         }
04777 
04778         # @todo FIXME: Regex doesn't respect extension tags or nowiki
04779         #  => Move this logic to braceSubstitution()
04780         $substWord = MagicWord::get( 'subst' );
04781         $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
04782         $substText = '{{' . $substWord->getSynonym( 0 );
04783 
04784         $text = preg_replace( $substRegex, $substText, $text );
04785         $text = self::cleanSigInSig( $text );
04786         $dom = $this->preprocessToDom( $text );
04787         $frame = $this->getPreprocessor()->newFrame();
04788         $text = $frame->expand( $dom );
04789 
04790         if ( !$parsing ) {
04791             $text = $this->mStripState->unstripBoth( $text );
04792         }
04793 
04794         return $text;
04795     }
04796 
04803     public static function cleanSigInSig( $text ) {
04804         $text = preg_replace( '/~{3,5}/', '', $text );
04805         return $text;
04806     }
04807 
04817     public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
04818         $this->startParse( $title, $options, $outputType, $clearState );
04819     }
04820 
04827     private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
04828         $this->setTitle( $title );
04829         $this->mOptions = $options;
04830         $this->setOutputType( $outputType );
04831         if ( $clearState ) {
04832             $this->clearState();
04833         }
04834     }
04835 
04844     public function transformMsg( $text, $options, $title = null ) {
04845         static $executing = false;
04846 
04847         # Guard against infinite recursion
04848         if ( $executing ) {
04849             return $text;
04850         }
04851         $executing = true;
04852 
04853         wfProfileIn( __METHOD__ );
04854         if ( !$title ) {
04855             global $wgTitle;
04856             $title = $wgTitle;
04857         }
04858 
04859         $text = $this->preprocess( $text, $title, $options );
04860 
04861         $executing = false;
04862         wfProfileOut( __METHOD__ );
04863         return $text;
04864     }
04865 
04890     public function setHook( $tag, $callback ) {
04891         $tag = strtolower( $tag );
04892         if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
04893             throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
04894         }
04895         $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
04896         $this->mTagHooks[$tag] = $callback;
04897         if ( !in_array( $tag, $this->mStripList ) ) {
04898             $this->mStripList[] = $tag;
04899         }
04900 
04901         return $oldVal;
04902     }
04903 
04921     function setTransparentTagHook( $tag, $callback ) {
04922         $tag = strtolower( $tag );
04923         if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
04924             throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
04925         }
04926         $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
04927         $this->mTransparentTagHooks[$tag] = $callback;
04928 
04929         return $oldVal;
04930     }
04931 
04935     function clearTagHooks() {
04936         $this->mTagHooks = array();
04937         $this->mFunctionTagHooks = array();
04938         $this->mStripList = $this->mDefaultStripList;
04939     }
04940 
04984     public function setFunctionHook( $id, $callback, $flags = 0 ) {
04985         global $wgContLang;
04986 
04987         $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
04988         $this->mFunctionHooks[$id] = array( $callback, $flags );
04989 
04990         # Add to function cache
04991         $mw = MagicWord::get( $id );
04992         if ( !$mw ) {
04993             throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
04994         }
04995 
04996         $synonyms = $mw->getSynonyms();
04997         $sensitive = intval( $mw->isCaseSensitive() );
04998 
04999         foreach ( $synonyms as $syn ) {
05000             # Case
05001             if ( !$sensitive ) {
05002                 $syn = $wgContLang->lc( $syn );
05003             }
05004             # Add leading hash
05005             if ( !( $flags & SFH_NO_HASH ) ) {
05006                 $syn = '#' . $syn;
05007             }
05008             # Remove trailing colon
05009             if ( substr( $syn, -1, 1 ) === ':' ) {
05010                 $syn = substr( $syn, 0, -1 );
05011             }
05012             $this->mFunctionSynonyms[$sensitive][$syn] = $id;
05013         }
05014         return $oldVal;
05015     }
05016 
05022     function getFunctionHooks() {
05023         return array_keys( $this->mFunctionHooks );
05024     }
05025 
05036     function setFunctionTagHook( $tag, $callback, $flags ) {
05037         $tag = strtolower( $tag );
05038         if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
05039             throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
05040         }
05041         $old = isset( $this->mFunctionTagHooks[$tag] ) ?
05042             $this->mFunctionTagHooks[$tag] : null;
05043         $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
05044 
05045         if ( !in_array( $tag, $this->mStripList ) ) {
05046             $this->mStripList[] = $tag;
05047         }
05048 
05049         return $old;
05050     }
05051 
05062     function replaceLinkHolders( &$text, $options = 0 ) {
05063         return $this->mLinkHolders->replace( $text );
05064     }
05065 
05073     function replaceLinkHoldersText( $text ) {
05074         return $this->mLinkHolders->replaceText( $text );
05075     }
05076 
05090     function renderImageGallery( $text, $params ) {
05091         wfProfileIn( __METHOD__ );
05092 
05093         $mode = false;
05094         if ( isset( $params['mode'] ) ) {
05095             $mode = $params['mode'];
05096         }
05097 
05098         try {
05099             $ig = ImageGalleryBase::factory( $mode );
05100         } catch ( MWException $e ) {
05101             // If invalid type set, fallback to default.
05102             $ig = ImageGalleryBase::factory( false );
05103         }
05104 
05105         $ig->setContextTitle( $this->mTitle );
05106         $ig->setShowBytes( false );
05107         $ig->setShowFilename( false );
05108         $ig->setParser( $this );
05109         $ig->setHideBadImages();
05110         $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
05111 
05112         if ( isset( $params['showfilename'] ) ) {
05113             $ig->setShowFilename( true );
05114         } else {
05115             $ig->setShowFilename( false );
05116         }
05117         if ( isset( $params['caption'] ) ) {
05118             $caption = $params['caption'];
05119             $caption = htmlspecialchars( $caption );
05120             $caption = $this->replaceInternalLinks( $caption );
05121             $ig->setCaptionHtml( $caption );
05122         }
05123         if ( isset( $params['perrow'] ) ) {
05124             $ig->setPerRow( $params['perrow'] );
05125         }
05126         if ( isset( $params['widths'] ) ) {
05127             $ig->setWidths( $params['widths'] );
05128         }
05129         if ( isset( $params['heights'] ) ) {
05130             $ig->setHeights( $params['heights'] );
05131         }
05132         $ig->setAdditionalOptions( $params );
05133 
05134         wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
05135 
05136         $lines = StringUtils::explode( "\n", $text );
05137         foreach ( $lines as $line ) {
05138             # match lines like these:
05139             # Image:someimage.jpg|This is some image
05140             $matches = array();
05141             preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
05142             # Skip empty lines
05143             if ( count( $matches ) == 0 ) {
05144                 continue;
05145             }
05146 
05147             if ( strpos( $matches[0], '%' ) !== false ) {
05148                 $matches[1] = rawurldecode( $matches[1] );
05149             }
05150             $title = Title::newFromText( $matches[1], NS_FILE );
05151             if ( is_null( $title ) ) {
05152                 # Bogus title. Ignore these so we don't bomb out later.
05153                 continue;
05154             }
05155 
05156             # We need to get what handler the file uses, to figure out parameters.
05157             # Note, a hook can overide the file name, and chose an entirely different
05158             # file (which potentially could be of a different type and have different handler).
05159             $options = array();
05160             $descQuery = false;
05161             wfRunHooks( 'BeforeParserFetchFileAndTitle',
05162                 array( $this, $title, &$options, &$descQuery ) );
05163             # Don't register it now, as ImageGallery does that later.
05164             $file = $this->fetchFileNoRegister( $title, $options );
05165             $handler = $file ? $file->getHandler() : false;
05166 
05167             wfProfileIn( __METHOD__ . '-getMagicWord' );
05168             $paramMap = array(
05169                 'img_alt' => 'gallery-internal-alt',
05170                 'img_link' => 'gallery-internal-link',
05171             );
05172             if ( $handler ) {
05173                 $paramMap = $paramMap + $handler->getParamMap();
05174                 // We don't want people to specify per-image widths.
05175                 // Additionally the width parameter would need special casing anyhow.
05176                 unset( $paramMap['img_width'] );
05177             }
05178 
05179             $mwArray = new MagicWordArray( array_keys( $paramMap ) );
05180             wfProfileOut( __METHOD__ . '-getMagicWord' );
05181 
05182             $label = '';
05183             $alt = '';
05184             $link = '';
05185             $handlerOptions = array();
05186             if ( isset( $matches[3] ) ) {
05187                 // look for an |alt= definition while trying not to break existing
05188                 // captions with multiple pipes (|) in it, until a more sensible grammar
05189                 // is defined for images in galleries
05190 
05191                 // FIXME: Doing recursiveTagParse at this stage, and the trim before
05192                 // splitting on '|' is a bit odd, and different from makeImage.
05193                 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
05194                 $parameterMatches = StringUtils::explode( '|', $matches[3] );
05195 
05196                 foreach ( $parameterMatches as $parameterMatch ) {
05197                     list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
05198                     if ( $magicName ) {
05199                         $paramName = $paramMap[$magicName];
05200 
05201                         switch ( $paramName ) {
05202                         case 'gallery-internal-alt':
05203                             $alt = $this->stripAltText( $match, false );
05204                             break;
05205                         case 'gallery-internal-link':
05206                             $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
05207                             $chars = self::EXT_LINK_URL_CLASS;
05208                             $prots = $this->mUrlProtocols;
05209                             //check to see if link matches an absolute url, if not then it must be a wiki link.
05210                             if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
05211                                 $link = $linkValue;
05212                             } else {
05213                                 $localLinkTitle = Title::newFromText( $linkValue );
05214                                 if ( $localLinkTitle !== null ) {
05215                                     $link = $localLinkTitle->getLocalURL();
05216                                 }
05217                             }
05218                             break;
05219                         default:
05220                             // Must be a handler specific parameter.
05221                             if ( $handler->validateParam( $paramName, $match ) ) {
05222                                 $handlerOptions[$paramName] = $match;
05223                             } else {
05224                                 // Guess not. Append it to the caption.
05225                                 wfDebug( "$parameterMatch failed parameter validation\n" );
05226                                 $label .= '|' . $parameterMatch;
05227                             }
05228                         }
05229 
05230                     } else {
05231                         // concatenate all other pipes
05232                         $label .= '|' . $parameterMatch;
05233                     }
05234                 }
05235                 // remove the first pipe
05236                 $label = substr( $label, 1 );
05237             }
05238 
05239             $ig->add( $title, $label, $alt, $link, $handlerOptions );
05240         }
05241         $html = $ig->toHTML();
05242         wfProfileOut( __METHOD__ );
05243         return $html;
05244     }
05245 
05250     function getImageParams( $handler ) {
05251         if ( $handler ) {
05252             $handlerClass = get_class( $handler );
05253         } else {
05254             $handlerClass = '';
05255         }
05256         if ( !isset( $this->mImageParams[$handlerClass] ) ) {
05257             # Initialise static lists
05258             static $internalParamNames = array(
05259                 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
05260                 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
05261                     'bottom', 'text-bottom' ),
05262                 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
05263                     'upright', 'border', 'link', 'alt', 'class' ),
05264             );
05265             static $internalParamMap;
05266             if ( !$internalParamMap ) {
05267                 $internalParamMap = array();
05268                 foreach ( $internalParamNames as $type => $names ) {
05269                     foreach ( $names as $name ) {
05270                         $magicName = str_replace( '-', '_', "img_$name" );
05271                         $internalParamMap[$magicName] = array( $type, $name );
05272                     }
05273                 }
05274             }
05275 
05276             # Add handler params
05277             $paramMap = $internalParamMap;
05278             if ( $handler ) {
05279                 $handlerParamMap = $handler->getParamMap();
05280                 foreach ( $handlerParamMap as $magic => $paramName ) {
05281                     $paramMap[$magic] = array( 'handler', $paramName );
05282                 }
05283             }
05284             $this->mImageParams[$handlerClass] = $paramMap;
05285             $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
05286         }
05287         return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
05288     }
05289 
05298     function makeImage( $title, $options, $holders = false ) {
05299         # Check if the options text is of the form "options|alt text"
05300         # Options are:
05301         #  * thumbnail  make a thumbnail with enlarge-icon and caption, alignment depends on lang
05302         #  * left       no resizing, just left align. label is used for alt= only
05303         #  * right      same, but right aligned
05304         #  * none       same, but not aligned
05305         #  * ___px      scale to ___ pixels width, no aligning. e.g. use in taxobox
05306         #  * center     center the image
05307         #  * frame      Keep original image size, no magnify-button.
05308         #  * framed     Same as "frame"
05309         #  * frameless  like 'thumb' but without a frame. Keeps user preferences for width
05310         #  * upright    reduce width for upright images, rounded to full __0 px
05311         #  * border     draw a 1px border around the image
05312         #  * alt        Text for HTML alt attribute (defaults to empty)
05313         #  * class      Set a class for img node
05314         #  * link       Set the target of the image link. Can be external, interwiki, or local
05315         # vertical-align values (no % or length right now):
05316         #  * baseline
05317         #  * sub
05318         #  * super
05319         #  * top
05320         #  * text-top
05321         #  * middle
05322         #  * bottom
05323         #  * text-bottom
05324 
05325         $parts = StringUtils::explode( "|", $options );
05326 
05327         # Give extensions a chance to select the file revision for us
05328         $options = array();
05329         $descQuery = false;
05330         wfRunHooks( 'BeforeParserFetchFileAndTitle',
05331             array( $this, $title, &$options, &$descQuery ) );
05332         # Fetch and register the file (file title may be different via hooks)
05333         list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
05334 
05335         # Get parameter map
05336         $handler = $file ? $file->getHandler() : false;
05337 
05338         list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
05339 
05340         if ( !$file ) {
05341             $this->addTrackingCategory( 'broken-file-category' );
05342         }
05343 
05344         # Process the input parameters
05345         $caption = '';
05346         $params = array( 'frame' => array(), 'handler' => array(),
05347             'horizAlign' => array(), 'vertAlign' => array() );
05348         $seenformat = false;
05349         foreach ( $parts as $part ) {
05350             $part = trim( $part );
05351             list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
05352             $validated = false;
05353             if ( isset( $paramMap[$magicName] ) ) {
05354                 list( $type, $paramName ) = $paramMap[$magicName];
05355 
05356                 # Special case; width and height come in one variable together
05357                 if ( $type === 'handler' && $paramName === 'width' ) {
05358                     $parsedWidthParam = $this->parseWidthParam( $value );
05359                     if ( isset( $parsedWidthParam['width'] ) ) {
05360                         $width = $parsedWidthParam['width'];
05361                         if ( $handler->validateParam( 'width', $width ) ) {
05362                             $params[$type]['width'] = $width;
05363                             $validated = true;
05364                         }
05365                     }
05366                     if ( isset( $parsedWidthParam['height'] ) ) {
05367                         $height = $parsedWidthParam['height'];
05368                         if ( $handler->validateParam( 'height', $height ) ) {
05369                             $params[$type]['height'] = $height;
05370                             $validated = true;
05371                         }
05372                     }
05373                     # else no validation -- bug 13436
05374                 } else {
05375                     if ( $type === 'handler' ) {
05376                         # Validate handler parameter
05377                         $validated = $handler->validateParam( $paramName, $value );
05378                     } else {
05379                         # Validate internal parameters
05380                         switch ( $paramName ) {
05381                         case 'manualthumb':
05382                         case 'alt':
05383                         case 'class':
05384                             # @todo FIXME: Possibly check validity here for
05385                             # manualthumb? downstream behavior seems odd with
05386                             # missing manual thumbs.
05387                             $validated = true;
05388                             $value = $this->stripAltText( $value, $holders );
05389                             break;
05390                         case 'link':
05391                             $chars = self::EXT_LINK_URL_CLASS;
05392                             $prots = $this->mUrlProtocols;
05393                             if ( $value === '' ) {
05394                                 $paramName = 'no-link';
05395                                 $value = true;
05396                                 $validated = true;
05397                             } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
05398                                 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
05399                                     $paramName = 'link-url';
05400                                     $this->mOutput->addExternalLink( $value );
05401                                     if ( $this->mOptions->getExternalLinkTarget() ) {
05402                                         $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
05403                                     }
05404                                     $validated = true;
05405                                 }
05406                             } else {
05407                                 $linkTitle = Title::newFromText( $value );
05408                                 if ( $linkTitle ) {
05409                                     $paramName = 'link-title';
05410                                     $value = $linkTitle;
05411                                     $this->mOutput->addLink( $linkTitle );
05412                                     $validated = true;
05413                                 }
05414                             }
05415                             break;
05416                         case 'frameless':
05417                         case 'framed':
05418                         case 'thumbnail':
05419                             // use first appearing option, discard others.
05420                             $validated = ! $seenformat;
05421                             $seenformat = true;
05422                             break;
05423                         default:
05424                             # Most other things appear to be empty or numeric...
05425                             $validated = ( $value === false || is_numeric( trim( $value ) ) );
05426                         }
05427                     }
05428 
05429                     if ( $validated ) {
05430                         $params[$type][$paramName] = $value;
05431                     }
05432                 }
05433             }
05434             if ( !$validated ) {
05435                 $caption = $part;
05436             }
05437         }
05438 
05439         # Process alignment parameters
05440         if ( $params['horizAlign'] ) {
05441             $params['frame']['align'] = key( $params['horizAlign'] );
05442         }
05443         if ( $params['vertAlign'] ) {
05444             $params['frame']['valign'] = key( $params['vertAlign'] );
05445         }
05446 
05447         $params['frame']['caption'] = $caption;
05448 
05449         # Will the image be presented in a frame, with the caption below?
05450         $imageIsFramed = isset( $params['frame']['frame'] )
05451             || isset( $params['frame']['framed'] )
05452             || isset( $params['frame']['thumbnail'] )
05453             || isset( $params['frame']['manualthumb'] );
05454 
05455         # In the old days, [[Image:Foo|text...]] would set alt text.  Later it
05456         # came to also set the caption, ordinary text after the image -- which
05457         # makes no sense, because that just repeats the text multiple times in
05458         # screen readers.  It *also* came to set the title attribute.
05459         #
05460         # Now that we have an alt attribute, we should not set the alt text to
05461         # equal the caption: that's worse than useless, it just repeats the
05462         # text.  This is the framed/thumbnail case.  If there's no caption, we
05463         # use the unnamed parameter for alt text as well, just for the time be-
05464         # ing, if the unnamed param is set and the alt param is not.
05465         #
05466         # For the future, we need to figure out if we want to tweak this more,
05467         # e.g., introducing a title= parameter for the title; ignoring the un-
05468         # named parameter entirely for images without a caption; adding an ex-
05469         # plicit caption= parameter and preserving the old magic unnamed para-
05470         # meter for BC; ...
05471         if ( $imageIsFramed ) { # Framed image
05472             if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
05473                 # No caption or alt text, add the filename as the alt text so
05474                 # that screen readers at least get some description of the image
05475                 $params['frame']['alt'] = $title->getText();
05476             }
05477             # Do not set $params['frame']['title'] because tooltips don't make sense
05478             # for framed images
05479         } else { # Inline image
05480             if ( !isset( $params['frame']['alt'] ) ) {
05481                 # No alt text, use the "caption" for the alt text
05482                 if ( $caption !== '' ) {
05483                     $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
05484                 } else {
05485                     # No caption, fall back to using the filename for the
05486                     # alt text
05487                     $params['frame']['alt'] = $title->getText();
05488                 }
05489             }
05490             # Use the "caption" for the tooltip text
05491             $params['frame']['title'] = $this->stripAltText( $caption, $holders );
05492         }
05493 
05494         wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
05495 
05496         # Linker does the rest
05497         $time = isset( $options['time'] ) ? $options['time'] : false;
05498         $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
05499             $time, $descQuery, $this->mOptions->getThumbSize() );
05500 
05501         # Give the handler a chance to modify the parser object
05502         if ( $handler ) {
05503             $handler->parserTransformHook( $this, $file );
05504         }
05505 
05506         return $ret;
05507     }
05508 
05514     protected function stripAltText( $caption, $holders ) {
05515         # Strip bad stuff out of the title (tooltip).  We can't just use
05516         # replaceLinkHoldersText() here, because if this function is called
05517         # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
05518         if ( $holders ) {
05519             $tooltip = $holders->replaceText( $caption );
05520         } else {
05521             $tooltip = $this->replaceLinkHoldersText( $caption );
05522         }
05523 
05524         # make sure there are no placeholders in thumbnail attributes
05525         # that are later expanded to html- so expand them now and
05526         # remove the tags
05527         $tooltip = $this->mStripState->unstripBoth( $tooltip );
05528         $tooltip = Sanitizer::stripAllTags( $tooltip );
05529 
05530         return $tooltip;
05531     }
05532 
05537     function disableCache() {
05538         wfDebug( "Parser output marked as uncacheable.\n" );
05539         if ( !$this->mOutput ) {
05540             throw new MWException( __METHOD__ .
05541                 " can only be called when actually parsing something" );
05542         }
05543         $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
05544         $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
05545     }
05546 
05555     function attributeStripCallback( &$text, $frame = false ) {
05556         $text = $this->replaceVariables( $text, $frame );
05557         $text = $this->mStripState->unstripBoth( $text );
05558         return $text;
05559     }
05560 
05566     function getTags() {
05567         return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
05568     }
05569 
05580     function replaceTransparentTags( $text ) {
05581         $matches = array();
05582         $elements = array_keys( $this->mTransparentTagHooks );
05583         $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
05584         $replacements = array();
05585 
05586         foreach ( $matches as $marker => $data ) {
05587             list( $element, $content, $params, $tag ) = $data;
05588             $tagName = strtolower( $element );
05589             if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
05590                 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
05591             } else {
05592                 $output = $tag;
05593             }
05594             $replacements[$marker] = $output;
05595         }
05596         return strtr( $text, $replacements );
05597     }
05598 
05628     private function extractSections( $text, $section, $mode, $newText = '' ) {
05629         global $wgTitle; # not generally used but removes an ugly failure mode
05630         $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
05631         $outText = '';
05632         $frame = $this->getPreprocessor()->newFrame();
05633 
05634         # Process section extraction flags
05635         $flags = 0;
05636         $sectionParts = explode( '-', $section );
05637         $sectionIndex = array_pop( $sectionParts );
05638         foreach ( $sectionParts as $part ) {
05639             if ( $part === 'T' ) {
05640                 $flags |= self::PTD_FOR_INCLUSION;
05641             }
05642         }
05643 
05644         # Check for empty input
05645         if ( strval( $text ) === '' ) {
05646             # Only sections 0 and T-0 exist in an empty document
05647             if ( $sectionIndex == 0 ) {
05648                 if ( $mode === 'get' ) {
05649                     return '';
05650                 } else {
05651                     return $newText;
05652                 }
05653             } else {
05654                 if ( $mode === 'get' ) {
05655                     return $newText;
05656                 } else {
05657                     return $text;
05658                 }
05659             }
05660         }
05661 
05662         # Preprocess the text
05663         $root = $this->preprocessToDom( $text, $flags );
05664 
05665         # <h> nodes indicate section breaks
05666         # They can only occur at the top level, so we can find them by iterating the root's children
05667         $node = $root->getFirstChild();
05668 
05669         # Find the target section
05670         if ( $sectionIndex == 0 ) {
05671             # Section zero doesn't nest, level=big
05672             $targetLevel = 1000;
05673         } else {
05674             while ( $node ) {
05675                 if ( $node->getName() === 'h' ) {
05676                     $bits = $node->splitHeading();
05677                     if ( $bits['i'] == $sectionIndex ) {
05678                         $targetLevel = $bits['level'];
05679                         break;
05680                     }
05681                 }
05682                 if ( $mode === 'replace' ) {
05683                     $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
05684                 }
05685                 $node = $node->getNextSibling();
05686             }
05687         }
05688 
05689         if ( !$node ) {
05690             # Not found
05691             if ( $mode === 'get' ) {
05692                 return $newText;
05693             } else {
05694                 return $text;
05695             }
05696         }
05697 
05698         # Find the end of the section, including nested sections
05699         do {
05700             if ( $node->getName() === 'h' ) {
05701                 $bits = $node->splitHeading();
05702                 $curLevel = $bits['level'];
05703                 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
05704                     break;
05705                 }
05706             }
05707             if ( $mode === 'get' ) {
05708                 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
05709             }
05710             $node = $node->getNextSibling();
05711         } while ( $node );
05712 
05713         # Write out the remainder (in replace mode only)
05714         if ( $mode === 'replace' ) {
05715             # Output the replacement text
05716             # Add two newlines on -- trailing whitespace in $newText is conventionally
05717             # stripped by the editor, so we need both newlines to restore the paragraph gap
05718             # Only add trailing whitespace if there is newText
05719             if ( $newText != "" ) {
05720                 $outText .= $newText . "\n\n";
05721             }
05722 
05723             while ( $node ) {
05724                 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
05725                 $node = $node->getNextSibling();
05726             }
05727         }
05728 
05729         if ( is_string( $outText ) ) {
05730             # Re-insert stripped tags
05731             $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
05732         }
05733 
05734         return $outText;
05735     }
05736 
05749     public function getSection( $text, $section, $deftext = '' ) {
05750         return $this->extractSections( $text, $section, "get", $deftext );
05751     }
05752 
05763     public function replaceSection( $oldtext, $section, $text ) {
05764         return $this->extractSections( $oldtext, $section, "replace", $text );
05765     }
05766 
05772     function getRevisionId() {
05773         return $this->mRevisionId;
05774     }
05775 
05782     public function getRevisionObject() {
05783         if ( !is_null( $this->mRevisionObject ) ) {
05784             return $this->mRevisionObject;
05785         }
05786         if ( is_null( $this->mRevisionId ) ) {
05787             return null;
05788         }
05789 
05790         $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
05791         return $this->mRevisionObject;
05792     }
05793 
05799     function getRevisionTimestamp() {
05800         if ( is_null( $this->mRevisionTimestamp ) ) {
05801             wfProfileIn( __METHOD__ );
05802 
05803             global $wgContLang;
05804 
05805             $revObject = $this->getRevisionObject();
05806             $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
05807 
05808             # The cryptic '' timezone parameter tells to use the site-default
05809             # timezone offset instead of the user settings.
05810             #
05811             # Since this value will be saved into the parser cache, served
05812             # to other users, and potentially even used inside links and such,
05813             # it needs to be consistent for all visitors.
05814             $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
05815 
05816             wfProfileOut( __METHOD__ );
05817         }
05818         return $this->mRevisionTimestamp;
05819     }
05820 
05826     function getRevisionUser() {
05827         if ( is_null( $this->mRevisionUser ) ) {
05828             $revObject = $this->getRevisionObject();
05829 
05830             # if this template is subst: the revision id will be blank,
05831             # so just use the current user's name
05832             if ( $revObject ) {
05833                 $this->mRevisionUser = $revObject->getUserText();
05834             } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
05835                 $this->mRevisionUser = $this->getUser()->getName();
05836             }
05837         }
05838         return $this->mRevisionUser;
05839     }
05840 
05846     function getRevisionSize() {
05847         if ( is_null( $this->mRevisionSize ) ) {
05848             $revObject = $this->getRevisionObject();
05849 
05850             # if this variable is subst: the revision id will be blank,
05851             # so just use the parser input size, because the own substituation
05852             # will change the size.
05853             if ( $revObject ) {
05854                 $this->mRevisionSize = $revObject->getSize();
05855             } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
05856                 $this->mRevisionSize = $this->mInputSize;
05857             }
05858         }
05859         return $this->mRevisionSize;
05860     }
05861 
05867     public function setDefaultSort( $sort ) {
05868         $this->mDefaultSort = $sort;
05869         $this->mOutput->setProperty( 'defaultsort', $sort );
05870     }
05871 
05882     public function getDefaultSort() {
05883         if ( $this->mDefaultSort !== false ) {
05884             return $this->mDefaultSort;
05885         } else {
05886             return '';
05887         }
05888     }
05889 
05896     public function getCustomDefaultSort() {
05897         return $this->mDefaultSort;
05898     }
05899 
05909     public function guessSectionNameFromWikiText( $text ) {
05910         # Strip out wikitext links(they break the anchor)
05911         $text = $this->stripSectionName( $text );
05912         $text = Sanitizer::normalizeSectionNameWhitespace( $text );
05913         return '#' . Sanitizer::escapeId( $text, 'noninitial' );
05914     }
05915 
05924     public function guessLegacySectionNameFromWikiText( $text ) {
05925         # Strip out wikitext links(they break the anchor)
05926         $text = $this->stripSectionName( $text );
05927         $text = Sanitizer::normalizeSectionNameWhitespace( $text );
05928         return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
05929     }
05930 
05945     public function stripSectionName( $text ) {
05946         # Strip internal link markup
05947         $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
05948         $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
05949 
05950         # Strip external link markup
05951         # @todo FIXME: Not tolerant to blank link text
05952         # I.E. [https://www.mediawiki.org] will render as [1] or something depending
05953         # on how many empty links there are on the page - need to figure that out.
05954         $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
05955 
05956         # Parse wikitext quotes (italics & bold)
05957         $text = $this->doQuotes( $text );
05958 
05959         # Strip HTML tags
05960         $text = StringUtils::delimiterReplace( '<', '>', '', $text );
05961         return $text;
05962     }
05963 
05974     function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
05975         $this->startParse( $title, $options, $outputType, true );
05976 
05977         $text = $this->replaceVariables( $text );
05978         $text = $this->mStripState->unstripBoth( $text );
05979         $text = Sanitizer::removeHTMLtags( $text );
05980         return $text;
05981     }
05982 
05989     function testPst( $text, Title $title, ParserOptions $options ) {
05990         return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
05991     }
05992 
05999     function testPreprocess( $text, Title $title, ParserOptions $options ) {
06000         return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
06001     }
06002 
06019     function markerSkipCallback( $s, $callback ) {
06020         $i = 0;
06021         $out = '';
06022         while ( $i < strlen( $s ) ) {
06023             $markerStart = strpos( $s, $this->mUniqPrefix, $i );
06024             if ( $markerStart === false ) {
06025                 $out .= call_user_func( $callback, substr( $s, $i ) );
06026                 break;
06027             } else {
06028                 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
06029                 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
06030                 if ( $markerEnd === false ) {
06031                     $out .= substr( $s, $markerStart );
06032                     break;
06033                 } else {
06034                     $markerEnd += strlen( self::MARKER_SUFFIX );
06035                     $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
06036                     $i = $markerEnd;
06037                 }
06038             }
06039         }
06040         return $out;
06041     }
06042 
06049     function killMarkers( $text ) {
06050         return $this->mStripState->killMarkers( $text );
06051     }
06052 
06069     function serializeHalfParsedText( $text ) {
06070         wfProfileIn( __METHOD__ );
06071         $data = array(
06072             'text' => $text,
06073             'version' => self::HALF_PARSED_VERSION,
06074             'stripState' => $this->mStripState->getSubState( $text ),
06075             'linkHolders' => $this->mLinkHolders->getSubArray( $text )
06076         );
06077         wfProfileOut( __METHOD__ );
06078         return $data;
06079     }
06080 
06096     function unserializeHalfParsedText( $data ) {
06097         if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
06098             throw new MWException( __METHOD__ . ': invalid version' );
06099         }
06100 
06101         # First, extract the strip state.
06102         $texts = array( $data['text'] );
06103         $texts = $this->mStripState->merge( $data['stripState'], $texts );
06104 
06105         # Now renumber links
06106         $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
06107 
06108         # Should be good to go.
06109         return $texts[0];
06110     }
06111 
06121     function isValidHalfParsedText( $data ) {
06122         return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
06123     }
06124 
06133     public function parseWidthParam( $value ) {
06134         $parsedWidthParam = array();
06135         if ( $value === '' ) {
06136             return $parsedWidthParam;
06137         }
06138         $m = array();
06139         # (bug 13500) In both cases (width/height and width only),
06140         # permit trailing "px" for backward compatibility.
06141         if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
06142             $width = intval( $m[1] );
06143             $height = intval( $m[2] );
06144             $parsedWidthParam['width'] = $width;
06145             $parsedWidthParam['height'] = $height;
06146         } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
06147             $width = intval( $value );
06148             $parsedWidthParam['width'] = $width;
06149         }
06150         return $parsedWidthParam;
06151     }
06152 }