MediaWiki
REL1_20
|
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 public function __construct( $conf = array() ) { 00209 $this->mConf = $conf; 00210 $this->mUrlProtocols = wfUrlProtocols(); 00211 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')'. 00212 self::EXT_LINK_URL_CLASS.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su'; 00213 if ( isset( $conf['preprocessorClass'] ) ) { 00214 $this->mPreprocessorClass = $conf['preprocessorClass']; 00215 } elseif ( defined( 'MW_COMPILED' ) ) { 00216 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode 00217 $this->mPreprocessorClass = 'Preprocessor_Hash'; 00218 } elseif ( extension_loaded( 'domxml' ) ) { 00219 # PECL extension that conflicts with the core DOM extension (bug 13770) 00220 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" ); 00221 $this->mPreprocessorClass = 'Preprocessor_Hash'; 00222 } elseif ( extension_loaded( 'dom' ) ) { 00223 $this->mPreprocessorClass = 'Preprocessor_DOM'; 00224 } else { 00225 $this->mPreprocessorClass = 'Preprocessor_Hash'; 00226 } 00227 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" ); 00228 } 00229 00233 function __destruct() { 00234 if ( isset( $this->mLinkHolders ) ) { 00235 unset( $this->mLinkHolders ); 00236 } 00237 foreach ( $this as $name => $value ) { 00238 unset( $this->$name ); 00239 } 00240 } 00241 00245 function firstCallInit() { 00246 if ( !$this->mFirstCall ) { 00247 return; 00248 } 00249 $this->mFirstCall = false; 00250 00251 wfProfileIn( __METHOD__ ); 00252 00253 CoreParserFunctions::register( $this ); 00254 CoreTagHooks::register( $this ); 00255 $this->initialiseVariables(); 00256 00257 wfRunHooks( 'ParserFirstCallInit', array( &$this ) ); 00258 wfProfileOut( __METHOD__ ); 00259 } 00260 00266 function clearState() { 00267 wfProfileIn( __METHOD__ ); 00268 if ( $this->mFirstCall ) { 00269 $this->firstCallInit(); 00270 } 00271 $this->mOutput = new ParserOutput; 00272 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) ); 00273 $this->mAutonumber = 0; 00274 $this->mLastSection = ''; 00275 $this->mDTopen = false; 00276 $this->mIncludeCount = array(); 00277 $this->mArgStack = false; 00278 $this->mInPre = false; 00279 $this->mLinkHolders = new LinkHolderArray( $this ); 00280 $this->mLinkID = 0; 00281 $this->mRevisionObject = $this->mRevisionTimestamp = 00282 $this->mRevisionId = $this->mRevisionUser = null; 00283 $this->mVarCache = array(); 00284 $this->mUser = null; 00285 00296 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString(); 00297 $this->mStripState = new StripState( $this->mUniqPrefix ); 00298 00299 00300 # Clear these on every parse, bug 4549 00301 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array(); 00302 00303 $this->mShowToc = true; 00304 $this->mForceTocPosition = false; 00305 $this->mIncludeSizes = array( 00306 'post-expand' => 0, 00307 'arg' => 0, 00308 ); 00309 $this->mPPNodeCount = 0; 00310 $this->mGeneratedPPNodeCount = 0; 00311 $this->mHighestExpansionDepth = 0; 00312 $this->mDefaultSort = false; 00313 $this->mHeadings = array(); 00314 $this->mDoubleUnderscores = array(); 00315 $this->mExpensiveFunctionCount = 0; 00316 00317 # Fix cloning 00318 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) { 00319 $this->mPreprocessor = null; 00320 } 00321 00322 wfRunHooks( 'ParserClearState', array( &$this ) ); 00323 wfProfileOut( __METHOD__ ); 00324 } 00325 00338 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) { 00344 global $wgUseTidy, $wgAlwaysUseTidy; 00345 $fname = __METHOD__.'-' . wfGetCaller(); 00346 wfProfileIn( __METHOD__ ); 00347 wfProfileIn( $fname ); 00348 00349 $this->startParse( $title, $options, self::OT_HTML, $clearState ); 00350 00351 # Remove the strip marker tag prefix from the input, if present. 00352 if ( $clearState ) { 00353 $text = str_replace( $this->mUniqPrefix, '', $text ); 00354 } 00355 00356 $oldRevisionId = $this->mRevisionId; 00357 $oldRevisionObject = $this->mRevisionObject; 00358 $oldRevisionTimestamp = $this->mRevisionTimestamp; 00359 $oldRevisionUser = $this->mRevisionUser; 00360 if ( $revid !== null ) { 00361 $this->mRevisionId = $revid; 00362 $this->mRevisionObject = null; 00363 $this->mRevisionTimestamp = null; 00364 $this->mRevisionUser = null; 00365 } 00366 00367 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 00368 # No more strip! 00369 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 00370 $text = $this->internalParse( $text ); 00371 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) ); 00372 00373 $text = $this->mStripState->unstripGeneral( $text ); 00374 00375 # Clean up special characters, only run once, next-to-last before doBlockLevels 00376 $fixtags = array( 00377 # french spaces, last one Guillemet-left 00378 # only if there is something before the space 00379 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ', 00380 # french spaces, Guillemet-right 00381 '/(\\302\\253) /' => '\\1 ', 00382 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874. 00383 ); 00384 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text ); 00385 00386 $text = $this->doBlockLevels( $text, $linestart ); 00387 00388 $this->replaceLinkHolders( $text ); 00389 00397 if ( !( $options->getDisableContentConversion() 00398 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) ) ) 00399 { 00400 # Run convert unconditionally in 1.18-compatible mode 00401 global $wgBug34832TransitionalRollback; 00402 if ( $wgBug34832TransitionalRollback || !$this->mOptions->getInterfaceMessage() ) { 00403 # The position of the convert() call should not be changed. it 00404 # assumes that the links are all replaced and the only thing left 00405 # is the <nowiki> mark. 00406 $text = $this->getConverterLanguage()->convert( $text ); 00407 } 00408 } 00409 00417 if ( !( $options->getDisableTitleConversion() 00418 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) 00419 || isset( $this->mDoubleUnderscores['notitleconvert'] ) 00420 || $this->mOutput->getDisplayTitle() !== false ) ) 00421 { 00422 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle(); 00423 if ( $convruletitle ) { 00424 $this->mOutput->setTitleText( $convruletitle ); 00425 } else { 00426 $titleText = $this->getConverterLanguage()->convertTitle( $title ); 00427 $this->mOutput->setTitleText( $titleText ); 00428 } 00429 } 00430 00431 $text = $this->mStripState->unstripNoWiki( $text ); 00432 00433 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) ); 00434 00435 $text = $this->replaceTransparentTags( $text ); 00436 $text = $this->mStripState->unstripGeneral( $text ); 00437 00438 $text = Sanitizer::normalizeCharReferences( $text ); 00439 00440 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) { 00441 $text = MWTidy::tidy( $text ); 00442 } else { 00443 # attempt to sanitize at least some nesting problems 00444 # (bug #2702 and quite a few others) 00445 $tidyregs = array( 00446 # ''Something [http://www.cool.com cool''] --> 00447 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a> 00448 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' => 00449 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9', 00450 # fix up an anchor inside another anchor, only 00451 # at least for a single single nested link (bug 3695) 00452 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' => 00453 '\\1\\2</a>\\3</a>\\1\\4</a>', 00454 # fix div inside inline elements- doBlockLevels won't wrap a line which 00455 # contains a div, so fix it up here; replace 00456 # div with escaped text 00457 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' => 00458 '\\1\\3<div\\5>\\6</div>\\8\\9', 00459 # remove empty italic or bold tag pairs, some 00460 # introduced by rules above 00461 '/<([bi])><\/\\1>/' => '', 00462 ); 00463 00464 $text = preg_replace( 00465 array_keys( $tidyregs ), 00466 array_values( $tidyregs ), 00467 $text ); 00468 } 00469 00470 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) { 00471 $this->limitationWarn( 'expensive-parserfunction', 00472 $this->mExpensiveFunctionCount, 00473 $this->mOptions->getExpensiveParserFunctionLimit() 00474 ); 00475 } 00476 00477 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) ); 00478 00479 # Information on include size limits, for the benefit of users who try to skirt them 00480 if ( $this->mOptions->getEnableLimitReport() ) { 00481 $max = $this->mOptions->getMaxIncludeSize(); 00482 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n"; 00483 $limitReport = 00484 "NewPP limit report\n" . 00485 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" . 00486 "Preprocessor generated node count: " . 00487 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" . 00488 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" . 00489 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n". 00490 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n". 00491 $PFreport; 00492 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) ); 00493 00494 // Sanitize for comment. Note '‐' in the replacement is U+2010, 00495 // which looks much like the problematic '-'. 00496 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport ); 00497 00498 $text .= "\n<!-- \n$limitReport-->\n"; 00499 } 00500 $this->mOutput->setText( $text ); 00501 00502 $this->mRevisionId = $oldRevisionId; 00503 $this->mRevisionObject = $oldRevisionObject; 00504 $this->mRevisionTimestamp = $oldRevisionTimestamp; 00505 $this->mRevisionUser = $oldRevisionUser; 00506 wfProfileOut( $fname ); 00507 wfProfileOut( __METHOD__ ); 00508 00509 return $this->mOutput; 00510 } 00511 00523 function recursiveTagParse( $text, $frame=false ) { 00524 wfProfileIn( __METHOD__ ); 00525 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 00526 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 00527 $text = $this->internalParse( $text, false, $frame ); 00528 wfProfileOut( __METHOD__ ); 00529 return $text; 00530 } 00531 00537 function preprocess( $text, Title $title, ParserOptions $options, $revid = null ) { 00538 wfProfileIn( __METHOD__ ); 00539 $this->startParse( $title, $options, self::OT_PREPROCESS, true ); 00540 if ( $revid !== null ) { 00541 $this->mRevisionId = $revid; 00542 } 00543 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) ); 00544 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) ); 00545 $text = $this->replaceVariables( $text ); 00546 $text = $this->mStripState->unstripBoth( $text ); 00547 wfProfileOut( __METHOD__ ); 00548 return $text; 00549 } 00550 00560 public function recursivePreprocess( $text, $frame = false ) { 00561 wfProfileIn( __METHOD__ ); 00562 $text = $this->replaceVariables( $text, $frame ); 00563 $text = $this->mStripState->unstripBoth( $text ); 00564 wfProfileOut( __METHOD__ ); 00565 return $text; 00566 } 00567 00580 public function getPreloadText( $text, Title $title, ParserOptions $options ) { 00581 # Parser (re)initialisation 00582 $this->startParse( $title, $options, self::OT_PLAIN, true ); 00583 00584 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES; 00585 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 00586 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags ); 00587 $text = $this->mStripState->unstripBoth( $text ); 00588 return $text; 00589 } 00590 00596 static public function getRandomString() { 00597 return wfRandomString( 16 ); 00598 } 00599 00606 function setUser( $user ) { 00607 $this->mUser = $user; 00608 } 00609 00615 public function uniqPrefix() { 00616 if ( !isset( $this->mUniqPrefix ) ) { 00617 # @todo FIXME: This is probably *horribly wrong* 00618 # LanguageConverter seems to want $wgParser's uniqPrefix, however 00619 # if this is called for a parser cache hit, the parser may not 00620 # have ever been initialized in the first place. 00621 # Not really sure what the heck is supposed to be going on here. 00622 return ''; 00623 # throw new MWException( "Accessing uninitialized mUniqPrefix" ); 00624 } 00625 return $this->mUniqPrefix; 00626 } 00627 00633 function setTitle( $t ) { 00634 if ( !$t || $t instanceof FakeTitle ) { 00635 $t = Title::newFromText( 'NO TITLE' ); 00636 } 00637 00638 if ( strval( $t->getFragment() ) !== '' ) { 00639 # Strip the fragment to avoid various odd effects 00640 $this->mTitle = clone $t; 00641 $this->mTitle->setFragment( '' ); 00642 } else { 00643 $this->mTitle = $t; 00644 } 00645 } 00646 00652 function getTitle() { 00653 return $this->mTitle; 00654 } 00655 00662 function Title( $x = null ) { 00663 return wfSetVar( $this->mTitle, $x ); 00664 } 00665 00671 function setOutputType( $ot ) { 00672 $this->mOutputType = $ot; 00673 # Shortcut alias 00674 $this->ot = array( 00675 'html' => $ot == self::OT_HTML, 00676 'wiki' => $ot == self::OT_WIKI, 00677 'pre' => $ot == self::OT_PREPROCESS, 00678 'plain' => $ot == self::OT_PLAIN, 00679 ); 00680 } 00681 00688 function OutputType( $x = null ) { 00689 return wfSetVar( $this->mOutputType, $x ); 00690 } 00691 00697 function getOutput() { 00698 return $this->mOutput; 00699 } 00700 00706 function getOptions() { 00707 return $this->mOptions; 00708 } 00709 00716 function Options( $x = null ) { 00717 return wfSetVar( $this->mOptions, $x ); 00718 } 00719 00723 function nextLinkID() { 00724 return $this->mLinkID++; 00725 } 00726 00730 function setLinkID( $id ) { 00731 $this->mLinkID = $id; 00732 } 00733 00738 function getFunctionLang() { 00739 return $this->getTargetLanguage(); 00740 } 00741 00750 public function getTargetLanguage() { 00751 $target = $this->mOptions->getTargetLanguage(); 00752 00753 if ( $target !== null ) { 00754 return $target; 00755 } elseif( $this->mOptions->getInterfaceMessage() ) { 00756 return $this->mOptions->getUserLangObj(); 00757 } elseif( is_null( $this->mTitle ) ) { 00758 throw new MWException( __METHOD__ . ': $this->mTitle is null' ); 00759 } 00760 00761 return $this->mTitle->getPageLanguage(); 00762 } 00763 00767 function getConverterLanguage() { 00768 global $wgBug34832TransitionalRollback, $wgContLang; 00769 if ( $wgBug34832TransitionalRollback ) { 00770 return $wgContLang; 00771 } else { 00772 return $this->getTargetLanguage(); 00773 } 00774 } 00775 00782 function getUser() { 00783 if ( !is_null( $this->mUser ) ) { 00784 return $this->mUser; 00785 } 00786 return $this->mOptions->getUser(); 00787 } 00788 00794 function getPreprocessor() { 00795 if ( !isset( $this->mPreprocessor ) ) { 00796 $class = $this->mPreprocessorClass; 00797 $this->mPreprocessor = new $class( $this ); 00798 } 00799 return $this->mPreprocessor; 00800 } 00801 00822 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) { 00823 static $n = 1; 00824 $stripped = ''; 00825 $matches = array(); 00826 00827 $taglist = implode( '|', $elements ); 00828 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i"; 00829 00830 while ( $text != '' ) { 00831 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE ); 00832 $stripped .= $p[0]; 00833 if ( count( $p ) < 5 ) { 00834 break; 00835 } 00836 if ( count( $p ) > 5 ) { 00837 # comment 00838 $element = $p[4]; 00839 $attributes = ''; 00840 $close = ''; 00841 $inside = $p[5]; 00842 } else { 00843 # tag 00844 $element = $p[1]; 00845 $attributes = $p[2]; 00846 $close = $p[3]; 00847 $inside = $p[4]; 00848 } 00849 00850 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX; 00851 $stripped .= $marker; 00852 00853 if ( $close === '/>' ) { 00854 # Empty element tag, <tag /> 00855 $content = null; 00856 $text = $inside; 00857 $tail = null; 00858 } else { 00859 if ( $element === '!--' ) { 00860 $end = '/(-->)/'; 00861 } else { 00862 $end = "/(<\\/$element\\s*>)/i"; 00863 } 00864 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE ); 00865 $content = $q[0]; 00866 if ( count( $q ) < 3 ) { 00867 # No end tag -- let it run out to the end of the text. 00868 $tail = ''; 00869 $text = ''; 00870 } else { 00871 $tail = $q[1]; 00872 $text = $q[2]; 00873 } 00874 } 00875 00876 $matches[$marker] = array( $element, 00877 $content, 00878 Sanitizer::decodeTagAttributes( $attributes ), 00879 "<$element$attributes$close$content$tail" ); 00880 } 00881 return $stripped; 00882 } 00883 00889 function getStripList() { 00890 return $this->mStripList; 00891 } 00892 00902 function insertStripItem( $text ) { 00903 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX; 00904 $this->mMarkerIndex++; 00905 $this->mStripState->addGeneral( $rnd, $text ); 00906 return $rnd; 00907 } 00908 00915 function doTableStuff( $text ) { 00916 wfProfileIn( __METHOD__ ); 00917 00918 $lines = StringUtils::explode( "\n", $text ); 00919 $out = ''; 00920 $td_history = array(); # Is currently a td tag open? 00921 $last_tag_history = array(); # Save history of last lag activated (td, th or caption) 00922 $tr_history = array(); # Is currently a tr tag open? 00923 $tr_attributes = array(); # history of tr attributes 00924 $has_opened_tr = array(); # Did this table open a <tr> element? 00925 $indent_level = 0; # indent level of the table 00926 00927 foreach ( $lines as $outLine ) { 00928 $line = trim( $outLine ); 00929 00930 if ( $line === '' ) { # empty line, go to next line 00931 $out .= $outLine."\n"; 00932 continue; 00933 } 00934 00935 $first_character = $line[0]; 00936 $matches = array(); 00937 00938 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) { 00939 # First check if we are starting a new table 00940 $indent_level = strlen( $matches[1] ); 00941 00942 $attributes = $this->mStripState->unstripBoth( $matches[2] ); 00943 $attributes = Sanitizer::fixTagAttributes( $attributes , 'table' ); 00944 00945 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>"; 00946 array_push( $td_history , false ); 00947 array_push( $last_tag_history , '' ); 00948 array_push( $tr_history , false ); 00949 array_push( $tr_attributes , '' ); 00950 array_push( $has_opened_tr , false ); 00951 } elseif ( count( $td_history ) == 0 ) { 00952 # Don't do any of the following 00953 $out .= $outLine."\n"; 00954 continue; 00955 } elseif ( substr( $line , 0 , 2 ) === '|}' ) { 00956 # We are ending a table 00957 $line = '</table>' . substr( $line , 2 ); 00958 $last_tag = array_pop( $last_tag_history ); 00959 00960 if ( !array_pop( $has_opened_tr ) ) { 00961 $line = "<tr><td></td></tr>{$line}"; 00962 } 00963 00964 if ( array_pop( $tr_history ) ) { 00965 $line = "</tr>{$line}"; 00966 } 00967 00968 if ( array_pop( $td_history ) ) { 00969 $line = "</{$last_tag}>{$line}"; 00970 } 00971 array_pop( $tr_attributes ); 00972 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level ); 00973 } elseif ( substr( $line , 0 , 2 ) === '|-' ) { 00974 # Now we have a table row 00975 $line = preg_replace( '#^\|-+#', '', $line ); 00976 00977 # Whats after the tag is now only attributes 00978 $attributes = $this->mStripState->unstripBoth( $line ); 00979 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' ); 00980 array_pop( $tr_attributes ); 00981 array_push( $tr_attributes, $attributes ); 00982 00983 $line = ''; 00984 $last_tag = array_pop( $last_tag_history ); 00985 array_pop( $has_opened_tr ); 00986 array_push( $has_opened_tr , true ); 00987 00988 if ( array_pop( $tr_history ) ) { 00989 $line = '</tr>'; 00990 } 00991 00992 if ( array_pop( $td_history ) ) { 00993 $line = "</{$last_tag}>{$line}"; 00994 } 00995 00996 $outLine = $line; 00997 array_push( $tr_history , false ); 00998 array_push( $td_history , false ); 00999 array_push( $last_tag_history , '' ); 01000 } elseif ( $first_character === '|' || $first_character === '!' || substr( $line , 0 , 2 ) === '|+' ) { 01001 # This might be cell elements, td, th or captions 01002 if ( substr( $line , 0 , 2 ) === '|+' ) { 01003 $first_character = '+'; 01004 $line = substr( $line , 1 ); 01005 } 01006 01007 $line = substr( $line , 1 ); 01008 01009 if ( $first_character === '!' ) { 01010 $line = str_replace( '!!' , '||' , $line ); 01011 } 01012 01013 # Split up multiple cells on the same line. 01014 # FIXME : This can result in improper nesting of tags processed 01015 # by earlier parser steps, but should avoid splitting up eg 01016 # attribute values containing literal "||". 01017 $cells = StringUtils::explodeMarkup( '||' , $line ); 01018 01019 $outLine = ''; 01020 01021 # Loop through each table cell 01022 foreach ( $cells as $cell ) { 01023 $previous = ''; 01024 if ( $first_character !== '+' ) { 01025 $tr_after = array_pop( $tr_attributes ); 01026 if ( !array_pop( $tr_history ) ) { 01027 $previous = "<tr{$tr_after}>\n"; 01028 } 01029 array_push( $tr_history , true ); 01030 array_push( $tr_attributes , '' ); 01031 array_pop( $has_opened_tr ); 01032 array_push( $has_opened_tr , true ); 01033 } 01034 01035 $last_tag = array_pop( $last_tag_history ); 01036 01037 if ( array_pop( $td_history ) ) { 01038 $previous = "</{$last_tag}>\n{$previous}"; 01039 } 01040 01041 if ( $first_character === '|' ) { 01042 $last_tag = 'td'; 01043 } elseif ( $first_character === '!' ) { 01044 $last_tag = 'th'; 01045 } elseif ( $first_character === '+' ) { 01046 $last_tag = 'caption'; 01047 } else { 01048 $last_tag = ''; 01049 } 01050 01051 array_push( $last_tag_history , $last_tag ); 01052 01053 # A cell could contain both parameters and data 01054 $cell_data = explode( '|' , $cell , 2 ); 01055 01056 # Bug 553: Note that a '|' inside an invalid link should not 01057 # be mistaken as delimiting cell parameters 01058 if ( strpos( $cell_data[0], '[[' ) !== false ) { 01059 $cell = "{$previous}<{$last_tag}>{$cell}"; 01060 } elseif ( count( $cell_data ) == 1 ) { 01061 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}"; 01062 } else { 01063 $attributes = $this->mStripState->unstripBoth( $cell_data[0] ); 01064 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag ); 01065 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}"; 01066 } 01067 01068 $outLine .= $cell; 01069 array_push( $td_history , true ); 01070 } 01071 } 01072 $out .= $outLine . "\n"; 01073 } 01074 01075 # Closing open td, tr && table 01076 while ( count( $td_history ) > 0 ) { 01077 if ( array_pop( $td_history ) ) { 01078 $out .= "</td>\n"; 01079 } 01080 if ( array_pop( $tr_history ) ) { 01081 $out .= "</tr>\n"; 01082 } 01083 if ( !array_pop( $has_opened_tr ) ) { 01084 $out .= "<tr><td></td></tr>\n" ; 01085 } 01086 01087 $out .= "</table>\n"; 01088 } 01089 01090 # Remove trailing line-ending (b/c) 01091 if ( substr( $out, -1 ) === "\n" ) { 01092 $out = substr( $out, 0, -1 ); 01093 } 01094 01095 # special case: don't return empty table 01096 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) { 01097 $out = ''; 01098 } 01099 01100 wfProfileOut( __METHOD__ ); 01101 01102 return $out; 01103 } 01104 01117 function internalParse( $text, $isMain = true, $frame = false ) { 01118 wfProfileIn( __METHOD__ ); 01119 01120 $origText = $text; 01121 01122 # Hook to suspend the parser in this state 01123 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) { 01124 wfProfileOut( __METHOD__ ); 01125 return $text ; 01126 } 01127 01128 # if $frame is provided, then use $frame for replacing any variables 01129 if ( $frame ) { 01130 # use frame depth to infer how include/noinclude tags should be handled 01131 # depth=0 means this is the top-level document; otherwise it's an included document 01132 if ( !$frame->depth ) { 01133 $flag = 0; 01134 } else { 01135 $flag = Parser::PTD_FOR_INCLUSION; 01136 } 01137 $dom = $this->preprocessToDom( $text, $flag ); 01138 $text = $frame->expand( $dom ); 01139 } else { 01140 # if $frame is not provided, then use old-style replaceVariables 01141 $text = $this->replaceVariables( $text ); 01142 } 01143 01144 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) ); 01145 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) ); 01146 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) ); 01147 01148 # Tables need to come after variable replacement for things to work 01149 # properly; putting them before other transformations should keep 01150 # exciting things like link expansions from showing up in surprising 01151 # places. 01152 $text = $this->doTableStuff( $text ); 01153 01154 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text ); 01155 01156 $text = $this->doDoubleUnderscore( $text ); 01157 01158 $text = $this->doHeadings( $text ); 01159 if ( $this->mOptions->getUseDynamicDates() ) { 01160 $df = DateFormatter::getInstance(); 01161 $text = $df->reformat( $this->mOptions->getDateFormat(), $text ); 01162 } 01163 $text = $this->replaceInternalLinks( $text ); 01164 $text = $this->doAllQuotes( $text ); 01165 $text = $this->replaceExternalLinks( $text ); 01166 01167 # replaceInternalLinks may sometimes leave behind 01168 # absolute URLs, which have to be masked to hide them from replaceExternalLinks 01169 $text = str_replace( $this->mUniqPrefix.'NOPARSE', '', $text ); 01170 01171 $text = $this->doMagicLinks( $text ); 01172 $text = $this->formatHeadings( $text, $origText, $isMain ); 01173 01174 wfProfileOut( __METHOD__ ); 01175 return $text; 01176 } 01177 01189 function doMagicLinks( $text ) { 01190 wfProfileIn( __METHOD__ ); 01191 $prots = wfUrlProtocolsWithoutProtRel(); 01192 $urlChar = self::EXT_LINK_URL_CLASS; 01193 $text = preg_replace_callback( 01194 '!(?: # Start cases 01195 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text 01196 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . " 01197 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . ' 01198 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number 01199 ISBN\s+(\b # m[5]: ISBN, capture number 01200 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix 01201 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters 01202 [0-9Xx] # check digit 01203 \b) 01204 )!xu', array( &$this, 'magicLinkCallback' ), $text ); 01205 wfProfileOut( __METHOD__ ); 01206 return $text; 01207 } 01208 01214 function magicLinkCallback( $m ) { 01215 if ( isset( $m[1] ) && $m[1] !== '' ) { 01216 # Skip anchor 01217 return $m[0]; 01218 } elseif ( isset( $m[2] ) && $m[2] !== '' ) { 01219 # Skip HTML element 01220 return $m[0]; 01221 } elseif ( isset( $m[3] ) && $m[3] !== '' ) { 01222 # Free external link 01223 return $this->makeFreeExternalLink( $m[0] ); 01224 } elseif ( isset( $m[4] ) && $m[4] !== '' ) { 01225 # RFC or PMID 01226 if ( substr( $m[0], 0, 3 ) === 'RFC' ) { 01227 $keyword = 'RFC'; 01228 $urlmsg = 'rfcurl'; 01229 $CssClass = 'mw-magiclink-rfc'; 01230 $id = $m[4]; 01231 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) { 01232 $keyword = 'PMID'; 01233 $urlmsg = 'pubmedurl'; 01234 $CssClass = 'mw-magiclink-pmid'; 01235 $id = $m[4]; 01236 } else { 01237 throw new MWException( __METHOD__.': unrecognised match type "' . 01238 substr( $m[0], 0, 20 ) . '"' ); 01239 } 01240 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text(); 01241 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass ); 01242 } elseif ( isset( $m[5] ) && $m[5] !== '' ) { 01243 # ISBN 01244 $isbn = $m[5]; 01245 $num = strtr( $isbn, array( 01246 '-' => '', 01247 ' ' => '', 01248 'x' => 'X', 01249 )); 01250 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num ); 01251 return'<a href="' . 01252 htmlspecialchars( $titleObj->getLocalUrl() ) . 01253 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>"; 01254 } else { 01255 return $m[0]; 01256 } 01257 } 01258 01267 function makeFreeExternalLink( $url ) { 01268 wfProfileIn( __METHOD__ ); 01269 01270 $trail = ''; 01271 01272 # The characters '<' and '>' (which were escaped by 01273 # removeHTMLtags()) should not be included in 01274 # URLs, per RFC 2396. 01275 $m2 = array(); 01276 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) { 01277 $trail = substr( $url, $m2[0][1] ) . $trail; 01278 $url = substr( $url, 0, $m2[0][1] ); 01279 } 01280 01281 # Move trailing punctuation to $trail 01282 $sep = ',;\.:!?'; 01283 # If there is no left bracket, then consider right brackets fair game too 01284 if ( strpos( $url, '(' ) === false ) { 01285 $sep .= ')'; 01286 } 01287 01288 $numSepChars = strspn( strrev( $url ), $sep ); 01289 if ( $numSepChars ) { 01290 $trail = substr( $url, -$numSepChars ) . $trail; 01291 $url = substr( $url, 0, -$numSepChars ); 01292 } 01293 01294 $url = Sanitizer::cleanUrl( $url ); 01295 01296 # Is this an external image? 01297 $text = $this->maybeMakeExternalImage( $url ); 01298 if ( $text === false ) { 01299 # Not an image, make a link 01300 $text = Linker::makeExternalLink( $url, 01301 $this->getConverterLanguage()->markNoConversion($url), true, 'free', 01302 $this->getExternalLinkAttribs( $url ) ); 01303 # Register it in the output object... 01304 # Replace unnecessary URL escape codes with their equivalent characters 01305 $pasteurized = self::replaceUnusualEscapes( $url ); 01306 $this->mOutput->addExternalLink( $pasteurized ); 01307 } 01308 wfProfileOut( __METHOD__ ); 01309 return $text . $trail; 01310 } 01311 01312 01322 function doHeadings( $text ) { 01323 wfProfileIn( __METHOD__ ); 01324 for ( $i = 6; $i >= 1; --$i ) { 01325 $h = str_repeat( '=', $i ); 01326 $text = preg_replace( "/^$h(.+)$h\\s*$/m", 01327 "<h$i>\\1</h$i>", $text ); 01328 } 01329 wfProfileOut( __METHOD__ ); 01330 return $text; 01331 } 01332 01341 function doAllQuotes( $text ) { 01342 wfProfileIn( __METHOD__ ); 01343 $outtext = ''; 01344 $lines = StringUtils::explode( "\n", $text ); 01345 foreach ( $lines as $line ) { 01346 $outtext .= $this->doQuotes( $line ) . "\n"; 01347 } 01348 $outtext = substr( $outtext, 0,-1 ); 01349 wfProfileOut( __METHOD__ ); 01350 return $outtext; 01351 } 01352 01360 public function doQuotes( $text ) { 01361 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE ); 01362 if ( count( $arr ) == 1 ) { 01363 return $text; 01364 } else { 01365 # First, do some preliminary work. This may shift some apostrophes from 01366 # being mark-up to being text. It also counts the number of occurrences 01367 # of bold and italics mark-ups. 01368 $numbold = 0; 01369 $numitalics = 0; 01370 for ( $i = 0; $i < count( $arr ); $i++ ) { 01371 if ( ( $i % 2 ) == 1 ) { 01372 # If there are ever four apostrophes, assume the first is supposed to 01373 # be text, and the remaining three constitute mark-up for bold text. 01374 if ( strlen( $arr[$i] ) == 4 ) { 01375 $arr[$i-1] .= "'"; 01376 $arr[$i] = "'''"; 01377 } elseif ( strlen( $arr[$i] ) > 5 ) { 01378 # If there are more than 5 apostrophes in a row, assume they're all 01379 # text except for the last 5. 01380 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 ); 01381 $arr[$i] = "'''''"; 01382 } 01383 # Count the number of occurrences of bold and italics mark-ups. 01384 # We are not counting sequences of five apostrophes. 01385 if ( strlen( $arr[$i] ) == 2 ) { 01386 $numitalics++; 01387 } elseif ( strlen( $arr[$i] ) == 3 ) { 01388 $numbold++; 01389 } elseif ( strlen( $arr[$i] ) == 5 ) { 01390 $numitalics++; 01391 $numbold++; 01392 } 01393 } 01394 } 01395 01396 # If there is an odd number of both bold and italics, it is likely 01397 # that one of the bold ones was meant to be an apostrophe followed 01398 # by italics. Which one we cannot know for certain, but it is more 01399 # likely to be one that has a single-letter word before it. 01400 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) { 01401 $i = 0; 01402 $firstsingleletterword = -1; 01403 $firstmultiletterword = -1; 01404 $firstspace = -1; 01405 foreach ( $arr as $r ) { 01406 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) { 01407 $x1 = substr( $arr[$i-1], -1 ); 01408 $x2 = substr( $arr[$i-1], -2, 1 ); 01409 if ( $x1 === ' ' ) { 01410 if ( $firstspace == -1 ) { 01411 $firstspace = $i; 01412 } 01413 } elseif ( $x2 === ' ') { 01414 if ( $firstsingleletterword == -1 ) { 01415 $firstsingleletterword = $i; 01416 } 01417 } else { 01418 if ( $firstmultiletterword == -1 ) { 01419 $firstmultiletterword = $i; 01420 } 01421 } 01422 } 01423 $i++; 01424 } 01425 01426 # If there is a single-letter word, use it! 01427 if ( $firstsingleletterword > -1 ) { 01428 $arr[$firstsingleletterword] = "''"; 01429 $arr[$firstsingleletterword-1] .= "'"; 01430 } elseif ( $firstmultiletterword > -1 ) { 01431 # If not, but there's a multi-letter word, use that one. 01432 $arr[$firstmultiletterword] = "''"; 01433 $arr[$firstmultiletterword-1] .= "'"; 01434 } elseif ( $firstspace > -1 ) { 01435 # ... otherwise use the first one that has neither. 01436 # (notice that it is possible for all three to be -1 if, for example, 01437 # there is only one pentuple-apostrophe in the line) 01438 $arr[$firstspace] = "''"; 01439 $arr[$firstspace-1] .= "'"; 01440 } 01441 } 01442 01443 # Now let's actually convert our apostrophic mush to HTML! 01444 $output = ''; 01445 $buffer = ''; 01446 $state = ''; 01447 $i = 0; 01448 foreach ( $arr as $r ) { 01449 if ( ( $i % 2 ) == 0 ) { 01450 if ( $state === 'both' ) { 01451 $buffer .= $r; 01452 } else { 01453 $output .= $r; 01454 } 01455 } else { 01456 if ( strlen( $r ) == 2 ) { 01457 if ( $state === 'i' ) { 01458 $output .= '</i>'; $state = ''; 01459 } elseif ( $state === 'bi' ) { 01460 $output .= '</i>'; $state = 'b'; 01461 } elseif ( $state === 'ib' ) { 01462 $output .= '</b></i><b>'; $state = 'b'; 01463 } elseif ( $state === 'both' ) { 01464 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; 01465 } else { # $state can be 'b' or '' 01466 $output .= '<i>'; $state .= 'i'; 01467 } 01468 } elseif ( strlen( $r ) == 3 ) { 01469 if ( $state === 'b' ) { 01470 $output .= '</b>'; $state = ''; 01471 } elseif ( $state === 'bi' ) { 01472 $output .= '</i></b><i>'; $state = 'i'; 01473 } elseif ( $state === 'ib' ) { 01474 $output .= '</b>'; $state = 'i'; 01475 } elseif ( $state === 'both' ) { 01476 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; 01477 } else { # $state can be 'i' or '' 01478 $output .= '<b>'; $state .= 'b'; 01479 } 01480 } elseif ( strlen( $r ) == 5 ) { 01481 if ( $state === 'b' ) { 01482 $output .= '</b><i>'; $state = 'i'; 01483 } elseif ( $state === 'i' ) { 01484 $output .= '</i><b>'; $state = 'b'; 01485 } elseif ( $state === 'bi' ) { 01486 $output .= '</i></b>'; $state = ''; 01487 } elseif ( $state === 'ib' ) { 01488 $output .= '</b></i>'; $state = ''; 01489 } elseif ( $state === 'both' ) { 01490 $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; 01491 } else { # ($state == '') 01492 $buffer = ''; $state = 'both'; 01493 } 01494 } 01495 } 01496 $i++; 01497 } 01498 # Now close all remaining tags. Notice that the order is important. 01499 if ( $state === 'b' || $state === 'ib' ) { 01500 $output .= '</b>'; 01501 } 01502 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) { 01503 $output .= '</i>'; 01504 } 01505 if ( $state === 'bi' ) { 01506 $output .= '</b>'; 01507 } 01508 # There might be lonely ''''', so make sure we have a buffer 01509 if ( $state === 'both' && $buffer ) { 01510 $output .= '<b><i>'.$buffer.'</i></b>'; 01511 } 01512 return $output; 01513 } 01514 } 01515 01528 function replaceExternalLinks( $text ) { 01529 wfProfileIn( __METHOD__ ); 01530 01531 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE ); 01532 if ( $bits === false ) { 01533 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" ); 01534 } 01535 $s = array_shift( $bits ); 01536 01537 $i = 0; 01538 while ( $i<count( $bits ) ) { 01539 $url = $bits[$i++]; 01540 $protocol = $bits[$i++]; 01541 $text = $bits[$i++]; 01542 $trail = $bits[$i++]; 01543 01544 # The characters '<' and '>' (which were escaped by 01545 # removeHTMLtags()) should not be included in 01546 # URLs, per RFC 2396. 01547 $m2 = array(); 01548 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) { 01549 $text = substr( $url, $m2[0][1] ) . ' ' . $text; 01550 $url = substr( $url, 0, $m2[0][1] ); 01551 } 01552 01553 # If the link text is an image URL, replace it with an <img> tag 01554 # This happened by accident in the original parser, but some people used it extensively 01555 $img = $this->maybeMakeExternalImage( $text ); 01556 if ( $img !== false ) { 01557 $text = $img; 01558 } 01559 01560 $dtrail = ''; 01561 01562 # Set linktype for CSS - if URL==text, link is essentially free 01563 $linktype = ( $text === $url ) ? 'free' : 'text'; 01564 01565 # No link text, e.g. [http://domain.tld/some.link] 01566 if ( $text == '' ) { 01567 # Autonumber 01568 $langObj = $this->getTargetLanguage(); 01569 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']'; 01570 $linktype = 'autonumber'; 01571 } else { 01572 # Have link text, e.g. [http://domain.tld/some.link text]s 01573 # Check for trail 01574 list( $dtrail, $trail ) = Linker::splitTrail( $trail ); 01575 } 01576 01577 $text = $this->getConverterLanguage()->markNoConversion( $text ); 01578 01579 $url = Sanitizer::cleanUrl( $url ); 01580 01581 # Use the encoded URL 01582 # This means that users can paste URLs directly into the text 01583 # Funny characters like ö aren't valid in URLs anyway 01584 # This was changed in August 2004 01585 $s .= Linker::makeExternalLink( $url, $text, false, $linktype, 01586 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail; 01587 01588 # Register link in the output object. 01589 # Replace unnecessary URL escape codes with the referenced character 01590 # This prevents spammers from hiding links from the filters 01591 $pasteurized = self::replaceUnusualEscapes( $url ); 01592 $this->mOutput->addExternalLink( $pasteurized ); 01593 } 01594 01595 wfProfileOut( __METHOD__ ); 01596 return $s; 01597 } 01598 01609 function getExternalLinkAttribs( $url = false ) { 01610 $attribs = array(); 01611 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions; 01612 $ns = $this->mTitle->getNamespace(); 01613 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) && 01614 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) ) 01615 { 01616 $attribs['rel'] = 'nofollow'; 01617 } 01618 if ( $this->mOptions->getExternalLinkTarget() ) { 01619 $attribs['target'] = $this->mOptions->getExternalLinkTarget(); 01620 } 01621 return $attribs; 01622 } 01623 01635 static function replaceUnusualEscapes( $url ) { 01636 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', 01637 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url ); 01638 } 01639 01648 private static function replaceUnusualEscapesCallback( $matches ) { 01649 $char = urldecode( $matches[0] ); 01650 $ord = ord( $char ); 01651 # Is it an unsafe or HTTP reserved character according to RFC 1738? 01652 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) { 01653 # No, shouldn't be escaped 01654 return $char; 01655 } else { 01656 # Yes, leave it escaped 01657 return $matches[0]; 01658 } 01659 } 01660 01670 function maybeMakeExternalImage( $url ) { 01671 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom(); 01672 $imagesexception = !empty( $imagesfrom ); 01673 $text = false; 01674 # $imagesfrom could be either a single string or an array of strings, parse out the latter 01675 if ( $imagesexception && is_array( $imagesfrom ) ) { 01676 $imagematch = false; 01677 foreach ( $imagesfrom as $match ) { 01678 if ( strpos( $url, $match ) === 0 ) { 01679 $imagematch = true; 01680 break; 01681 } 01682 } 01683 } elseif ( $imagesexception ) { 01684 $imagematch = ( strpos( $url, $imagesfrom ) === 0 ); 01685 } else { 01686 $imagematch = false; 01687 } 01688 if ( $this->mOptions->getAllowExternalImages() 01689 || ( $imagesexception && $imagematch ) ) { 01690 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) { 01691 # Image found 01692 $text = Linker::makeExternalImage( $url ); 01693 } 01694 } 01695 if ( !$text && $this->mOptions->getEnableImageWhitelist() 01696 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) { 01697 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() ); 01698 foreach ( $whitelist as $entry ) { 01699 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments 01700 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) { 01701 continue; 01702 } 01703 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) { 01704 # Image matches a whitelist entry 01705 $text = Linker::makeExternalImage( $url ); 01706 break; 01707 } 01708 } 01709 } 01710 return $text; 01711 } 01712 01722 function replaceInternalLinks( $s ) { 01723 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) ); 01724 return $s; 01725 } 01726 01733 function replaceInternalLinks2( &$s ) { 01734 wfProfileIn( __METHOD__ ); 01735 01736 wfProfileIn( __METHOD__.'-setup' ); 01737 static $tc = FALSE, $e1, $e1_img; 01738 # the % is needed to support urlencoded titles as well 01739 if ( !$tc ) { 01740 $tc = Title::legalChars() . '#%'; 01741 # Match a link having the form [[namespace:link|alternate]]trail 01742 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; 01743 # Match cases where there is no "]]", which might still be images 01744 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; 01745 } 01746 01747 $holders = new LinkHolderArray( $this ); 01748 01749 # split the entire text string on occurrences of [[ 01750 $a = StringUtils::explode( '[[', ' ' . $s ); 01751 # get the first element (all text up to first [[), and remove the space we added 01752 $s = $a->current(); 01753 $a->next(); 01754 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void" 01755 $s = substr( $s, 1 ); 01756 01757 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension(); 01758 $e2 = null; 01759 if ( $useLinkPrefixExtension ) { 01760 # Match the end of a line for a word that's not followed by whitespace, 01761 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched 01762 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text(); 01763 } 01764 01765 if ( is_null( $this->mTitle ) ) { 01766 wfProfileOut( __METHOD__.'-setup' ); 01767 wfProfileOut( __METHOD__ ); 01768 throw new MWException( __METHOD__.": \$this->mTitle is null\n" ); 01769 } 01770 $nottalk = !$this->mTitle->isTalkPage(); 01771 01772 if ( $useLinkPrefixExtension ) { 01773 $m = array(); 01774 if ( preg_match( $e2, $s, $m ) ) { 01775 $first_prefix = $m[2]; 01776 } else { 01777 $first_prefix = false; 01778 } 01779 } else { 01780 $prefix = ''; 01781 } 01782 01783 if ( $this->getConverterLanguage()->hasVariants() ) { 01784 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants( 01785 $this->mTitle->getPrefixedText() ); 01786 } else { 01787 $selflink = array( $this->mTitle->getPrefixedText() ); 01788 } 01789 $useSubpages = $this->areSubpagesAllowed(); 01790 wfProfileOut( __METHOD__.'-setup' ); 01791 01792 # Loop for each link 01793 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) { 01794 # Check for excessive memory usage 01795 if ( $holders->isBig() ) { 01796 # Too big 01797 # Do the existence check, replace the link holders and clear the array 01798 $holders->replace( $s ); 01799 $holders->clear(); 01800 } 01801 01802 if ( $useLinkPrefixExtension ) { 01803 wfProfileIn( __METHOD__.'-prefixhandling' ); 01804 if ( preg_match( $e2, $s, $m ) ) { 01805 $prefix = $m[2]; 01806 $s = $m[1]; 01807 } else { 01808 $prefix=''; 01809 } 01810 # first link 01811 if ( $first_prefix ) { 01812 $prefix = $first_prefix; 01813 $first_prefix = false; 01814 } 01815 wfProfileOut( __METHOD__.'-prefixhandling' ); 01816 } 01817 01818 $might_be_img = false; 01819 01820 wfProfileIn( __METHOD__."-e1" ); 01821 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt 01822 $text = $m[2]; 01823 # If we get a ] at the beginning of $m[3] that means we have a link that's something like: 01824 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up, 01825 # the real problem is with the $e1 regex 01826 # See bug 1300. 01827 # 01828 # Still some problems for cases where the ] is meant to be outside punctuation, 01829 # and no image is in sight. See bug 2095. 01830 # 01831 if ( $text !== '' && 01832 substr( $m[3], 0, 1 ) === ']' && 01833 strpos( $text, '[' ) !== false 01834 ) 01835 { 01836 $text .= ']'; # so that replaceExternalLinks($text) works later 01837 $m[3] = substr( $m[3], 1 ); 01838 } 01839 # fix up urlencoded title texts 01840 if ( strpos( $m[1], '%' ) !== false ) { 01841 # Should anchors '#' also be rejected? 01842 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) ); 01843 } 01844 $trail = $m[3]; 01845 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption 01846 $might_be_img = true; 01847 $text = $m[2]; 01848 if ( strpos( $m[1], '%' ) !== false ) { 01849 $m[1] = rawurldecode( $m[1] ); 01850 } 01851 $trail = ""; 01852 } else { # Invalid form; output directly 01853 $s .= $prefix . '[[' . $line ; 01854 wfProfileOut( __METHOD__."-e1" ); 01855 continue; 01856 } 01857 wfProfileOut( __METHOD__."-e1" ); 01858 wfProfileIn( __METHOD__."-misc" ); 01859 01860 # Don't allow internal links to pages containing 01861 # PROTO: where PROTO is a valid URL protocol; these 01862 # should be external links. 01863 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) { 01864 $s .= $prefix . '[[' . $line ; 01865 wfProfileOut( __METHOD__."-misc" ); 01866 continue; 01867 } 01868 01869 # Make subpage if necessary 01870 if ( $useSubpages ) { 01871 $link = $this->maybeDoSubpageLink( $m[1], $text ); 01872 } else { 01873 $link = $m[1]; 01874 } 01875 01876 $noforce = ( substr( $m[1], 0, 1 ) !== ':' ); 01877 if ( !$noforce ) { 01878 # Strip off leading ':' 01879 $link = substr( $link, 1 ); 01880 } 01881 01882 wfProfileOut( __METHOD__."-misc" ); 01883 wfProfileIn( __METHOD__."-title" ); 01884 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) ); 01885 if ( $nt === null ) { 01886 $s .= $prefix . '[[' . $line; 01887 wfProfileOut( __METHOD__."-title" ); 01888 continue; 01889 } 01890 01891 $ns = $nt->getNamespace(); 01892 $iw = $nt->getInterWiki(); 01893 wfProfileOut( __METHOD__."-title" ); 01894 01895 if ( $might_be_img ) { # if this is actually an invalid link 01896 wfProfileIn( __METHOD__."-might_be_img" ); 01897 if ( $ns == NS_FILE && $noforce ) { # but might be an image 01898 $found = false; 01899 while ( true ) { 01900 # look at the next 'line' to see if we can close it there 01901 $a->next(); 01902 $next_line = $a->current(); 01903 if ( $next_line === false || $next_line === null ) { 01904 break; 01905 } 01906 $m = explode( ']]', $next_line, 3 ); 01907 if ( count( $m ) == 3 ) { 01908 # the first ]] closes the inner link, the second the image 01909 $found = true; 01910 $text .= "[[{$m[0]}]]{$m[1]}"; 01911 $trail = $m[2]; 01912 break; 01913 } elseif ( count( $m ) == 2 ) { 01914 # if there's exactly one ]] that's fine, we'll keep looking 01915 $text .= "[[{$m[0]}]]{$m[1]}"; 01916 } else { 01917 # if $next_line is invalid too, we need look no further 01918 $text .= '[[' . $next_line; 01919 break; 01920 } 01921 } 01922 if ( !$found ) { 01923 # we couldn't find the end of this imageLink, so output it raw 01924 # but don't ignore what might be perfectly normal links in the text we've examined 01925 $holders->merge( $this->replaceInternalLinks2( $text ) ); 01926 $s .= "{$prefix}[[$link|$text"; 01927 # note: no $trail, because without an end, there *is* no trail 01928 wfProfileOut( __METHOD__."-might_be_img" ); 01929 continue; 01930 } 01931 } else { # it's not an image, so output it raw 01932 $s .= "{$prefix}[[$link|$text"; 01933 # note: no $trail, because without an end, there *is* no trail 01934 wfProfileOut( __METHOD__."-might_be_img" ); 01935 continue; 01936 } 01937 wfProfileOut( __METHOD__."-might_be_img" ); 01938 } 01939 01940 $wasblank = ( $text == '' ); 01941 if ( $wasblank ) { 01942 $text = $link; 01943 } else { 01944 # Bug 4598 madness. Handle the quotes only if they come from the alternate part 01945 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a> 01946 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']] 01947 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a> 01948 $text = $this->doQuotes( $text ); 01949 } 01950 01951 # Link not escaped by : , create the various objects 01952 if ( $noforce ) { 01953 # Interwikis 01954 wfProfileIn( __METHOD__."-interwiki" ); 01955 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) { 01956 $this->mOutput->addLanguageLink( $nt->getFullText() ); 01957 $s = rtrim( $s . $prefix ); 01958 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail; 01959 wfProfileOut( __METHOD__."-interwiki" ); 01960 continue; 01961 } 01962 wfProfileOut( __METHOD__."-interwiki" ); 01963 01964 if ( $ns == NS_FILE ) { 01965 wfProfileIn( __METHOD__."-image" ); 01966 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) { 01967 if ( $wasblank ) { 01968 # if no parameters were passed, $text 01969 # becomes something like "File:Foo.png", 01970 # which we don't want to pass on to the 01971 # image generator 01972 $text = ''; 01973 } else { 01974 # recursively parse links inside the image caption 01975 # actually, this will parse them in any other parameters, too, 01976 # but it might be hard to fix that, and it doesn't matter ATM 01977 $text = $this->replaceExternalLinks( $text ); 01978 $holders->merge( $this->replaceInternalLinks2( $text ) ); 01979 } 01980 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them 01981 $s .= $prefix . $this->armorLinks( 01982 $this->makeImage( $nt, $text, $holders ) ) . $trail; 01983 } else { 01984 $s .= $prefix . $trail; 01985 } 01986 wfProfileOut( __METHOD__."-image" ); 01987 continue; 01988 } 01989 01990 if ( $ns == NS_CATEGORY ) { 01991 wfProfileIn( __METHOD__."-category" ); 01992 $s = rtrim( $s . "\n" ); # bug 87 01993 01994 if ( $wasblank ) { 01995 $sortkey = $this->getDefaultSort(); 01996 } else { 01997 $sortkey = $text; 01998 } 01999 $sortkey = Sanitizer::decodeCharReferences( $sortkey ); 02000 $sortkey = str_replace( "\n", '', $sortkey ); 02001 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey ); 02002 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey ); 02003 02008 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail; 02009 02010 wfProfileOut( __METHOD__."-category" ); 02011 continue; 02012 } 02013 } 02014 02015 # Self-link checking 02016 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) { 02017 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) { 02018 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail ); 02019 continue; 02020 } 02021 } 02022 02023 # NS_MEDIA is a pseudo-namespace for linking directly to a file 02024 # @todo FIXME: Should do batch file existence checks, see comment below 02025 if ( $ns == NS_MEDIA ) { 02026 wfProfileIn( __METHOD__."-media" ); 02027 # Give extensions a chance to select the file revision for us 02028 $options = array(); 02029 $descQuery = false; 02030 wfRunHooks( 'BeforeParserFetchFileAndTitle', 02031 array( $this, $nt, &$options, &$descQuery ) ); 02032 # Fetch and register the file (file title may be different via hooks) 02033 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options ); 02034 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks 02035 $s .= $prefix . $this->armorLinks( 02036 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail; 02037 wfProfileOut( __METHOD__."-media" ); 02038 continue; 02039 } 02040 02041 wfProfileIn( __METHOD__."-always_known" ); 02042 # Some titles, such as valid special pages or files in foreign repos, should 02043 # be shown as bluelinks even though they're not included in the page table 02044 # 02045 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do 02046 # batch file existence checks for NS_FILE and NS_MEDIA 02047 if ( $iw == '' && $nt->isAlwaysKnown() ) { 02048 $this->mOutput->addLink( $nt ); 02049 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix ); 02050 } else { 02051 # Links will be added to the output link list after checking 02052 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix ); 02053 } 02054 wfProfileOut( __METHOD__."-always_known" ); 02055 } 02056 wfProfileOut( __METHOD__ ); 02057 return $holders; 02058 } 02059 02074 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) { 02075 list( $inside, $trail ) = Linker::splitTrail( $trail ); 02076 02077 if ( is_string( $query ) ) { 02078 $query = wfCgiToArray( $query ); 02079 } 02080 if ( $text == '' ) { 02081 $text = htmlspecialchars( $nt->getPrefixedText() ); 02082 } 02083 02084 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query ); 02085 02086 return $this->armorLinks( $link ) . $trail; 02087 } 02088 02099 function armorLinks( $text ) { 02100 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/', 02101 "{$this->mUniqPrefix}NOPARSE$1", $text ); 02102 } 02103 02108 function areSubpagesAllowed() { 02109 # Some namespaces don't allow subpages 02110 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() ); 02111 } 02112 02121 function maybeDoSubpageLink( $target, &$text ) { 02122 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text ); 02123 } 02124 02131 function closeParagraph() { 02132 $result = ''; 02133 if ( $this->mLastSection != '' ) { 02134 $result = '</' . $this->mLastSection . ">\n"; 02135 } 02136 $this->mInPre = false; 02137 $this->mLastSection = ''; 02138 return $result; 02139 } 02140 02151 function getCommon( $st1, $st2 ) { 02152 $fl = strlen( $st1 ); 02153 $shorter = strlen( $st2 ); 02154 if ( $fl < $shorter ) { 02155 $shorter = $fl; 02156 } 02157 02158 for ( $i = 0; $i < $shorter; ++$i ) { 02159 if ( $st1[$i] != $st2[$i] ) { 02160 break; 02161 } 02162 } 02163 return $i; 02164 } 02165 02175 function openList( $char ) { 02176 $result = $this->closeParagraph(); 02177 02178 if ( '*' === $char ) { 02179 $result .= '<ul><li>'; 02180 } elseif ( '#' === $char ) { 02181 $result .= '<ol><li>'; 02182 } elseif ( ':' === $char ) { 02183 $result .= '<dl><dd>'; 02184 } elseif ( ';' === $char ) { 02185 $result .= '<dl><dt>'; 02186 $this->mDTopen = true; 02187 } else { 02188 $result = '<!-- ERR 1 -->'; 02189 } 02190 02191 return $result; 02192 } 02193 02201 function nextItem( $char ) { 02202 if ( '*' === $char || '#' === $char ) { 02203 return '</li><li>'; 02204 } elseif ( ':' === $char || ';' === $char ) { 02205 $close = '</dd>'; 02206 if ( $this->mDTopen ) { 02207 $close = '</dt>'; 02208 } 02209 if ( ';' === $char ) { 02210 $this->mDTopen = true; 02211 return $close . '<dt>'; 02212 } else { 02213 $this->mDTopen = false; 02214 return $close . '<dd>'; 02215 } 02216 } 02217 return '<!-- ERR 2 -->'; 02218 } 02219 02227 function closeList( $char ) { 02228 if ( '*' === $char ) { 02229 $text = '</li></ul>'; 02230 } elseif ( '#' === $char ) { 02231 $text = '</li></ol>'; 02232 } elseif ( ':' === $char ) { 02233 if ( $this->mDTopen ) { 02234 $this->mDTopen = false; 02235 $text = '</dt></dl>'; 02236 } else { 02237 $text = '</dd></dl>'; 02238 } 02239 } else { 02240 return '<!-- ERR 3 -->'; 02241 } 02242 return $text."\n"; 02243 } 02254 function doBlockLevels( $text, $linestart ) { 02255 wfProfileIn( __METHOD__ ); 02256 02257 # Parsing through the text line by line. The main thing 02258 # happening here is handling of block-level elements p, pre, 02259 # and making lists from lines starting with * # : etc. 02260 # 02261 $textLines = StringUtils::explode( "\n", $text ); 02262 02263 $lastPrefix = $output = ''; 02264 $this->mDTopen = $inBlockElem = false; 02265 $prefixLength = 0; 02266 $paragraphStack = false; 02267 02268 foreach ( $textLines as $oLine ) { 02269 # Fix up $linestart 02270 if ( !$linestart ) { 02271 $output .= $oLine; 02272 $linestart = true; 02273 continue; 02274 } 02275 # * = ul 02276 # # = ol 02277 # ; = dt 02278 # : = dd 02279 02280 $lastPrefixLength = strlen( $lastPrefix ); 02281 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine ); 02282 $preOpenMatch = preg_match( '/<pre/i', $oLine ); 02283 # If not in a <pre> element, scan for and figure out what prefixes are there. 02284 if ( !$this->mInPre ) { 02285 # Multiple prefixes may abut each other for nested lists. 02286 $prefixLength = strspn( $oLine, '*#:;' ); 02287 $prefix = substr( $oLine, 0, $prefixLength ); 02288 02289 # eh? 02290 # ; and : are both from definition-lists, so they're equivalent 02291 # for the purposes of determining whether or not we need to open/close 02292 # elements. 02293 $prefix2 = str_replace( ';', ':', $prefix ); 02294 $t = substr( $oLine, $prefixLength ); 02295 $this->mInPre = (bool)$preOpenMatch; 02296 } else { 02297 # Don't interpret any other prefixes in preformatted text 02298 $prefixLength = 0; 02299 $prefix = $prefix2 = ''; 02300 $t = $oLine; 02301 } 02302 02303 # List generation 02304 if ( $prefixLength && $lastPrefix === $prefix2 ) { 02305 # Same as the last item, so no need to deal with nesting or opening stuff 02306 $output .= $this->nextItem( substr( $prefix, -1 ) ); 02307 $paragraphStack = false; 02308 02309 if ( substr( $prefix, -1 ) === ';') { 02310 # The one nasty exception: definition lists work like this: 02311 # ; title : definition text 02312 # So we check for : in the remainder text to split up the 02313 # title and definition, without b0rking links. 02314 $term = $t2 = ''; 02315 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) { 02316 $t = $t2; 02317 $output .= $term . $this->nextItem( ':' ); 02318 } 02319 } 02320 } elseif ( $prefixLength || $lastPrefixLength ) { 02321 # We need to open or close prefixes, or both. 02322 02323 # Either open or close a level... 02324 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix ); 02325 $paragraphStack = false; 02326 02327 # Close all the prefixes which aren't shared. 02328 while ( $commonPrefixLength < $lastPrefixLength ) { 02329 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] ); 02330 --$lastPrefixLength; 02331 } 02332 02333 # Continue the current prefix if appropriate. 02334 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) { 02335 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] ); 02336 } 02337 02338 # Open prefixes where appropriate. 02339 while ( $prefixLength > $commonPrefixLength ) { 02340 $char = substr( $prefix, $commonPrefixLength, 1 ); 02341 $output .= $this->openList( $char ); 02342 02343 if ( ';' === $char ) { 02344 # @todo FIXME: This is dupe of code above 02345 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) { 02346 $t = $t2; 02347 $output .= $term . $this->nextItem( ':' ); 02348 } 02349 } 02350 ++$commonPrefixLength; 02351 } 02352 $lastPrefix = $prefix2; 02353 } 02354 02355 # If we have no prefixes, go to paragraph mode. 02356 if ( 0 == $prefixLength ) { 02357 wfProfileIn( __METHOD__."-paragraph" ); 02358 # No prefix (not in list)--go to paragraph mode 02359 # XXX: use a stack for nestable elements like span, table and div 02360 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t ); 02361 $closematch = preg_match( 02362 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'. 02363 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t ); 02364 if ( $openmatch or $closematch ) { 02365 $paragraphStack = false; 02366 # TODO bug 5718: paragraph closed 02367 $output .= $this->closeParagraph(); 02368 if ( $preOpenMatch and !$preCloseMatch ) { 02369 $this->mInPre = true; 02370 } 02371 $inBlockElem = !$closematch; 02372 } elseif ( !$inBlockElem && !$this->mInPre ) { 02373 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) { 02374 # pre 02375 if ( $this->mLastSection !== 'pre' ) { 02376 $paragraphStack = false; 02377 $output .= $this->closeParagraph().'<pre>'; 02378 $this->mLastSection = 'pre'; 02379 } 02380 $t = substr( $t, 1 ); 02381 } else { 02382 # paragraph 02383 if ( trim( $t ) === '' ) { 02384 if ( $paragraphStack ) { 02385 $output .= $paragraphStack.'<br />'; 02386 $paragraphStack = false; 02387 $this->mLastSection = 'p'; 02388 } else { 02389 if ( $this->mLastSection !== 'p' ) { 02390 $output .= $this->closeParagraph(); 02391 $this->mLastSection = ''; 02392 $paragraphStack = '<p>'; 02393 } else { 02394 $paragraphStack = '</p><p>'; 02395 } 02396 } 02397 } else { 02398 if ( $paragraphStack ) { 02399 $output .= $paragraphStack; 02400 $paragraphStack = false; 02401 $this->mLastSection = 'p'; 02402 } elseif ( $this->mLastSection !== 'p' ) { 02403 $output .= $this->closeParagraph().'<p>'; 02404 $this->mLastSection = 'p'; 02405 } 02406 } 02407 } 02408 } 02409 wfProfileOut( __METHOD__."-paragraph" ); 02410 } 02411 # somewhere above we forget to get out of pre block (bug 785) 02412 if ( $preCloseMatch && $this->mInPre ) { 02413 $this->mInPre = false; 02414 } 02415 if ( $paragraphStack === false ) { 02416 $output .= $t."\n"; 02417 } 02418 } 02419 while ( $prefixLength ) { 02420 $output .= $this->closeList( $prefix2[$prefixLength-1] ); 02421 --$prefixLength; 02422 } 02423 if ( $this->mLastSection != '' ) { 02424 $output .= '</' . $this->mLastSection . '>'; 02425 $this->mLastSection = ''; 02426 } 02427 02428 wfProfileOut( __METHOD__ ); 02429 return $output; 02430 } 02431 02441 function findColonNoLinks( $str, &$before, &$after ) { 02442 wfProfileIn( __METHOD__ ); 02443 02444 $pos = strpos( $str, ':' ); 02445 if ( $pos === false ) { 02446 # Nothing to find! 02447 wfProfileOut( __METHOD__ ); 02448 return false; 02449 } 02450 02451 $lt = strpos( $str, '<' ); 02452 if ( $lt === false || $lt > $pos ) { 02453 # Easy; no tag nesting to worry about 02454 $before = substr( $str, 0, $pos ); 02455 $after = substr( $str, $pos+1 ); 02456 wfProfileOut( __METHOD__ ); 02457 return $pos; 02458 } 02459 02460 # Ugly state machine to walk through avoiding tags. 02461 $state = self::COLON_STATE_TEXT; 02462 $stack = 0; 02463 $len = strlen( $str ); 02464 for( $i = 0; $i < $len; $i++ ) { 02465 $c = $str[$i]; 02466 02467 switch( $state ) { 02468 # (Using the number is a performance hack for common cases) 02469 case 0: # self::COLON_STATE_TEXT: 02470 switch( $c ) { 02471 case "<": 02472 # Could be either a <start> tag or an </end> tag 02473 $state = self::COLON_STATE_TAGSTART; 02474 break; 02475 case ":": 02476 if ( $stack == 0 ) { 02477 # We found it! 02478 $before = substr( $str, 0, $i ); 02479 $after = substr( $str, $i + 1 ); 02480 wfProfileOut( __METHOD__ ); 02481 return $i; 02482 } 02483 # Embedded in a tag; don't break it. 02484 break; 02485 default: 02486 # Skip ahead looking for something interesting 02487 $colon = strpos( $str, ':', $i ); 02488 if ( $colon === false ) { 02489 # Nothing else interesting 02490 wfProfileOut( __METHOD__ ); 02491 return false; 02492 } 02493 $lt = strpos( $str, '<', $i ); 02494 if ( $stack === 0 ) { 02495 if ( $lt === false || $colon < $lt ) { 02496 # We found it! 02497 $before = substr( $str, 0, $colon ); 02498 $after = substr( $str, $colon + 1 ); 02499 wfProfileOut( __METHOD__ ); 02500 return $i; 02501 } 02502 } 02503 if ( $lt === false ) { 02504 # Nothing else interesting to find; abort! 02505 # We're nested, but there's no close tags left. Abort! 02506 break 2; 02507 } 02508 # Skip ahead to next tag start 02509 $i = $lt; 02510 $state = self::COLON_STATE_TAGSTART; 02511 } 02512 break; 02513 case 1: # self::COLON_STATE_TAG: 02514 # In a <tag> 02515 switch( $c ) { 02516 case ">": 02517 $stack++; 02518 $state = self::COLON_STATE_TEXT; 02519 break; 02520 case "/": 02521 # Slash may be followed by >? 02522 $state = self::COLON_STATE_TAGSLASH; 02523 break; 02524 default: 02525 # ignore 02526 } 02527 break; 02528 case 2: # self::COLON_STATE_TAGSTART: 02529 switch( $c ) { 02530 case "/": 02531 $state = self::COLON_STATE_CLOSETAG; 02532 break; 02533 case "!": 02534 $state = self::COLON_STATE_COMMENT; 02535 break; 02536 case ">": 02537 # Illegal early close? This shouldn't happen D: 02538 $state = self::COLON_STATE_TEXT; 02539 break; 02540 default: 02541 $state = self::COLON_STATE_TAG; 02542 } 02543 break; 02544 case 3: # self::COLON_STATE_CLOSETAG: 02545 # In a </tag> 02546 if ( $c === ">" ) { 02547 $stack--; 02548 if ( $stack < 0 ) { 02549 wfDebug( __METHOD__.": Invalid input; too many close tags\n" ); 02550 wfProfileOut( __METHOD__ ); 02551 return false; 02552 } 02553 $state = self::COLON_STATE_TEXT; 02554 } 02555 break; 02556 case self::COLON_STATE_TAGSLASH: 02557 if ( $c === ">" ) { 02558 # Yes, a self-closed tag <blah/> 02559 $state = self::COLON_STATE_TEXT; 02560 } else { 02561 # Probably we're jumping the gun, and this is an attribute 02562 $state = self::COLON_STATE_TAG; 02563 } 02564 break; 02565 case 5: # self::COLON_STATE_COMMENT: 02566 if ( $c === "-" ) { 02567 $state = self::COLON_STATE_COMMENTDASH; 02568 } 02569 break; 02570 case self::COLON_STATE_COMMENTDASH: 02571 if ( $c === "-" ) { 02572 $state = self::COLON_STATE_COMMENTDASHDASH; 02573 } else { 02574 $state = self::COLON_STATE_COMMENT; 02575 } 02576 break; 02577 case self::COLON_STATE_COMMENTDASHDASH: 02578 if ( $c === ">" ) { 02579 $state = self::COLON_STATE_TEXT; 02580 } else { 02581 $state = self::COLON_STATE_COMMENT; 02582 } 02583 break; 02584 default: 02585 throw new MWException( "State machine error in " . __METHOD__ ); 02586 } 02587 } 02588 if ( $stack > 0 ) { 02589 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" ); 02590 wfProfileOut( __METHOD__ ); 02591 return false; 02592 } 02593 wfProfileOut( __METHOD__ ); 02594 return false; 02595 } 02596 02607 function getVariableValue( $index, $frame = false ) { 02608 global $wgContLang, $wgSitename, $wgServer; 02609 global $wgArticlePath, $wgScriptPath, $wgStylePath; 02610 02611 if ( is_null( $this->mTitle ) ) { 02612 // If no title set, bad things are going to happen 02613 // later. Title should always be set since this 02614 // should only be called in the middle of a parse 02615 // operation (but the unit-tests do funky stuff) 02616 throw new MWException( __METHOD__ . ' Should only be ' 02617 . ' called while parsing (no title set)' ); 02618 } 02619 02624 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) { 02625 if ( isset( $this->mVarCache[$index] ) ) { 02626 return $this->mVarCache[$index]; 02627 } 02628 } 02629 02630 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() ); 02631 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) ); 02632 02633 # Use the time zone 02634 global $wgLocaltimezone; 02635 if ( isset( $wgLocaltimezone ) ) { 02636 $oldtz = date_default_timezone_get(); 02637 date_default_timezone_set( $wgLocaltimezone ); 02638 } 02639 02640 $localTimestamp = date( 'YmdHis', $ts ); 02641 $localMonth = date( 'm', $ts ); 02642 $localMonth1 = date( 'n', $ts ); 02643 $localMonthName = date( 'n', $ts ); 02644 $localDay = date( 'j', $ts ); 02645 $localDay2 = date( 'd', $ts ); 02646 $localDayOfWeek = date( 'w', $ts ); 02647 $localWeek = date( 'W', $ts ); 02648 $localYear = date( 'Y', $ts ); 02649 $localHour = date( 'H', $ts ); 02650 if ( isset( $wgLocaltimezone ) ) { 02651 date_default_timezone_set( $oldtz ); 02652 } 02653 02654 $pageLang = $this->getFunctionLang(); 02655 02656 switch ( $index ) { 02657 case 'currentmonth': 02658 $value = $pageLang->formatNum( gmdate( 'm', $ts ) ); 02659 break; 02660 case 'currentmonth1': 02661 $value = $pageLang->formatNum( gmdate( 'n', $ts ) ); 02662 break; 02663 case 'currentmonthname': 02664 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) ); 02665 break; 02666 case 'currentmonthnamegen': 02667 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) ); 02668 break; 02669 case 'currentmonthabbrev': 02670 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) ); 02671 break; 02672 case 'currentday': 02673 $value = $pageLang->formatNum( gmdate( 'j', $ts ) ); 02674 break; 02675 case 'currentday2': 02676 $value = $pageLang->formatNum( gmdate( 'd', $ts ) ); 02677 break; 02678 case 'localmonth': 02679 $value = $pageLang->formatNum( $localMonth ); 02680 break; 02681 case 'localmonth1': 02682 $value = $pageLang->formatNum( $localMonth1 ); 02683 break; 02684 case 'localmonthname': 02685 $value = $pageLang->getMonthName( $localMonthName ); 02686 break; 02687 case 'localmonthnamegen': 02688 $value = $pageLang->getMonthNameGen( $localMonthName ); 02689 break; 02690 case 'localmonthabbrev': 02691 $value = $pageLang->getMonthAbbreviation( $localMonthName ); 02692 break; 02693 case 'localday': 02694 $value = $pageLang->formatNum( $localDay ); 02695 break; 02696 case 'localday2': 02697 $value = $pageLang->formatNum( $localDay2 ); 02698 break; 02699 case 'pagename': 02700 $value = wfEscapeWikiText( $this->mTitle->getText() ); 02701 break; 02702 case 'pagenamee': 02703 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() ); 02704 break; 02705 case 'fullpagename': 02706 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() ); 02707 break; 02708 case 'fullpagenamee': 02709 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() ); 02710 break; 02711 case 'subpagename': 02712 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() ); 02713 break; 02714 case 'subpagenamee': 02715 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() ); 02716 break; 02717 case 'basepagename': 02718 $value = wfEscapeWikiText( $this->mTitle->getBaseText() ); 02719 break; 02720 case 'basepagenamee': 02721 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) ); 02722 break; 02723 case 'talkpagename': 02724 if ( $this->mTitle->canTalk() ) { 02725 $talkPage = $this->mTitle->getTalkPage(); 02726 $value = wfEscapeWikiText( $talkPage->getPrefixedText() ); 02727 } else { 02728 $value = ''; 02729 } 02730 break; 02731 case 'talkpagenamee': 02732 if ( $this->mTitle->canTalk() ) { 02733 $talkPage = $this->mTitle->getTalkPage(); 02734 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() ); 02735 } else { 02736 $value = ''; 02737 } 02738 break; 02739 case 'subjectpagename': 02740 $subjPage = $this->mTitle->getSubjectPage(); 02741 $value = wfEscapeWikiText( $subjPage->getPrefixedText() ); 02742 break; 02743 case 'subjectpagenamee': 02744 $subjPage = $this->mTitle->getSubjectPage(); 02745 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() ); 02746 break; 02747 case 'pageid': // requested in bug 23427 02748 $pageid = $this->getTitle()->getArticleId(); 02749 if( $pageid == 0 ) { 02750 # 0 means the page doesn't exist in the database, 02751 # which means the user is previewing a new page. 02752 # The vary-revision flag must be set, because the magic word 02753 # will have a different value once the page is saved. 02754 $this->mOutput->setFlag( 'vary-revision' ); 02755 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" ); 02756 } 02757 $value = $pageid ? $pageid : null; 02758 break; 02759 case 'revisionid': 02760 # Let the edit saving system know we should parse the page 02761 # *after* a revision ID has been assigned. 02762 $this->mOutput->setFlag( 'vary-revision' ); 02763 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" ); 02764 $value = $this->mRevisionId; 02765 break; 02766 case 'revisionday': 02767 # Let the edit saving system know we should parse the page 02768 # *after* a revision ID has been assigned. This is for null edits. 02769 $this->mOutput->setFlag( 'vary-revision' ); 02770 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" ); 02771 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) ); 02772 break; 02773 case 'revisionday2': 02774 # Let the edit saving system know we should parse the page 02775 # *after* a revision ID has been assigned. This is for null edits. 02776 $this->mOutput->setFlag( 'vary-revision' ); 02777 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" ); 02778 $value = substr( $this->getRevisionTimestamp(), 6, 2 ); 02779 break; 02780 case 'revisionmonth': 02781 # Let the edit saving system know we should parse the page 02782 # *after* a revision ID has been assigned. This is for null edits. 02783 $this->mOutput->setFlag( 'vary-revision' ); 02784 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" ); 02785 $value = substr( $this->getRevisionTimestamp(), 4, 2 ); 02786 break; 02787 case 'revisionmonth1': 02788 # Let the edit saving system know we should parse the page 02789 # *after* a revision ID has been assigned. This is for null edits. 02790 $this->mOutput->setFlag( 'vary-revision' ); 02791 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" ); 02792 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) ); 02793 break; 02794 case 'revisionyear': 02795 # Let the edit saving system know we should parse the page 02796 # *after* a revision ID has been assigned. This is for null edits. 02797 $this->mOutput->setFlag( 'vary-revision' ); 02798 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" ); 02799 $value = substr( $this->getRevisionTimestamp(), 0, 4 ); 02800 break; 02801 case 'revisiontimestamp': 02802 # Let the edit saving system know we should parse the page 02803 # *after* a revision ID has been assigned. This is for null edits. 02804 $this->mOutput->setFlag( 'vary-revision' ); 02805 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" ); 02806 $value = $this->getRevisionTimestamp(); 02807 break; 02808 case 'revisionuser': 02809 # Let the edit saving system know we should parse the page 02810 # *after* a revision ID has been assigned. This is for null edits. 02811 $this->mOutput->setFlag( 'vary-revision' ); 02812 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" ); 02813 $value = $this->getRevisionUser(); 02814 break; 02815 case 'namespace': 02816 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) ); 02817 break; 02818 case 'namespacee': 02819 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) ); 02820 break; 02821 case 'namespacenumber': 02822 $value = $this->mTitle->getNamespace(); 02823 break; 02824 case 'talkspace': 02825 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : ''; 02826 break; 02827 case 'talkspacee': 02828 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : ''; 02829 break; 02830 case 'subjectspace': 02831 $value = $this->mTitle->getSubjectNsText(); 02832 break; 02833 case 'subjectspacee': 02834 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) ); 02835 break; 02836 case 'currentdayname': 02837 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) + 1 ); 02838 break; 02839 case 'currentyear': 02840 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true ); 02841 break; 02842 case 'currenttime': 02843 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false ); 02844 break; 02845 case 'currenthour': 02846 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true ); 02847 break; 02848 case 'currentweek': 02849 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to 02850 # int to remove the padding 02851 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) ); 02852 break; 02853 case 'currentdow': 02854 $value = $pageLang->formatNum( gmdate( 'w', $ts ) ); 02855 break; 02856 case 'localdayname': 02857 $value = $pageLang->getWeekdayName( $localDayOfWeek + 1 ); 02858 break; 02859 case 'localyear': 02860 $value = $pageLang->formatNum( $localYear, true ); 02861 break; 02862 case 'localtime': 02863 $value = $pageLang->time( $localTimestamp, false, false ); 02864 break; 02865 case 'localhour': 02866 $value = $pageLang->formatNum( $localHour, true ); 02867 break; 02868 case 'localweek': 02869 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to 02870 # int to remove the padding 02871 $value = $pageLang->formatNum( (int)$localWeek ); 02872 break; 02873 case 'localdow': 02874 $value = $pageLang->formatNum( $localDayOfWeek ); 02875 break; 02876 case 'numberofarticles': 02877 $value = $pageLang->formatNum( SiteStats::articles() ); 02878 break; 02879 case 'numberoffiles': 02880 $value = $pageLang->formatNum( SiteStats::images() ); 02881 break; 02882 case 'numberofusers': 02883 $value = $pageLang->formatNum( SiteStats::users() ); 02884 break; 02885 case 'numberofactiveusers': 02886 $value = $pageLang->formatNum( SiteStats::activeUsers() ); 02887 break; 02888 case 'numberofpages': 02889 $value = $pageLang->formatNum( SiteStats::pages() ); 02890 break; 02891 case 'numberofadmins': 02892 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) ); 02893 break; 02894 case 'numberofedits': 02895 $value = $pageLang->formatNum( SiteStats::edits() ); 02896 break; 02897 case 'numberofviews': 02898 global $wgDisableCounters; 02899 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : ''; 02900 break; 02901 case 'currenttimestamp': 02902 $value = wfTimestamp( TS_MW, $ts ); 02903 break; 02904 case 'localtimestamp': 02905 $value = $localTimestamp; 02906 break; 02907 case 'currentversion': 02908 $value = SpecialVersion::getVersion(); 02909 break; 02910 case 'articlepath': 02911 return $wgArticlePath; 02912 case 'sitename': 02913 return $wgSitename; 02914 case 'server': 02915 return $wgServer; 02916 case 'servername': 02917 $serverParts = wfParseUrl( $wgServer ); 02918 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer; 02919 case 'scriptpath': 02920 return $wgScriptPath; 02921 case 'stylepath': 02922 return $wgStylePath; 02923 case 'directionmark': 02924 return $pageLang->getDirMark(); 02925 case 'contentlanguage': 02926 global $wgLanguageCode; 02927 return $wgLanguageCode; 02928 default: 02929 $ret = null; 02930 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) { 02931 return $ret; 02932 } else { 02933 return null; 02934 } 02935 } 02936 02937 if ( $index ) { 02938 $this->mVarCache[$index] = $value; 02939 } 02940 02941 return $value; 02942 } 02943 02949 function initialiseVariables() { 02950 wfProfileIn( __METHOD__ ); 02951 $variableIDs = MagicWord::getVariableIDs(); 02952 $substIDs = MagicWord::getSubstIDs(); 02953 02954 $this->mVariables = new MagicWordArray( $variableIDs ); 02955 $this->mSubstWords = new MagicWordArray( $substIDs ); 02956 wfProfileOut( __METHOD__ ); 02957 } 02958 02983 function preprocessToDom( $text, $flags = 0 ) { 02984 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags ); 02985 return $dom; 02986 } 02987 02995 public static function splitWhitespace( $s ) { 02996 $ltrimmed = ltrim( $s ); 02997 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) ); 02998 $trimmed = rtrim( $ltrimmed ); 02999 $diff = strlen( $ltrimmed ) - strlen( $trimmed ); 03000 if ( $diff > 0 ) { 03001 $w2 = substr( $ltrimmed, -$diff ); 03002 } else { 03003 $w2 = ''; 03004 } 03005 return array( $w1, $trimmed, $w2 ); 03006 } 03007 03027 function replaceVariables( $text, $frame = false, $argsOnly = false ) { 03028 # Is there any text? Also, Prevent too big inclusions! 03029 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) { 03030 return $text; 03031 } 03032 wfProfileIn( __METHOD__ ); 03033 03034 if ( $frame === false ) { 03035 $frame = $this->getPreprocessor()->newFrame(); 03036 } elseif ( !( $frame instanceof PPFrame ) ) { 03037 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" ); 03038 $frame = $this->getPreprocessor()->newCustomFrame( $frame ); 03039 } 03040 03041 $dom = $this->preprocessToDom( $text ); 03042 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0; 03043 $text = $frame->expand( $dom, $flags ); 03044 03045 wfProfileOut( __METHOD__ ); 03046 return $text; 03047 } 03048 03056 static function createAssocArgs( $args ) { 03057 $assocArgs = array(); 03058 $index = 1; 03059 foreach ( $args as $arg ) { 03060 $eqpos = strpos( $arg, '=' ); 03061 if ( $eqpos === false ) { 03062 $assocArgs[$index++] = $arg; 03063 } else { 03064 $name = trim( substr( $arg, 0, $eqpos ) ); 03065 $value = trim( substr( $arg, $eqpos+1 ) ); 03066 if ( $value === false ) { 03067 $value = ''; 03068 } 03069 if ( $name !== false ) { 03070 $assocArgs[$name] = $value; 03071 } 03072 } 03073 } 03074 03075 return $assocArgs; 03076 } 03077 03096 function limitationWarn( $limitationType, $current = '', $max = '' ) { 03097 # does no harm if $current and $max are present but are unnecessary for the message 03098 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max ) 03099 ->inContentLanguage()->escaped(); 03100 $this->mOutput->addWarning( $warning ); 03101 $this->addTrackingCategory( "$limitationType-category" ); 03102 } 03103 03116 function braceSubstitution( $piece, $frame ) { 03117 global $wgContLang; 03118 wfProfileIn( __METHOD__ ); 03119 wfProfileIn( __METHOD__.'-setup' ); 03120 03121 # Flags 03122 $found = false; # $text has been filled 03123 $nowiki = false; # wiki markup in $text should be escaped 03124 $isHTML = false; # $text is HTML, armour it against wikitext transformation 03125 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered 03126 $isChildObj = false; # $text is a DOM node needing expansion in a child frame 03127 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame 03128 03129 # Title object, where $text came from 03130 $title = false; 03131 03132 # $part1 is the bit before the first |, and must contain only title characters. 03133 # Various prefixes will be stripped from it later. 03134 $titleWithSpaces = $frame->expand( $piece['title'] ); 03135 $part1 = trim( $titleWithSpaces ); 03136 $titleText = false; 03137 03138 # Original title text preserved for various purposes 03139 $originalTitle = $part1; 03140 03141 # $args is a list of argument nodes, starting from index 0, not including $part1 03142 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object 03143 $args = ( null == $piece['parts'] ) ? array() : $piece['parts']; 03144 wfProfileOut( __METHOD__.'-setup' ); 03145 03146 $titleProfileIn = null; // profile templates 03147 03148 # SUBST 03149 wfProfileIn( __METHOD__.'-modifiers' ); 03150 if ( !$found ) { 03151 03152 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 ); 03153 03154 # Possibilities for substMatch: "subst", "safesubst" or FALSE 03155 # Decide whether to expand template or keep wikitext as-is. 03156 if ( $this->ot['wiki'] ) { 03157 if ( $substMatch === false ) { 03158 $literal = true; # literal when in PST with no prefix 03159 } else { 03160 $literal = false; # expand when in PST with subst: or safesubst: 03161 } 03162 } else { 03163 if ( $substMatch == 'subst' ) { 03164 $literal = true; # literal when not in PST with plain subst: 03165 } else { 03166 $literal = false; # expand when not in PST with safesubst: or no prefix 03167 } 03168 } 03169 if ( $literal ) { 03170 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args ); 03171 $isLocalObj = true; 03172 $found = true; 03173 } 03174 } 03175 03176 # Variables 03177 if ( !$found && $args->getLength() == 0 ) { 03178 $id = $this->mVariables->matchStartToEnd( $part1 ); 03179 if ( $id !== false ) { 03180 $text = $this->getVariableValue( $id, $frame ); 03181 if ( MagicWord::getCacheTTL( $id ) > -1 ) { 03182 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) ); 03183 } 03184 $found = true; 03185 } 03186 } 03187 03188 # MSG, MSGNW and RAW 03189 if ( !$found ) { 03190 # Check for MSGNW: 03191 $mwMsgnw = MagicWord::get( 'msgnw' ); 03192 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) { 03193 $nowiki = true; 03194 } else { 03195 # Remove obsolete MSG: 03196 $mwMsg = MagicWord::get( 'msg' ); 03197 $mwMsg->matchStartAndRemove( $part1 ); 03198 } 03199 03200 # Check for RAW: 03201 $mwRaw = MagicWord::get( 'raw' ); 03202 if ( $mwRaw->matchStartAndRemove( $part1 ) ) { 03203 $forceRawInterwiki = true; 03204 } 03205 } 03206 wfProfileOut( __METHOD__.'-modifiers' ); 03207 03208 # Parser functions 03209 if ( !$found ) { 03210 wfProfileIn( __METHOD__ . '-pfunc' ); 03211 03212 $colonPos = strpos( $part1, ':' ); 03213 if ( $colonPos !== false ) { 03214 # Case sensitive functions 03215 $function = substr( $part1, 0, $colonPos ); 03216 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) { 03217 $function = $this->mFunctionSynonyms[1][$function]; 03218 } else { 03219 # Case insensitive functions 03220 $function = $wgContLang->lc( $function ); 03221 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) { 03222 $function = $this->mFunctionSynonyms[0][$function]; 03223 } else { 03224 $function = false; 03225 } 03226 } 03227 if ( $function ) { 03228 wfProfileIn( __METHOD__ . '-pfunc-' . $function ); 03229 list( $callback, $flags ) = $this->mFunctionHooks[$function]; 03230 $initialArgs = array( &$this ); 03231 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) ); 03232 if ( $flags & SFH_OBJECT_ARGS ) { 03233 # Add a frame parameter, and pass the arguments as an array 03234 $allArgs = $initialArgs; 03235 $allArgs[] = $frame; 03236 for ( $i = 0; $i < $args->getLength(); $i++ ) { 03237 $funcArgs[] = $args->item( $i ); 03238 } 03239 $allArgs[] = $funcArgs; 03240 } else { 03241 # Convert arguments to plain text 03242 for ( $i = 0; $i < $args->getLength(); $i++ ) { 03243 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) ); 03244 } 03245 $allArgs = array_merge( $initialArgs, $funcArgs ); 03246 } 03247 03248 # Workaround for PHP bug 35229 and similar 03249 if ( !is_callable( $callback ) ) { 03250 wfProfileOut( __METHOD__ . '-pfunc-' . $function ); 03251 wfProfileOut( __METHOD__ . '-pfunc' ); 03252 wfProfileOut( __METHOD__ ); 03253 throw new MWException( "Tag hook for $function is not callable\n" ); 03254 } 03255 $result = call_user_func_array( $callback, $allArgs ); 03256 $found = true; 03257 $noparse = true; 03258 $preprocessFlags = 0; 03259 03260 if ( is_array( $result ) ) { 03261 if ( isset( $result[0] ) ) { 03262 $text = $result[0]; 03263 unset( $result[0] ); 03264 } 03265 03266 # Extract flags into the local scope 03267 # This allows callers to set flags such as nowiki, found, etc. 03268 extract( $result ); 03269 } else { 03270 $text = $result; 03271 } 03272 if ( !$noparse ) { 03273 $text = $this->preprocessToDom( $text, $preprocessFlags ); 03274 $isChildObj = true; 03275 } 03276 wfProfileOut( __METHOD__ . '-pfunc-' . $function ); 03277 } 03278 } 03279 wfProfileOut( __METHOD__ . '-pfunc' ); 03280 } 03281 03282 # Finish mangling title and then check for loops. 03283 # Set $title to a Title object and $titleText to the PDBK 03284 if ( !$found ) { 03285 $ns = NS_TEMPLATE; 03286 # Split the title into page and subpage 03287 $subpage = ''; 03288 $part1 = $this->maybeDoSubpageLink( $part1, $subpage ); 03289 if ( $subpage !== '' ) { 03290 $ns = $this->mTitle->getNamespace(); 03291 } 03292 $title = Title::newFromText( $part1, $ns ); 03293 if ( $title ) { 03294 $titleText = $title->getPrefixedText(); 03295 # Check for language variants if the template is not found 03296 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) { 03297 $this->getConverterLanguage()->findVariantLink( $part1, $title, true ); 03298 } 03299 # Do recursion depth check 03300 $limit = $this->mOptions->getMaxTemplateDepth(); 03301 if ( $frame->depth >= $limit ) { 03302 $found = true; 03303 $text = '<span class="error">' 03304 . wfMessage( 'parser-template-recursion-depth-warning' ) 03305 ->numParams( $limit )->inContentLanguage()->text() 03306 . '</span>'; 03307 } 03308 } 03309 } 03310 03311 # Load from database 03312 if ( !$found && $title ) { 03313 if ( !Profiler::instance()->isPersistent() ) { 03314 # Too many unique items can kill profiling DBs/collectors 03315 $titleProfileIn = __METHOD__ . "-title-" . $title->getDBKey(); 03316 wfProfileIn( $titleProfileIn ); // template in 03317 } 03318 wfProfileIn( __METHOD__ . '-loadtpl' ); 03319 if ( !$title->isExternal() ) { 03320 if ( $title->isSpecialPage() 03321 && $this->mOptions->getAllowSpecialInclusion() 03322 && $this->ot['html'] ) 03323 { 03324 // Pass the template arguments as URL parameters. 03325 // "uselang" will have no effect since the Language object 03326 // is forced to the one defined in ParserOptions. 03327 $pageArgs = array(); 03328 for ( $i = 0; $i < $args->getLength(); $i++ ) { 03329 $bits = $args->item( $i )->splitArg(); 03330 if ( strval( $bits['index'] ) === '' ) { 03331 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) ); 03332 $value = trim( $frame->expand( $bits['value'] ) ); 03333 $pageArgs[$name] = $value; 03334 } 03335 } 03336 03337 // Create a new context to execute the special page 03338 $context = new RequestContext; 03339 $context->setTitle( $title ); 03340 $context->setRequest( new FauxRequest( $pageArgs ) ); 03341 $context->setUser( $this->getUser() ); 03342 $context->setLanguage( $this->mOptions->getUserLangObj() ); 03343 $ret = SpecialPageFactory::capturePath( $title, $context ); 03344 if ( $ret ) { 03345 $text = $context->getOutput()->getHTML(); 03346 $this->mOutput->addOutputPageMetadata( $context->getOutput() ); 03347 $found = true; 03348 $isHTML = true; 03349 $this->disableCache(); 03350 } 03351 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) { 03352 $found = false; # access denied 03353 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() ); 03354 } else { 03355 list( $text, $title ) = $this->getTemplateDom( $title ); 03356 if ( $text !== false ) { 03357 $found = true; 03358 $isChildObj = true; 03359 } 03360 } 03361 03362 # If the title is valid but undisplayable, make a link to it 03363 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) { 03364 $text = "[[:$titleText]]"; 03365 $found = true; 03366 } 03367 } elseif ( $title->isTrans() ) { 03368 # Interwiki transclusion 03369 if ( $this->ot['html'] && !$forceRawInterwiki ) { 03370 $text = $this->interwikiTransclude( $title, 'render' ); 03371 $isHTML = true; 03372 } else { 03373 $text = $this->interwikiTransclude( $title, 'raw' ); 03374 # Preprocess it like a template 03375 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 03376 $isChildObj = true; 03377 } 03378 $found = true; 03379 } 03380 03381 # Do infinite loop check 03382 # This has to be done after redirect resolution to avoid infinite loops via redirects 03383 if ( !$frame->loopCheck( $title ) ) { 03384 $found = true; 03385 $text = '<span class="error">' 03386 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text() 03387 . '</span>'; 03388 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" ); 03389 } 03390 wfProfileOut( __METHOD__ . '-loadtpl' ); 03391 } 03392 03393 # If we haven't found text to substitute by now, we're done 03394 # Recover the source wikitext and return it 03395 if ( !$found ) { 03396 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args ); 03397 if ( $titleProfileIn ) { 03398 wfProfileOut( $titleProfileIn ); // template out 03399 } 03400 wfProfileOut( __METHOD__ ); 03401 return array( 'object' => $text ); 03402 } 03403 03404 # Expand DOM-style return values in a child frame 03405 if ( $isChildObj ) { 03406 # Clean up argument array 03407 $newFrame = $frame->newChild( $args, $title ); 03408 03409 if ( $nowiki ) { 03410 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG ); 03411 } elseif ( $titleText !== false && $newFrame->isEmpty() ) { 03412 # Expansion is eligible for the empty-frame cache 03413 if ( isset( $this->mTplExpandCache[$titleText] ) ) { 03414 $text = $this->mTplExpandCache[$titleText]; 03415 } else { 03416 $text = $newFrame->expand( $text ); 03417 $this->mTplExpandCache[$titleText] = $text; 03418 } 03419 } else { 03420 # Uncached expansion 03421 $text = $newFrame->expand( $text ); 03422 } 03423 } 03424 if ( $isLocalObj && $nowiki ) { 03425 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG ); 03426 $isLocalObj = false; 03427 } 03428 03429 if ( $titleProfileIn ) { 03430 wfProfileOut( $titleProfileIn ); // template out 03431 } 03432 03433 # Replace raw HTML by a placeholder 03434 if ( $isHTML ) { 03435 $text = $this->insertStripItem( $text ); 03436 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) { 03437 # Escape nowiki-style return values 03438 $text = wfEscapeWikiText( $text ); 03439 } elseif ( is_string( $text ) 03440 && !$piece['lineStart'] 03441 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) ) 03442 { 03443 # Bug 529: if the template begins with a table or block-level 03444 # element, it should be treated as beginning a new line. 03445 # This behaviour is somewhat controversial. 03446 $text = "\n" . $text; 03447 } 03448 03449 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) { 03450 # Error, oversize inclusion 03451 if ( $titleText !== false ) { 03452 # Make a working, properly escaped link if possible (bug 23588) 03453 $text = "[[:$titleText]]"; 03454 } else { 03455 # This will probably not be a working link, but at least it may 03456 # provide some hint of where the problem is 03457 preg_replace( '/^:/', '', $originalTitle ); 03458 $text = "[[:$originalTitle]]"; 03459 } 03460 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' ); 03461 $this->limitationWarn( 'post-expand-template-inclusion' ); 03462 } 03463 03464 if ( $isLocalObj ) { 03465 $ret = array( 'object' => $text ); 03466 } else { 03467 $ret = array( 'text' => $text ); 03468 } 03469 03470 wfProfileOut( __METHOD__ ); 03471 return $ret; 03472 } 03473 03482 function getTemplateDom( $title ) { 03483 $cacheTitle = $title; 03484 $titleText = $title->getPrefixedDBkey(); 03485 03486 if ( isset( $this->mTplRedirCache[$titleText] ) ) { 03487 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText]; 03488 $title = Title::makeTitle( $ns, $dbk ); 03489 $titleText = $title->getPrefixedDBkey(); 03490 } 03491 if ( isset( $this->mTplDomCache[$titleText] ) ) { 03492 return array( $this->mTplDomCache[$titleText], $title ); 03493 } 03494 03495 # Cache miss, go to the database 03496 list( $text, $title ) = $this->fetchTemplateAndTitle( $title ); 03497 03498 if ( $text === false ) { 03499 $this->mTplDomCache[$titleText] = false; 03500 return array( false, $title ); 03501 } 03502 03503 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION ); 03504 $this->mTplDomCache[ $titleText ] = $dom; 03505 03506 if ( !$title->equals( $cacheTitle ) ) { 03507 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] = 03508 array( $title->getNamespace(), $cdb = $title->getDBkey() ); 03509 } 03510 03511 return array( $dom, $title ); 03512 } 03513 03519 function fetchTemplateAndTitle( $title ) { 03520 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate() 03521 $stuff = call_user_func( $templateCb, $title, $this ); 03522 $text = $stuff['text']; 03523 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title; 03524 if ( isset( $stuff['deps'] ) ) { 03525 foreach ( $stuff['deps'] as $dep ) { 03526 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] ); 03527 } 03528 } 03529 return array( $text, $finalTitle ); 03530 } 03531 03537 function fetchTemplate( $title ) { 03538 $rv = $this->fetchTemplateAndTitle( $title ); 03539 return $rv[0]; 03540 } 03541 03551 static function statelessFetchTemplate( $title, $parser = false ) { 03552 $text = $skip = false; 03553 $finalTitle = $title; 03554 $deps = array(); 03555 03556 # Loop to fetch the article, with up to 1 redirect 03557 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) { 03558 # Give extensions a chance to select the revision instead 03559 $id = false; # Assume current 03560 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', 03561 array( $parser, $title, &$skip, &$id ) ); 03562 03563 if ( $skip ) { 03564 $text = false; 03565 $deps[] = array( 03566 'title' => $title, 03567 'page_id' => $title->getArticleID(), 03568 'rev_id' => null 03569 ); 03570 break; 03571 } 03572 # Get the revision 03573 $rev = $id 03574 ? Revision::newFromId( $id ) 03575 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL ); 03576 $rev_id = $rev ? $rev->getId() : 0; 03577 # If there is no current revision, there is no page 03578 if ( $id === false && !$rev ) { 03579 $linkCache = LinkCache::singleton(); 03580 $linkCache->addBadLinkObj( $title ); 03581 } 03582 03583 $deps[] = array( 03584 'title' => $title, 03585 'page_id' => $title->getArticleID(), 03586 'rev_id' => $rev_id ); 03587 if ( $rev && !$title->equals( $rev->getTitle() ) ) { 03588 # We fetched a rev from a different title; register it too... 03589 $deps[] = array( 03590 'title' => $rev->getTitle(), 03591 'page_id' => $rev->getPage(), 03592 'rev_id' => $rev_id ); 03593 } 03594 03595 if ( $rev ) { 03596 $text = $rev->getText(); 03597 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) { 03598 global $wgContLang; 03599 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage(); 03600 if ( !$message->exists() ) { 03601 $text = false; 03602 break; 03603 } 03604 $text = $message->plain(); 03605 } else { 03606 break; 03607 } 03608 if ( $text === false ) { 03609 break; 03610 } 03611 # Redirect? 03612 $finalTitle = $title; 03613 $title = Title::newFromRedirect( $text ); 03614 } 03615 return array( 03616 'text' => $text, 03617 'finalTitle' => $finalTitle, 03618 'deps' => $deps ); 03619 } 03620 03628 function fetchFile( $title, $options = array() ) { 03629 $res = $this->fetchFileAndTitle( $title, $options ); 03630 return $res[0]; 03631 } 03632 03640 function fetchFileAndTitle( $title, $options = array() ) { 03641 if ( isset( $options['broken'] ) ) { 03642 $file = false; // broken thumbnail forced by hook 03643 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp) 03644 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options ); 03645 } else { // get by (name,timestamp) 03646 $file = wfFindFile( $title, $options ); 03647 } 03648 $time = $file ? $file->getTimestamp() : false; 03649 $sha1 = $file ? $file->getSha1() : false; 03650 # Register the file as a dependency... 03651 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 ); 03652 if ( $file && !$title->equals( $file->getTitle() ) ) { 03653 # Update fetched file title 03654 $title = $file->getTitle(); 03655 if ( is_null( $file->getRedirectedTitle() ) ) { 03656 # This file was not a redirect, but the title does not match. 03657 # Register under the new name because otherwise the link will 03658 # get lost. 03659 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 ); 03660 } 03661 } 03662 return array( $file, $title ); 03663 } 03664 03673 function interwikiTransclude( $title, $action ) { 03674 global $wgEnableScaryTranscluding; 03675 03676 if ( !$wgEnableScaryTranscluding ) { 03677 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text(); 03678 } 03679 03680 $url = $title->getFullUrl( "action=$action" ); 03681 03682 if ( strlen( $url ) > 255 ) { 03683 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text(); 03684 } 03685 return $this->fetchScaryTemplateMaybeFromCache( $url ); 03686 } 03687 03692 function fetchScaryTemplateMaybeFromCache( $url ) { 03693 global $wgTranscludeCacheExpiry; 03694 $dbr = wfGetDB( DB_SLAVE ); 03695 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry ); 03696 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ), 03697 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) ); 03698 if ( $obj ) { 03699 return $obj->tc_contents; 03700 } 03701 03702 $text = Http::get( $url ); 03703 if ( !$text ) { 03704 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text(); 03705 } 03706 03707 $dbw = wfGetDB( DB_MASTER ); 03708 $dbw->replace( 'transcache', array('tc_url'), array( 03709 'tc_url' => $url, 03710 'tc_time' => $dbw->timestamp( time() ), 03711 'tc_contents' => $text) 03712 ); 03713 return $text; 03714 } 03715 03725 function argSubstitution( $piece, $frame ) { 03726 wfProfileIn( __METHOD__ ); 03727 03728 $error = false; 03729 $parts = $piece['parts']; 03730 $nameWithSpaces = $frame->expand( $piece['title'] ); 03731 $argName = trim( $nameWithSpaces ); 03732 $object = false; 03733 $text = $frame->getArgument( $argName ); 03734 if ( $text === false && $parts->getLength() > 0 03735 && ( 03736 $this->ot['html'] 03737 || $this->ot['pre'] 03738 || ( $this->ot['wiki'] && $frame->isTemplate() ) 03739 ) 03740 ) { 03741 # No match in frame, use the supplied default 03742 $object = $parts->item( 0 )->getChildren(); 03743 } 03744 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) { 03745 $error = '<!-- WARNING: argument omitted, expansion size too large -->'; 03746 $this->limitationWarn( 'post-expand-template-argument' ); 03747 } 03748 03749 if ( $text === false && $object === false ) { 03750 # No match anywhere 03751 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts ); 03752 } 03753 if ( $error !== false ) { 03754 $text .= $error; 03755 } 03756 if ( $object !== false ) { 03757 $ret = array( 'object' => $object ); 03758 } else { 03759 $ret = array( 'text' => $text ); 03760 } 03761 03762 wfProfileOut( __METHOD__ ); 03763 return $ret; 03764 } 03765 03780 function extensionSubstitution( $params, $frame ) { 03781 $name = $frame->expand( $params['name'] ); 03782 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] ); 03783 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] ); 03784 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX; 03785 03786 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) && 03787 ( $this->ot['html'] || $this->ot['pre'] ); 03788 if ( $isFunctionTag ) { 03789 $markerType = 'none'; 03790 } else { 03791 $markerType = 'general'; 03792 } 03793 if ( $this->ot['html'] || $isFunctionTag ) { 03794 $name = strtolower( $name ); 03795 $attributes = Sanitizer::decodeTagAttributes( $attrText ); 03796 if ( isset( $params['attributes'] ) ) { 03797 $attributes = $attributes + $params['attributes']; 03798 } 03799 03800 if ( isset( $this->mTagHooks[$name] ) ) { 03801 # Workaround for PHP bug 35229 and similar 03802 if ( !is_callable( $this->mTagHooks[$name] ) ) { 03803 throw new MWException( "Tag hook for $name is not callable\n" ); 03804 } 03805 $output = call_user_func_array( $this->mTagHooks[$name], 03806 array( $content, $attributes, $this, $frame ) ); 03807 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) { 03808 list( $callback, $flags ) = $this->mFunctionTagHooks[$name]; 03809 if ( !is_callable( $callback ) ) { 03810 throw new MWException( "Tag hook for $name is not callable\n" ); 03811 } 03812 03813 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) ); 03814 } else { 03815 $output = '<span class="error">Invalid tag extension name: ' . 03816 htmlspecialchars( $name ) . '</span>'; 03817 } 03818 03819 if ( is_array( $output ) ) { 03820 # Extract flags to local scope (to override $markerType) 03821 $flags = $output; 03822 $output = $flags[0]; 03823 unset( $flags[0] ); 03824 extract( $flags ); 03825 } 03826 } else { 03827 if ( is_null( $attrText ) ) { 03828 $attrText = ''; 03829 } 03830 if ( isset( $params['attributes'] ) ) { 03831 foreach ( $params['attributes'] as $attrName => $attrValue ) { 03832 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' . 03833 htmlspecialchars( $attrValue ) . '"'; 03834 } 03835 } 03836 if ( $content === null ) { 03837 $output = "<$name$attrText/>"; 03838 } else { 03839 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] ); 03840 $output = "<$name$attrText>$content$close"; 03841 } 03842 } 03843 03844 if ( $markerType === 'none' ) { 03845 return $output; 03846 } elseif ( $markerType === 'nowiki' ) { 03847 $this->mStripState->addNoWiki( $marker, $output ); 03848 } elseif ( $markerType === 'general' ) { 03849 $this->mStripState->addGeneral( $marker, $output ); 03850 } else { 03851 throw new MWException( __METHOD__.': invalid marker type' ); 03852 } 03853 return $marker; 03854 } 03855 03863 function incrementIncludeSize( $type, $size ) { 03864 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) { 03865 return false; 03866 } else { 03867 $this->mIncludeSizes[$type] += $size; 03868 return true; 03869 } 03870 } 03871 03877 function incrementExpensiveFunctionCount() { 03878 $this->mExpensiveFunctionCount++; 03879 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit(); 03880 } 03881 03890 function doDoubleUnderscore( $text ) { 03891 wfProfileIn( __METHOD__ ); 03892 03893 # The position of __TOC__ needs to be recorded 03894 $mw = MagicWord::get( 'toc' ); 03895 if ( $mw->match( $text ) ) { 03896 $this->mShowToc = true; 03897 $this->mForceTocPosition = true; 03898 03899 # Set a placeholder. At the end we'll fill it in with the TOC. 03900 $text = $mw->replace( '<!--MWTOC-->', $text, 1 ); 03901 03902 # Only keep the first one. 03903 $text = $mw->replace( '', $text ); 03904 } 03905 03906 # Now match and remove the rest of them 03907 $mwa = MagicWord::getDoubleUnderscoreArray(); 03908 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text ); 03909 03910 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) { 03911 $this->mOutput->mNoGallery = true; 03912 } 03913 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) { 03914 $this->mShowToc = false; 03915 } 03916 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) { 03917 $this->addTrackingCategory( 'hidden-category-category' ); 03918 } 03919 # (bug 8068) Allow control over whether robots index a page. 03920 # 03921 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This 03922 # is not desirable, the last one on the page should win. 03923 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) { 03924 $this->mOutput->setIndexPolicy( 'noindex' ); 03925 $this->addTrackingCategory( 'noindex-category' ); 03926 } 03927 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) { 03928 $this->mOutput->setIndexPolicy( 'index' ); 03929 $this->addTrackingCategory( 'index-category' ); 03930 } 03931 03932 # Cache all double underscores in the database 03933 foreach ( $this->mDoubleUnderscores as $key => $val ) { 03934 $this->mOutput->setProperty( $key, '' ); 03935 } 03936 03937 wfProfileOut( __METHOD__ ); 03938 return $text; 03939 } 03940 03948 public function addTrackingCategory( $msg ) { 03949 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) { 03950 wfDebug( __METHOD__.": Not adding tracking category $msg to special page!\n" ); 03951 return false; 03952 } 03953 // Important to parse with correct title (bug 31469) 03954 $cat = wfMessage( $msg ) 03955 ->title( $this->getTitle() ) 03956 ->inContentLanguage() 03957 ->text(); 03958 03959 # Allow tracking categories to be disabled by setting them to "-" 03960 if ( $cat === '-' ) { 03961 return false; 03962 } 03963 03964 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat ); 03965 if ( $containerCategory ) { 03966 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() ); 03967 return true; 03968 } else { 03969 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" ); 03970 return false; 03971 } 03972 } 03973 03990 function formatHeadings( $text, $origText, $isMain=true ) { 03991 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds; 03992 03993 # Inhibit editsection links if requested in the page 03994 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) { 03995 $maybeShowEditLink = $showEditLink = false; 03996 } else { 03997 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */ 03998 $showEditLink = $this->mOptions->getEditSection(); 03999 } 04000 if ( $showEditLink ) { 04001 $this->mOutput->setEditSectionTokens( true ); 04002 } 04003 04004 # Get all headlines for numbering them and adding funky stuff like [edit] 04005 # links - this is for later, but we need the number of headlines right now 04006 $matches = array(); 04007 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches ); 04008 04009 # if there are fewer than 4 headlines in the article, do not show TOC 04010 # unless it's been explicitly enabled. 04011 $enoughToc = $this->mShowToc && 04012 ( ( $numMatches >= 4 ) || $this->mForceTocPosition ); 04013 04014 # Allow user to stipulate that a page should have a "new section" 04015 # link added via __NEWSECTIONLINK__ 04016 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) { 04017 $this->mOutput->setNewSection( true ); 04018 } 04019 04020 # Allow user to remove the "new section" 04021 # link via __NONEWSECTIONLINK__ 04022 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) { 04023 $this->mOutput->hideNewSection( true ); 04024 } 04025 04026 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML, 04027 # override above conditions and always show TOC above first header 04028 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) { 04029 $this->mShowToc = true; 04030 $enoughToc = true; 04031 } 04032 04033 # headline counter 04034 $headlineCount = 0; 04035 $numVisible = 0; 04036 04037 # Ugh .. the TOC should have neat indentation levels which can be 04038 # passed to the skin functions. These are determined here 04039 $toc = ''; 04040 $full = ''; 04041 $head = array(); 04042 $sublevelCount = array(); 04043 $levelCount = array(); 04044 $level = 0; 04045 $prevlevel = 0; 04046 $toclevel = 0; 04047 $prevtoclevel = 0; 04048 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX; 04049 $baseTitleText = $this->mTitle->getPrefixedDBkey(); 04050 $oldType = $this->mOutputType; 04051 $this->setOutputType( self::OT_WIKI ); 04052 $frame = $this->getPreprocessor()->newFrame(); 04053 $root = $this->preprocessToDom( $origText ); 04054 $node = $root->getFirstChild(); 04055 $byteOffset = 0; 04056 $tocraw = array(); 04057 $refers = array(); 04058 04059 foreach ( $matches[3] as $headline ) { 04060 $isTemplate = false; 04061 $titleText = false; 04062 $sectionIndex = false; 04063 $numbering = ''; 04064 $markerMatches = array(); 04065 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) { 04066 $serial = $markerMatches[1]; 04067 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial]; 04068 $isTemplate = ( $titleText != $baseTitleText ); 04069 $headline = preg_replace( "/^$markerRegex/", "", $headline ); 04070 } 04071 04072 if ( $toclevel ) { 04073 $prevlevel = $level; 04074 } 04075 $level = $matches[1][$headlineCount]; 04076 04077 if ( $level > $prevlevel ) { 04078 # Increase TOC level 04079 $toclevel++; 04080 $sublevelCount[$toclevel] = 0; 04081 if ( $toclevel<$wgMaxTocLevel ) { 04082 $prevtoclevel = $toclevel; 04083 $toc .= Linker::tocIndent(); 04084 $numVisible++; 04085 } 04086 } elseif ( $level < $prevlevel && $toclevel > 1 ) { 04087 # Decrease TOC level, find level to jump to 04088 04089 for ( $i = $toclevel; $i > 0; $i-- ) { 04090 if ( $levelCount[$i] == $level ) { 04091 # Found last matching level 04092 $toclevel = $i; 04093 break; 04094 } elseif ( $levelCount[$i] < $level ) { 04095 # Found first matching level below current level 04096 $toclevel = $i + 1; 04097 break; 04098 } 04099 } 04100 if ( $i == 0 ) { 04101 $toclevel = 1; 04102 } 04103 if ( $toclevel<$wgMaxTocLevel ) { 04104 if ( $prevtoclevel < $wgMaxTocLevel ) { 04105 # Unindent only if the previous toc level was shown :p 04106 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel ); 04107 $prevtoclevel = $toclevel; 04108 } else { 04109 $toc .= Linker::tocLineEnd(); 04110 } 04111 } 04112 } else { 04113 # No change in level, end TOC line 04114 if ( $toclevel<$wgMaxTocLevel ) { 04115 $toc .= Linker::tocLineEnd(); 04116 } 04117 } 04118 04119 $levelCount[$toclevel] = $level; 04120 04121 # count number of headlines for each level 04122 @$sublevelCount[$toclevel]++; 04123 $dot = 0; 04124 for( $i = 1; $i <= $toclevel; $i++ ) { 04125 if ( !empty( $sublevelCount[$i] ) ) { 04126 if ( $dot ) { 04127 $numbering .= '.'; 04128 } 04129 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] ); 04130 $dot = 1; 04131 } 04132 } 04133 04134 # The safe header is a version of the header text safe to use for links 04135 04136 # Remove link placeholders by the link text. 04137 # <!--LINK number--> 04138 # turns into 04139 # link text with suffix 04140 # Do this before unstrip since link text can contain strip markers 04141 $safeHeadline = $this->replaceLinkHoldersText( $headline ); 04142 04143 # Avoid insertion of weird stuff like <math> by expanding the relevant sections 04144 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline ); 04145 04146 # Strip out HTML (first regex removes any tag not allowed) 04147 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284) 04148 # We strip any parameter from accepted tags (second regex) 04149 $tocline = preg_replace( 04150 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ), 04151 array( '', '<$1>' ), 04152 $safeHeadline 04153 ); 04154 $tocline = trim( $tocline ); 04155 04156 # For the anchor, strip out HTML-y stuff period 04157 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline ); 04158 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline ); 04159 04160 # Save headline for section edit hint before it's escaped 04161 $headlineHint = $safeHeadline; 04162 04163 if ( $wgHtml5 && $wgExperimentalHtmlIds ) { 04164 # For reverse compatibility, provide an id that's 04165 # HTML4-compatible, like we used to. 04166 # 04167 # It may be worth noting, academically, that it's possible for 04168 # the legacy anchor to conflict with a non-legacy headline 04169 # anchor on the page. In this case likely the "correct" thing 04170 # would be to either drop the legacy anchors or make sure 04171 # they're numbered first. However, this would require people 04172 # to type in section names like "abc_.D7.93.D7.90.D7.A4" 04173 # manually, so let's not bother worrying about it. 04174 $legacyHeadline = Sanitizer::escapeId( $safeHeadline, 04175 array( 'noninitial', 'legacy' ) ); 04176 $safeHeadline = Sanitizer::escapeId( $safeHeadline ); 04177 04178 if ( $legacyHeadline == $safeHeadline ) { 04179 # No reason to have both (in fact, we can't) 04180 $legacyHeadline = false; 04181 } 04182 } else { 04183 $legacyHeadline = false; 04184 $safeHeadline = Sanitizer::escapeId( $safeHeadline, 04185 'noninitial' ); 04186 } 04187 04188 # HTML names must be case-insensitively unique (bug 10721). 04189 # This does not apply to Unicode characters per 04190 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison 04191 # @todo FIXME: We may be changing them depending on the current locale. 04192 $arrayKey = strtolower( $safeHeadline ); 04193 if ( $legacyHeadline === false ) { 04194 $legacyArrayKey = false; 04195 } else { 04196 $legacyArrayKey = strtolower( $legacyHeadline ); 04197 } 04198 04199 # count how many in assoc. array so we can track dupes in anchors 04200 if ( isset( $refers[$arrayKey] ) ) { 04201 $refers[$arrayKey]++; 04202 } else { 04203 $refers[$arrayKey] = 1; 04204 } 04205 if ( isset( $refers[$legacyArrayKey] ) ) { 04206 $refers[$legacyArrayKey]++; 04207 } else { 04208 $refers[$legacyArrayKey] = 1; 04209 } 04210 04211 # Don't number the heading if it is the only one (looks silly) 04212 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) { 04213 # the two are different if the line contains a link 04214 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline; 04215 } 04216 04217 # Create the anchor for linking from the TOC to the section 04218 $anchor = $safeHeadline; 04219 $legacyAnchor = $legacyHeadline; 04220 if ( $refers[$arrayKey] > 1 ) { 04221 $anchor .= '_' . $refers[$arrayKey]; 04222 } 04223 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) { 04224 $legacyAnchor .= '_' . $refers[$legacyArrayKey]; 04225 } 04226 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) { 04227 $toc .= Linker::tocLine( $anchor, $tocline, 04228 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) ); 04229 } 04230 04231 # Add the section to the section tree 04232 # Find the DOM node for this header 04233 while ( $node && !$isTemplate ) { 04234 if ( $node->getName() === 'h' ) { 04235 $bits = $node->splitHeading(); 04236 if ( $bits['i'] == $sectionIndex ) { 04237 break; 04238 } 04239 } 04240 $byteOffset += mb_strlen( $this->mStripState->unstripBoth( 04241 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) ); 04242 $node = $node->getNextSibling(); 04243 } 04244 $tocraw[] = array( 04245 'toclevel' => $toclevel, 04246 'level' => $level, 04247 'line' => $tocline, 04248 'number' => $numbering, 04249 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex, 04250 'fromtitle' => $titleText, 04251 'byteoffset' => ( $isTemplate ? null : $byteOffset ), 04252 'anchor' => $anchor, 04253 ); 04254 04255 # give headline the correct <h#> tag 04256 if ( $maybeShowEditLink && $sectionIndex !== false ) { 04257 // Output edit section links as markers with styles that can be customized by skins 04258 if ( $isTemplate ) { 04259 # Put a T flag in the section identifier, to indicate to extractSections() 04260 # that sections inside <includeonly> should be counted. 04261 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ ); 04262 } else { 04263 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint ); 04264 } 04265 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on 04266 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff 04267 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped 04268 // so we don't have to worry about a user trying to input one of these markers directly. 04269 // We use a page and section attribute to stop the language converter from converting these important bits 04270 // of data, but put the headline hint inside a content block because the language converter is supposed to 04271 // be able to convert that piece of data. 04272 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]); 04273 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"'; 04274 if ( isset($editlinkArgs[2]) ) { 04275 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>'; 04276 } else { 04277 $editlink .= '/>'; 04278 } 04279 } else { 04280 $editlink = ''; 04281 } 04282 $head[$headlineCount] = Linker::makeHeadline( $level, 04283 $matches['attrib'][$headlineCount], $anchor, $headline, 04284 $editlink, $legacyAnchor ); 04285 04286 $headlineCount++; 04287 } 04288 04289 $this->setOutputType( $oldType ); 04290 04291 # Never ever show TOC if no headers 04292 if ( $numVisible < 1 ) { 04293 $enoughToc = false; 04294 } 04295 04296 if ( $enoughToc ) { 04297 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) { 04298 $toc .= Linker::tocUnindent( $prevtoclevel - 1 ); 04299 } 04300 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() ); 04301 $this->mOutput->setTOCHTML( $toc ); 04302 } 04303 04304 if ( $isMain ) { 04305 $this->mOutput->setSections( $tocraw ); 04306 } 04307 04308 # split up and insert constructed headlines 04309 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text ); 04310 $i = 0; 04311 04312 // build an array of document sections 04313 $sections = array(); 04314 foreach ( $blocks as $block ) { 04315 // $head is zero-based, sections aren't. 04316 if ( empty( $head[$i - 1] ) ) { 04317 $sections[$i] = $block; 04318 } else { 04319 $sections[$i] = $head[$i - 1] . $block; 04320 } 04321 04332 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) ); 04333 04334 $i++; 04335 } 04336 04337 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) { 04338 // append the TOC at the beginning 04339 // Top anchor now in skin 04340 $sections[0] = $sections[0] . $toc . "\n"; 04341 } 04342 04343 $full .= join( '', $sections ); 04344 04345 if ( $this->mForceTocPosition ) { 04346 return str_replace( '<!--MWTOC-->', $toc, $full ); 04347 } else { 04348 return $full; 04349 } 04350 } 04351 04363 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) { 04364 $this->startParse( $title, $options, self::OT_WIKI, $clearState ); 04365 $this->setUser( $user ); 04366 04367 $pairs = array( 04368 "\r\n" => "\n", 04369 ); 04370 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text ); 04371 if( $options->getPreSaveTransform() ) { 04372 $text = $this->pstPass2( $text, $user ); 04373 } 04374 $text = $this->mStripState->unstripBoth( $text ); 04375 04376 $this->setUser( null ); #Reset 04377 04378 return $text; 04379 } 04380 04390 function pstPass2( $text, $user ) { 04391 global $wgContLang, $wgLocaltimezone; 04392 04393 # Note: This is the timestamp saved as hardcoded wikitext to 04394 # the database, we use $wgContLang here in order to give 04395 # everyone the same signature and use the default one rather 04396 # than the one selected in each user's preferences. 04397 # (see also bug 12815) 04398 $ts = $this->mOptions->getTimestamp(); 04399 if ( isset( $wgLocaltimezone ) ) { 04400 $tz = $wgLocaltimezone; 04401 } else { 04402 $tz = date_default_timezone_get(); 04403 } 04404 04405 $unixts = wfTimestamp( TS_UNIX, $ts ); 04406 $oldtz = date_default_timezone_get(); 04407 date_default_timezone_set( $tz ); 04408 $ts = date( 'YmdHis', $unixts ); 04409 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover! 04410 04411 # Allow translation of timezones through wiki. date() can return 04412 # whatever crap the system uses, localised or not, so we cannot 04413 # ship premade translations. 04414 $key = 'timezone-' . strtolower( trim( $tzMsg ) ); 04415 $msg = wfMessage( $key )->inContentLanguage(); 04416 if ( $msg->exists() ) { 04417 $tzMsg = $msg->text(); 04418 } 04419 04420 date_default_timezone_set( $oldtz ); 04421 04422 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)"; 04423 04424 # Variable replacement 04425 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags 04426 $text = $this->replaceVariables( $text ); 04427 04428 # This works almost by chance, as the replaceVariables are done before the getUserSig(), 04429 # which may corrupt this parser instance via its wfMessage()->text() call- 04430 04431 # Signatures 04432 $sigText = $this->getUserSig( $user ); 04433 $text = strtr( $text, array( 04434 '~~~~~' => $d, 04435 '~~~~' => "$sigText $d", 04436 '~~~' => $sigText 04437 ) ); 04438 04439 # Context links: [[|name]] and [[name (context)|]] 04440 $tc = '[' . Title::legalChars() . ']'; 04441 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii! 04442 04443 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]] 04444 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] 04445 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] 04446 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] 04447 04448 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]" 04449 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text ); 04450 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text ); 04451 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text ); 04452 04453 $t = $this->mTitle->getText(); 04454 $m = array(); 04455 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) { 04456 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text ); 04457 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) { 04458 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text ); 04459 } else { 04460 # if there's no context, don't bother duplicating the title 04461 $text = preg_replace( $p2, '[[\\1]]', $text ); 04462 } 04463 04464 # Trim trailing whitespace 04465 $text = rtrim( $text ); 04466 04467 return $text; 04468 } 04469 04484 function getUserSig( &$user, $nickname = false, $fancySig = null ) { 04485 global $wgMaxSigChars; 04486 04487 $username = $user->getName(); 04488 04489 # If not given, retrieve from the user object. 04490 if ( $nickname === false ) 04491 $nickname = $user->getOption( 'nickname' ); 04492 04493 if ( is_null( $fancySig ) ) { 04494 $fancySig = $user->getBoolOption( 'fancysig' ); 04495 } 04496 04497 $nickname = $nickname == null ? $username : $nickname; 04498 04499 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) { 04500 $nickname = $username; 04501 wfDebug( __METHOD__ . ": $username has overlong signature.\n" ); 04502 } elseif ( $fancySig !== false ) { 04503 # Sig. might contain markup; validate this 04504 if ( $this->validateSig( $nickname ) !== false ) { 04505 # Validated; clean up (if needed) and return it 04506 return $this->cleanSig( $nickname, true ); 04507 } else { 04508 # Failed to validate; fall back to the default 04509 $nickname = $username; 04510 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" ); 04511 } 04512 } 04513 04514 # Make sure nickname doesnt get a sig in a sig 04515 $nickname = self::cleanSigInSig( $nickname ); 04516 04517 # If we're still here, make it a link to the user page 04518 $userText = wfEscapeWikiText( $username ); 04519 $nickText = wfEscapeWikiText( $nickname ); 04520 $msgName = $user->isAnon() ? 'signature-anon' : 'signature'; 04521 04522 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text(); 04523 } 04524 04531 function validateSig( $text ) { 04532 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false ); 04533 } 04534 04545 public function cleanSig( $text, $parsing = false ) { 04546 if ( !$parsing ) { 04547 global $wgTitle; 04548 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true ); 04549 } 04550 04551 # Option to disable this feature 04552 if ( !$this->mOptions->getCleanSignatures() ) { 04553 return $text; 04554 } 04555 04556 # @todo FIXME: Regex doesn't respect extension tags or nowiki 04557 # => Move this logic to braceSubstitution() 04558 $substWord = MagicWord::get( 'subst' ); 04559 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase(); 04560 $substText = '{{' . $substWord->getSynonym( 0 ); 04561 04562 $text = preg_replace( $substRegex, $substText, $text ); 04563 $text = self::cleanSigInSig( $text ); 04564 $dom = $this->preprocessToDom( $text ); 04565 $frame = $this->getPreprocessor()->newFrame(); 04566 $text = $frame->expand( $dom ); 04567 04568 if ( !$parsing ) { 04569 $text = $this->mStripState->unstripBoth( $text ); 04570 } 04571 04572 return $text; 04573 } 04574 04581 public static function cleanSigInSig( $text ) { 04582 $text = preg_replace( '/~{3,5}/', '', $text ); 04583 return $text; 04584 } 04585 04595 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) { 04596 $this->startParse( $title, $options, $outputType, $clearState ); 04597 } 04598 04605 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) { 04606 $this->setTitle( $title ); 04607 $this->mOptions = $options; 04608 $this->setOutputType( $outputType ); 04609 if ( $clearState ) { 04610 $this->clearState(); 04611 } 04612 } 04613 04622 public function transformMsg( $text, $options, $title = null ) { 04623 static $executing = false; 04624 04625 # Guard against infinite recursion 04626 if ( $executing ) { 04627 return $text; 04628 } 04629 $executing = true; 04630 04631 wfProfileIn( __METHOD__ ); 04632 if ( !$title ) { 04633 global $wgTitle; 04634 $title = $wgTitle; 04635 } 04636 if ( !$title ) { 04637 # It's not uncommon having a null $wgTitle in scripts. See r80898 04638 # Create a ghost title in such case 04639 $title = Title::newFromText( 'Dwimmerlaik' ); 04640 } 04641 $text = $this->preprocess( $text, $title, $options ); 04642 04643 $executing = false; 04644 wfProfileOut( __METHOD__ ); 04645 return $text; 04646 } 04647 04671 public function setHook( $tag, $callback ) { 04672 $tag = strtolower( $tag ); 04673 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { 04674 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" ); 04675 } 04676 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null; 04677 $this->mTagHooks[$tag] = $callback; 04678 if ( !in_array( $tag, $this->mStripList ) ) { 04679 $this->mStripList[] = $tag; 04680 } 04681 04682 return $oldVal; 04683 } 04684 04701 function setTransparentTagHook( $tag, $callback ) { 04702 $tag = strtolower( $tag ); 04703 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) { 04704 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" ); 04705 } 04706 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null; 04707 $this->mTransparentTagHooks[$tag] = $callback; 04708 04709 return $oldVal; 04710 } 04711 04715 function clearTagHooks() { 04716 $this->mTagHooks = array(); 04717 $this->mFunctionTagHooks = array(); 04718 $this->mStripList = $this->mDefaultStripList; 04719 } 04720 04763 public function setFunctionHook( $id, $callback, $flags = 0 ) { 04764 global $wgContLang; 04765 04766 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null; 04767 $this->mFunctionHooks[$id] = array( $callback, $flags ); 04768 04769 # Add to function cache 04770 $mw = MagicWord::get( $id ); 04771 if ( !$mw ) 04772 throw new MWException( __METHOD__.'() expecting a magic word identifier.' ); 04773 04774 $synonyms = $mw->getSynonyms(); 04775 $sensitive = intval( $mw->isCaseSensitive() ); 04776 04777 foreach ( $synonyms as $syn ) { 04778 # Case 04779 if ( !$sensitive ) { 04780 $syn = $wgContLang->lc( $syn ); 04781 } 04782 # Add leading hash 04783 if ( !( $flags & SFH_NO_HASH ) ) { 04784 $syn = '#' . $syn; 04785 } 04786 # Remove trailing colon 04787 if ( substr( $syn, -1, 1 ) === ':' ) { 04788 $syn = substr( $syn, 0, -1 ); 04789 } 04790 $this->mFunctionSynonyms[$sensitive][$syn] = $id; 04791 } 04792 return $oldVal; 04793 } 04794 04800 function getFunctionHooks() { 04801 return array_keys( $this->mFunctionHooks ); 04802 } 04803 04810 function setFunctionTagHook( $tag, $callback, $flags ) { 04811 $tag = strtolower( $tag ); 04812 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" ); 04813 $old = isset( $this->mFunctionTagHooks[$tag] ) ? 04814 $this->mFunctionTagHooks[$tag] : null; 04815 $this->mFunctionTagHooks[$tag] = array( $callback, $flags ); 04816 04817 if ( !in_array( $tag, $this->mStripList ) ) { 04818 $this->mStripList[] = $tag; 04819 } 04820 04821 return $old; 04822 } 04823 04834 function replaceLinkHolders( &$text, $options = 0 ) { 04835 return $this->mLinkHolders->replace( $text ); 04836 } 04837 04845 function replaceLinkHoldersText( $text ) { 04846 return $this->mLinkHolders->replaceText( $text ); 04847 } 04848 04862 function renderImageGallery( $text, $params ) { 04863 $ig = new ImageGallery(); 04864 $ig->setContextTitle( $this->mTitle ); 04865 $ig->setShowBytes( false ); 04866 $ig->setShowFilename( false ); 04867 $ig->setParser( $this ); 04868 $ig->setHideBadImages(); 04869 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) ); 04870 04871 if ( isset( $params['showfilename'] ) ) { 04872 $ig->setShowFilename( true ); 04873 } else { 04874 $ig->setShowFilename( false ); 04875 } 04876 if ( isset( $params['caption'] ) ) { 04877 $caption = $params['caption']; 04878 $caption = htmlspecialchars( $caption ); 04879 $caption = $this->replaceInternalLinks( $caption ); 04880 $ig->setCaptionHtml( $caption ); 04881 } 04882 if ( isset( $params['perrow'] ) ) { 04883 $ig->setPerRow( $params['perrow'] ); 04884 } 04885 if ( isset( $params['widths'] ) ) { 04886 $ig->setWidths( $params['widths'] ); 04887 } 04888 if ( isset( $params['heights'] ) ) { 04889 $ig->setHeights( $params['heights'] ); 04890 } 04891 04892 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) ); 04893 04894 $lines = StringUtils::explode( "\n", $text ); 04895 foreach ( $lines as $line ) { 04896 # match lines like these: 04897 # Image:someimage.jpg|This is some image 04898 $matches = array(); 04899 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches ); 04900 # Skip empty lines 04901 if ( count( $matches ) == 0 ) { 04902 continue; 04903 } 04904 04905 if ( strpos( $matches[0], '%' ) !== false ) { 04906 $matches[1] = rawurldecode( $matches[1] ); 04907 } 04908 $title = Title::newFromText( $matches[1], NS_FILE ); 04909 if ( is_null( $title ) ) { 04910 # Bogus title. Ignore these so we don't bomb out later. 04911 continue; 04912 } 04913 04914 $label = ''; 04915 $alt = ''; 04916 $link = ''; 04917 if ( isset( $matches[3] ) ) { 04918 // look for an |alt= definition while trying not to break existing 04919 // captions with multiple pipes (|) in it, until a more sensible grammar 04920 // is defined for images in galleries 04921 04922 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) ); 04923 $parameterMatches = StringUtils::explode('|', $matches[3]); 04924 $magicWordAlt = MagicWord::get( 'img_alt' ); 04925 $magicWordLink = MagicWord::get( 'img_link' ); 04926 04927 foreach ( $parameterMatches as $parameterMatch ) { 04928 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) { 04929 $alt = $this->stripAltText( $match, false ); 04930 } 04931 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){ 04932 $link = strip_tags($this->replaceLinkHoldersText($match)); 04933 $chars = self::EXT_LINK_URL_CLASS; 04934 $prots = $this->mUrlProtocols; 04935 //check to see if link matches an absolute url, if not then it must be a wiki link. 04936 if(!preg_match( "/^($prots)$chars+$/u", $link)){ 04937 $localLinkTitle = Title::newFromText($link); 04938 $link = $localLinkTitle->getLocalURL(); 04939 } 04940 } 04941 else { 04942 // concatenate all other pipes 04943 $label .= '|' . $parameterMatch; 04944 } 04945 } 04946 // remove the first pipe 04947 $label = substr( $label, 1 ); 04948 } 04949 04950 $ig->add( $title, $label, $alt ,$link); 04951 } 04952 return $ig->toHTML(); 04953 } 04954 04959 function getImageParams( $handler ) { 04960 if ( $handler ) { 04961 $handlerClass = get_class( $handler ); 04962 } else { 04963 $handlerClass = ''; 04964 } 04965 if ( !isset( $this->mImageParams[$handlerClass] ) ) { 04966 # Initialise static lists 04967 static $internalParamNames = array( 04968 'horizAlign' => array( 'left', 'right', 'center', 'none' ), 04969 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 04970 'bottom', 'text-bottom' ), 04971 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless', 04972 'upright', 'border', 'link', 'alt', 'class' ), 04973 ); 04974 static $internalParamMap; 04975 if ( !$internalParamMap ) { 04976 $internalParamMap = array(); 04977 foreach ( $internalParamNames as $type => $names ) { 04978 foreach ( $names as $name ) { 04979 $magicName = str_replace( '-', '_', "img_$name" ); 04980 $internalParamMap[$magicName] = array( $type, $name ); 04981 } 04982 } 04983 } 04984 04985 # Add handler params 04986 $paramMap = $internalParamMap; 04987 if ( $handler ) { 04988 $handlerParamMap = $handler->getParamMap(); 04989 foreach ( $handlerParamMap as $magic => $paramName ) { 04990 $paramMap[$magic] = array( 'handler', $paramName ); 04991 } 04992 } 04993 $this->mImageParams[$handlerClass] = $paramMap; 04994 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) ); 04995 } 04996 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ); 04997 } 04998 05007 function makeImage( $title, $options, $holders = false ) { 05008 # Check if the options text is of the form "options|alt text" 05009 # Options are: 05010 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang 05011 # * left no resizing, just left align. label is used for alt= only 05012 # * right same, but right aligned 05013 # * none same, but not aligned 05014 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox 05015 # * center center the image 05016 # * frame Keep original image size, no magnify-button. 05017 # * framed Same as "frame" 05018 # * frameless like 'thumb' but without a frame. Keeps user preferences for width 05019 # * upright reduce width for upright images, rounded to full __0 px 05020 # * border draw a 1px border around the image 05021 # * alt Text for HTML alt attribute (defaults to empty) 05022 # * class Set a class for img node 05023 # * link Set the target of the image link. Can be external, interwiki, or local 05024 # vertical-align values (no % or length right now): 05025 # * baseline 05026 # * sub 05027 # * super 05028 # * top 05029 # * text-top 05030 # * middle 05031 # * bottom 05032 # * text-bottom 05033 05034 $parts = StringUtils::explode( "|", $options ); 05035 05036 # Give extensions a chance to select the file revision for us 05037 $options = array(); 05038 $descQuery = false; 05039 wfRunHooks( 'BeforeParserFetchFileAndTitle', 05040 array( $this, $title, &$options, &$descQuery ) ); 05041 # Fetch and register the file (file title may be different via hooks) 05042 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options ); 05043 05044 # Get parameter map 05045 $handler = $file ? $file->getHandler() : false; 05046 05047 list( $paramMap, $mwArray ) = $this->getImageParams( $handler ); 05048 05049 if ( !$file ) { 05050 $this->addTrackingCategory( 'broken-file-category' ); 05051 } 05052 05053 # Process the input parameters 05054 $caption = ''; 05055 $params = array( 'frame' => array(), 'handler' => array(), 05056 'horizAlign' => array(), 'vertAlign' => array() ); 05057 foreach ( $parts as $part ) { 05058 $part = trim( $part ); 05059 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part ); 05060 $validated = false; 05061 if ( isset( $paramMap[$magicName] ) ) { 05062 list( $type, $paramName ) = $paramMap[$magicName]; 05063 05064 # Special case; width and height come in one variable together 05065 if ( $type === 'handler' && $paramName === 'width' ) { 05066 $parsedWidthParam = $this->parseWidthParam( $value ); 05067 if( isset( $parsedWidthParam['width'] ) ) { 05068 $width = $parsedWidthParam['width']; 05069 if ( $handler->validateParam( 'width', $width ) ) { 05070 $params[$type]['width'] = $width; 05071 $validated = true; 05072 } 05073 } 05074 if( isset( $parsedWidthParam['height'] ) ) { 05075 $height = $parsedWidthParam['height']; 05076 if ( $handler->validateParam( 'height', $height ) ) { 05077 $params[$type]['height'] = $height; 05078 $validated = true; 05079 } 05080 } 05081 # else no validation -- bug 13436 05082 } else { 05083 if ( $type === 'handler' ) { 05084 # Validate handler parameter 05085 $validated = $handler->validateParam( $paramName, $value ); 05086 } else { 05087 # Validate internal parameters 05088 switch( $paramName ) { 05089 case 'manualthumb': 05090 case 'alt': 05091 case 'class': 05092 # @todo FIXME: Possibly check validity here for 05093 # manualthumb? downstream behavior seems odd with 05094 # missing manual thumbs. 05095 $validated = true; 05096 $value = $this->stripAltText( $value, $holders ); 05097 break; 05098 case 'link': 05099 $chars = self::EXT_LINK_URL_CLASS; 05100 $prots = $this->mUrlProtocols; 05101 if ( $value === '' ) { 05102 $paramName = 'no-link'; 05103 $value = true; 05104 $validated = true; 05105 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) { 05106 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) { 05107 $paramName = 'link-url'; 05108 $this->mOutput->addExternalLink( $value ); 05109 if ( $this->mOptions->getExternalLinkTarget() ) { 05110 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget(); 05111 } 05112 $validated = true; 05113 } 05114 } else { 05115 $linkTitle = Title::newFromText( $value ); 05116 if ( $linkTitle ) { 05117 $paramName = 'link-title'; 05118 $value = $linkTitle; 05119 $this->mOutput->addLink( $linkTitle ); 05120 $validated = true; 05121 } 05122 } 05123 break; 05124 default: 05125 # Most other things appear to be empty or numeric... 05126 $validated = ( $value === false || is_numeric( trim( $value ) ) ); 05127 } 05128 } 05129 05130 if ( $validated ) { 05131 $params[$type][$paramName] = $value; 05132 } 05133 } 05134 } 05135 if ( !$validated ) { 05136 $caption = $part; 05137 } 05138 } 05139 05140 # Process alignment parameters 05141 if ( $params['horizAlign'] ) { 05142 $params['frame']['align'] = key( $params['horizAlign'] ); 05143 } 05144 if ( $params['vertAlign'] ) { 05145 $params['frame']['valign'] = key( $params['vertAlign'] ); 05146 } 05147 05148 $params['frame']['caption'] = $caption; 05149 05150 # Will the image be presented in a frame, with the caption below? 05151 $imageIsFramed = isset( $params['frame']['frame'] ) || 05152 isset( $params['frame']['framed'] ) || 05153 isset( $params['frame']['thumbnail'] ) || 05154 isset( $params['frame']['manualthumb'] ); 05155 05156 # In the old days, [[Image:Foo|text...]] would set alt text. Later it 05157 # came to also set the caption, ordinary text after the image -- which 05158 # makes no sense, because that just repeats the text multiple times in 05159 # screen readers. It *also* came to set the title attribute. 05160 # 05161 # Now that we have an alt attribute, we should not set the alt text to 05162 # equal the caption: that's worse than useless, it just repeats the 05163 # text. This is the framed/thumbnail case. If there's no caption, we 05164 # use the unnamed parameter for alt text as well, just for the time be- 05165 # ing, if the unnamed param is set and the alt param is not. 05166 # 05167 # For the future, we need to figure out if we want to tweak this more, 05168 # e.g., introducing a title= parameter for the title; ignoring the un- 05169 # named parameter entirely for images without a caption; adding an ex- 05170 # plicit caption= parameter and preserving the old magic unnamed para- 05171 # meter for BC; ... 05172 if ( $imageIsFramed ) { # Framed image 05173 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) { 05174 # No caption or alt text, add the filename as the alt text so 05175 # that screen readers at least get some description of the image 05176 $params['frame']['alt'] = $title->getText(); 05177 } 05178 # Do not set $params['frame']['title'] because tooltips don't make sense 05179 # for framed images 05180 } else { # Inline image 05181 if ( !isset( $params['frame']['alt'] ) ) { 05182 # No alt text, use the "caption" for the alt text 05183 if ( $caption !== '') { 05184 $params['frame']['alt'] = $this->stripAltText( $caption, $holders ); 05185 } else { 05186 # No caption, fall back to using the filename for the 05187 # alt text 05188 $params['frame']['alt'] = $title->getText(); 05189 } 05190 } 05191 # Use the "caption" for the tooltip text 05192 $params['frame']['title'] = $this->stripAltText( $caption, $holders ); 05193 } 05194 05195 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) ); 05196 05197 # Linker does the rest 05198 $time = isset( $options['time'] ) ? $options['time'] : false; 05199 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'], 05200 $time, $descQuery, $this->mOptions->getThumbSize() ); 05201 05202 # Give the handler a chance to modify the parser object 05203 if ( $handler ) { 05204 $handler->parserTransformHook( $this, $file ); 05205 } 05206 05207 return $ret; 05208 } 05209 05215 protected function stripAltText( $caption, $holders ) { 05216 # Strip bad stuff out of the title (tooltip). We can't just use 05217 # replaceLinkHoldersText() here, because if this function is called 05218 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date. 05219 if ( $holders ) { 05220 $tooltip = $holders->replaceText( $caption ); 05221 } else { 05222 $tooltip = $this->replaceLinkHoldersText( $caption ); 05223 } 05224 05225 # make sure there are no placeholders in thumbnail attributes 05226 # that are later expanded to html- so expand them now and 05227 # remove the tags 05228 $tooltip = $this->mStripState->unstripBoth( $tooltip ); 05229 $tooltip = Sanitizer::stripAllTags( $tooltip ); 05230 05231 return $tooltip; 05232 } 05233 05238 function disableCache() { 05239 wfDebug( "Parser output marked as uncacheable.\n" ); 05240 if ( !$this->mOutput ) { 05241 throw new MWException( __METHOD__ . 05242 " can only be called when actually parsing something" ); 05243 } 05244 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility 05245 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency 05246 } 05247 05256 function attributeStripCallback( &$text, $frame = false ) { 05257 $text = $this->replaceVariables( $text, $frame ); 05258 $text = $this->mStripState->unstripBoth( $text ); 05259 return $text; 05260 } 05261 05267 function getTags() { 05268 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) ); 05269 } 05270 05281 function replaceTransparentTags( $text ) { 05282 $matches = array(); 05283 $elements = array_keys( $this->mTransparentTagHooks ); 05284 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix ); 05285 $replacements = array(); 05286 05287 foreach ( $matches as $marker => $data ) { 05288 list( $element, $content, $params, $tag ) = $data; 05289 $tagName = strtolower( $element ); 05290 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) { 05291 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) ); 05292 } else { 05293 $output = $tag; 05294 } 05295 $replacements[$marker] = $output; 05296 } 05297 return strtr( $text, $replacements ); 05298 } 05299 05329 private function extractSections( $text, $section, $mode, $newText='' ) { 05330 global $wgTitle; # not generally used but removes an ugly failure mode 05331 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true ); 05332 $outText = ''; 05333 $frame = $this->getPreprocessor()->newFrame(); 05334 05335 # Process section extraction flags 05336 $flags = 0; 05337 $sectionParts = explode( '-', $section ); 05338 $sectionIndex = array_pop( $sectionParts ); 05339 foreach ( $sectionParts as $part ) { 05340 if ( $part === 'T' ) { 05341 $flags |= self::PTD_FOR_INCLUSION; 05342 } 05343 } 05344 05345 # Check for empty input 05346 if ( strval( $text ) === '' ) { 05347 # Only sections 0 and T-0 exist in an empty document 05348 if ( $sectionIndex == 0 ) { 05349 if ( $mode === 'get' ) { 05350 return ''; 05351 } else { 05352 return $newText; 05353 } 05354 } else { 05355 if ( $mode === 'get' ) { 05356 return $newText; 05357 } else { 05358 return $text; 05359 } 05360 } 05361 } 05362 05363 # Preprocess the text 05364 $root = $this->preprocessToDom( $text, $flags ); 05365 05366 # <h> nodes indicate section breaks 05367 # They can only occur at the top level, so we can find them by iterating the root's children 05368 $node = $root->getFirstChild(); 05369 05370 # Find the target section 05371 if ( $sectionIndex == 0 ) { 05372 # Section zero doesn't nest, level=big 05373 $targetLevel = 1000; 05374 } else { 05375 while ( $node ) { 05376 if ( $node->getName() === 'h' ) { 05377 $bits = $node->splitHeading(); 05378 if ( $bits['i'] == $sectionIndex ) { 05379 $targetLevel = $bits['level']; 05380 break; 05381 } 05382 } 05383 if ( $mode === 'replace' ) { 05384 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 05385 } 05386 $node = $node->getNextSibling(); 05387 } 05388 } 05389 05390 if ( !$node ) { 05391 # Not found 05392 if ( $mode === 'get' ) { 05393 return $newText; 05394 } else { 05395 return $text; 05396 } 05397 } 05398 05399 # Find the end of the section, including nested sections 05400 do { 05401 if ( $node->getName() === 'h' ) { 05402 $bits = $node->splitHeading(); 05403 $curLevel = $bits['level']; 05404 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) { 05405 break; 05406 } 05407 } 05408 if ( $mode === 'get' ) { 05409 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 05410 } 05411 $node = $node->getNextSibling(); 05412 } while ( $node ); 05413 05414 # Write out the remainder (in replace mode only) 05415 if ( $mode === 'replace' ) { 05416 # Output the replacement text 05417 # Add two newlines on -- trailing whitespace in $newText is conventionally 05418 # stripped by the editor, so we need both newlines to restore the paragraph gap 05419 # Only add trailing whitespace if there is newText 05420 if ( $newText != "" ) { 05421 $outText .= $newText . "\n\n"; 05422 } 05423 05424 while ( $node ) { 05425 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG ); 05426 $node = $node->getNextSibling(); 05427 } 05428 } 05429 05430 if ( is_string( $outText ) ) { 05431 # Re-insert stripped tags 05432 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) ); 05433 } 05434 05435 return $outText; 05436 } 05437 05450 public function getSection( $text, $section, $deftext='' ) { 05451 return $this->extractSections( $text, $section, "get", $deftext ); 05452 } 05453 05464 public function replaceSection( $oldtext, $section, $text ) { 05465 return $this->extractSections( $oldtext, $section, "replace", $text ); 05466 } 05467 05473 function getRevisionId() { 05474 return $this->mRevisionId; 05475 } 05476 05482 protected function getRevisionObject() { 05483 if ( !is_null( $this->mRevisionObject ) ) { 05484 return $this->mRevisionObject; 05485 } 05486 if ( is_null( $this->mRevisionId ) ) { 05487 return null; 05488 } 05489 05490 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId ); 05491 return $this->mRevisionObject; 05492 } 05493 05498 function getRevisionTimestamp() { 05499 if ( is_null( $this->mRevisionTimestamp ) ) { 05500 wfProfileIn( __METHOD__ ); 05501 05502 global $wgContLang; 05503 05504 $revObject = $this->getRevisionObject(); 05505 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow(); 05506 05507 # The cryptic '' timezone parameter tells to use the site-default 05508 # timezone offset instead of the user settings. 05509 # 05510 # Since this value will be saved into the parser cache, served 05511 # to other users, and potentially even used inside links and such, 05512 # it needs to be consistent for all visitors. 05513 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' ); 05514 05515 wfProfileOut( __METHOD__ ); 05516 } 05517 return $this->mRevisionTimestamp; 05518 } 05519 05525 function getRevisionUser() { 05526 if( is_null( $this->mRevisionUser ) ) { 05527 $revObject = $this->getRevisionObject(); 05528 05529 # if this template is subst: the revision id will be blank, 05530 # so just use the current user's name 05531 if( $revObject ) { 05532 $this->mRevisionUser = $revObject->getUserText(); 05533 } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) { 05534 $this->mRevisionUser = $this->getUser()->getName(); 05535 } 05536 } 05537 return $this->mRevisionUser; 05538 } 05539 05545 public function setDefaultSort( $sort ) { 05546 $this->mDefaultSort = $sort; 05547 $this->mOutput->setProperty( 'defaultsort', $sort ); 05548 } 05549 05560 public function getDefaultSort() { 05561 if ( $this->mDefaultSort !== false ) { 05562 return $this->mDefaultSort; 05563 } else { 05564 return ''; 05565 } 05566 } 05567 05574 public function getCustomDefaultSort() { 05575 return $this->mDefaultSort; 05576 } 05577 05587 public function guessSectionNameFromWikiText( $text ) { 05588 # Strip out wikitext links(they break the anchor) 05589 $text = $this->stripSectionName( $text ); 05590 $text = Sanitizer::normalizeSectionNameWhitespace( $text ); 05591 return '#' . Sanitizer::escapeId( $text, 'noninitial' ); 05592 } 05593 05602 public function guessLegacySectionNameFromWikiText( $text ) { 05603 # Strip out wikitext links(they break the anchor) 05604 $text = $this->stripSectionName( $text ); 05605 $text = Sanitizer::normalizeSectionNameWhitespace( $text ); 05606 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) ); 05607 } 05608 05623 public function stripSectionName( $text ) { 05624 # Strip internal link markup 05625 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text ); 05626 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text ); 05627 05628 # Strip external link markup 05629 # @todo FIXME: Not tolerant to blank link text 05630 # I.E. [http://www.mediawiki.org] will render as [1] or something depending 05631 # on how many empty links there are on the page - need to figure that out. 05632 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text ); 05633 05634 # Parse wikitext quotes (italics & bold) 05635 $text = $this->doQuotes( $text ); 05636 05637 # Strip HTML tags 05638 $text = StringUtils::delimiterReplace( '<', '>', '', $text ); 05639 return $text; 05640 } 05641 05652 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) { 05653 $this->startParse( $title, $options, $outputType, true ); 05654 05655 $text = $this->replaceVariables( $text ); 05656 $text = $this->mStripState->unstripBoth( $text ); 05657 $text = Sanitizer::removeHTMLtags( $text ); 05658 return $text; 05659 } 05660 05667 function testPst( $text, Title $title, ParserOptions $options ) { 05668 return $this->preSaveTransform( $text, $title, $options->getUser(), $options ); 05669 } 05670 05677 function testPreprocess( $text, Title $title, ParserOptions $options ) { 05678 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS ); 05679 } 05680 05697 function markerSkipCallback( $s, $callback ) { 05698 $i = 0; 05699 $out = ''; 05700 while ( $i < strlen( $s ) ) { 05701 $markerStart = strpos( $s, $this->mUniqPrefix, $i ); 05702 if ( $markerStart === false ) { 05703 $out .= call_user_func( $callback, substr( $s, $i ) ); 05704 break; 05705 } else { 05706 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) ); 05707 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart ); 05708 if ( $markerEnd === false ) { 05709 $out .= substr( $s, $markerStart ); 05710 break; 05711 } else { 05712 $markerEnd += strlen( self::MARKER_SUFFIX ); 05713 $out .= substr( $s, $markerStart, $markerEnd - $markerStart ); 05714 $i = $markerEnd; 05715 } 05716 } 05717 } 05718 return $out; 05719 } 05720 05727 function killMarkers( $text ) { 05728 return $this->mStripState->killMarkers( $text ); 05729 } 05730 05747 function serializeHalfParsedText( $text ) { 05748 wfProfileIn( __METHOD__ ); 05749 $data = array( 05750 'text' => $text, 05751 'version' => self::HALF_PARSED_VERSION, 05752 'stripState' => $this->mStripState->getSubState( $text ), 05753 'linkHolders' => $this->mLinkHolders->getSubArray( $text ) 05754 ); 05755 wfProfileOut( __METHOD__ ); 05756 return $data; 05757 } 05758 05773 function unserializeHalfParsedText( $data ) { 05774 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) { 05775 throw new MWException( __METHOD__.': invalid version' ); 05776 } 05777 05778 # First, extract the strip state. 05779 $texts = array( $data['text'] ); 05780 $texts = $this->mStripState->merge( $data['stripState'], $texts ); 05781 05782 # Now renumber links 05783 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts ); 05784 05785 # Should be good to go. 05786 return $texts[0]; 05787 } 05788 05798 function isValidHalfParsedText( $data ) { 05799 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION; 05800 } 05801 05810 public function parseWidthParam( $value ) { 05811 $parsedWidthParam = array(); 05812 if( $value === '' ) { 05813 return $parsedWidthParam; 05814 } 05815 $m = array(); 05816 # (bug 13500) In both cases (width/height and width only), 05817 # permit trailing "px" for backward compatibility. 05818 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) { 05819 $width = intval( $m[1] ); 05820 $height = intval( $m[2] ); 05821 $parsedWidthParam['width'] = $width; 05822 $parsedWidthParam['height'] = $height; 05823 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) { 05824 $width = intval( $value ); 05825 $parsedWidthParam['width'] = $width; 05826 } 05827 return $parsedWidthParam; 05828 } 05829 }