MediaWiki  master
Parser.php
Go to the documentation of this file.
00001 <?php
00069 class Parser {
00075         const VERSION = '1.6.4';
00076 
00081         const HALF_PARSED_VERSION = 2;
00082 
00083         # Flags for Parser::setFunctionHook
00084         # Also available as global constants from Defines.php
00085         const SFH_NO_HASH = 1;
00086         const SFH_OBJECT_ARGS = 2;
00087 
00088         # Constants needed for external link processing
00089         # Everything except bracket, space, or control characters
00090         # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
00091         # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
00092         const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
00093         const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
00094                 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
00095 
00096         # State constants for the definition list colon extraction
00097         const COLON_STATE_TEXT = 0;
00098         const COLON_STATE_TAG = 1;
00099         const COLON_STATE_TAGSTART = 2;
00100         const COLON_STATE_CLOSETAG = 3;
00101         const COLON_STATE_TAGSLASH = 4;
00102         const COLON_STATE_COMMENT = 5;
00103         const COLON_STATE_COMMENTDASH = 6;
00104         const COLON_STATE_COMMENTDASHDASH = 7;
00105 
00106         # Flags for preprocessToDom
00107         const PTD_FOR_INCLUSION = 1;
00108 
00109         # Allowed values for $this->mOutputType
00110         # Parameter to startExternalParse().
00111         const OT_HTML = 1; # like parse()
00112         const OT_WIKI = 2; # like preSaveTransform()
00113         const OT_PREPROCESS = 3; # like preprocess()
00114         const OT_MSG = 3;
00115         const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
00116 
00117         # Marker Suffix needs to be accessible staticly.
00118         const MARKER_SUFFIX = "-QINU\x7f";
00119 
00120         # Persistent:
00121         var $mTagHooks = array();
00122         var $mTransparentTagHooks = array();
00123         var $mFunctionHooks = array();
00124         var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
00125         var $mFunctionTagHooks = array();
00126         var $mStripList  = array();
00127         var $mDefaultStripList  = array();
00128         var $mVarCache = array();
00129         var $mImageParams = array();
00130         var $mImageParamsMagicArray = array();
00131         var $mMarkerIndex = 0;
00132         var $mFirstCall = true;
00133 
00134         # Initialised by initialiseVariables()
00135 
00139         var $mVariables;
00140 
00144         var $mSubstWords;
00145         var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
00146 
00147         # Cleared with clearState():
00148 
00151         var $mOutput;
00152         var $mAutonumber, $mDTopen;
00153 
00157         var $mStripState;
00158 
00159         var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
00163         var $mLinkHolders;
00164 
00165         var $mLinkID;
00166         var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
00167         var $mDefaultSort;
00168         var $mTplExpandCache; # empty-frame expansion cache
00169         var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
00170         var $mExpensiveFunctionCount; # number of expensive parser function calls
00171         var $mShowToc, $mForceTocPosition;
00172 
00176         var $mUser; # User object; only used when doing pre-save transform
00177 
00178         # Temporary
00179         # These are variables reset at least once per parse regardless of $clearState
00180 
00184         var $mOptions;
00185 
00189         var $mTitle;        # Title context, used for self-link rendering and similar things
00190         var $mOutputType;   # Output type, one of the OT_xxx constants
00191         var $ot;            # Shortcut alias, see setOutputType()
00192         var $mRevisionObject; # The revision object of the specified revision ID
00193         var $mRevisionId;   # ID to display in {{REVISIONID}} tags
00194         var $mRevisionTimestamp; # The timestamp of the specified revision ID
00195         var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
00196         var $mRevIdForTs;   # The revision ID which was used to fetch the timestamp
00197 
00201         var $mUniqPrefix;
00202 
00208         var $mLangLinkLanguages;
00209 
00215         public function __construct( $conf = array() ) {
00216                 $this->mConf = $conf;
00217                 $this->mUrlProtocols = wfUrlProtocols();
00218                 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')'.
00219                         self::EXT_LINK_URL_CLASS.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
00220                 if ( isset( $conf['preprocessorClass'] ) ) {
00221                         $this->mPreprocessorClass = $conf['preprocessorClass'];
00222                 } elseif ( defined( 'MW_COMPILED' ) ) {
00223                         # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
00224                         $this->mPreprocessorClass = 'Preprocessor_Hash';
00225                 } elseif ( extension_loaded( 'domxml' ) ) {
00226                         # PECL extension that conflicts with the core DOM extension (bug 13770)
00227                         wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
00228                         $this->mPreprocessorClass = 'Preprocessor_Hash';
00229                 } elseif ( extension_loaded( 'dom' ) ) {
00230                         $this->mPreprocessorClass = 'Preprocessor_DOM';
00231                 } else {
00232                         $this->mPreprocessorClass = 'Preprocessor_Hash';
00233                 }
00234                 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
00235         }
00236 
00240         function __destruct() {
00241                 if ( isset( $this->mLinkHolders ) ) {
00242                         unset( $this->mLinkHolders );
00243                 }
00244                 foreach ( $this as $name => $value ) {
00245                         unset( $this->$name );
00246                 }
00247         }
00248 
00252         function firstCallInit() {
00253                 if ( !$this->mFirstCall ) {
00254                         return;
00255                 }
00256                 $this->mFirstCall = false;
00257 
00258                 wfProfileIn( __METHOD__ );
00259 
00260                 CoreParserFunctions::register( $this );
00261                 CoreTagHooks::register( $this );
00262                 $this->initialiseVariables();
00263 
00264                 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
00265                 wfProfileOut( __METHOD__ );
00266         }
00267 
00273         function clearState() {
00274                 wfProfileIn( __METHOD__ );
00275                 if ( $this->mFirstCall ) {
00276                         $this->firstCallInit();
00277                 }
00278                 $this->mOutput = new ParserOutput;
00279                 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
00280                 $this->mAutonumber = 0;
00281                 $this->mLastSection = '';
00282                 $this->mDTopen = false;
00283                 $this->mIncludeCount = array();
00284                 $this->mArgStack = false;
00285                 $this->mInPre = false;
00286                 $this->mLinkHolders = new LinkHolderArray( $this );
00287                 $this->mLinkID = 0;
00288                 $this->mRevisionObject = $this->mRevisionTimestamp =
00289                         $this->mRevisionId = $this->mRevisionUser = null;
00290                 $this->mVarCache = array();
00291                 $this->mUser = null;
00292                 $this->mLangLinkLanguages = array();
00293 
00304                 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
00305                 $this->mStripState = new StripState( $this->mUniqPrefix );
00306 
00307 
00308                 # Clear these on every parse, bug 4549
00309                 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
00310 
00311                 $this->mShowToc = true;
00312                 $this->mForceTocPosition = false;
00313                 $this->mIncludeSizes = array(
00314                         'post-expand' => 0,
00315                         'arg' => 0,
00316                 );
00317                 $this->mPPNodeCount = 0;
00318                 $this->mGeneratedPPNodeCount = 0;
00319                 $this->mHighestExpansionDepth = 0;
00320                 $this->mDefaultSort = false;
00321                 $this->mHeadings = array();
00322                 $this->mDoubleUnderscores = array();
00323                 $this->mExpensiveFunctionCount = 0;
00324 
00325                 # Fix cloning
00326                 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
00327                         $this->mPreprocessor = null;
00328                 }
00329 
00330                 wfRunHooks( 'ParserClearState', array( &$this ) );
00331                 wfProfileOut( __METHOD__ );
00332         }
00333 
00346         public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
00352                 global $wgUseTidy, $wgAlwaysUseTidy;
00353                 $fname = __METHOD__.'-' . wfGetCaller();
00354                 wfProfileIn( __METHOD__ );
00355                 wfProfileIn( $fname );
00356 
00357                 $this->startParse( $title, $options, self::OT_HTML, $clearState );
00358 
00359                 # Remove the strip marker tag prefix from the input, if present.
00360                 if ( $clearState ) {
00361                         $text = str_replace( $this->mUniqPrefix, '', $text );
00362                 }
00363 
00364                 $oldRevisionId = $this->mRevisionId;
00365                 $oldRevisionObject = $this->mRevisionObject;
00366                 $oldRevisionTimestamp = $this->mRevisionTimestamp;
00367                 $oldRevisionUser = $this->mRevisionUser;
00368                 if ( $revid !== null ) {
00369                         $this->mRevisionId = $revid;
00370                         $this->mRevisionObject = null;
00371                         $this->mRevisionTimestamp = null;
00372                         $this->mRevisionUser = null;
00373                 }
00374 
00375                 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
00376                 # No more strip!
00377                 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
00378                 $text = $this->internalParse( $text );
00379                 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
00380 
00381                 $text = $this->mStripState->unstripGeneral( $text );
00382 
00383                 # Clean up special characters, only run once, next-to-last before doBlockLevels
00384                 $fixtags = array(
00385                         # french spaces, last one Guillemet-left
00386                         # only if there is something before the space
00387                         '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
00388                         # french spaces, Guillemet-right
00389                         '/(\\302\\253) /' => '\\1&#160;',
00390                         '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
00391                 );
00392                 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
00393 
00394                 $text = $this->doBlockLevels( $text, $linestart );
00395 
00396                 $this->replaceLinkHolders( $text );
00397 
00405                 if ( !( $options->getDisableContentConversion()
00406                                 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) ) )
00407                 {
00408                         # Run convert unconditionally in 1.18-compatible mode
00409                         global $wgBug34832TransitionalRollback;
00410                         if ( $wgBug34832TransitionalRollback || !$this->mOptions->getInterfaceMessage() ) {
00411                                 # The position of the convert() call should not be changed. it
00412                                 # assumes that the links are all replaced and the only thing left
00413                                 # is the <nowiki> mark.
00414                                 $text = $this->getConverterLanguage()->convert( $text );
00415                         }
00416                 }
00417 
00425                 if ( !( $options->getDisableTitleConversion()
00426                                 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
00427                                 || isset( $this->mDoubleUnderscores['notitleconvert'] )
00428                                 || $this->mOutput->getDisplayTitle() !== false ) )
00429                 {
00430                         $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
00431                         if ( $convruletitle ) {
00432                                 $this->mOutput->setTitleText( $convruletitle );
00433                         } else {
00434                                 $titleText = $this->getConverterLanguage()->convertTitle( $title );
00435                                 $this->mOutput->setTitleText( $titleText );
00436                         }
00437                 }
00438 
00439                 $text = $this->mStripState->unstripNoWiki( $text );
00440 
00441                 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
00442 
00443                 $text = $this->replaceTransparentTags( $text );
00444                 $text = $this->mStripState->unstripGeneral( $text );
00445 
00446                 $text = Sanitizer::normalizeCharReferences( $text );
00447 
00448                 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
00449                         $text = MWTidy::tidy( $text );
00450                 } else {
00451                         # attempt to sanitize at least some nesting problems
00452                         # (bug #2702 and quite a few others)
00453                         $tidyregs = array(
00454                                 # ''Something [http://www.cool.com cool''] -->
00455                                 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
00456                                 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
00457                                 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
00458                                 # fix up an anchor inside another anchor, only
00459                                 # at least for a single single nested link (bug 3695)
00460                                 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
00461                                 '\\1\\2</a>\\3</a>\\1\\4</a>',
00462                                 # fix div inside inline elements- doBlockLevels won't wrap a line which
00463                                 # contains a div, so fix it up here; replace
00464                                 # div with escaped text
00465                                 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
00466                                 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
00467                                 # remove empty italic or bold tag pairs, some
00468                                 # introduced by rules above
00469                                 '/<([bi])><\/\\1>/' => '',
00470                         );
00471 
00472                         $text = preg_replace(
00473                                 array_keys( $tidyregs ),
00474                                 array_values( $tidyregs ),
00475                                 $text );
00476                 }
00477 
00478                 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
00479                         $this->limitationWarn( 'expensive-parserfunction',
00480                                 $this->mExpensiveFunctionCount,
00481                                 $this->mOptions->getExpensiveParserFunctionLimit()
00482                         );
00483                 }
00484 
00485                 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
00486 
00487                 # Information on include size limits, for the benefit of users who try to skirt them
00488                 if ( $this->mOptions->getEnableLimitReport() ) {
00489                         $max = $this->mOptions->getMaxIncludeSize();
00490                         $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
00491                         $limitReport =
00492                                 "NewPP limit report\n" .
00493                                 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
00494                                 "Preprocessor generated node count: " .
00495                                         "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
00496                                 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
00497                                 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
00498                                 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
00499                                 $PFreport;
00500                         wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
00501                         $text .= "\n<!-- \n$limitReport-->\n";
00502 
00503                         if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
00504                                 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
00505                                         $this->mTitle->getPrefixedDBkey() );
00506                         }
00507                 }
00508                 $this->mOutput->setText( $text );
00509 
00510                 $this->mRevisionId = $oldRevisionId;
00511                 $this->mRevisionObject = $oldRevisionObject;
00512                 $this->mRevisionTimestamp = $oldRevisionTimestamp;
00513                 $this->mRevisionUser = $oldRevisionUser;
00514                 wfProfileOut( $fname );
00515                 wfProfileOut( __METHOD__ );
00516 
00517                 return $this->mOutput;
00518         }
00519 
00531         function recursiveTagParse( $text, $frame=false ) {
00532                 wfProfileIn( __METHOD__ );
00533                 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
00534                 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
00535                 $text = $this->internalParse( $text, false, $frame );
00536                 wfProfileOut( __METHOD__ );
00537                 return $text;
00538         }
00539 
00545         function preprocess( $text, Title $title, ParserOptions $options, $revid = null ) {
00546                 wfProfileIn( __METHOD__ );
00547                 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
00548                 if ( $revid !== null ) {
00549                         $this->mRevisionId = $revid;
00550                 }
00551                 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
00552                 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
00553                 $text = $this->replaceVariables( $text );
00554                 $text = $this->mStripState->unstripBoth( $text );
00555                 wfProfileOut( __METHOD__ );
00556                 return $text;
00557         }
00558 
00568         public function recursivePreprocess( $text, $frame = false ) {
00569                 wfProfileIn( __METHOD__ );
00570                 $text = $this->replaceVariables( $text, $frame );
00571                 $text = $this->mStripState->unstripBoth( $text );
00572                 wfProfileOut( __METHOD__ );
00573                 return $text;
00574         }
00575 
00588         public function getPreloadText( $text, Title $title, ParserOptions $options ) {
00589                 # Parser (re)initialisation
00590                 $this->startParse( $title, $options, self::OT_PLAIN, true );
00591 
00592                 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
00593                 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
00594                 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
00595                 $text = $this->mStripState->unstripBoth( $text );
00596                 return $text;
00597         }
00598 
00604         static public function getRandomString() {
00605                 return wfRandomString( 16 );
00606         }
00607 
00614         function setUser( $user ) {
00615                 $this->mUser = $user;
00616         }
00617 
00623         public function uniqPrefix() {
00624                 if ( !isset( $this->mUniqPrefix ) ) {
00625                         # @todo FIXME: This is probably *horribly wrong*
00626                         # LanguageConverter seems to want $wgParser's uniqPrefix, however
00627                         # if this is called for a parser cache hit, the parser may not
00628                         # have ever been initialized in the first place.
00629                         # Not really sure what the heck is supposed to be going on here.
00630                         return '';
00631                         # throw new MWException( "Accessing uninitialized mUniqPrefix" );
00632                 }
00633                 return $this->mUniqPrefix;
00634         }
00635 
00641         function setTitle( $t ) {
00642                 if ( !$t || $t instanceof FakeTitle ) {
00643                         $t = Title::newFromText( 'NO TITLE' );
00644                 }
00645 
00646                 if ( strval( $t->getFragment() ) !== '' ) {
00647                         # Strip the fragment to avoid various odd effects
00648                         $this->mTitle = clone $t;
00649                         $this->mTitle->setFragment( '' );
00650                 } else {
00651                         $this->mTitle = $t;
00652                 }
00653         }
00654 
00660         function getTitle() {
00661                 return $this->mTitle;
00662         }
00663 
00670         function Title( $x = null ) {
00671                 return wfSetVar( $this->mTitle, $x );
00672         }
00673 
00679         function setOutputType( $ot ) {
00680                 $this->mOutputType = $ot;
00681                 # Shortcut alias
00682                 $this->ot = array(
00683                         'html' => $ot == self::OT_HTML,
00684                         'wiki' => $ot == self::OT_WIKI,
00685                         'pre' => $ot == self::OT_PREPROCESS,
00686                         'plain' => $ot == self::OT_PLAIN,
00687                 );
00688         }
00689 
00696         function OutputType( $x = null ) {
00697                 return wfSetVar( $this->mOutputType, $x );
00698         }
00699 
00705         function getOutput() {
00706                 return $this->mOutput;
00707         }
00708 
00714         function getOptions() {
00715                 return $this->mOptions;
00716         }
00717 
00724         function Options( $x = null ) {
00725                 return wfSetVar( $this->mOptions, $x );
00726         }
00727 
00731         function nextLinkID() {
00732                 return $this->mLinkID++;
00733         }
00734 
00738         function setLinkID( $id ) {
00739                 $this->mLinkID = $id;
00740         }
00741 
00746         function getFunctionLang() {
00747                 return $this->getTargetLanguage();
00748         }
00749 
00759         public function getTargetLanguage() {
00760                 $target = $this->mOptions->getTargetLanguage();
00761 
00762                 if ( $target !== null ) {
00763                         return $target;
00764                 } elseif( $this->mOptions->getInterfaceMessage() ) {
00765                         return $this->mOptions->getUserLangObj();
00766                 } elseif( is_null( $this->mTitle ) ) {
00767                         throw new MWException( __METHOD__ . ': $this->mTitle is null' );
00768                 }
00769 
00770                 return $this->mTitle->getPageLanguage();
00771         }
00772 
00776         function getConverterLanguage() {
00777                 global $wgBug34832TransitionalRollback, $wgContLang;
00778                 if ( $wgBug34832TransitionalRollback ) {
00779                         return $wgContLang;
00780                 } else {
00781                         return $this->getTargetLanguage();
00782                 }
00783         }
00784 
00791         function getUser() {
00792                 if ( !is_null( $this->mUser ) ) {
00793                         return $this->mUser;
00794                 }
00795                 return $this->mOptions->getUser();
00796         }
00797 
00803         function getPreprocessor() {
00804                 if ( !isset( $this->mPreprocessor ) ) {
00805                         $class = $this->mPreprocessorClass;
00806                         $this->mPreprocessor = new $class( $this );
00807                 }
00808                 return $this->mPreprocessor;
00809         }
00810 
00831         public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
00832                 static $n = 1;
00833                 $stripped = '';
00834                 $matches = array();
00835 
00836                 $taglist = implode( '|', $elements );
00837                 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
00838 
00839                 while ( $text != '' ) {
00840                         $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
00841                         $stripped .= $p[0];
00842                         if ( count( $p ) < 5 ) {
00843                                 break;
00844                         }
00845                         if ( count( $p ) > 5 ) {
00846                                 # comment
00847                                 $element    = $p[4];
00848                                 $attributes = '';
00849                                 $close      = '';
00850                                 $inside     = $p[5];
00851                         } else {
00852                                 # tag
00853                                 $element    = $p[1];
00854                                 $attributes = $p[2];
00855                                 $close      = $p[3];
00856                                 $inside     = $p[4];
00857                         }
00858 
00859                         $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
00860                         $stripped .= $marker;
00861 
00862                         if ( $close === '/>' ) {
00863                                 # Empty element tag, <tag />
00864                                 $content = null;
00865                                 $text = $inside;
00866                                 $tail = null;
00867                         } else {
00868                                 if ( $element === '!--' ) {
00869                                         $end = '/(-->)/';
00870                                 } else {
00871                                         $end = "/(<\\/$element\\s*>)/i";
00872                                 }
00873                                 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
00874                                 $content = $q[0];
00875                                 if ( count( $q ) < 3 ) {
00876                                         # No end tag -- let it run out to the end of the text.
00877                                         $tail = '';
00878                                         $text = '';
00879                                 } else {
00880                                         $tail = $q[1];
00881                                         $text = $q[2];
00882                                 }
00883                         }
00884 
00885                         $matches[$marker] = array( $element,
00886                                 $content,
00887                                 Sanitizer::decodeTagAttributes( $attributes ),
00888                                 "<$element$attributes$close$content$tail" );
00889                 }
00890                 return $stripped;
00891         }
00892 
00898         function getStripList() {
00899                 return $this->mStripList;
00900         }
00901 
00911         function insertStripItem( $text ) {
00912                 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
00913                 $this->mMarkerIndex++;
00914                 $this->mStripState->addGeneral( $rnd, $text );
00915                 return $rnd;
00916         }
00917 
00924         function doTableStuff( $text ) {
00925                 wfProfileIn( __METHOD__ );
00926 
00927                 $lines = StringUtils::explode( "\n", $text );
00928                 $out = '';
00929                 $td_history = array(); # Is currently a td tag open?
00930                 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
00931                 $tr_history = array(); # Is currently a tr tag open?
00932                 $tr_attributes = array(); # history of tr attributes
00933                 $has_opened_tr = array(); # Did this table open a <tr> element?
00934                 $indent_level = 0; # indent level of the table
00935 
00936                 foreach ( $lines as $outLine ) {
00937                         $line = trim( $outLine );
00938 
00939                         if ( $line === '' ) { # empty line, go to next line
00940                                 $out .= $outLine."\n";
00941                                 continue;
00942                         }
00943 
00944                         $first_character = $line[0];
00945                         $matches = array();
00946 
00947                         if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
00948                                 # First check if we are starting a new table
00949                                 $indent_level = strlen( $matches[1] );
00950 
00951                                 $attributes = $this->mStripState->unstripBoth( $matches[2] );
00952                                 $attributes = Sanitizer::fixTagAttributes( $attributes , 'table' );
00953 
00954                                 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
00955                                 array_push( $td_history , false );
00956                                 array_push( $last_tag_history , '' );
00957                                 array_push( $tr_history , false );
00958                                 array_push( $tr_attributes , '' );
00959                                 array_push( $has_opened_tr , false );
00960                         } elseif ( count( $td_history ) == 0 ) {
00961                                 # Don't do any of the following
00962                                 $out .= $outLine."\n";
00963                                 continue;
00964                         } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
00965                                 # We are ending a table
00966                                 $line = '</table>' . substr( $line , 2 );
00967                                 $last_tag = array_pop( $last_tag_history );
00968 
00969                                 if ( !array_pop( $has_opened_tr ) ) {
00970                                         $line = "<tr><td></td></tr>{$line}";
00971                                 }
00972 
00973                                 if ( array_pop( $tr_history ) ) {
00974                                         $line = "</tr>{$line}";
00975                                 }
00976 
00977                                 if ( array_pop( $td_history ) ) {
00978                                         $line = "</{$last_tag}>{$line}";
00979                                 }
00980                                 array_pop( $tr_attributes );
00981                                 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
00982                         } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
00983                                 # Now we have a table row
00984                                 $line = preg_replace( '#^\|-+#', '', $line );
00985 
00986                                 # Whats after the tag is now only attributes
00987                                 $attributes = $this->mStripState->unstripBoth( $line );
00988                                 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
00989                                 array_pop( $tr_attributes );
00990                                 array_push( $tr_attributes, $attributes );
00991 
00992                                 $line = '';
00993                                 $last_tag = array_pop( $last_tag_history );
00994                                 array_pop( $has_opened_tr );
00995                                 array_push( $has_opened_tr , true );
00996 
00997                                 if ( array_pop( $tr_history ) ) {
00998                                         $line = '</tr>';
00999                                 }
01000 
01001                                 if ( array_pop( $td_history ) ) {
01002                                         $line = "</{$last_tag}>{$line}";
01003                                 }
01004 
01005                                 $outLine = $line;
01006                                 array_push( $tr_history , false );
01007                                 array_push( $td_history , false );
01008                                 array_push( $last_tag_history , '' );
01009                         } elseif ( $first_character === '|' || $first_character === '!' || substr( $line , 0 , 2 )  === '|+' ) {
01010                                 # This might be cell elements, td, th or captions
01011                                 if ( substr( $line , 0 , 2 ) === '|+' ) {
01012                                         $first_character = '+';
01013                                         $line = substr( $line , 1 );
01014                                 }
01015 
01016                                 $line = substr( $line , 1 );
01017 
01018                                 if ( $first_character === '!' ) {
01019                                         $line = str_replace( '!!' , '||' , $line );
01020                                 }
01021 
01022                                 # Split up multiple cells on the same line.
01023                                 # FIXME : This can result in improper nesting of tags processed
01024                                 # by earlier parser steps, but should avoid splitting up eg
01025                                 # attribute values containing literal "||".
01026                                 $cells = StringUtils::explodeMarkup( '||' , $line );
01027 
01028                                 $outLine = '';
01029 
01030                                 # Loop through each table cell
01031                                 foreach ( $cells as $cell ) {
01032                                         $previous = '';
01033                                         if ( $first_character !== '+' ) {
01034                                                 $tr_after = array_pop( $tr_attributes );
01035                                                 if ( !array_pop( $tr_history ) ) {
01036                                                         $previous = "<tr{$tr_after}>\n";
01037                                                 }
01038                                                 array_push( $tr_history , true );
01039                                                 array_push( $tr_attributes , '' );
01040                                                 array_pop( $has_opened_tr );
01041                                                 array_push( $has_opened_tr , true );
01042                                         }
01043 
01044                                         $last_tag = array_pop( $last_tag_history );
01045 
01046                                         if ( array_pop( $td_history ) ) {
01047                                                 $previous = "</{$last_tag}>\n{$previous}";
01048                                         }
01049 
01050                                         if ( $first_character === '|' ) {
01051                                                 $last_tag = 'td';
01052                                         } elseif ( $first_character === '!' ) {
01053                                                 $last_tag = 'th';
01054                                         } elseif ( $first_character === '+' ) {
01055                                                 $last_tag = 'caption';
01056                                         } else {
01057                                                 $last_tag = '';
01058                                         }
01059 
01060                                         array_push( $last_tag_history , $last_tag );
01061 
01062                                         # A cell could contain both parameters and data
01063                                         $cell_data = explode( '|' , $cell , 2 );
01064 
01065                                         # Bug 553: Note that a '|' inside an invalid link should not
01066                                         # be mistaken as delimiting cell parameters
01067                                         if ( strpos( $cell_data[0], '[[' ) !== false ) {
01068                                                 $cell = "{$previous}<{$last_tag}>{$cell}";
01069                                         } elseif ( count( $cell_data ) == 1 ) {
01070                                                 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
01071                                         } else {
01072                                                 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
01073                                                 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
01074                                                 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
01075                                         }
01076 
01077                                         $outLine .= $cell;
01078                                         array_push( $td_history , true );
01079                                 }
01080                         }
01081                         $out .= $outLine . "\n";
01082                 }
01083 
01084                 # Closing open td, tr && table
01085                 while ( count( $td_history ) > 0 ) {
01086                         if ( array_pop( $td_history ) ) {
01087                                 $out .= "</td>\n";
01088                         }
01089                         if ( array_pop( $tr_history ) ) {
01090                                 $out .= "</tr>\n";
01091                         }
01092                         if ( !array_pop( $has_opened_tr ) ) {
01093                                 $out .= "<tr><td></td></tr>\n" ;
01094                         }
01095 
01096                         $out .= "</table>\n";
01097                 }
01098 
01099                 # Remove trailing line-ending (b/c)
01100                 if ( substr( $out, -1 ) === "\n" ) {
01101                         $out = substr( $out, 0, -1 );
01102                 }
01103 
01104                 # special case: don't return empty table
01105                 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
01106                         $out = '';
01107                 }
01108 
01109                 wfProfileOut( __METHOD__ );
01110 
01111                 return $out;
01112         }
01113 
01126         function internalParse( $text, $isMain = true, $frame = false ) {
01127                 wfProfileIn( __METHOD__ );
01128 
01129                 $origText = $text;
01130 
01131                 # Hook to suspend the parser in this state
01132                 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
01133                         wfProfileOut( __METHOD__ );
01134                         return $text ;
01135                 }
01136 
01137                 # if $frame is provided, then use $frame for replacing any variables
01138                 if ( $frame ) {
01139                         # use frame depth to infer how include/noinclude tags should be handled
01140                         # depth=0 means this is the top-level document; otherwise it's an included document
01141                         if ( !$frame->depth ) {
01142                                 $flag = 0;
01143                         } else {
01144                                 $flag = Parser::PTD_FOR_INCLUSION;
01145                         }
01146                         $dom = $this->preprocessToDom( $text, $flag );
01147                         $text = $frame->expand( $dom );
01148                 } else {
01149                         # if $frame is not provided, then use old-style replaceVariables
01150                         $text = $this->replaceVariables( $text );
01151                 }
01152 
01153                 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
01154                 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
01155                 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
01156 
01157                 # Tables need to come after variable replacement for things to work
01158                 # properly; putting them before other transformations should keep
01159                 # exciting things like link expansions from showing up in surprising
01160                 # places.
01161                 $text = $this->doTableStuff( $text );
01162 
01163                 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
01164 
01165                 $text = $this->doDoubleUnderscore( $text );
01166 
01167                 $text = $this->doHeadings( $text );
01168                 if ( $this->mOptions->getUseDynamicDates() ) {
01169                         $df = DateFormatter::getInstance();
01170                         $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
01171                 }
01172                 $text = $this->replaceInternalLinks( $text );
01173                 $text = $this->doAllQuotes( $text );
01174                 $text = $this->replaceExternalLinks( $text );
01175 
01176                 # replaceInternalLinks may sometimes leave behind
01177                 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
01178                 $text = str_replace( $this->mUniqPrefix.'NOPARSE', '', $text );
01179 
01180                 $text = $this->doMagicLinks( $text );
01181                 $text = $this->formatHeadings( $text, $origText, $isMain );
01182 
01183                 wfProfileOut( __METHOD__ );
01184                 return $text;
01185         }
01186 
01198         function doMagicLinks( $text ) {
01199                 wfProfileIn( __METHOD__ );
01200                 $prots = wfUrlProtocolsWithoutProtRel();
01201                 $urlChar = self::EXT_LINK_URL_CLASS;
01202                 $text = preg_replace_callback(
01203                         '!(?:                           # Start cases
01204                                 (<a[ \t\r\n>].*?</a>) |     # m[1]: Skip link text
01205                                 (<.*?>) |                   # m[2]: Skip stuff inside HTML elements' . "
01206                                 (\\b(?i:$prots)$urlChar+) |  # m[3]: Free external links" . '
01207                                 (?:RFC|PMID)\s+([0-9]+) |   # m[4]: RFC or PMID, capture number
01208                                 ISBN\s+(\b                  # m[5]: ISBN, capture number
01209                                         (?: 97[89] [\ \-]? )?   # optional 13-digit ISBN prefix
01210                                         (?: [0-9]  [\ \-]? ){9} # 9 digits with opt. delimiters
01211                                         [0-9Xx]                 # check digit
01212                                         \b)
01213                         )!xu', array( &$this, 'magicLinkCallback' ), $text );
01214                 wfProfileOut( __METHOD__ );
01215                 return $text;
01216         }
01217 
01223         function magicLinkCallback( $m ) {
01224                 if ( isset( $m[1] ) && $m[1] !== '' ) {
01225                         # Skip anchor
01226                         return $m[0];
01227                 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
01228                         # Skip HTML element
01229                         return $m[0];
01230                 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
01231                         # Free external link
01232                         return $this->makeFreeExternalLink( $m[0] );
01233                 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
01234                         # RFC or PMID
01235                         if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
01236                                 $keyword = 'RFC';
01237                                 $urlmsg = 'rfcurl';
01238                                 $CssClass = 'mw-magiclink-rfc';
01239                                 $id = $m[4];
01240                         } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
01241                                 $keyword = 'PMID';
01242                                 $urlmsg = 'pubmedurl';
01243                                 $CssClass = 'mw-magiclink-pmid';
01244                                 $id = $m[4];
01245                         } else {
01246                                 throw new MWException( __METHOD__.': unrecognised match type "' .
01247                                         substr( $m[0], 0, 20 ) . '"' );
01248                         }
01249                         $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
01250                         return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
01251                 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
01252                         # ISBN
01253                         $isbn = $m[5];
01254                         $num = strtr( $isbn, array(
01255                                 '-' => '',
01256                                 ' ' => '',
01257                                 'x' => 'X',
01258                         ));
01259                         $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
01260                         return'<a href="' .
01261                                 htmlspecialchars( $titleObj->getLocalUrl() ) .
01262                                 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
01263                 } else {
01264                         return $m[0];
01265                 }
01266         }
01267 
01276         function makeFreeExternalLink( $url ) {
01277                 wfProfileIn( __METHOD__ );
01278 
01279                 $trail = '';
01280 
01281                 # The characters '<' and '>' (which were escaped by
01282                 # removeHTMLtags()) should not be included in
01283                 # URLs, per RFC 2396.
01284                 $m2 = array();
01285                 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
01286                         $trail = substr( $url, $m2[0][1] ) . $trail;
01287                         $url = substr( $url, 0, $m2[0][1] );
01288                 }
01289 
01290                 # Move trailing punctuation to $trail
01291                 $sep = ',;\.:!?';
01292                 # If there is no left bracket, then consider right brackets fair game too
01293                 if ( strpos( $url, '(' ) === false ) {
01294                         $sep .= ')';
01295                 }
01296 
01297                 $numSepChars = strspn( strrev( $url ), $sep );
01298                 if ( $numSepChars ) {
01299                         $trail = substr( $url, -$numSepChars ) . $trail;
01300                         $url = substr( $url, 0, -$numSepChars );
01301                 }
01302 
01303                 $url = Sanitizer::cleanUrl( $url );
01304 
01305                 # Is this an external image?
01306                 $text = $this->maybeMakeExternalImage( $url );
01307                 if ( $text === false ) {
01308                         # Not an image, make a link
01309                         $text = Linker::makeExternalLink( $url,
01310                                 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
01311                                 $this->getExternalLinkAttribs( $url ) );
01312                         # Register it in the output object...
01313                         # Replace unnecessary URL escape codes with their equivalent characters
01314                         $pasteurized = self::replaceUnusualEscapes( $url );
01315                         $this->mOutput->addExternalLink( $pasteurized );
01316                 }
01317                 wfProfileOut( __METHOD__ );
01318                 return $text . $trail;
01319         }
01320 
01321 
01331         function doHeadings( $text ) {
01332                 wfProfileIn( __METHOD__ );
01333                 for ( $i = 6; $i >= 1; --$i ) {
01334                         $h = str_repeat( '=', $i );
01335                         $text = preg_replace( "/^$h(.+)$h\\s*$/m",
01336                           "<h$i>\\1</h$i>", $text );
01337                 }
01338                 wfProfileOut( __METHOD__ );
01339                 return $text;
01340         }
01341 
01350         function doAllQuotes( $text ) {
01351                 wfProfileIn( __METHOD__ );
01352                 $outtext = '';
01353                 $lines = StringUtils::explode( "\n", $text );
01354                 foreach ( $lines as $line ) {
01355                         $outtext .= $this->doQuotes( $line ) . "\n";
01356                 }
01357                 $outtext = substr( $outtext, 0,-1 );
01358                 wfProfileOut( __METHOD__ );
01359                 return $outtext;
01360         }
01361 
01369         public function doQuotes( $text ) {
01370                 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
01371                 if ( count( $arr ) == 1 ) {
01372                         return $text;
01373                 } else {
01374                         # First, do some preliminary work. This may shift some apostrophes from
01375                         # being mark-up to being text. It also counts the number of occurrences
01376                         # of bold and italics mark-ups.
01377                         $numbold = 0;
01378                         $numitalics = 0;
01379                         for ( $i = 0; $i < count( $arr ); $i++ ) {
01380                                 if ( ( $i % 2 ) == 1 ) {
01381                                         # If there are ever four apostrophes, assume the first is supposed to
01382                                         # be text, and the remaining three constitute mark-up for bold text.
01383                                         if ( strlen( $arr[$i] ) == 4 ) {
01384                                                 $arr[$i-1] .= "'";
01385                                                 $arr[$i] = "'''";
01386                                         } elseif ( strlen( $arr[$i] ) > 5 ) {
01387                                                 # If there are more than 5 apostrophes in a row, assume they're all
01388                                                 # text except for the last 5.
01389                                                 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
01390                                                 $arr[$i] = "'''''";
01391                                         }
01392                                         # Count the number of occurrences of bold and italics mark-ups.
01393                                         # We are not counting sequences of five apostrophes.
01394                                         if ( strlen( $arr[$i] ) == 2 ) {
01395                                                 $numitalics++;
01396                                         } elseif ( strlen( $arr[$i] ) == 3 ) {
01397                                                 $numbold++;
01398                                         } elseif ( strlen( $arr[$i] ) == 5 ) {
01399                                                 $numitalics++;
01400                                                 $numbold++;
01401                                         }
01402                                 }
01403                         }
01404 
01405                         # If there is an odd number of both bold and italics, it is likely
01406                         # that one of the bold ones was meant to be an apostrophe followed
01407                         # by italics. Which one we cannot know for certain, but it is more
01408                         # likely to be one that has a single-letter word before it.
01409                         if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
01410                                 $i = 0;
01411                                 $firstsingleletterword = -1;
01412                                 $firstmultiletterword = -1;
01413                                 $firstspace = -1;
01414                                 foreach ( $arr as $r ) {
01415                                         if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) {
01416                                                 $x1 = substr( $arr[$i-1], -1 );
01417                                                 $x2 = substr( $arr[$i-1], -2, 1 );
01418                                                 if ( $x1 === ' ' ) {
01419                                                         if ( $firstspace == -1 ) {
01420                                                                 $firstspace = $i;
01421                                                         }
01422                                                 } elseif ( $x2 === ' ') {
01423                                                         if ( $firstsingleletterword == -1 ) {
01424                                                                 $firstsingleletterword = $i;
01425                                                         }
01426                                                 } else {
01427                                                         if ( $firstmultiletterword == -1 ) {
01428                                                                 $firstmultiletterword = $i;
01429                                                         }
01430                                                 }
01431                                         }
01432                                         $i++;
01433                                 }
01434 
01435                                 # If there is a single-letter word, use it!
01436                                 if ( $firstsingleletterword > -1 ) {
01437                                         $arr[$firstsingleletterword] = "''";
01438                                         $arr[$firstsingleletterword-1] .= "'";
01439                                 } elseif ( $firstmultiletterword > -1 ) {
01440                                         # If not, but there's a multi-letter word, use that one.
01441                                         $arr[$firstmultiletterword] = "''";
01442                                         $arr[$firstmultiletterword-1] .= "'";
01443                                 } elseif ( $firstspace > -1 ) {
01444                                         # ... otherwise use the first one that has neither.
01445                                         # (notice that it is possible for all three to be -1 if, for example,
01446                                         # there is only one pentuple-apostrophe in the line)
01447                                         $arr[$firstspace] = "''";
01448                                         $arr[$firstspace-1] .= "'";
01449                                 }
01450                         }
01451 
01452                         # Now let's actually convert our apostrophic mush to HTML!
01453                         $output = '';
01454                         $buffer = '';
01455                         $state = '';
01456                         $i = 0;
01457                         foreach ( $arr as $r ) {
01458                                 if ( ( $i % 2 ) == 0 ) {
01459                                         if ( $state === 'both' ) {
01460                                                 $buffer .= $r;
01461                                         } else {
01462                                                 $output .= $r;
01463                                         }
01464                                 } else {
01465                                         if ( strlen( $r ) == 2 ) {
01466                                                 if ( $state === 'i' ) {
01467                                                         $output .= '</i>'; $state = '';
01468                                                 } elseif ( $state === 'bi' ) {
01469                                                         $output .= '</i>'; $state = 'b';
01470                                                 } elseif ( $state === 'ib' ) {
01471                                                         $output .= '</b></i><b>'; $state = 'b';
01472                                                 } elseif ( $state === 'both' ) {
01473                                                         $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
01474                                                 } else { # $state can be 'b' or ''
01475                                                         $output .= '<i>'; $state .= 'i';
01476                                                 }
01477                                         } elseif ( strlen( $r ) == 3 ) {
01478                                                 if ( $state === 'b' ) {
01479                                                         $output .= '</b>'; $state = '';
01480                                                 } elseif ( $state === 'bi' ) {
01481                                                         $output .= '</i></b><i>'; $state = 'i';
01482                                                 } elseif ( $state === 'ib' ) {
01483                                                         $output .= '</b>'; $state = 'i';
01484                                                 } elseif ( $state === 'both' ) {
01485                                                         $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
01486                                                 } else { # $state can be 'i' or ''
01487                                                         $output .= '<b>'; $state .= 'b';
01488                                                 }
01489                                         } elseif ( strlen( $r ) == 5 ) {
01490                                                 if ( $state === 'b' ) {
01491                                                         $output .= '</b><i>'; $state = 'i';
01492                                                 } elseif ( $state === 'i' ) {
01493                                                         $output .= '</i><b>'; $state = 'b';
01494                                                 } elseif ( $state === 'bi' ) {
01495                                                         $output .= '</i></b>'; $state = '';
01496                                                 } elseif ( $state === 'ib' ) {
01497                                                         $output .= '</b></i>'; $state = '';
01498                                                 } elseif ( $state === 'both' ) {
01499                                                         $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
01500                                                 } else { # ($state == '')
01501                                                         $buffer = ''; $state = 'both';
01502                                                 }
01503                                         }
01504                                 }
01505                                 $i++;
01506                         }
01507                         # Now close all remaining tags.  Notice that the order is important.
01508                         if ( $state === 'b' || $state === 'ib' ) {
01509                                 $output .= '</b>';
01510                         }
01511                         if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
01512                                 $output .= '</i>';
01513                         }
01514                         if ( $state === 'bi' ) {
01515                                 $output .= '</b>';
01516                         }
01517                         # There might be lonely ''''', so make sure we have a buffer
01518                         if ( $state === 'both' && $buffer ) {
01519                                 $output .= '<b><i>'.$buffer.'</i></b>';
01520                         }
01521                         return $output;
01522                 }
01523         }
01524 
01538         function replaceExternalLinks( $text ) {
01539                 wfProfileIn( __METHOD__ );
01540 
01541                 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
01542                 if ( $bits === false ) {
01543                         throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
01544                 }
01545                 $s = array_shift( $bits );
01546 
01547                 $i = 0;
01548                 while ( $i<count( $bits ) ) {
01549                         $url = $bits[$i++];
01550                         // @todo FIXME: Unused variable.
01551                         $protocol = $bits[$i++];
01552                         $text = $bits[$i++];
01553                         $trail = $bits[$i++];
01554 
01555                         # The characters '<' and '>' (which were escaped by
01556                         # removeHTMLtags()) should not be included in
01557                         # URLs, per RFC 2396.
01558                         $m2 = array();
01559                         if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
01560                                 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
01561                                 $url = substr( $url, 0, $m2[0][1] );
01562                         }
01563 
01564                         # If the link text is an image URL, replace it with an <img> tag
01565                         # This happened by accident in the original parser, but some people used it extensively
01566                         $img = $this->maybeMakeExternalImage( $text );
01567                         if ( $img !== false ) {
01568                                 $text = $img;
01569                         }
01570 
01571                         $dtrail = '';
01572 
01573                         # Set linktype for CSS - if URL==text, link is essentially free
01574                         $linktype = ( $text === $url ) ? 'free' : 'text';
01575 
01576                         # No link text, e.g. [http://domain.tld/some.link]
01577                         if ( $text == '' ) {
01578                                 # Autonumber
01579                                 $langObj = $this->getTargetLanguage();
01580                                 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
01581                                 $linktype = 'autonumber';
01582                         } else {
01583                                 # Have link text, e.g. [http://domain.tld/some.link text]s
01584                                 # Check for trail
01585                                 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
01586                         }
01587 
01588                         $text = $this->getConverterLanguage()->markNoConversion( $text );
01589 
01590                         $url = Sanitizer::cleanUrl( $url );
01591 
01592                         # Use the encoded URL
01593                         # This means that users can paste URLs directly into the text
01594                         # Funny characters like ö aren't valid in URLs anyway
01595                         # This was changed in August 2004
01596                         $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
01597                                 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
01598 
01599                         # Register link in the output object.
01600                         # Replace unnecessary URL escape codes with the referenced character
01601                         # This prevents spammers from hiding links from the filters
01602                         $pasteurized = self::replaceUnusualEscapes( $url );
01603                         $this->mOutput->addExternalLink( $pasteurized );
01604                 }
01605 
01606                 wfProfileOut( __METHOD__ );
01607                 return $s;
01608         }
01609 
01620         function getExternalLinkAttribs( $url = false ) {
01621                 $attribs = array();
01622                 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
01623                 $ns = $this->mTitle->getNamespace();
01624                 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
01625                                 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
01626                 {
01627                         $attribs['rel'] = 'nofollow';
01628                 }
01629                 if ( $this->mOptions->getExternalLinkTarget() ) {
01630                         $attribs['target'] = $this->mOptions->getExternalLinkTarget();
01631                 }
01632                 return $attribs;
01633         }
01634 
01646         static function replaceUnusualEscapes( $url ) {
01647                 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
01648                         array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
01649         }
01650 
01659         private static function replaceUnusualEscapesCallback( $matches ) {
01660                 $char = urldecode( $matches[0] );
01661                 $ord = ord( $char );
01662                 # Is it an unsafe or HTTP reserved character according to RFC 1738?
01663                 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
01664                         # No, shouldn't be escaped
01665                         return $char;
01666                 } else {
01667                         # Yes, leave it escaped
01668                         return $matches[0];
01669                 }
01670         }
01671 
01681         function maybeMakeExternalImage( $url ) {
01682                 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
01683                 $imagesexception = !empty( $imagesfrom );
01684                 $text = false;
01685                 # $imagesfrom could be either a single string or an array of strings, parse out the latter
01686                 if ( $imagesexception && is_array( $imagesfrom ) ) {
01687                         $imagematch = false;
01688                         foreach ( $imagesfrom as $match ) {
01689                                 if ( strpos( $url, $match ) === 0 ) {
01690                                         $imagematch = true;
01691                                         break;
01692                                 }
01693                         }
01694                 } elseif ( $imagesexception ) {
01695                         $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
01696                 } else {
01697                         $imagematch = false;
01698                 }
01699                 if ( $this->mOptions->getAllowExternalImages()
01700                          || ( $imagesexception && $imagematch ) ) {
01701                         if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
01702                                 # Image found
01703                                 $text = Linker::makeExternalImage( $url );
01704                         }
01705                 }
01706                 if ( !$text && $this->mOptions->getEnableImageWhitelist()
01707                          && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
01708                         $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
01709                         foreach ( $whitelist as $entry ) {
01710                                 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
01711                                 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
01712                                         continue;
01713                                 }
01714                                 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
01715                                         # Image matches a whitelist entry
01716                                         $text = Linker::makeExternalImage( $url );
01717                                         break;
01718                                 }
01719                         }
01720                 }
01721                 return $text;
01722         }
01723 
01733         function replaceInternalLinks( $s ) {
01734                 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
01735                 return $s;
01736         }
01737 
01746         function replaceInternalLinks2( &$s ) {
01747                 wfProfileIn( __METHOD__ );
01748 
01749                 wfProfileIn( __METHOD__.'-setup' );
01750                 static $tc = FALSE, $e1, $e1_img;
01751                 # the % is needed to support urlencoded titles as well
01752                 if ( !$tc ) {
01753                         $tc = Title::legalChars() . '#%';
01754                         # Match a link having the form [[namespace:link|alternate]]trail
01755                         $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
01756                         # Match cases where there is no "]]", which might still be images
01757                         $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
01758                 }
01759 
01760                 $holders = new LinkHolderArray( $this );
01761 
01762                 # split the entire text string on occurrences of [[
01763                 $a = StringUtils::explode( '[[', ' ' . $s );
01764                 # get the first element (all text up to first [[), and remove the space we added
01765                 $s = $a->current();
01766                 $a->next();
01767                 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
01768                 $s = substr( $s, 1 );
01769 
01770                 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
01771                 $e2 = null;
01772                 if ( $useLinkPrefixExtension ) {
01773                         # Match the end of a line for a word that's not followed by whitespace,
01774                         # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
01775                         $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
01776                 }
01777 
01778                 if ( is_null( $this->mTitle ) ) {
01779                         wfProfileOut( __METHOD__.'-setup' );
01780                         wfProfileOut( __METHOD__ );
01781                         throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
01782                 }
01783                 $nottalk = !$this->mTitle->isTalkPage();
01784 
01785                 if ( $useLinkPrefixExtension ) {
01786                         $m = array();
01787                         if ( preg_match( $e2, $s, $m ) ) {
01788                                 $first_prefix = $m[2];
01789                         } else {
01790                                 $first_prefix = false;
01791                         }
01792                 } else {
01793                         $prefix = '';
01794                 }
01795 
01796                 if ( $this->getConverterLanguage()->hasVariants() ) {
01797                         $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
01798                                 $this->mTitle->getPrefixedText() );
01799                 } else {
01800                         $selflink = array( $this->mTitle->getPrefixedText() );
01801                 }
01802                 $useSubpages = $this->areSubpagesAllowed();
01803                 wfProfileOut( __METHOD__.'-setup' );
01804 
01805                 # Loop for each link
01806                 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
01807                         # Check for excessive memory usage
01808                         if ( $holders->isBig() ) {
01809                                 # Too big
01810                                 # Do the existence check, replace the link holders and clear the array
01811                                 $holders->replace( $s );
01812                                 $holders->clear();
01813                         }
01814 
01815                         if ( $useLinkPrefixExtension ) {
01816                                 wfProfileIn( __METHOD__.'-prefixhandling' );
01817                                 if ( preg_match( $e2, $s, $m ) ) {
01818                                         $prefix = $m[2];
01819                                         $s = $m[1];
01820                                 } else {
01821                                         $prefix='';
01822                                 }
01823                                 # first link
01824                                 if ( $first_prefix ) {
01825                                         $prefix = $first_prefix;
01826                                         $first_prefix = false;
01827                                 }
01828                                 wfProfileOut( __METHOD__.'-prefixhandling' );
01829                         }
01830 
01831                         $might_be_img = false;
01832 
01833                         wfProfileIn( __METHOD__."-e1" );
01834                         if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
01835                                 $text = $m[2];
01836                                 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
01837                                 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
01838                                 # the real problem is with the $e1 regex
01839                                 # See bug 1300.
01840                                 #
01841                                 # Still some problems for cases where the ] is meant to be outside punctuation,
01842                                 # and no image is in sight. See bug 2095.
01843                                 #
01844                                 if ( $text !== '' &&
01845                                         substr( $m[3], 0, 1 ) === ']' &&
01846                                         strpos( $text, '[' ) !== false
01847                                 )
01848                                 {
01849                                         $text .= ']'; # so that replaceExternalLinks($text) works later
01850                                         $m[3] = substr( $m[3], 1 );
01851                                 }
01852                                 # fix up urlencoded title texts
01853                                 if ( strpos( $m[1], '%' ) !== false ) {
01854                                         # Should anchors '#' also be rejected?
01855                                         $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), rawurldecode( $m[1] ) );
01856                                 }
01857                                 $trail = $m[3];
01858                         } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
01859                                 $might_be_img = true;
01860                                 $text = $m[2];
01861                                 if ( strpos( $m[1], '%' ) !== false ) {
01862                                         $m[1] = rawurldecode( $m[1] );
01863                                 }
01864                                 $trail = "";
01865                         } else { # Invalid form; output directly
01866                                 $s .= $prefix . '[[' . $line ;
01867                                 wfProfileOut( __METHOD__."-e1" );
01868                                 continue;
01869                         }
01870                         wfProfileOut( __METHOD__."-e1" );
01871                         wfProfileIn( __METHOD__."-misc" );
01872 
01873                         # Don't allow internal links to pages containing
01874                         # PROTO: where PROTO is a valid URL protocol; these
01875                         # should be external links.
01876                         if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
01877                                 $s .= $prefix . '[[' . $line ;
01878                                 wfProfileOut( __METHOD__."-misc" );
01879                                 continue;
01880                         }
01881 
01882                         # Make subpage if necessary
01883                         if ( $useSubpages ) {
01884                                 $link = $this->maybeDoSubpageLink( $m[1], $text );
01885                         } else {
01886                                 $link = $m[1];
01887                         }
01888 
01889                         $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
01890                         if ( !$noforce ) {
01891                                 # Strip off leading ':'
01892                                 $link = substr( $link, 1 );
01893                         }
01894 
01895                         wfProfileOut( __METHOD__."-misc" );
01896                         wfProfileIn( __METHOD__."-title" );
01897                         $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
01898                         if ( $nt === null ) {
01899                                 $s .= $prefix . '[[' . $line;
01900                                 wfProfileOut( __METHOD__."-title" );
01901                                 continue;
01902                         }
01903 
01904                         $ns = $nt->getNamespace();
01905                         $iw = $nt->getInterWiki();
01906                         wfProfileOut( __METHOD__."-title" );
01907 
01908                         if ( $might_be_img ) { # if this is actually an invalid link
01909                                 wfProfileIn( __METHOD__."-might_be_img" );
01910                                 if ( $ns == NS_FILE && $noforce ) { # but might be an image
01911                                         $found = false;
01912                                         while ( true ) {
01913                                                 # look at the next 'line' to see if we can close it there
01914                                                 $a->next();
01915                                                 $next_line = $a->current();
01916                                                 if ( $next_line === false || $next_line === null ) {
01917                                                         break;
01918                                                 }
01919                                                 $m = explode( ']]', $next_line, 3 );
01920                                                 if ( count( $m ) == 3 ) {
01921                                                         # the first ]] closes the inner link, the second the image
01922                                                         $found = true;
01923                                                         $text .= "[[{$m[0]}]]{$m[1]}";
01924                                                         $trail = $m[2];
01925                                                         break;
01926                                                 } elseif ( count( $m ) == 2 ) {
01927                                                         # if there's exactly one ]] that's fine, we'll keep looking
01928                                                         $text .= "[[{$m[0]}]]{$m[1]}";
01929                                                 } else {
01930                                                         # if $next_line is invalid too, we need look no further
01931                                                         $text .= '[[' . $next_line;
01932                                                         break;
01933                                                 }
01934                                         }
01935                                         if ( !$found ) {
01936                                                 # we couldn't find the end of this imageLink, so output it raw
01937                                                 # but don't ignore what might be perfectly normal links in the text we've examined
01938                                                 $holders->merge( $this->replaceInternalLinks2( $text ) );
01939                                                 $s .= "{$prefix}[[$link|$text";
01940                                                 # note: no $trail, because without an end, there *is* no trail
01941                                                 wfProfileOut( __METHOD__."-might_be_img" );
01942                                                 continue;
01943                                         }
01944                                 } else { # it's not an image, so output it raw
01945                                         $s .= "{$prefix}[[$link|$text";
01946                                         # note: no $trail, because without an end, there *is* no trail
01947                                         wfProfileOut( __METHOD__."-might_be_img" );
01948                                         continue;
01949                                 }
01950                                 wfProfileOut( __METHOD__."-might_be_img" );
01951                         }
01952 
01953                         $wasblank = ( $text  == '' );
01954                         if ( $wasblank ) {
01955                                 $text = $link;
01956                         } else {
01957                                 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
01958                                 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
01959                                 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
01960                                 #    -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
01961                                 $text = $this->doQuotes( $text );
01962                         }
01963 
01964                         # Link not escaped by : , create the various objects
01965                         if ( $noforce ) {
01966                                 # Interwikis
01967                                 wfProfileIn( __METHOD__."-interwiki" );
01968                                 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) {
01969                                         // XXX: the above check prevents links to sites with identifiers that are not language codes
01970 
01971                                         # Bug 24502: filter duplicates
01972                                         if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
01973                                                 $this->mLangLinkLanguages[$iw] = true;
01974                                                 $this->mOutput->addLanguageLink( $nt->getFullText() );
01975                                         }
01976 
01977                                         $s = rtrim( $s . $prefix );
01978                                         $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
01979                                         wfProfileOut( __METHOD__."-interwiki" );
01980                                         continue;
01981                                 }
01982                                 wfProfileOut( __METHOD__."-interwiki" );
01983 
01984                                 if ( $ns == NS_FILE ) {
01985                                         wfProfileIn( __METHOD__."-image" );
01986                                         if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
01987                                                 if ( $wasblank ) {
01988                                                         # if no parameters were passed, $text
01989                                                         # becomes something like "File:Foo.png",
01990                                                         # which we don't want to pass on to the
01991                                                         # image generator
01992                                                         $text = '';
01993                                                 } else {
01994                                                         # recursively parse links inside the image caption
01995                                                         # actually, this will parse them in any other parameters, too,
01996                                                         # but it might be hard to fix that, and it doesn't matter ATM
01997                                                         $text = $this->replaceExternalLinks( $text );
01998                                                         $holders->merge( $this->replaceInternalLinks2( $text ) );
01999                                                 }
02000                                                 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
02001                                                 $s .= $prefix . $this->armorLinks(
02002                                                         $this->makeImage( $nt, $text, $holders ) ) . $trail;
02003                                         } else {
02004                                                 $s .= $prefix . $trail;
02005                                         }
02006                                         wfProfileOut( __METHOD__."-image" );
02007                                         continue;
02008                                 }
02009 
02010                                 if ( $ns == NS_CATEGORY ) {
02011                                         wfProfileIn( __METHOD__."-category" );
02012                                         $s = rtrim( $s . "\n" ); # bug 87
02013 
02014                                         if ( $wasblank ) {
02015                                                 $sortkey = $this->getDefaultSort();
02016                                         } else {
02017                                                 $sortkey = $text;
02018                                         }
02019                                         $sortkey = Sanitizer::decodeCharReferences( $sortkey );
02020                                         $sortkey = str_replace( "\n", '', $sortkey );
02021                                         $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
02022                                         $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
02023 
02028                                         $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
02029 
02030                                         wfProfileOut( __METHOD__."-category" );
02031                                         continue;
02032                                 }
02033                         }
02034 
02035                         # Self-link checking
02036                         if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
02037                                 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
02038                                         $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
02039                                         continue;
02040                                 }
02041                         }
02042 
02043                         # NS_MEDIA is a pseudo-namespace for linking directly to a file
02044                         # @todo FIXME: Should do batch file existence checks, see comment below
02045                         if ( $ns == NS_MEDIA ) {
02046                                 wfProfileIn( __METHOD__."-media" );
02047                                 # Give extensions a chance to select the file revision for us
02048                                 $options = array();
02049                                 $descQuery = false;
02050                                 wfRunHooks( 'BeforeParserFetchFileAndTitle',
02051                                         array( $this, $nt, &$options, &$descQuery ) );
02052                                 # Fetch and register the file (file title may be different via hooks)
02053                                 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
02054                                 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
02055                                 $s .= $prefix . $this->armorLinks(
02056                                         Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
02057                                 wfProfileOut( __METHOD__."-media" );
02058                                 continue;
02059                         }
02060 
02061                         wfProfileIn( __METHOD__."-always_known" );
02062                         # Some titles, such as valid special pages or files in foreign repos, should
02063                         # be shown as bluelinks even though they're not included in the page table
02064                         #
02065                         # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
02066                         # batch file existence checks for NS_FILE and NS_MEDIA
02067                         if ( $iw == '' && $nt->isAlwaysKnown() ) {
02068                                 $this->mOutput->addLink( $nt );
02069                                 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
02070                         } else {
02071                                 # Links will be added to the output link list after checking
02072                                 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
02073                         }
02074                         wfProfileOut( __METHOD__."-always_known" );
02075                 }
02076                 wfProfileOut( __METHOD__ );
02077                 return $holders;
02078         }
02079 
02094         function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
02095                 list( $inside, $trail ) = Linker::splitTrail( $trail );
02096 
02097                 if ( is_string( $query ) ) {
02098                         $query = wfCgiToArray( $query );
02099                 }
02100                 if ( $text == '' ) {
02101                         $text = htmlspecialchars( $nt->getPrefixedText() );
02102                 }
02103 
02104                 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
02105 
02106                 return $this->armorLinks( $link ) . $trail;
02107         }
02108 
02119         function armorLinks( $text ) {
02120                 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
02121                         "{$this->mUniqPrefix}NOPARSE$1", $text );
02122         }
02123 
02128         function areSubpagesAllowed() {
02129                 # Some namespaces don't allow subpages
02130                 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
02131         }
02132 
02141         function maybeDoSubpageLink( $target, &$text ) {
02142                 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
02143         }
02144 
02151         function closeParagraph() {
02152                 $result = '';
02153                 if ( $this->mLastSection != '' ) {
02154                         $result = '</' . $this->mLastSection  . ">\n";
02155                 }
02156                 $this->mInPre = false;
02157                 $this->mLastSection = '';
02158                 return $result;
02159         }
02160 
02171         function getCommon( $st1, $st2 ) {
02172                 $fl = strlen( $st1 );
02173                 $shorter = strlen( $st2 );
02174                 if ( $fl < $shorter ) {
02175                         $shorter = $fl;
02176                 }
02177 
02178                 for ( $i = 0; $i < $shorter; ++$i ) {
02179                         if ( $st1[$i] != $st2[$i] ) {
02180                                 break;
02181                         }
02182                 }
02183                 return $i;
02184         }
02185 
02195         function openList( $char ) {
02196                 $result = $this->closeParagraph();
02197 
02198                 if ( '*' === $char ) {
02199                         $result .= '<ul><li>';
02200                 } elseif ( '#' === $char ) {
02201                         $result .= '<ol><li>';
02202                 } elseif ( ':' === $char ) {
02203                         $result .= '<dl><dd>';
02204                 } elseif ( ';' === $char ) {
02205                         $result .= '<dl><dt>';
02206                         $this->mDTopen = true;
02207                 } else {
02208                         $result = '<!-- ERR 1 -->';
02209                 }
02210 
02211                 return $result;
02212         }
02213 
02221         function nextItem( $char ) {
02222                 if ( '*' === $char || '#' === $char ) {
02223                         return '</li><li>';
02224                 } elseif ( ':' === $char || ';' === $char ) {
02225                         $close = '</dd>';
02226                         if ( $this->mDTopen ) {
02227                                 $close = '</dt>';
02228                         }
02229                         if ( ';' === $char ) {
02230                                 $this->mDTopen = true;
02231                                 return $close . '<dt>';
02232                         } else {
02233                                 $this->mDTopen = false;
02234                                 return $close . '<dd>';
02235                         }
02236                 }
02237                 return '<!-- ERR 2 -->';
02238         }
02239 
02247         function closeList( $char ) {
02248                 if ( '*' === $char ) {
02249                         $text = '</li></ul>';
02250                 } elseif ( '#' === $char ) {
02251                         $text = '</li></ol>';
02252                 } elseif ( ':' === $char ) {
02253                         if ( $this->mDTopen ) {
02254                                 $this->mDTopen = false;
02255                                 $text = '</dt></dl>';
02256                         } else {
02257                                 $text = '</dd></dl>';
02258                         }
02259                 } else {
02260                         return '<!-- ERR 3 -->';
02261                 }
02262                 return $text."\n";
02263         }
02274         function doBlockLevels( $text, $linestart ) {
02275                 wfProfileIn( __METHOD__ );
02276 
02277                 # Parsing through the text line by line.  The main thing
02278                 # happening here is handling of block-level elements p, pre,
02279                 # and making lists from lines starting with * # : etc.
02280                 #
02281                 $textLines = StringUtils::explode( "\n", $text );
02282 
02283                 $lastPrefix = $output = '';
02284                 $this->mDTopen = $inBlockElem = false;
02285                 $prefixLength = 0;
02286                 $paragraphStack = false;
02287 
02288                 foreach ( $textLines as $oLine ) {
02289                         # Fix up $linestart
02290                         if ( !$linestart ) {
02291                                 $output .= $oLine;
02292                                 $linestart = true;
02293                                 continue;
02294                         }
02295                         # * = ul
02296                         # # = ol
02297                         # ; = dt
02298                         # : = dd
02299 
02300                         $lastPrefixLength = strlen( $lastPrefix );
02301                         $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
02302                         $preOpenMatch = preg_match( '/<pre/i', $oLine );
02303                         # If not in a <pre> element, scan for and figure out what prefixes are there.
02304                         if ( !$this->mInPre ) {
02305                                 # Multiple prefixes may abut each other for nested lists.
02306                                 $prefixLength = strspn( $oLine, '*#:;' );
02307                                 $prefix = substr( $oLine, 0, $prefixLength );
02308 
02309                                 # eh?
02310                                 # ; and : are both from definition-lists, so they're equivalent
02311                                 #  for the purposes of determining whether or not we need to open/close
02312                                 #  elements.
02313                                 $prefix2 = str_replace( ';', ':', $prefix );
02314                                 $t = substr( $oLine, $prefixLength );
02315                                 $this->mInPre = (bool)$preOpenMatch;
02316                         } else {
02317                                 # Don't interpret any other prefixes in preformatted text
02318                                 $prefixLength = 0;
02319                                 $prefix = $prefix2 = '';
02320                                 $t = $oLine;
02321                         }
02322 
02323                         # List generation
02324                         if ( $prefixLength && $lastPrefix === $prefix2 ) {
02325                                 # Same as the last item, so no need to deal with nesting or opening stuff
02326                                 $output .= $this->nextItem( substr( $prefix, -1 ) );
02327                                 $paragraphStack = false;
02328 
02329                                 if ( substr( $prefix, -1 ) === ';') {
02330                                         # The one nasty exception: definition lists work like this:
02331                                         # ; title : definition text
02332                                         # So we check for : in the remainder text to split up the
02333                                         # title and definition, without b0rking links.
02334                                         $term = $t2 = '';
02335                                         if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
02336                                                 $t = $t2;
02337                                                 $output .= $term . $this->nextItem( ':' );
02338                                         }
02339                                 }
02340                         } elseif ( $prefixLength || $lastPrefixLength ) {
02341                                 # We need to open or close prefixes, or both.
02342 
02343                                 # Either open or close a level...
02344                                 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
02345                                 $paragraphStack = false;
02346 
02347                                 # Close all the prefixes which aren't shared.
02348                                 while ( $commonPrefixLength < $lastPrefixLength ) {
02349                                         $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
02350                                         --$lastPrefixLength;
02351                                 }
02352 
02353                                 # Continue the current prefix if appropriate.
02354                                 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
02355                                         $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
02356                                 }
02357 
02358                                 # Open prefixes where appropriate.
02359                                 while ( $prefixLength > $commonPrefixLength ) {
02360                                         $char = substr( $prefix, $commonPrefixLength, 1 );
02361                                         $output .= $this->openList( $char );
02362 
02363                                         if ( ';' === $char ) {
02364                                                 # @todo FIXME: This is dupe of code above
02365                                                 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
02366                                                         $t = $t2;
02367                                                         $output .= $term . $this->nextItem( ':' );
02368                                                 }
02369                                         }
02370                                         ++$commonPrefixLength;
02371                                 }
02372                                 $lastPrefix = $prefix2;
02373                         }
02374 
02375                         # If we have no prefixes, go to paragraph mode.
02376                         if ( 0 == $prefixLength ) {
02377                                 wfProfileIn( __METHOD__."-paragraph" );
02378                                 # No prefix (not in list)--go to paragraph mode
02379                                 # XXX: use a stack for nestable elements like span, table and div
02380                                 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
02381                                 $closematch = preg_match(
02382                                         '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
02383                                         '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
02384                                 if ( $openmatch or $closematch ) {
02385                                         $paragraphStack = false;
02386                                         # TODO bug 5718: paragraph closed
02387                                         $output .= $this->closeParagraph();
02388                                         if ( $preOpenMatch and !$preCloseMatch ) {
02389                                                 $this->mInPre = true;
02390                                         }
02391                                         $inBlockElem = !$closematch;
02392                                 } elseif ( !$inBlockElem && !$this->mInPre ) {
02393                                         if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
02394                                                 # pre
02395                                                 if ( $this->mLastSection !== 'pre' ) {
02396                                                         $paragraphStack = false;
02397                                                         $output .= $this->closeParagraph().'<pre>';
02398                                                         $this->mLastSection = 'pre';
02399                                                 }
02400                                                 $t = substr( $t, 1 );
02401                                         } else {
02402                                                 # paragraph
02403                                                 if ( trim( $t ) === '' ) {
02404                                                         if ( $paragraphStack ) {
02405                                                                 $output .= $paragraphStack.'<br />';
02406                                                                 $paragraphStack = false;
02407                                                                 $this->mLastSection = 'p';
02408                                                         } else {
02409                                                                 if ( $this->mLastSection !== 'p' ) {
02410                                                                         $output .= $this->closeParagraph();
02411                                                                         $this->mLastSection = '';
02412                                                                         $paragraphStack = '<p>';
02413                                                                 } else {
02414                                                                         $paragraphStack = '</p><p>';
02415                                                                 }
02416                                                         }
02417                                                 } else {
02418                                                         if ( $paragraphStack ) {
02419                                                                 $output .= $paragraphStack;
02420                                                                 $paragraphStack = false;
02421                                                                 $this->mLastSection = 'p';
02422                                                         } elseif ( $this->mLastSection !== 'p' ) {
02423                                                                 $output .= $this->closeParagraph().'<p>';
02424                                                                 $this->mLastSection = 'p';
02425                                                         }
02426                                                 }
02427                                         }
02428                                 }
02429                                 wfProfileOut( __METHOD__."-paragraph" );
02430                         }
02431                         # somewhere above we forget to get out of pre block (bug 785)
02432                         if ( $preCloseMatch && $this->mInPre ) {
02433                                 $this->mInPre = false;
02434                         }
02435                         if ( $paragraphStack === false ) {
02436                                 $output .= $t."\n";
02437                         }
02438                 }
02439                 while ( $prefixLength ) {
02440                         $output .= $this->closeList( $prefix2[$prefixLength-1] );
02441                         --$prefixLength;
02442                 }
02443                 if ( $this->mLastSection != '' ) {
02444                         $output .= '</' . $this->mLastSection . '>';
02445                         $this->mLastSection = '';
02446                 }
02447 
02448                 wfProfileOut( __METHOD__ );
02449                 return $output;
02450         }
02451 
02462         function findColonNoLinks( $str, &$before, &$after ) {
02463                 wfProfileIn( __METHOD__ );
02464 
02465                 $pos = strpos( $str, ':' );
02466                 if ( $pos === false ) {
02467                         # Nothing to find!
02468                         wfProfileOut( __METHOD__ );
02469                         return false;
02470                 }
02471 
02472                 $lt = strpos( $str, '<' );
02473                 if ( $lt === false || $lt > $pos ) {
02474                         # Easy; no tag nesting to worry about
02475                         $before = substr( $str, 0, $pos );
02476                         $after = substr( $str, $pos+1 );
02477                         wfProfileOut( __METHOD__ );
02478                         return $pos;
02479                 }
02480 
02481                 # Ugly state machine to walk through avoiding tags.
02482                 $state = self::COLON_STATE_TEXT;
02483                 $stack = 0;
02484                 $len = strlen( $str );
02485                 for( $i = 0; $i < $len; $i++ ) {
02486                         $c = $str[$i];
02487 
02488                         switch( $state ) {
02489                         # (Using the number is a performance hack for common cases)
02490                         case 0: # self::COLON_STATE_TEXT:
02491                                 switch( $c ) {
02492                                 case "<":
02493                                         # Could be either a <start> tag or an </end> tag
02494                                         $state = self::COLON_STATE_TAGSTART;
02495                                         break;
02496                                 case ":":
02497                                         if ( $stack == 0 ) {
02498                                                 # We found it!
02499                                                 $before = substr( $str, 0, $i );
02500                                                 $after = substr( $str, $i + 1 );
02501                                                 wfProfileOut( __METHOD__ );
02502                                                 return $i;
02503                                         }
02504                                         # Embedded in a tag; don't break it.
02505                                         break;
02506                                 default:
02507                                         # Skip ahead looking for something interesting
02508                                         $colon = strpos( $str, ':', $i );
02509                                         if ( $colon === false ) {
02510                                                 # Nothing else interesting
02511                                                 wfProfileOut( __METHOD__ );
02512                                                 return false;
02513                                         }
02514                                         $lt = strpos( $str, '<', $i );
02515                                         if ( $stack === 0 ) {
02516                                                 if ( $lt === false || $colon < $lt ) {
02517                                                         # We found it!
02518                                                         $before = substr( $str, 0, $colon );
02519                                                         $after = substr( $str, $colon + 1 );
02520                                                         wfProfileOut( __METHOD__ );
02521                                                         return $i;
02522                                                 }
02523                                         }
02524                                         if ( $lt === false ) {
02525                                                 # Nothing else interesting to find; abort!
02526                                                 # We're nested, but there's no close tags left. Abort!
02527                                                 break 2;
02528                                         }
02529                                         # Skip ahead to next tag start
02530                                         $i = $lt;
02531                                         $state = self::COLON_STATE_TAGSTART;
02532                                 }
02533                                 break;
02534                         case 1: # self::COLON_STATE_TAG:
02535                                 # In a <tag>
02536                                 switch( $c ) {
02537                                 case ">":
02538                                         $stack++;
02539                                         $state = self::COLON_STATE_TEXT;
02540                                         break;
02541                                 case "/":
02542                                         # Slash may be followed by >?
02543                                         $state = self::COLON_STATE_TAGSLASH;
02544                                         break;
02545                                 default:
02546                                         # ignore
02547                                 }
02548                                 break;
02549                         case 2: # self::COLON_STATE_TAGSTART:
02550                                 switch( $c ) {
02551                                 case "/":
02552                                         $state = self::COLON_STATE_CLOSETAG;
02553                                         break;
02554                                 case "!":
02555                                         $state = self::COLON_STATE_COMMENT;
02556                                         break;
02557                                 case ">":
02558                                         # Illegal early close? This shouldn't happen D:
02559                                         $state = self::COLON_STATE_TEXT;
02560                                         break;
02561                                 default:
02562                                         $state = self::COLON_STATE_TAG;
02563                                 }
02564                                 break;
02565                         case 3: # self::COLON_STATE_CLOSETAG:
02566                                 # In a </tag>
02567                                 if ( $c === ">" ) {
02568                                         $stack--;
02569                                         if ( $stack < 0 ) {
02570                                                 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
02571                                                 wfProfileOut( __METHOD__ );
02572                                                 return false;
02573                                         }
02574                                         $state = self::COLON_STATE_TEXT;
02575                                 }
02576                                 break;
02577                         case self::COLON_STATE_TAGSLASH:
02578                                 if ( $c === ">" ) {
02579                                         # Yes, a self-closed tag <blah/>
02580                                         $state = self::COLON_STATE_TEXT;
02581                                 } else {
02582                                         # Probably we're jumping the gun, and this is an attribute
02583                                         $state = self::COLON_STATE_TAG;
02584                                 }
02585                                 break;
02586                         case 5: # self::COLON_STATE_COMMENT:
02587                                 if ( $c === "-" ) {
02588                                         $state = self::COLON_STATE_COMMENTDASH;
02589                                 }
02590                                 break;
02591                         case self::COLON_STATE_COMMENTDASH:
02592                                 if ( $c === "-" ) {
02593                                         $state = self::COLON_STATE_COMMENTDASHDASH;
02594                                 } else {
02595                                         $state = self::COLON_STATE_COMMENT;
02596                                 }
02597                                 break;
02598                         case self::COLON_STATE_COMMENTDASHDASH:
02599                                 if ( $c === ">" ) {
02600                                         $state = self::COLON_STATE_TEXT;
02601                                 } else {
02602                                         $state = self::COLON_STATE_COMMENT;
02603                                 }
02604                                 break;
02605                         default:
02606                                 throw new MWException( "State machine error in " . __METHOD__ );
02607                         }
02608                 }
02609                 if ( $stack > 0 ) {
02610                         wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
02611                         wfProfileOut( __METHOD__ );
02612                         return false;
02613                 }
02614                 wfProfileOut( __METHOD__ );
02615                 return false;
02616         }
02617 
02629         function getVariableValue( $index, $frame = false ) {
02630                 global $wgContLang, $wgSitename, $wgServer;
02631                 global $wgArticlePath, $wgScriptPath, $wgStylePath;
02632 
02633                 if ( is_null( $this->mTitle ) ) {
02634                         // If no title set, bad things are going to happen
02635                         // later. Title should always be set since this
02636                         // should only be called in the middle of a parse
02637                         // operation (but the unit-tests do funky stuff)
02638                         throw new MWException( __METHOD__ . ' Should only be '
02639                                 . ' called while parsing (no title set)' );
02640                 }
02641 
02646                 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
02647                         if ( isset( $this->mVarCache[$index] ) ) {
02648                                 return $this->mVarCache[$index];
02649                         }
02650                 }
02651 
02652                 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
02653                 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
02654 
02655                 # Use the time zone
02656                 global $wgLocaltimezone;
02657                 if ( isset( $wgLocaltimezone ) ) {
02658                         $oldtz = date_default_timezone_get();
02659                         date_default_timezone_set( $wgLocaltimezone );
02660                 }
02661 
02662                 $localTimestamp = date( 'YmdHis', $ts );
02663                 $localMonth = date( 'm', $ts );
02664                 $localMonth1 = date( 'n', $ts );
02665                 $localMonthName = date( 'n', $ts );
02666                 $localDay = date( 'j', $ts );
02667                 $localDay2 = date( 'd', $ts );
02668                 $localDayOfWeek = date( 'w', $ts );
02669                 $localWeek = date( 'W', $ts );
02670                 $localYear = date( 'Y', $ts );
02671                 $localHour = date( 'H', $ts );
02672                 if ( isset( $wgLocaltimezone ) ) {
02673                         date_default_timezone_set( $oldtz );
02674                 }
02675 
02676                 $pageLang = $this->getFunctionLang();
02677 
02678                 switch ( $index ) {
02679                         case 'currentmonth':
02680                                 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
02681                                 break;
02682                         case 'currentmonth1':
02683                                 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
02684                                 break;
02685                         case 'currentmonthname':
02686                                 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
02687                                 break;
02688                         case 'currentmonthnamegen':
02689                                 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
02690                                 break;
02691                         case 'currentmonthabbrev':
02692                                 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
02693                                 break;
02694                         case 'currentday':
02695                                 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
02696                                 break;
02697                         case 'currentday2':
02698                                 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
02699                                 break;
02700                         case 'localmonth':
02701                                 $value = $pageLang->formatNum( $localMonth );
02702                                 break;
02703                         case 'localmonth1':
02704                                 $value = $pageLang->formatNum( $localMonth1 );
02705                                 break;
02706                         case 'localmonthname':
02707                                 $value = $pageLang->getMonthName( $localMonthName );
02708                                 break;
02709                         case 'localmonthnamegen':
02710                                 $value = $pageLang->getMonthNameGen( $localMonthName );
02711                                 break;
02712                         case 'localmonthabbrev':
02713                                 $value = $pageLang->getMonthAbbreviation( $localMonthName );
02714                                 break;
02715                         case 'localday':
02716                                 $value = $pageLang->formatNum( $localDay );
02717                                 break;
02718                         case 'localday2':
02719                                 $value = $pageLang->formatNum( $localDay2 );
02720                                 break;
02721                         case 'pagename':
02722                                 $value = wfEscapeWikiText( $this->mTitle->getText() );
02723                                 break;
02724                         case 'pagenamee':
02725                                 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
02726                                 break;
02727                         case 'fullpagename':
02728                                 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
02729                                 break;
02730                         case 'fullpagenamee':
02731                                 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
02732                                 break;
02733                         case 'subpagename':
02734                                 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
02735                                 break;
02736                         case 'subpagenamee':
02737                                 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
02738                                 break;
02739                         case 'basepagename':
02740                                 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
02741                                 break;
02742                         case 'basepagenamee':
02743                                 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) );
02744                                 break;
02745                         case 'talkpagename':
02746                                 if ( $this->mTitle->canTalk() ) {
02747                                         $talkPage = $this->mTitle->getTalkPage();
02748                                         $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
02749                                 } else {
02750                                         $value = '';
02751                                 }
02752                                 break;
02753                         case 'talkpagenamee':
02754                                 if ( $this->mTitle->canTalk() ) {
02755                                         $talkPage = $this->mTitle->getTalkPage();
02756                                         $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
02757                                 } else {
02758                                         $value = '';
02759                                 }
02760                                 break;
02761                         case 'subjectpagename':
02762                                 $subjPage = $this->mTitle->getSubjectPage();
02763                                 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
02764                                 break;
02765                         case 'subjectpagenamee':
02766                                 $subjPage = $this->mTitle->getSubjectPage();
02767                                 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
02768                                 break;
02769                         case 'pageid': // requested in bug 23427
02770                                 $pageid = $this->getTitle()->getArticleId();
02771                                 if( $pageid == 0 ) {
02772                                         # 0 means the page doesn't exist in the database,
02773                                         # which means the user is previewing a new page.
02774                                         # The vary-revision flag must be set, because the magic word
02775                                         # will have a different value once the page is saved.
02776                                         $this->mOutput->setFlag( 'vary-revision' );
02777                                         wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
02778                                 }
02779                                 $value = $pageid ? $pageid : null;
02780                                 break;
02781                         case 'revisionid':
02782                                 # Let the edit saving system know we should parse the page
02783                                 # *after* a revision ID has been assigned.
02784                                 $this->mOutput->setFlag( 'vary-revision' );
02785                                 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
02786                                 $value = $this->mRevisionId;
02787                                 break;
02788                         case 'revisionday':
02789                                 # Let the edit saving system know we should parse the page
02790                                 # *after* a revision ID has been assigned. This is for null edits.
02791                                 $this->mOutput->setFlag( 'vary-revision' );
02792                                 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
02793                                 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
02794                                 break;
02795                         case 'revisionday2':
02796                                 # Let the edit saving system know we should parse the page
02797                                 # *after* a revision ID has been assigned. This is for null edits.
02798                                 $this->mOutput->setFlag( 'vary-revision' );
02799                                 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
02800                                 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
02801                                 break;
02802                         case 'revisionmonth':
02803                                 # Let the edit saving system know we should parse the page
02804                                 # *after* a revision ID has been assigned. This is for null edits.
02805                                 $this->mOutput->setFlag( 'vary-revision' );
02806                                 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
02807                                 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
02808                                 break;
02809                         case 'revisionmonth1':
02810                                 # Let the edit saving system know we should parse the page
02811                                 # *after* a revision ID has been assigned. This is for null edits.
02812                                 $this->mOutput->setFlag( 'vary-revision' );
02813                                 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
02814                                 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
02815                                 break;
02816                         case 'revisionyear':
02817                                 # Let the edit saving system know we should parse the page
02818                                 # *after* a revision ID has been assigned. This is for null edits.
02819                                 $this->mOutput->setFlag( 'vary-revision' );
02820                                 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
02821                                 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
02822                                 break;
02823                         case 'revisiontimestamp':
02824                                 # Let the edit saving system know we should parse the page
02825                                 # *after* a revision ID has been assigned. This is for null edits.
02826                                 $this->mOutput->setFlag( 'vary-revision' );
02827                                 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
02828                                 $value = $this->getRevisionTimestamp();
02829                                 break;
02830                         case 'revisionuser':
02831                                 # Let the edit saving system know we should parse the page
02832                                 # *after* a revision ID has been assigned. This is for null edits.
02833                                 $this->mOutput->setFlag( 'vary-revision' );
02834                                 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
02835                                 $value = $this->getRevisionUser();
02836                                 break;
02837                         case 'namespace':
02838                                 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
02839                                 break;
02840                         case 'namespacee':
02841                                 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
02842                                 break;
02843                         case 'namespacenumber':
02844                                 $value = $this->mTitle->getNamespace();
02845                                 break;
02846                         case 'talkspace':
02847                                 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : '';
02848                                 break;
02849                         case 'talkspacee':
02850                                 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
02851                                 break;
02852                         case 'subjectspace':
02853                                 $value = $this->mTitle->getSubjectNsText();
02854                                 break;
02855                         case 'subjectspacee':
02856                                 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
02857                                 break;
02858                         case 'currentdayname':
02859                                 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
02860                                 break;
02861                         case 'currentyear':
02862                                 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
02863                                 break;
02864                         case 'currenttime':
02865                                 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
02866                                 break;
02867                         case 'currenthour':
02868                                 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
02869                                 break;
02870                         case 'currentweek':
02871                                 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
02872                                 # int to remove the padding
02873                                 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
02874                                 break;
02875                         case 'currentdow':
02876                                 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
02877                                 break;
02878                         case 'localdayname':
02879                                 $value = $pageLang->getWeekdayName( $localDayOfWeek + 1 );
02880                                 break;
02881                         case 'localyear':
02882                                 $value = $pageLang->formatNum( $localYear, true );
02883                                 break;
02884                         case 'localtime':
02885                                 $value = $pageLang->time( $localTimestamp, false, false );
02886                                 break;
02887                         case 'localhour':
02888                                 $value = $pageLang->formatNum( $localHour, true );
02889                                 break;
02890                         case 'localweek':
02891                                 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
02892                                 # int to remove the padding
02893                                 $value = $pageLang->formatNum( (int)$localWeek );
02894                                 break;
02895                         case 'localdow':
02896                                 $value = $pageLang->formatNum( $localDayOfWeek );
02897                                 break;
02898                         case 'numberofarticles':
02899                                 $value = $pageLang->formatNum( SiteStats::articles() );
02900                                 break;
02901                         case 'numberoffiles':
02902                                 $value = $pageLang->formatNum( SiteStats::images() );
02903                                 break;
02904                         case 'numberofusers':
02905                                 $value = $pageLang->formatNum( SiteStats::users() );
02906                                 break;
02907                         case 'numberofactiveusers':
02908                                 $value = $pageLang->formatNum( SiteStats::activeUsers() );
02909                                 break;
02910                         case 'numberofpages':
02911                                 $value = $pageLang->formatNum( SiteStats::pages() );
02912                                 break;
02913                         case 'numberofadmins':
02914                                 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
02915                                 break;
02916                         case 'numberofedits':
02917                                 $value = $pageLang->formatNum( SiteStats::edits() );
02918                                 break;
02919                         case 'numberofviews':
02920                                 global $wgDisableCounters;
02921                                 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
02922                                 break;
02923                         case 'currenttimestamp':
02924                                 $value = wfTimestamp( TS_MW, $ts );
02925                                 break;
02926                         case 'localtimestamp':
02927                                 $value = $localTimestamp;
02928                                 break;
02929                         case 'currentversion':
02930                                 $value = SpecialVersion::getVersion();
02931                                 break;
02932                         case 'articlepath':
02933                                 return $wgArticlePath;
02934                         case 'sitename':
02935                                 return $wgSitename;
02936                         case 'server':
02937                                 return $wgServer;
02938                         case 'servername':
02939                                 $serverParts = wfParseUrl( $wgServer );
02940                                 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer;
02941                         case 'scriptpath':
02942                                 return $wgScriptPath;
02943                         case 'stylepath':
02944                                 return $wgStylePath;
02945                         case 'directionmark':
02946                                 return $pageLang->getDirMark();
02947                         case 'contentlanguage':
02948                                 global $wgLanguageCode;
02949                                 return $wgLanguageCode;
02950                         default:
02951                                 $ret = null;
02952                                 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
02953                                         return $ret;
02954                                 } else {
02955                                         return null;
02956                                 }
02957                 }
02958 
02959                 if ( $index ) {
02960                         $this->mVarCache[$index] = $value;
02961                 }
02962 
02963                 return $value;
02964         }
02965 
02971         function initialiseVariables() {
02972                 wfProfileIn( __METHOD__ );
02973                 $variableIDs = MagicWord::getVariableIDs();
02974                 $substIDs = MagicWord::getSubstIDs();
02975 
02976                 $this->mVariables = new MagicWordArray( $variableIDs );
02977                 $this->mSubstWords = new MagicWordArray( $substIDs );
02978                 wfProfileOut( __METHOD__ );
02979         }
02980 
03005         function preprocessToDom( $text, $flags = 0 ) {
03006                 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
03007                 return $dom;
03008         }
03009 
03017         public static function splitWhitespace( $s ) {
03018                 $ltrimmed = ltrim( $s );
03019                 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
03020                 $trimmed = rtrim( $ltrimmed );
03021                 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
03022                 if ( $diff > 0 ) {
03023                         $w2 = substr( $ltrimmed, -$diff );
03024                 } else {
03025                         $w2 = '';
03026                 }
03027                 return array( $w1, $trimmed, $w2 );
03028         }
03029 
03049         function replaceVariables( $text, $frame = false, $argsOnly = false ) {
03050                 # Is there any text? Also, Prevent too big inclusions!
03051                 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
03052                         return $text;
03053                 }
03054                 wfProfileIn( __METHOD__ );
03055 
03056                 if ( $frame === false ) {
03057                         $frame = $this->getPreprocessor()->newFrame();
03058                 } elseif ( !( $frame instanceof PPFrame ) ) {
03059                         wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
03060                         $frame = $this->getPreprocessor()->newCustomFrame( $frame );
03061                 }
03062 
03063                 $dom = $this->preprocessToDom( $text );
03064                 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
03065                 $text = $frame->expand( $dom, $flags );
03066 
03067                 wfProfileOut( __METHOD__ );
03068                 return $text;
03069         }
03070 
03078         static function createAssocArgs( $args ) {
03079                 $assocArgs = array();
03080                 $index = 1;
03081                 foreach ( $args as $arg ) {
03082                         $eqpos = strpos( $arg, '=' );
03083                         if ( $eqpos === false ) {
03084                                 $assocArgs[$index++] = $arg;
03085                         } else {
03086                                 $name = trim( substr( $arg, 0, $eqpos ) );
03087                                 $value = trim( substr( $arg, $eqpos+1 ) );
03088                                 if ( $value === false ) {
03089                                         $value = '';
03090                                 }
03091                                 if ( $name !== false ) {
03092                                         $assocArgs[$name] = $value;
03093                                 }
03094                         }
03095                 }
03096 
03097                 return $assocArgs;
03098         }
03099 
03118         function limitationWarn( $limitationType, $current = '', $max = '' ) {
03119                 # does no harm if $current and $max are present but are unnecessary for the message
03120                 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
03121                         ->inContentLanguage()->escaped();
03122                 $this->mOutput->addWarning( $warning );
03123                 $this->addTrackingCategory( "$limitationType-category" );
03124         }
03125 
03139         function braceSubstitution( $piece, $frame ) {
03140                 global $wgContLang;
03141                 wfProfileIn( __METHOD__ );
03142                 wfProfileIn( __METHOD__.'-setup' );
03143 
03144                 # Flags
03145                 $found = false;             # $text has been filled
03146                 $nowiki = false;            # wiki markup in $text should be escaped
03147                 $isHTML = false;            # $text is HTML, armour it against wikitext transformation
03148                 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
03149                 $isChildObj = false;        # $text is a DOM node needing expansion in a child frame
03150                 $isLocalObj = false;        # $text is a DOM node needing expansion in the current frame
03151 
03152                 # Title object, where $text came from
03153                 $title = false;
03154 
03155                 # $part1 is the bit before the first |, and must contain only title characters.
03156                 # Various prefixes will be stripped from it later.
03157                 $titleWithSpaces = $frame->expand( $piece['title'] );
03158                 $part1 = trim( $titleWithSpaces );
03159                 $titleText = false;
03160 
03161                 # Original title text preserved for various purposes
03162                 $originalTitle = $part1;
03163 
03164                 # $args is a list of argument nodes, starting from index 0, not including $part1
03165                 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
03166                 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
03167                 wfProfileOut( __METHOD__.'-setup' );
03168 
03169                 $titleProfileIn = null; // profile templates
03170 
03171                 # SUBST
03172                 wfProfileIn( __METHOD__.'-modifiers' );
03173                 if ( !$found ) {
03174 
03175                         $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
03176 
03177                         # Possibilities for substMatch: "subst", "safesubst" or FALSE
03178                         # Decide whether to expand template or keep wikitext as-is.
03179                         if ( $this->ot['wiki'] ) {
03180                                 if ( $substMatch === false ) {
03181                                         $literal = true;  # literal when in PST with no prefix
03182                                 } else {
03183                                         $literal = false; # expand when in PST with subst: or safesubst:
03184                                 }
03185                         } else {
03186                                 if ( $substMatch == 'subst' ) {
03187                                         $literal = true;  # literal when not in PST with plain subst:
03188                                 } else {
03189                                         $literal = false; # expand when not in PST with safesubst: or no prefix
03190                                 }
03191                         }
03192                         if ( $literal ) {
03193                                 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
03194                                 $isLocalObj = true;
03195                                 $found = true;
03196                         }
03197                 }
03198 
03199                 # Variables
03200                 if ( !$found && $args->getLength() == 0 ) {
03201                         $id = $this->mVariables->matchStartToEnd( $part1 );
03202                         if ( $id !== false ) {
03203                                 $text = $this->getVariableValue( $id, $frame );
03204                                 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
03205                                         $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
03206                                 }
03207                                 $found = true;
03208                         }
03209                 }
03210 
03211                 # MSG, MSGNW and RAW
03212                 if ( !$found ) {
03213                         # Check for MSGNW:
03214                         $mwMsgnw = MagicWord::get( 'msgnw' );
03215                         if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
03216                                 $nowiki = true;
03217                         } else {
03218                                 # Remove obsolete MSG:
03219                                 $mwMsg = MagicWord::get( 'msg' );
03220                                 $mwMsg->matchStartAndRemove( $part1 );
03221                         }
03222 
03223                         # Check for RAW:
03224                         $mwRaw = MagicWord::get( 'raw' );
03225                         if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
03226                                 $forceRawInterwiki = true;
03227                         }
03228                 }
03229                 wfProfileOut( __METHOD__.'-modifiers' );
03230 
03231                 # Parser functions
03232                 if ( !$found ) {
03233                         wfProfileIn( __METHOD__ . '-pfunc' );
03234 
03235                         $colonPos = strpos( $part1, ':' );
03236                         if ( $colonPos !== false ) {
03237                                 # Case sensitive functions
03238                                 $function = substr( $part1, 0, $colonPos );
03239                                 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
03240                                         $function = $this->mFunctionSynonyms[1][$function];
03241                                 } else {
03242                                         # Case insensitive functions
03243                                         $function = $wgContLang->lc( $function );
03244                                         if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
03245                                                 $function = $this->mFunctionSynonyms[0][$function];
03246                                         } else {
03247                                                 $function = false;
03248                                         }
03249                                 }
03250                                 if ( $function ) {
03251                                         wfProfileIn( __METHOD__ . '-pfunc-' . $function );
03252                                         list( $callback, $flags ) = $this->mFunctionHooks[$function];
03253                                         $initialArgs = array( &$this );
03254                                         $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
03255                                         if ( $flags & SFH_OBJECT_ARGS ) {
03256                                                 # Add a frame parameter, and pass the arguments as an array
03257                                                 $allArgs = $initialArgs;
03258                                                 $allArgs[] = $frame;
03259                                                 for ( $i = 0; $i < $args->getLength(); $i++ ) {
03260                                                         $funcArgs[] = $args->item( $i );
03261                                                 }
03262                                                 $allArgs[] = $funcArgs;
03263                                         } else {
03264                                                 # Convert arguments to plain text
03265                                                 for ( $i = 0; $i < $args->getLength(); $i++ ) {
03266                                                         $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
03267                                                 }
03268                                                 $allArgs = array_merge( $initialArgs, $funcArgs );
03269                                         }
03270 
03271                                         # Workaround for PHP bug 35229 and similar
03272                                         if ( !is_callable( $callback ) ) {
03273                                                 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
03274                                                 wfProfileOut( __METHOD__ . '-pfunc' );
03275                                                 wfProfileOut( __METHOD__ );
03276                                                 throw new MWException( "Tag hook for $function is not callable\n" );
03277                                         }
03278                                         $result = call_user_func_array( $callback, $allArgs );
03279                                         $found = true;
03280                                         $noparse = true;
03281                                         $preprocessFlags = 0;
03282 
03283                                         if ( is_array( $result ) ) {
03284                                                 if ( isset( $result[0] ) ) {
03285                                                         $text = $result[0];
03286                                                         unset( $result[0] );
03287                                                 }
03288 
03289                                                 # Extract flags into the local scope
03290                                                 # This allows callers to set flags such as nowiki, found, etc.
03291                                                 extract( $result );
03292                                         } else {
03293                                                 $text = $result;
03294                                         }
03295                                         if ( !$noparse ) {
03296                                                 $text = $this->preprocessToDom( $text, $preprocessFlags );
03297                                                 $isChildObj = true;
03298                                         }
03299                                         wfProfileOut( __METHOD__ . '-pfunc-' . $function );
03300                                 }
03301                         }
03302                         wfProfileOut( __METHOD__ . '-pfunc' );
03303                 }
03304 
03305                 # Finish mangling title and then check for loops.
03306                 # Set $title to a Title object and $titleText to the PDBK
03307                 if ( !$found ) {
03308                         $ns = NS_TEMPLATE;
03309                         # Split the title into page and subpage
03310                         $subpage = '';
03311                         $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
03312                         if ( $subpage !== '' ) {
03313                                 $ns = $this->mTitle->getNamespace();
03314                         }
03315                         $title = Title::newFromText( $part1, $ns );
03316                         if ( $title ) {
03317                                 $titleText = $title->getPrefixedText();
03318                                 # Check for language variants if the template is not found
03319                                 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
03320                                         $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
03321                                 }
03322                                 # Do recursion depth check
03323                                 $limit = $this->mOptions->getMaxTemplateDepth();
03324                                 if ( $frame->depth >= $limit ) {
03325                                         $found = true;
03326                                         $text = '<span class="error">'
03327                                                 . wfMessage( 'parser-template-recursion-depth-warning' )
03328                                                         ->numParams( $limit )->inContentLanguage()->text()
03329                                                 . '</span>';
03330                                 }
03331                         }
03332                 }
03333 
03334                 # Load from database
03335                 if ( !$found && $title ) {
03336                         if ( !Profiler::instance()->isPersistent() ) {
03337                                 # Too many unique items can kill profiling DBs/collectors
03338                                 $titleProfileIn = __METHOD__ . "-title-" . $title->getDBKey();
03339                                 wfProfileIn( $titleProfileIn ); // template in
03340                         }
03341                         wfProfileIn( __METHOD__ . '-loadtpl' );
03342                         if ( !$title->isExternal() ) {
03343                                 if ( $title->isSpecialPage()
03344                                         && $this->mOptions->getAllowSpecialInclusion()
03345                                         && $this->ot['html'] )
03346                                 {
03347                                         // Pass the template arguments as URL parameters.
03348                                         // "uselang" will have no effect since the Language object
03349                                         // is forced to the one defined in ParserOptions.
03350                                         $pageArgs = array();
03351                                         for ( $i = 0; $i < $args->getLength(); $i++ ) {
03352                                                 $bits = $args->item( $i )->splitArg();
03353                                                 if ( strval( $bits['index'] ) === '' ) {
03354                                                         $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
03355                                                         $value = trim( $frame->expand( $bits['value'] ) );
03356                                                         $pageArgs[$name] = $value;
03357                                                 }
03358                                         }
03359 
03360                                         // Create a new context to execute the special page
03361                                         $context = new RequestContext;
03362                                         $context->setTitle( $title );
03363                                         $context->setRequest( new FauxRequest( $pageArgs ) );
03364                                         $context->setUser( $this->getUser() );
03365                                         $context->setLanguage( $this->mOptions->getUserLangObj() );
03366                                         $ret = SpecialPageFactory::capturePath( $title, $context );
03367                                         if ( $ret ) {
03368                                                 $text = $context->getOutput()->getHTML();
03369                                                 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
03370                                                 $found = true;
03371                                                 $isHTML = true;
03372                                                 $this->disableCache();
03373                                         }
03374                                 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
03375                                         $found = false; # access denied
03376                                         wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
03377                                 } else {
03378                                         list( $text, $title ) = $this->getTemplateDom( $title );
03379                                         if ( $text !== false ) {
03380                                                 $found = true;
03381                                                 $isChildObj = true;
03382                                         }
03383                                 }
03384 
03385                                 # If the title is valid but undisplayable, make a link to it
03386                                 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
03387                                         $text = "[[:$titleText]]";
03388                                         $found = true;
03389                                 }
03390                         } elseif ( $title->isTrans() ) {
03391                                 # Interwiki transclusion
03392                                 if ( $this->ot['html'] && !$forceRawInterwiki ) {
03393                                         $text = $this->interwikiTransclude( $title, 'render' );
03394                                         $isHTML = true;
03395                                 } else {
03396                                         $text = $this->interwikiTransclude( $title, 'raw' );
03397                                         # Preprocess it like a template
03398                                         $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
03399                                         $isChildObj = true;
03400                                 }
03401                                 $found = true;
03402                         }
03403 
03404                         # Do infinite loop check
03405                         # This has to be done after redirect resolution to avoid infinite loops via redirects
03406                         if ( !$frame->loopCheck( $title ) ) {
03407                                 $found = true;
03408                                 $text = '<span class="error">'
03409                                         . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
03410                                         . '</span>';
03411                                 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
03412                         }
03413                         wfProfileOut( __METHOD__ . '-loadtpl' );
03414                 }
03415 
03416                 # If we haven't found text to substitute by now, we're done
03417                 # Recover the source wikitext and return it
03418                 if ( !$found ) {
03419                         $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
03420                         if ( $titleProfileIn ) {
03421                                 wfProfileOut( $titleProfileIn ); // template out
03422                         }
03423                         wfProfileOut( __METHOD__ );
03424                         return array( 'object' => $text );
03425                 }
03426 
03427                 # Expand DOM-style return values in a child frame
03428                 if ( $isChildObj ) {
03429                         # Clean up argument array
03430                         $newFrame = $frame->newChild( $args, $title );
03431 
03432                         if ( $nowiki ) {
03433                                 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
03434                         } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
03435                                 # Expansion is eligible for the empty-frame cache
03436                                 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
03437                                         $text = $this->mTplExpandCache[$titleText];
03438                                 } else {
03439                                         $text = $newFrame->expand( $text );
03440                                         $this->mTplExpandCache[$titleText] = $text;
03441                                 }
03442                         } else {
03443                                 # Uncached expansion
03444                                 $text = $newFrame->expand( $text );
03445                         }
03446                 }
03447                 if ( $isLocalObj && $nowiki ) {
03448                         $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
03449                         $isLocalObj = false;
03450                 }
03451 
03452                 if ( $titleProfileIn ) {
03453                         wfProfileOut( $titleProfileIn ); // template out
03454                 }
03455 
03456                 # Replace raw HTML by a placeholder
03457                 if ( $isHTML ) {
03458                         $text = $this->insertStripItem( $text );
03459                 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
03460                         # Escape nowiki-style return values
03461                         $text = wfEscapeWikiText( $text );
03462                 } elseif ( is_string( $text )
03463                         && !$piece['lineStart']
03464                         && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
03465                 {
03466                         # Bug 529: if the template begins with a table or block-level
03467                         # element, it should be treated as beginning a new line.
03468                         # This behaviour is somewhat controversial.
03469                         $text = "\n" . $text;
03470                 }
03471 
03472                 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
03473                         # Error, oversize inclusion
03474                         if ( $titleText !== false ) {
03475                                 # Make a working, properly escaped link if possible (bug 23588)
03476                                 $text = "[[:$titleText]]";
03477                         } else {
03478                                 # This will probably not be a working link, but at least it may
03479                                 # provide some hint of where the problem is
03480                                 preg_replace( '/^:/', '', $originalTitle );
03481                                 $text = "[[:$originalTitle]]";
03482                         }
03483                         $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
03484                         $this->limitationWarn( 'post-expand-template-inclusion' );
03485                 }
03486 
03487                 if ( $isLocalObj ) {
03488                         $ret = array( 'object' => $text );
03489                 } else {
03490                         $ret = array( 'text' => $text );
03491                 }
03492 
03493                 wfProfileOut( __METHOD__ );
03494                 return $ret;
03495         }
03496 
03505         function getTemplateDom( $title ) {
03506                 $cacheTitle = $title;
03507                 $titleText = $title->getPrefixedDBkey();
03508 
03509                 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
03510                         list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
03511                         $title = Title::makeTitle( $ns, $dbk );
03512                         $titleText = $title->getPrefixedDBkey();
03513                 }
03514                 if ( isset( $this->mTplDomCache[$titleText] ) ) {
03515                         return array( $this->mTplDomCache[$titleText], $title );
03516                 }
03517 
03518                 # Cache miss, go to the database
03519                 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
03520 
03521                 if ( $text === false ) {
03522                         $this->mTplDomCache[$titleText] = false;
03523                         return array( false, $title );
03524                 }
03525 
03526                 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
03527                 $this->mTplDomCache[ $titleText ] = $dom;
03528 
03529                 if ( !$title->equals( $cacheTitle ) ) {
03530                         $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
03531                                 array( $title->getNamespace(), $cdb = $title->getDBkey() );
03532                 }
03533 
03534                 return array( $dom, $title );
03535         }
03536 
03542         function fetchTemplateAndTitle( $title ) {
03543                 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
03544                 $stuff = call_user_func( $templateCb, $title, $this );
03545                 $text = $stuff['text'];
03546                 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
03547                 if ( isset( $stuff['deps'] ) ) {
03548                         foreach ( $stuff['deps'] as $dep ) {
03549                                 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
03550                         }
03551                 }
03552                 return array( $text, $finalTitle );
03553         }
03554 
03560         function fetchTemplate( $title ) {
03561                 $rv = $this->fetchTemplateAndTitle( $title );
03562                 return $rv[0];
03563         }
03564 
03574         static function statelessFetchTemplate( $title, $parser = false ) {
03575                 $text = $skip = false;
03576                 $finalTitle = $title;
03577                 $deps = array();
03578 
03579                 # Loop to fetch the article, with up to 1 redirect
03580                 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
03581                         # Give extensions a chance to select the revision instead
03582                         $id = false; # Assume current
03583                         wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
03584                                 array( $parser, $title, &$skip, &$id ) );
03585 
03586                         if ( $skip ) {
03587                                 $text = false;
03588                                 $deps[] = array(
03589                                         'title'         => $title,
03590                                         'page_id'       => $title->getArticleID(),
03591                                         'rev_id'        => null
03592                                 );
03593                                 break;
03594                         }
03595                         # Get the revision
03596                         $rev = $id
03597                                 ? Revision::newFromId( $id )
03598                                 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
03599                         $rev_id = $rev ? $rev->getId() : 0;
03600                         # If there is no current revision, there is no page
03601                         if ( $id === false && !$rev ) {
03602                                 $linkCache = LinkCache::singleton();
03603                                 $linkCache->addBadLinkObj( $title );
03604                         }
03605 
03606                         $deps[] = array(
03607                                 'title'         => $title,
03608                                 'page_id'       => $title->getArticleID(),
03609                                 'rev_id'        => $rev_id );
03610                         if ( $rev && !$title->equals( $rev->getTitle() ) ) {
03611                                 # We fetched a rev from a different title; register it too...
03612                                 $deps[] = array(
03613                                         'title'         => $rev->getTitle(),
03614                                         'page_id'       => $rev->getPage(),
03615                                         'rev_id'        => $rev_id );
03616                         }
03617 
03618                         if ( $rev ) {
03619                                 $content = $rev->getContent();
03620                                 $text = $content ? $content->getWikitextForTransclusion() : null;
03621 
03622                                 if ( $text === false || $text === null ) {
03623                                         $text = false;
03624                                         break;
03625                                 }
03626                         } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
03627                                 global $wgContLang;
03628                                 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
03629                                 if ( !$message->exists() ) {
03630                                         $text = false;
03631                                         break;
03632                                 }
03633                                 $content = $message->content();
03634                                 $text = $message->plain();
03635                         } else {
03636                                 break;
03637                         }
03638                         if ( !$content ) {
03639                                 break;
03640                         }
03641                         # Redirect?
03642                         $finalTitle = $title;
03643                         $title = $content->getRedirectTarget();
03644                 }
03645                 return array(
03646                         'text' => $text,
03647                         'finalTitle' => $finalTitle,
03648                         'deps' => $deps );
03649         }
03650 
03658         function fetchFile( $title, $options = array() ) {
03659                 $res = $this->fetchFileAndTitle( $title, $options );
03660                 return $res[0];
03661         }
03662 
03670         function fetchFileAndTitle( $title, $options = array() ) {
03671                 if ( isset( $options['broken'] ) ) {
03672                         $file = false; // broken thumbnail forced by hook
03673                 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
03674                         $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
03675                 } else { // get by (name,timestamp)
03676                         $file = wfFindFile( $title, $options );
03677                 }
03678                 $time = $file ? $file->getTimestamp() : false;
03679                 $sha1 = $file ? $file->getSha1() : false;
03680                 # Register the file as a dependency...
03681                 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
03682                 if ( $file && !$title->equals( $file->getTitle() ) ) {
03683                         # Update fetched file title
03684                         $title = $file->getTitle();
03685                         if ( is_null( $file->getRedirectedTitle() ) ) {
03686                                 # This file was not a redirect, but the title does not match.
03687                                 # Register under the new name because otherwise the link will
03688                                 # get lost.
03689                                 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
03690                         }
03691                 }
03692                 return array( $file, $title );
03693         }
03694 
03703         function interwikiTransclude( $title, $action ) {
03704                 global $wgEnableScaryTranscluding;
03705 
03706                 if ( !$wgEnableScaryTranscluding ) {
03707                         return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
03708                 }
03709 
03710                 $url = $title->getFullUrl( "action=$action" );
03711 
03712                 if ( strlen( $url ) > 255 ) {
03713                         return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
03714                 }
03715                 return $this->fetchScaryTemplateMaybeFromCache( $url );
03716         }
03717 
03722         function fetchScaryTemplateMaybeFromCache( $url ) {
03723                 global $wgTranscludeCacheExpiry;
03724                 $dbr = wfGetDB( DB_SLAVE );
03725                 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
03726                 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
03727                                 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
03728                 if ( $obj ) {
03729                         return $obj->tc_contents;
03730                 }
03731 
03732                 $req = MWHttpRequest::factory( $url );
03733                 $status = $req->execute(); // Status object
03734                 if ( $status->isOK() ) {
03735                         $text = $req->getContent();
03736                 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
03737                         return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
03738                 } else {
03739                         return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
03740                 }
03741 
03742                 $dbw = wfGetDB( DB_MASTER );
03743                 $dbw->replace( 'transcache', array('tc_url'), array(
03744                         'tc_url' => $url,
03745                         'tc_time' => $dbw->timestamp( time() ),
03746                         'tc_contents' => $text)
03747                 );
03748                 return $text;
03749         }
03750 
03760         function argSubstitution( $piece, $frame ) {
03761                 wfProfileIn( __METHOD__ );
03762 
03763                 $error = false;
03764                 $parts = $piece['parts'];
03765                 $nameWithSpaces = $frame->expand( $piece['title'] );
03766                 $argName = trim( $nameWithSpaces );
03767                 $object = false;
03768                 $text = $frame->getArgument( $argName );
03769                 if (  $text === false && $parts->getLength() > 0
03770                   && (
03771                         $this->ot['html']
03772                         || $this->ot['pre']
03773                         || ( $this->ot['wiki'] && $frame->isTemplate() )
03774                   )
03775                 ) {
03776                         # No match in frame, use the supplied default
03777                         $object = $parts->item( 0 )->getChildren();
03778                 }
03779                 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
03780                         $error = '<!-- WARNING: argument omitted, expansion size too large -->';
03781                         $this->limitationWarn( 'post-expand-template-argument' );
03782                 }
03783 
03784                 if ( $text === false && $object === false ) {
03785                         # No match anywhere
03786                         $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
03787                 }
03788                 if ( $error !== false ) {
03789                         $text .= $error;
03790                 }
03791                 if ( $object !== false ) {
03792                         $ret = array( 'object' => $object );
03793                 } else {
03794                         $ret = array( 'text' => $text );
03795                 }
03796 
03797                 wfProfileOut( __METHOD__ );
03798                 return $ret;
03799         }
03800 
03816         function extensionSubstitution( $params, $frame ) {
03817                 $name = $frame->expand( $params['name'] );
03818                 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
03819                 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
03820                 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
03821 
03822                 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
03823                         ( $this->ot['html'] || $this->ot['pre'] );
03824                 if ( $isFunctionTag ) {
03825                         $markerType = 'none';
03826                 } else {
03827                         $markerType = 'general';
03828                 }
03829                 if ( $this->ot['html'] || $isFunctionTag ) {
03830                         $name = strtolower( $name );
03831                         $attributes = Sanitizer::decodeTagAttributes( $attrText );
03832                         if ( isset( $params['attributes'] ) ) {
03833                                 $attributes = $attributes + $params['attributes'];
03834                         }
03835 
03836                         if ( isset( $this->mTagHooks[$name] ) ) {
03837                                 # Workaround for PHP bug 35229 and similar
03838                                 if ( !is_callable( $this->mTagHooks[$name] ) ) {
03839                                         throw new MWException( "Tag hook for $name is not callable\n" );
03840                                 }
03841                                 $output = call_user_func_array( $this->mTagHooks[$name],
03842                                         array( $content, $attributes, $this, $frame ) );
03843                         } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
03844                                 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
03845                                 if ( !is_callable( $callback ) ) {
03846                                         throw new MWException( "Tag hook for $name is not callable\n" );
03847                                 }
03848 
03849                                 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
03850                         } else {
03851                                 $output = '<span class="error">Invalid tag extension name: ' .
03852                                         htmlspecialchars( $name ) . '</span>';
03853                         }
03854 
03855                         if ( is_array( $output ) ) {
03856                                 # Extract flags to local scope (to override $markerType)
03857                                 $flags = $output;
03858                                 $output = $flags[0];
03859                                 unset( $flags[0] );
03860                                 extract( $flags );
03861                         }
03862                 } else {
03863                         if ( is_null( $attrText ) ) {
03864                                 $attrText = '';
03865                         }
03866                         if ( isset( $params['attributes'] ) ) {
03867                                 foreach ( $params['attributes'] as $attrName => $attrValue ) {
03868                                         $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
03869                                                 htmlspecialchars( $attrValue ) . '"';
03870                                 }
03871                         }
03872                         if ( $content === null ) {
03873                                 $output = "<$name$attrText/>";
03874                         } else {
03875                                 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
03876                                 $output = "<$name$attrText>$content$close";
03877                         }
03878                 }
03879 
03880                 if ( $markerType === 'none' ) {
03881                         return $output;
03882                 } elseif ( $markerType === 'nowiki' ) {
03883                         $this->mStripState->addNoWiki( $marker, $output );
03884                 } elseif ( $markerType === 'general' ) {
03885                         $this->mStripState->addGeneral( $marker, $output );
03886                 } else {
03887                         throw new MWException( __METHOD__.': invalid marker type' );
03888                 }
03889                 return $marker;
03890         }
03891 
03899         function incrementIncludeSize( $type, $size ) {
03900                 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
03901                         return false;
03902                 } else {
03903                         $this->mIncludeSizes[$type] += $size;
03904                         return true;
03905                 }
03906         }
03907 
03913         function incrementExpensiveFunctionCount() {
03914                 $this->mExpensiveFunctionCount++;
03915                 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
03916         }
03917 
03926         function doDoubleUnderscore( $text ) {
03927                 wfProfileIn( __METHOD__ );
03928 
03929                 # The position of __TOC__ needs to be recorded
03930                 $mw = MagicWord::get( 'toc' );
03931                 if ( $mw->match( $text ) ) {
03932                         $this->mShowToc = true;
03933                         $this->mForceTocPosition = true;
03934 
03935                         # Set a placeholder. At the end we'll fill it in with the TOC.
03936                         $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
03937 
03938                         # Only keep the first one.
03939                         $text = $mw->replace( '', $text );
03940                 }
03941 
03942                 # Now match and remove the rest of them
03943                 $mwa = MagicWord::getDoubleUnderscoreArray();
03944                 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
03945 
03946                 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
03947                         $this->mOutput->mNoGallery = true;
03948                 }
03949                 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
03950                         $this->mShowToc = false;
03951                 }
03952                 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
03953                         $this->addTrackingCategory( 'hidden-category-category' );
03954                 }
03955                 # (bug 8068) Allow control over whether robots index a page.
03956                 #
03957                 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here!  This
03958                 # is not desirable, the last one on the page should win.
03959                 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
03960                         $this->mOutput->setIndexPolicy( 'noindex' );
03961                         $this->addTrackingCategory( 'noindex-category' );
03962                 }
03963                 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
03964                         $this->mOutput->setIndexPolicy( 'index' );
03965                         $this->addTrackingCategory( 'index-category' );
03966                 }
03967 
03968                 # Cache all double underscores in the database
03969                 foreach ( $this->mDoubleUnderscores as $key => $val ) {
03970                         $this->mOutput->setProperty( $key, '' );
03971                 }
03972 
03973                 wfProfileOut( __METHOD__ );
03974                 return $text;
03975         }
03976 
03984         public function addTrackingCategory( $msg ) {
03985                 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
03986                         wfDebug( __METHOD__.": Not adding tracking category $msg to special page!\n" );
03987                         return false;
03988                 }
03989                 // Important to parse with correct title (bug 31469)
03990                 $cat = wfMessage( $msg )
03991                         ->title( $this->getTitle() )
03992                         ->inContentLanguage()
03993                         ->text();
03994 
03995                 # Allow tracking categories to be disabled by setting them to "-"
03996                 if ( $cat === '-' ) {
03997                         return false;
03998                 }
03999 
04000                 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
04001                 if ( $containerCategory ) {
04002                         $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
04003                         return true;
04004                 } else {
04005                         wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
04006                         return false;
04007                 }
04008         }
04009 
04026         function formatHeadings( $text, $origText, $isMain=true ) {
04027                 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
04028 
04029                 # Inhibit editsection links if requested in the page
04030                 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
04031                         $maybeShowEditLink = $showEditLink = false;
04032                 } else {
04033                         $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
04034                         $showEditLink = $this->mOptions->getEditSection();
04035                 }
04036                 if ( $showEditLink ) {
04037                         $this->mOutput->setEditSectionTokens( true );
04038                 }
04039 
04040                 # Get all headlines for numbering them and adding funky stuff like [edit]
04041                 # links - this is for later, but we need the number of headlines right now
04042                 $matches = array();
04043                 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
04044 
04045                 # if there are fewer than 4 headlines in the article, do not show TOC
04046                 # unless it's been explicitly enabled.
04047                 $enoughToc = $this->mShowToc &&
04048                         ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
04049 
04050                 # Allow user to stipulate that a page should have a "new section"
04051                 # link added via __NEWSECTIONLINK__
04052                 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
04053                         $this->mOutput->setNewSection( true );
04054                 }
04055 
04056                 # Allow user to remove the "new section"
04057                 # link via __NONEWSECTIONLINK__
04058                 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
04059                         $this->mOutput->hideNewSection( true );
04060                 }
04061 
04062                 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
04063                 # override above conditions and always show TOC above first header
04064                 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
04065                         $this->mShowToc = true;
04066                         $enoughToc = true;
04067                 }
04068 
04069                 # headline counter
04070                 $headlineCount = 0;
04071                 $numVisible = 0;
04072 
04073                 # Ugh .. the TOC should have neat indentation levels which can be
04074                 # passed to the skin functions. These are determined here
04075                 $toc = '';
04076                 $full = '';
04077                 $head = array();
04078                 $sublevelCount = array();
04079                 $levelCount = array();
04080                 $level = 0;
04081                 $prevlevel = 0;
04082                 $toclevel = 0;
04083                 $prevtoclevel = 0;
04084                 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
04085                 $baseTitleText = $this->mTitle->getPrefixedDBkey();
04086                 $oldType = $this->mOutputType;
04087                 $this->setOutputType( self::OT_WIKI );
04088                 $frame = $this->getPreprocessor()->newFrame();
04089                 $root = $this->preprocessToDom( $origText );
04090                 $node = $root->getFirstChild();
04091                 $byteOffset = 0;
04092                 $tocraw = array();
04093                 $refers = array();
04094 
04095                 foreach ( $matches[3] as $headline ) {
04096                         $isTemplate = false;
04097                         $titleText = false;
04098                         $sectionIndex = false;
04099                         $numbering = '';
04100                         $markerMatches = array();
04101                         if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
04102                                 $serial = $markerMatches[1];
04103                                 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
04104                                 $isTemplate = ( $titleText != $baseTitleText );
04105                                 $headline = preg_replace( "/^$markerRegex/", "", $headline );
04106                         }
04107 
04108                         if ( $toclevel ) {
04109                                 $prevlevel = $level;
04110                         }
04111                         $level = $matches[1][$headlineCount];
04112 
04113                         if ( $level > $prevlevel ) {
04114                                 # Increase TOC level
04115                                 $toclevel++;
04116                                 $sublevelCount[$toclevel] = 0;
04117                                 if ( $toclevel<$wgMaxTocLevel ) {
04118                                         $prevtoclevel = $toclevel;
04119                                         $toc .= Linker::tocIndent();
04120                                         $numVisible++;
04121                                 }
04122                         } elseif ( $level < $prevlevel && $toclevel > 1 ) {
04123                                 # Decrease TOC level, find level to jump to
04124 
04125                                 for ( $i = $toclevel; $i > 0; $i-- ) {
04126                                         if ( $levelCount[$i] == $level ) {
04127                                                 # Found last matching level
04128                                                 $toclevel = $i;
04129                                                 break;
04130                                         } elseif ( $levelCount[$i] < $level ) {
04131                                                 # Found first matching level below current level
04132                                                 $toclevel = $i + 1;
04133                                                 break;
04134                                         }
04135                                 }
04136                                 if ( $i == 0 ) {
04137                                         $toclevel = 1;
04138                                 }
04139                                 if ( $toclevel<$wgMaxTocLevel ) {
04140                                         if ( $prevtoclevel < $wgMaxTocLevel ) {
04141                                                 # Unindent only if the previous toc level was shown :p
04142                                                 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
04143                                                 $prevtoclevel = $toclevel;
04144                                         } else {
04145                                                 $toc .= Linker::tocLineEnd();
04146                                         }
04147                                 }
04148                         } else {
04149                                 # No change in level, end TOC line
04150                                 if ( $toclevel<$wgMaxTocLevel ) {
04151                                         $toc .= Linker::tocLineEnd();
04152                                 }
04153                         }
04154 
04155                         $levelCount[$toclevel] = $level;
04156 
04157                         # count number of headlines for each level
04158                         @$sublevelCount[$toclevel]++;
04159                         $dot = 0;
04160                         for( $i = 1; $i <= $toclevel; $i++ ) {
04161                                 if ( !empty( $sublevelCount[$i] ) ) {
04162                                         if ( $dot ) {
04163                                                 $numbering .= '.';
04164                                         }
04165                                         $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
04166                                         $dot = 1;
04167                                 }
04168                         }
04169 
04170                         # The safe header is a version of the header text safe to use for links
04171 
04172                         # Remove link placeholders by the link text.
04173                         #     <!--LINK number-->
04174                         # turns into
04175                         #     link text with suffix
04176                         # Do this before unstrip since link text can contain strip markers
04177                         $safeHeadline = $this->replaceLinkHoldersText( $headline );
04178 
04179                         # Avoid insertion of weird stuff like <math> by expanding the relevant sections
04180                         $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
04181 
04182                         # Strip out HTML (first regex removes any tag not allowed)
04183                         # Allowed tags are:
04184                         # * <sup> and <sub> (bug 8393)
04185                         # * <i> (bug 26375)
04186                         # * <b> (r105284)
04187                         # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
04188                         #
04189                         # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
04190                         # to allow setting directionality in toc items.
04191                         $tocline = preg_replace(
04192                                 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
04193                                 array( '',                          '<$1>' ),
04194                                 $safeHeadline
04195                         );
04196                         $tocline = trim( $tocline );
04197 
04198                         # For the anchor, strip out HTML-y stuff period
04199                         $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
04200                         $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
04201 
04202                         # Save headline for section edit hint before it's escaped
04203                         $headlineHint = $safeHeadline;
04204 
04205                         if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
04206                                 # For reverse compatibility, provide an id that's
04207                                 # HTML4-compatible, like we used to.
04208                                 #
04209                                 # It may be worth noting, academically, that it's possible for
04210                                 # the legacy anchor to conflict with a non-legacy headline
04211                                 # anchor on the page.  In this case likely the "correct" thing
04212                                 # would be to either drop the legacy anchors or make sure
04213                                 # they're numbered first.  However, this would require people
04214                                 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
04215                                 # manually, so let's not bother worrying about it.
04216                                 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
04217                                         array( 'noninitial', 'legacy' ) );
04218                                 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
04219 
04220                                 if ( $legacyHeadline == $safeHeadline ) {
04221                                         # No reason to have both (in fact, we can't)
04222                                         $legacyHeadline = false;
04223                                 }
04224                         } else {
04225                                 $legacyHeadline = false;
04226                                 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
04227                                         'noninitial' );
04228                         }
04229 
04230                         # HTML names must be case-insensitively unique (bug 10721).
04231                         # This does not apply to Unicode characters per
04232                         # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
04233                         # @todo FIXME: We may be changing them depending on the current locale.
04234                         $arrayKey = strtolower( $safeHeadline );
04235                         if ( $legacyHeadline === false ) {
04236                                 $legacyArrayKey = false;
04237                         } else {
04238                                 $legacyArrayKey = strtolower( $legacyHeadline );
04239                         }
04240 
04241                         # count how many in assoc. array so we can track dupes in anchors
04242                         if ( isset( $refers[$arrayKey] ) ) {
04243                                 $refers[$arrayKey]++;
04244                         } else {
04245                                 $refers[$arrayKey] = 1;
04246                         }
04247                         if ( isset( $refers[$legacyArrayKey] ) ) {
04248                                 $refers[$legacyArrayKey]++;
04249                         } else {
04250                                 $refers[$legacyArrayKey] = 1;
04251                         }
04252 
04253                         # Don't number the heading if it is the only one (looks silly)
04254                         if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
04255                                 # the two are different if the line contains a link
04256                                 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
04257                         }
04258 
04259                         # Create the anchor for linking from the TOC to the section
04260                         $anchor = $safeHeadline;
04261                         $legacyAnchor = $legacyHeadline;
04262                         if ( $refers[$arrayKey] > 1 ) {
04263                                 $anchor .= '_' . $refers[$arrayKey];
04264                         }
04265                         if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
04266                                 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
04267                         }
04268                         if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
04269                                 $toc .= Linker::tocLine( $anchor, $tocline,
04270                                         $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
04271                         }
04272 
04273                         # Add the section to the section tree
04274                         # Find the DOM node for this header
04275                         while ( $node && !$isTemplate ) {
04276                                 if ( $node->getName() === 'h' ) {
04277                                         $bits = $node->splitHeading();
04278                                         if ( $bits['i'] == $sectionIndex ) {
04279                                                 break;
04280                                         }
04281                                 }
04282                                 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
04283                                         $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
04284                                 $node = $node->getNextSibling();
04285                         }
04286                         $tocraw[] = array(
04287                                 'toclevel' => $toclevel,
04288                                 'level' => $level,
04289                                 'line' => $tocline,
04290                                 'number' => $numbering,
04291                                 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
04292                                 'fromtitle' => $titleText,
04293                                 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
04294                                 'anchor' => $anchor,
04295                         );
04296 
04297                         # give headline the correct <h#> tag
04298                         if ( $maybeShowEditLink && $sectionIndex !== false ) {
04299                                 // Output edit section links as markers with styles that can be customized by skins
04300                                 if ( $isTemplate ) {
04301                                         # Put a T flag in the section identifier, to indicate to extractSections()
04302                                         # that sections inside <includeonly> should be counted.
04303                                         $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
04304                                 } else {
04305                                         $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
04306                                 }
04307                                 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
04308                                 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
04309                                 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
04310                                 // so we don't have to worry about a user trying to input one of these markers directly.
04311                                 // We use a page and section attribute to stop the language converter from converting these important bits
04312                                 // of data, but put the headline hint inside a content block because the language converter is supposed to
04313                                 // be able to convert that piece of data.
04314                                 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
04315                                 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
04316                                 if ( isset($editlinkArgs[2]) ) {
04317                                         $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
04318                                 } else {
04319                                         $editlink .= '/>';
04320                                 }
04321                         } else {
04322                                 $editlink = '';
04323                         }
04324                         $head[$headlineCount] = Linker::makeHeadline( $level,
04325                                 $matches['attrib'][$headlineCount], $anchor, $headline,
04326                                 $editlink, $legacyAnchor );
04327 
04328                         $headlineCount++;
04329                 }
04330 
04331                 $this->setOutputType( $oldType );
04332 
04333                 # Never ever show TOC if no headers
04334                 if ( $numVisible < 1 ) {
04335                         $enoughToc = false;
04336                 }
04337 
04338                 if ( $enoughToc ) {
04339                         if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
04340                                 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
04341                         }
04342                         $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
04343                         $this->mOutput->setTOCHTML( $toc );
04344                 }
04345 
04346                 if ( $isMain ) {
04347                         $this->mOutput->setSections( $tocraw );
04348                 }
04349 
04350                 # split up and insert constructed headlines
04351                 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
04352                 $i = 0;
04353 
04354                 // build an array of document sections
04355                 $sections = array();
04356                 foreach ( $blocks as $block ) {
04357                         // $head is zero-based, sections aren't.
04358                         if ( empty( $head[$i - 1] ) ) {
04359                                 $sections[$i] = $block;
04360                         } else {
04361                                 $sections[$i] = $head[$i - 1] . $block;
04362                         }
04363 
04374                         wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
04375 
04376                         $i++;
04377                 }
04378 
04379                 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
04380                         // append the TOC at the beginning
04381                         // Top anchor now in skin
04382                         $sections[0] = $sections[0] . $toc . "\n";
04383                 }
04384 
04385                 $full .= join( '', $sections );
04386 
04387                 if ( $this->mForceTocPosition ) {
04388                         return str_replace( '<!--MWTOC-->', $toc, $full );
04389                 } else {
04390                         return $full;
04391                 }
04392         }
04393 
04405         public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
04406                 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
04407                 $this->setUser( $user );
04408 
04409                 $pairs = array(
04410                         "\r\n" => "\n",
04411                 );
04412                 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
04413                 if( $options->getPreSaveTransform() ) {
04414                         $text = $this->pstPass2( $text, $user );
04415                 }
04416                 $text = $this->mStripState->unstripBoth( $text );
04417 
04418                 $this->setUser( null ); #Reset
04419 
04420                 return $text;
04421         }
04422 
04432         function pstPass2( $text, $user ) {
04433                 global $wgContLang, $wgLocaltimezone;
04434 
04435                 # Note: This is the timestamp saved as hardcoded wikitext to
04436                 # the database, we use $wgContLang here in order to give
04437                 # everyone the same signature and use the default one rather
04438                 # than the one selected in each user's preferences.
04439                 # (see also bug 12815)
04440                 $ts = $this->mOptions->getTimestamp();
04441                 if ( isset( $wgLocaltimezone ) ) {
04442                         $tz = $wgLocaltimezone;
04443                 } else {
04444                         $tz = date_default_timezone_get();
04445                 }
04446 
04447                 $unixts = wfTimestamp( TS_UNIX, $ts );
04448                 $oldtz = date_default_timezone_get();
04449                 date_default_timezone_set( $tz );
04450                 $ts = date( 'YmdHis', $unixts );
04451                 $tzMsg = date( 'T', $unixts );  # might vary on DST changeover!
04452 
04453                 # Allow translation of timezones through wiki. date() can return
04454                 # whatever crap the system uses, localised or not, so we cannot
04455                 # ship premade translations.
04456                 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
04457                 $msg = wfMessage( $key )->inContentLanguage();
04458                 if ( $msg->exists() ) {
04459                         $tzMsg = $msg->text();
04460                 }
04461 
04462                 date_default_timezone_set( $oldtz );
04463 
04464                 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
04465 
04466                 # Variable replacement
04467                 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
04468                 $text = $this->replaceVariables( $text );
04469 
04470                 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
04471                 # which may corrupt this parser instance via its wfMessage()->text() call-
04472 
04473                 # Signatures
04474                 $sigText = $this->getUserSig( $user );
04475                 $text = strtr( $text, array(
04476                         '~~~~~' => $d,
04477                         '~~~~' => "$sigText $d",
04478                         '~~~' => $sigText
04479                 ) );
04480 
04481                 # Context links: [[|name]] and [[name (context)|]]
04482                 $tc = '[' . Title::legalChars() . ']';
04483                 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
04484 
04485                 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";           # [[ns:page (context)|]]
04486                 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";           # [[ns:page(context)|]]
04487                 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
04488                 $p2 = "/\[\[\\|($tc+)]]/";                                      # [[|page]]
04489 
04490                 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
04491                 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
04492                 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
04493                 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
04494 
04495                 $t = $this->mTitle->getText();
04496                 $m = array();
04497                 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
04498                         $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
04499                 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
04500                         $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
04501                 } else {
04502                         # if there's no context, don't bother duplicating the title
04503                         $text = preg_replace( $p2, '[[\\1]]', $text );
04504                 }
04505 
04506                 # Trim trailing whitespace
04507                 $text = rtrim( $text );
04508 
04509                 return $text;
04510         }
04511 
04526         function getUserSig( &$user, $nickname = false, $fancySig = null ) {
04527                 global $wgMaxSigChars;
04528 
04529                 $username = $user->getName();
04530 
04531                 # If not given, retrieve from the user object.
04532                 if ( $nickname === false )
04533                         $nickname = $user->getOption( 'nickname' );
04534 
04535                 if ( is_null( $fancySig ) ) {
04536                         $fancySig = $user->getBoolOption( 'fancysig' );
04537                 }
04538 
04539                 $nickname = $nickname == null ? $username : $nickname;
04540 
04541                 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
04542                         $nickname = $username;
04543                         wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
04544                 } elseif ( $fancySig !== false ) {
04545                         # Sig. might contain markup; validate this
04546                         if ( $this->validateSig( $nickname ) !== false ) {
04547                                 # Validated; clean up (if needed) and return it
04548                                 return $this->cleanSig( $nickname, true );
04549                         } else {
04550                                 # Failed to validate; fall back to the default
04551                                 $nickname = $username;
04552                                 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
04553                         }
04554                 }
04555 
04556                 # Make sure nickname doesnt get a sig in a sig
04557                 $nickname = self::cleanSigInSig( $nickname );
04558 
04559                 # If we're still here, make it a link to the user page
04560                 $userText = wfEscapeWikiText( $username );
04561                 $nickText = wfEscapeWikiText( $nickname );
04562                 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
04563 
04564                 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
04565         }
04566 
04573         function validateSig( $text ) {
04574                 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
04575         }
04576 
04587         public function cleanSig( $text, $parsing = false ) {
04588                 if ( !$parsing ) {
04589                         global $wgTitle;
04590                         $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
04591                 }
04592 
04593                 # Option to disable this feature
04594                 if ( !$this->mOptions->getCleanSignatures() ) {
04595                         return $text;
04596                 }
04597 
04598                 # @todo FIXME: Regex doesn't respect extension tags or nowiki
04599                 #  => Move this logic to braceSubstitution()
04600                 $substWord = MagicWord::get( 'subst' );
04601                 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
04602                 $substText = '{{' . $substWord->getSynonym( 0 );
04603 
04604                 $text = preg_replace( $substRegex, $substText, $text );
04605                 $text = self::cleanSigInSig( $text );
04606                 $dom = $this->preprocessToDom( $text );
04607                 $frame = $this->getPreprocessor()->newFrame();
04608                 $text = $frame->expand( $dom );
04609 
04610                 if ( !$parsing ) {
04611                         $text = $this->mStripState->unstripBoth( $text );
04612                 }
04613 
04614                 return $text;
04615         }
04616 
04623         public static function cleanSigInSig( $text ) {
04624                 $text = preg_replace( '/~{3,5}/', '', $text );
04625                 return $text;
04626         }
04627 
04637         public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
04638                 $this->startParse( $title, $options, $outputType, $clearState );
04639         }
04640 
04647         private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
04648                 $this->setTitle( $title );
04649                 $this->mOptions = $options;
04650                 $this->setOutputType( $outputType );
04651                 if ( $clearState ) {
04652                         $this->clearState();
04653                 }
04654         }
04655 
04664         public function transformMsg( $text, $options, $title = null ) {
04665                 static $executing = false;
04666 
04667                 # Guard against infinite recursion
04668                 if ( $executing ) {
04669                         return $text;
04670                 }
04671                 $executing = true;
04672 
04673                 wfProfileIn( __METHOD__ );
04674                 if ( !$title ) {
04675                         global $wgTitle;
04676                         $title = $wgTitle;
04677                 }
04678                 if ( !$title ) {
04679                         # It's not uncommon having a null $wgTitle in scripts. See r80898
04680                         # Create a ghost title in such case
04681                         $title = Title::newFromText( 'Dwimmerlaik' );
04682                 }
04683                 $text = $this->preprocess( $text, $title, $options );
04684 
04685                 $executing = false;
04686                 wfProfileOut( __METHOD__ );
04687                 return $text;
04688         }
04689 
04714         public function setHook( $tag, $callback ) {
04715                 $tag = strtolower( $tag );
04716                 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
04717                         throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
04718                 }
04719                 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
04720                 $this->mTagHooks[$tag] = $callback;
04721                 if ( !in_array( $tag, $this->mStripList ) ) {
04722                         $this->mStripList[] = $tag;
04723                 }
04724 
04725                 return $oldVal;
04726         }
04727 
04745         function setTransparentTagHook( $tag, $callback ) {
04746                 $tag = strtolower( $tag );
04747                 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
04748                         throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
04749                 }
04750                 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
04751                 $this->mTransparentTagHooks[$tag] = $callback;
04752 
04753                 return $oldVal;
04754         }
04755 
04759         function clearTagHooks() {
04760                 $this->mTagHooks = array();
04761                 $this->mFunctionTagHooks = array();
04762                 $this->mStripList = $this->mDefaultStripList;
04763         }
04764 
04808         public function setFunctionHook( $id, $callback, $flags = 0 ) {
04809                 global $wgContLang;
04810 
04811                 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
04812                 $this->mFunctionHooks[$id] = array( $callback, $flags );
04813 
04814                 # Add to function cache
04815                 $mw = MagicWord::get( $id );
04816                 if ( !$mw )
04817                         throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
04818 
04819                 $synonyms = $mw->getSynonyms();
04820                 $sensitive = intval( $mw->isCaseSensitive() );
04821 
04822                 foreach ( $synonyms as $syn ) {
04823                         # Case
04824                         if ( !$sensitive ) {
04825                                 $syn = $wgContLang->lc( $syn );
04826                         }
04827                         # Add leading hash
04828                         if ( !( $flags & SFH_NO_HASH ) ) {
04829                                 $syn = '#' . $syn;
04830                         }
04831                         # Remove trailing colon
04832                         if ( substr( $syn, -1, 1 ) === ':' ) {
04833                                 $syn = substr( $syn, 0, -1 );
04834                         }
04835                         $this->mFunctionSynonyms[$sensitive][$syn] = $id;
04836                 }
04837                 return $oldVal;
04838         }
04839 
04845         function getFunctionHooks() {
04846                 return array_keys( $this->mFunctionHooks );
04847         }
04848 
04859         function setFunctionTagHook( $tag, $callback, $flags ) {
04860                 $tag = strtolower( $tag );
04861                 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
04862                 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
04863                         $this->mFunctionTagHooks[$tag] : null;
04864                 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
04865 
04866                 if ( !in_array( $tag, $this->mStripList ) ) {
04867                         $this->mStripList[] = $tag;
04868                 }
04869 
04870                 return $old;
04871         }
04872 
04883         function replaceLinkHolders( &$text, $options = 0 ) {
04884                 return $this->mLinkHolders->replace( $text );
04885         }
04886 
04894         function replaceLinkHoldersText( $text ) {
04895                 return $this->mLinkHolders->replaceText( $text );
04896         }
04897 
04911         function renderImageGallery( $text, $params ) {
04912                 $ig = new ImageGallery();
04913                 $ig->setContextTitle( $this->mTitle );
04914                 $ig->setShowBytes( false );
04915                 $ig->setShowFilename( false );
04916                 $ig->setParser( $this );
04917                 $ig->setHideBadImages();
04918                 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
04919 
04920                 if ( isset( $params['showfilename'] ) ) {
04921                         $ig->setShowFilename( true );
04922                 } else {
04923                         $ig->setShowFilename( false );
04924                 }
04925                 if ( isset( $params['caption'] ) ) {
04926                         $caption = $params['caption'];
04927                         $caption = htmlspecialchars( $caption );
04928                         $caption = $this->replaceInternalLinks( $caption );
04929                         $ig->setCaptionHtml( $caption );
04930                 }
04931                 if ( isset( $params['perrow'] ) ) {
04932                         $ig->setPerRow( $params['perrow'] );
04933                 }
04934                 if ( isset( $params['widths'] ) ) {
04935                         $ig->setWidths( $params['widths'] );
04936                 }
04937                 if ( isset( $params['heights'] ) ) {
04938                         $ig->setHeights( $params['heights'] );
04939                 }
04940 
04941                 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
04942 
04943                 $lines = StringUtils::explode( "\n", $text );
04944                 foreach ( $lines as $line ) {
04945                         # match lines like these:
04946                         # Image:someimage.jpg|This is some image
04947                         $matches = array();
04948                         preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
04949                         # Skip empty lines
04950                         if ( count( $matches ) == 0 ) {
04951                                 continue;
04952                         }
04953 
04954                         if ( strpos( $matches[0], '%' ) !== false ) {
04955                                 $matches[1] = rawurldecode( $matches[1] );
04956                         }
04957                         $title = Title::newFromText( $matches[1], NS_FILE );
04958                         if ( is_null( $title ) ) {
04959                                 # Bogus title. Ignore these so we don't bomb out later.
04960                                 continue;
04961                         }
04962 
04963                         $label = '';
04964                         $alt = '';
04965                         $link = '';
04966                         if ( isset( $matches[3] ) ) {
04967                                 // look for an |alt= definition while trying not to break existing
04968                                 // captions with multiple pipes (|) in it, until a more sensible grammar
04969                                 // is defined for images in galleries
04970 
04971                                 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
04972                                 $parameterMatches = StringUtils::explode('|', $matches[3]);
04973                                 $magicWordAlt = MagicWord::get( 'img_alt' );
04974                                 $magicWordLink = MagicWord::get( 'img_link' );
04975 
04976                                 foreach ( $parameterMatches as $parameterMatch ) {
04977                                         if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
04978                                                 $alt = $this->stripAltText( $match, false );
04979                                         }
04980                                         elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
04981                                                 $link = strip_tags($this->replaceLinkHoldersText($match));
04982                                                 $chars = self::EXT_LINK_URL_CLASS;
04983                                                 $prots = $this->mUrlProtocols;
04984                                                 //check to see if link matches an absolute url, if not then it must be a wiki link.
04985                                                 if(!preg_match( "/^($prots)$chars+$/u", $link)){
04986                                                         $localLinkTitle = Title::newFromText($link);
04987                                                         $link = $localLinkTitle->getLocalURL();
04988                                                 }
04989                                         }
04990                                         else {
04991                                                 // concatenate all other pipes
04992                                                 $label .= '|' . $parameterMatch;
04993                                         }
04994                                 }
04995                                 // remove the first pipe
04996                                 $label = substr( $label, 1 );
04997                         }
04998 
04999                         $ig->add( $title, $label, $alt ,$link);
05000                 }
05001                 return $ig->toHTML();
05002         }
05003 
05008         function getImageParams( $handler ) {
05009                 if ( $handler ) {
05010                         $handlerClass = get_class( $handler );
05011                 } else {
05012                         $handlerClass = '';
05013                 }
05014                 if ( !isset( $this->mImageParams[$handlerClass]  ) ) {
05015                         # Initialise static lists
05016                         static $internalParamNames = array(
05017                                 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
05018                                 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
05019                                         'bottom', 'text-bottom' ),
05020                                 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
05021                                         'upright', 'border', 'link', 'alt', 'class' ),
05022                         );
05023                         static $internalParamMap;
05024                         if ( !$internalParamMap ) {
05025                                 $internalParamMap = array();
05026                                 foreach ( $internalParamNames as $type => $names ) {
05027                                         foreach ( $names as $name ) {
05028                                                 $magicName = str_replace( '-', '_', "img_$name" );
05029                                                 $internalParamMap[$magicName] = array( $type, $name );
05030                                         }
05031                                 }
05032                         }
05033 
05034                         # Add handler params
05035                         $paramMap = $internalParamMap;
05036                         if ( $handler ) {
05037                                 $handlerParamMap = $handler->getParamMap();
05038                                 foreach ( $handlerParamMap as $magic => $paramName ) {
05039                                         $paramMap[$magic] = array( 'handler', $paramName );
05040                                 }
05041                         }
05042                         $this->mImageParams[$handlerClass] = $paramMap;
05043                         $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
05044                 }
05045                 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
05046         }
05047 
05056         function makeImage( $title, $options, $holders = false ) {
05057                 # Check if the options text is of the form "options|alt text"
05058                 # Options are:
05059                 #  * thumbnail  make a thumbnail with enlarge-icon and caption, alignment depends on lang
05060                 #  * left       no resizing, just left align. label is used for alt= only
05061                 #  * right      same, but right aligned
05062                 #  * none       same, but not aligned
05063                 #  * ___px      scale to ___ pixels width, no aligning. e.g. use in taxobox
05064                 #  * center     center the image
05065                 #  * frame      Keep original image size, no magnify-button.
05066                 #  * framed     Same as "frame"
05067                 #  * frameless  like 'thumb' but without a frame. Keeps user preferences for width
05068                 #  * upright    reduce width for upright images, rounded to full __0 px
05069                 #  * border     draw a 1px border around the image
05070                 #  * alt        Text for HTML alt attribute (defaults to empty)
05071                 #  * class      Set a class for img node
05072                 #  * link       Set the target of the image link. Can be external, interwiki, or local
05073                 # vertical-align values (no % or length right now):
05074                 #  * baseline
05075                 #  * sub
05076                 #  * super
05077                 #  * top
05078                 #  * text-top
05079                 #  * middle
05080                 #  * bottom
05081                 #  * text-bottom
05082 
05083                 $parts = StringUtils::explode( "|", $options );
05084 
05085                 # Give extensions a chance to select the file revision for us
05086                 $options = array();
05087                 $descQuery = false;
05088                 wfRunHooks( 'BeforeParserFetchFileAndTitle',
05089                         array( $this, $title, &$options, &$descQuery ) );
05090                 # Fetch and register the file (file title may be different via hooks)
05091                 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
05092 
05093                 # Get parameter map
05094                 $handler = $file ? $file->getHandler() : false;
05095 
05096                 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
05097 
05098                 if ( !$file ) {
05099                         $this->addTrackingCategory( 'broken-file-category' );
05100                 }
05101 
05102                 # Process the input parameters
05103                 $caption = '';
05104                 $params = array( 'frame' => array(), 'handler' => array(),
05105                         'horizAlign' => array(), 'vertAlign' => array() );
05106                 foreach ( $parts as $part ) {
05107                         $part = trim( $part );
05108                         list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
05109                         $validated = false;
05110                         if ( isset( $paramMap[$magicName] ) ) {
05111                                 list( $type, $paramName ) = $paramMap[$magicName];
05112 
05113                                 # Special case; width and height come in one variable together
05114                                 if ( $type === 'handler' && $paramName === 'width' ) {
05115                                         $parsedWidthParam = $this->parseWidthParam( $value );
05116                                         if( isset( $parsedWidthParam['width'] ) ) {
05117                                                 $width = $parsedWidthParam['width'];
05118                                                 if ( $handler->validateParam( 'width', $width ) ) {
05119                                                         $params[$type]['width'] = $width;
05120                                                         $validated = true;
05121                                                 }
05122                                         }
05123                                         if( isset( $parsedWidthParam['height'] ) ) {
05124                                                 $height = $parsedWidthParam['height'];
05125                                                 if ( $handler->validateParam( 'height', $height ) ) {
05126                                                         $params[$type]['height'] = $height;
05127                                                         $validated = true;
05128                                                 }
05129                                         }
05130                                         # else no validation -- bug 13436
05131                                 } else {
05132                                         if ( $type === 'handler' ) {
05133                                                 # Validate handler parameter
05134                                                 $validated = $handler->validateParam( $paramName, $value );
05135                                         } else {
05136                                                 # Validate internal parameters
05137                                                 switch( $paramName ) {
05138                                                 case 'manualthumb':
05139                                                 case 'alt':
05140                                                 case 'class':
05141                                                         # @todo FIXME: Possibly check validity here for
05142                                                         # manualthumb? downstream behavior seems odd with
05143                                                         # missing manual thumbs.
05144                                                         $validated = true;
05145                                                         $value = $this->stripAltText( $value, $holders );
05146                                                         break;
05147                                                 case 'link':
05148                                                         $chars = self::EXT_LINK_URL_CLASS;
05149                                                         $prots = $this->mUrlProtocols;
05150                                                         if ( $value === '' ) {
05151                                                                 $paramName = 'no-link';
05152                                                                 $value = true;
05153                                                                 $validated = true;
05154                                                         } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
05155                                                                 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
05156                                                                         $paramName = 'link-url';
05157                                                                         $this->mOutput->addExternalLink( $value );
05158                                                                         if ( $this->mOptions->getExternalLinkTarget() ) {
05159                                                                                 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
05160                                                                         }
05161                                                                         $validated = true;
05162                                                                 }
05163                                                         } else {
05164                                                                 $linkTitle = Title::newFromText( $value );
05165                                                                 if ( $linkTitle ) {
05166                                                                         $paramName = 'link-title';
05167                                                                         $value = $linkTitle;
05168                                                                         $this->mOutput->addLink( $linkTitle );
05169                                                                         $validated = true;
05170                                                                 }
05171                                                         }
05172                                                         break;
05173                                                 default:
05174                                                         # Most other things appear to be empty or numeric...
05175                                                         $validated = ( $value === false || is_numeric( trim( $value ) ) );
05176                                                 }
05177                                         }
05178 
05179                                         if ( $validated ) {
05180                                                 $params[$type][$paramName] = $value;
05181                                         }
05182                                 }
05183                         }
05184                         if ( !$validated ) {
05185                                 $caption = $part;
05186                         }
05187                 }
05188 
05189                 # Process alignment parameters
05190                 if ( $params['horizAlign'] ) {
05191                         $params['frame']['align'] = key( $params['horizAlign'] );
05192                 }
05193                 if ( $params['vertAlign'] ) {
05194                         $params['frame']['valign'] = key( $params['vertAlign'] );
05195                 }
05196 
05197                 $params['frame']['caption'] = $caption;
05198 
05199                 # Will the image be presented in a frame, with the caption below?
05200                 $imageIsFramed = isset( $params['frame']['frame'] ) ||
05201                                                  isset( $params['frame']['framed'] ) ||
05202                                                  isset( $params['frame']['thumbnail'] ) ||
05203                                                  isset( $params['frame']['manualthumb'] );
05204 
05205                 # In the old days, [[Image:Foo|text...]] would set alt text.  Later it
05206                 # came to also set the caption, ordinary text after the image -- which
05207                 # makes no sense, because that just repeats the text multiple times in
05208                 # screen readers.  It *also* came to set the title attribute.
05209                 #
05210                 # Now that we have an alt attribute, we should not set the alt text to
05211                 # equal the caption: that's worse than useless, it just repeats the
05212                 # text.  This is the framed/thumbnail case.  If there's no caption, we
05213                 # use the unnamed parameter for alt text as well, just for the time be-
05214                 # ing, if the unnamed param is set and the alt param is not.
05215                 #
05216                 # For the future, we need to figure out if we want to tweak this more,
05217                 # e.g., introducing a title= parameter for the title; ignoring the un-
05218                 # named parameter entirely for images without a caption; adding an ex-
05219                 # plicit caption= parameter and preserving the old magic unnamed para-
05220                 # meter for BC; ...
05221                 if ( $imageIsFramed ) { # Framed image
05222                         if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
05223                                 # No caption or alt text, add the filename as the alt text so
05224                                 # that screen readers at least get some description of the image
05225                                 $params['frame']['alt'] = $title->getText();
05226                         }
05227                         # Do not set $params['frame']['title'] because tooltips don't make sense
05228                         # for framed images
05229                 } else { # Inline image
05230                         if ( !isset( $params['frame']['alt'] ) ) {
05231                                 # No alt text, use the "caption" for the alt text
05232                                 if ( $caption !== '') {
05233                                         $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
05234                                 } else {
05235                                         # No caption, fall back to using the filename for the
05236                                         # alt text
05237                                         $params['frame']['alt'] = $title->getText();
05238                                 }
05239                         }
05240                         # Use the "caption" for the tooltip text
05241                         $params['frame']['title'] = $this->stripAltText( $caption, $holders );
05242                 }
05243 
05244                 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
05245 
05246                 # Linker does the rest
05247                 $time = isset( $options['time'] ) ? $options['time'] : false;
05248                 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
05249                         $time, $descQuery, $this->mOptions->getThumbSize() );
05250 
05251                 # Give the handler a chance to modify the parser object
05252                 if ( $handler ) {
05253                         $handler->parserTransformHook( $this, $file );
05254                 }
05255 
05256                 return $ret;
05257         }
05258 
05264         protected function stripAltText( $caption, $holders ) {
05265                 # Strip bad stuff out of the title (tooltip).  We can't just use
05266                 # replaceLinkHoldersText() here, because if this function is called
05267                 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
05268                 if ( $holders ) {
05269                         $tooltip = $holders->replaceText( $caption );
05270                 } else {
05271                         $tooltip = $this->replaceLinkHoldersText( $caption );
05272                 }
05273 
05274                 # make sure there are no placeholders in thumbnail attributes
05275                 # that are later expanded to html- so expand them now and
05276                 # remove the tags
05277                 $tooltip = $this->mStripState->unstripBoth( $tooltip );
05278                 $tooltip = Sanitizer::stripAllTags( $tooltip );
05279 
05280                 return $tooltip;
05281         }
05282 
05287         function disableCache() {
05288                 wfDebug( "Parser output marked as uncacheable.\n" );
05289                 if ( !$this->mOutput ) {
05290                         throw new MWException( __METHOD__ .
05291                                 " can only be called when actually parsing something" );
05292                 }
05293                 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
05294                 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
05295         }
05296 
05305         function attributeStripCallback( &$text, $frame = false ) {
05306                 $text = $this->replaceVariables( $text, $frame );
05307                 $text = $this->mStripState->unstripBoth( $text );
05308                 return $text;
05309         }
05310 
05316         function getTags() {
05317                 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
05318         }
05319 
05330         function replaceTransparentTags( $text ) {
05331                 $matches = array();
05332                 $elements = array_keys( $this->mTransparentTagHooks );
05333                 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
05334                 $replacements = array();
05335 
05336                 foreach ( $matches as $marker => $data ) {
05337                         list( $element, $content, $params, $tag ) = $data;
05338                         $tagName = strtolower( $element );
05339                         if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
05340                                 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
05341                         } else {
05342                                 $output = $tag;
05343                         }
05344                         $replacements[$marker] = $output;
05345                 }
05346                 return strtr( $text, $replacements );
05347         }
05348 
05378         private function extractSections( $text, $section, $mode, $newText='' ) {
05379                 global $wgTitle; # not generally used but removes an ugly failure mode
05380                 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
05381                 $outText = '';
05382                 $frame = $this->getPreprocessor()->newFrame();
05383 
05384                 # Process section extraction flags
05385                 $flags = 0;
05386                 $sectionParts = explode( '-', $section );
05387                 $sectionIndex = array_pop( $sectionParts );
05388                 foreach ( $sectionParts as $part ) {
05389                         if ( $part === 'T' ) {
05390                                 $flags |= self::PTD_FOR_INCLUSION;
05391                         }
05392                 }
05393 
05394                 # Check for empty input
05395                 if ( strval( $text ) === '' ) {
05396                         # Only sections 0 and T-0 exist in an empty document
05397                         if ( $sectionIndex == 0 ) {
05398                                 if ( $mode === 'get' ) {
05399                                         return '';
05400                                 } else {
05401                                         return $newText;
05402                                 }
05403                         } else {
05404                                 if ( $mode === 'get' ) {
05405                                         return $newText;
05406                                 } else {
05407                                         return $text;
05408                                 }
05409                         }
05410                 }
05411 
05412                 # Preprocess the text
05413                 $root = $this->preprocessToDom( $text, $flags );
05414 
05415                 # <h> nodes indicate section breaks
05416                 # They can only occur at the top level, so we can find them by iterating the root's children
05417                 $node = $root->getFirstChild();
05418 
05419                 # Find the target section
05420                 if ( $sectionIndex == 0 ) {
05421                         # Section zero doesn't nest, level=big
05422                         $targetLevel = 1000;
05423                 } else {
05424                         while ( $node ) {
05425                                 if ( $node->getName() === 'h' ) {
05426                                         $bits = $node->splitHeading();
05427                                         if ( $bits['i'] == $sectionIndex ) {
05428                                                 $targetLevel = $bits['level'];
05429                                                 break;
05430                                         }
05431                                 }
05432                                 if ( $mode === 'replace' ) {
05433                                         $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
05434                                 }
05435                                 $node = $node->getNextSibling();
05436                         }
05437                 }
05438 
05439                 if ( !$node ) {
05440                         # Not found
05441                         if ( $mode === 'get' ) {
05442                                 return $newText;
05443                         } else {
05444                                 return $text;
05445                         }
05446                 }
05447 
05448                 # Find the end of the section, including nested sections
05449                 do {
05450                         if ( $node->getName() === 'h' ) {
05451                                 $bits = $node->splitHeading();
05452                                 $curLevel = $bits['level'];
05453                                 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
05454                                         break;
05455                                 }
05456                         }
05457                         if ( $mode === 'get' ) {
05458                                 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
05459                         }
05460                         $node = $node->getNextSibling();
05461                 } while ( $node );
05462 
05463                 # Write out the remainder (in replace mode only)
05464                 if ( $mode === 'replace' ) {
05465                         # Output the replacement text
05466                         # Add two newlines on -- trailing whitespace in $newText is conventionally
05467                         # stripped by the editor, so we need both newlines to restore the paragraph gap
05468                         # Only add trailing whitespace if there is newText
05469                         if ( $newText != "" ) {
05470                                 $outText .= $newText . "\n\n";
05471                         }
05472 
05473                         while ( $node ) {
05474                                 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
05475                                 $node = $node->getNextSibling();
05476                         }
05477                 }
05478 
05479                 if ( is_string( $outText ) ) {
05480                         # Re-insert stripped tags
05481                         $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
05482                 }
05483 
05484                 return $outText;
05485         }
05486 
05499         public function getSection( $text, $section, $deftext='' ) {
05500                 return $this->extractSections( $text, $section, "get", $deftext );
05501         }
05502 
05513         public function replaceSection( $oldtext, $section, $text ) {
05514                 return $this->extractSections( $oldtext, $section, "replace", $text );
05515         }
05516 
05522         function getRevisionId() {
05523                 return $this->mRevisionId;
05524         }
05525 
05531         protected function getRevisionObject() {
05532                 if ( !is_null( $this->mRevisionObject ) ) {
05533                         return $this->mRevisionObject;
05534                 }
05535                 if ( is_null( $this->mRevisionId ) ) {
05536                         return null;
05537                 }
05538 
05539                 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
05540                 return $this->mRevisionObject;
05541         }
05542 
05547         function getRevisionTimestamp() {
05548                 if ( is_null( $this->mRevisionTimestamp ) ) {
05549                         wfProfileIn( __METHOD__ );
05550 
05551                         global $wgContLang;
05552 
05553                         $revObject = $this->getRevisionObject();
05554                         $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
05555 
05556                         # The cryptic '' timezone parameter tells to use the site-default
05557                         # timezone offset instead of the user settings.
05558                         #
05559                         # Since this value will be saved into the parser cache, served
05560                         # to other users, and potentially even used inside links and such,
05561                         # it needs to be consistent for all visitors.
05562                         $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
05563 
05564                         wfProfileOut( __METHOD__ );
05565                 }
05566                 return $this->mRevisionTimestamp;
05567         }
05568 
05574         function getRevisionUser() {
05575                 if( is_null( $this->mRevisionUser ) ) {
05576                         $revObject = $this->getRevisionObject();
05577 
05578                         # if this template is subst: the revision id will be blank,
05579                         # so just use the current user's name
05580                         if( $revObject ) {
05581                                 $this->mRevisionUser = $revObject->getUserText();
05582                         } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
05583                                 $this->mRevisionUser = $this->getUser()->getName();
05584                         }
05585                 }
05586                 return $this->mRevisionUser;
05587         }
05588 
05594         public function setDefaultSort( $sort ) {
05595                 $this->mDefaultSort = $sort;
05596                 $this->mOutput->setProperty( 'defaultsort', $sort );
05597         }
05598 
05609         public function getDefaultSort() {
05610                 if ( $this->mDefaultSort !== false ) {
05611                         return $this->mDefaultSort;
05612                 } else {
05613                         return '';
05614                 }
05615         }
05616 
05623         public function getCustomDefaultSort() {
05624                 return $this->mDefaultSort;
05625         }
05626 
05636         public function guessSectionNameFromWikiText( $text ) {
05637                 # Strip out wikitext links(they break the anchor)
05638                 $text = $this->stripSectionName( $text );
05639                 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
05640                 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
05641         }
05642 
05651         public function guessLegacySectionNameFromWikiText( $text ) {
05652                 # Strip out wikitext links(they break the anchor)
05653                 $text = $this->stripSectionName( $text );
05654                 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
05655                 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
05656         }
05657 
05672         public function stripSectionName( $text ) {
05673                 # Strip internal link markup
05674                 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
05675                 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
05676 
05677                 # Strip external link markup
05678                 # @todo FIXME: Not tolerant to blank link text
05679                 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
05680                 # on how many empty links there are on the page - need to figure that out.
05681                 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
05682 
05683                 # Parse wikitext quotes (italics & bold)
05684                 $text = $this->doQuotes( $text );
05685 
05686                 # Strip HTML tags
05687                 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
05688                 return $text;
05689         }
05690 
05701         function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
05702                 $this->startParse( $title, $options, $outputType, true );
05703 
05704                 $text = $this->replaceVariables( $text );
05705                 $text = $this->mStripState->unstripBoth( $text );
05706                 $text = Sanitizer::removeHTMLtags( $text );
05707                 return $text;
05708         }
05709 
05716         function testPst( $text, Title $title, ParserOptions $options ) {
05717                 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
05718         }
05719 
05726         function testPreprocess( $text, Title $title, ParserOptions $options ) {
05727                 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
05728         }
05729 
05746         function markerSkipCallback( $s, $callback ) {
05747                 $i = 0;
05748                 $out = '';
05749                 while ( $i < strlen( $s ) ) {
05750                         $markerStart = strpos( $s, $this->mUniqPrefix, $i );
05751                         if ( $markerStart === false ) {
05752                                 $out .= call_user_func( $callback, substr( $s, $i ) );
05753                                 break;
05754                         } else {
05755                                 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
05756                                 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
05757                                 if ( $markerEnd === false ) {
05758                                         $out .= substr( $s, $markerStart );
05759                                         break;
05760                                 } else {
05761                                         $markerEnd += strlen( self::MARKER_SUFFIX );
05762                                         $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
05763                                         $i = $markerEnd;
05764                                 }
05765                         }
05766                 }
05767                 return $out;
05768         }
05769 
05776         function killMarkers( $text ) {
05777                 return $this->mStripState->killMarkers( $text );
05778         }
05779 
05796         function serializeHalfParsedText( $text ) {
05797                 wfProfileIn( __METHOD__ );
05798                 $data = array(
05799                         'text' => $text,
05800                         'version' => self::HALF_PARSED_VERSION,
05801                         'stripState' => $this->mStripState->getSubState( $text ),
05802                         'linkHolders' => $this->mLinkHolders->getSubArray( $text )
05803                 );
05804                 wfProfileOut( __METHOD__ );
05805                 return $data;
05806         }
05807 
05823         function unserializeHalfParsedText( $data ) {
05824                 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
05825                         throw new MWException( __METHOD__.': invalid version' );
05826                 }
05827 
05828                 # First, extract the strip state.
05829                 $texts = array( $data['text'] );
05830                 $texts = $this->mStripState->merge( $data['stripState'], $texts );
05831 
05832                 # Now renumber links
05833                 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
05834 
05835                 # Should be good to go.
05836                 return $texts[0];
05837         }
05838 
05848         function isValidHalfParsedText( $data ) {
05849                 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
05850         }
05851 
05860         public function parseWidthParam( $value ) {
05861                 $parsedWidthParam = array();
05862                 if( $value === '' ) {
05863                         return $parsedWidthParam;
05864                 }
05865                 $m = array();
05866                 # (bug 13500) In both cases (width/height and width only),
05867                 # permit trailing "px" for backward compatibility.
05868                 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
05869                         $width = intval( $m[1] );
05870                         $height = intval( $m[2] );
05871                         $parsedWidthParam['width'] = $width;
05872                         $parsedWidthParam['height'] = $height;
05873                 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
05874                         $width = intval( $value );
05875                         $parsedWidthParam['width'] = $width;
05876                 }
05877                 return $parsedWidthParam;
05878         }
05879 }