73 const VERSION =
'1.6.4';
79 const HALF_PARSED_VERSION = 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS =
'[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX =
'/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT = 0;
96 const COLON_STATE_TAG = 1;
97 const COLON_STATE_TAGSTART = 2;
98 const COLON_STATE_CLOSETAG = 3;
99 const COLON_STATE_TAGSLASH = 4;
100 const COLON_STATE_COMMENT = 5;
101 const COLON_STATE_COMMENTDASH = 6;
102 const COLON_STATE_COMMENTDASHDASH = 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION = 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
110 const
OT_WIKI = 2;
# like preSaveTransform()
113 const
OT_PLAIN = 4;
# like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 # Must have a character that needs escaping in attributes (since 1.25.6)
117 const MARKER_SUFFIX =
"-QINU`\"'\x7f";
119 # Markers used for wrapping the table of contents
120 const TOC_START =
'<mw:toc>';
121 const TOC_END =
'</mw:toc>';
124 var $mTagHooks =
array();
125 var $mTransparentTagHooks =
array();
126 var $mFunctionHooks =
array();
128 var $mFunctionTagHooks =
array();
129 var $mStripList =
array();
130 var $mDefaultStripList =
array();
131 var $mVarCache =
array();
132 var $mImageParams =
array();
133 var $mImageParamsMagicArray =
array();
134 var $mMarkerIndex = 0;
135 var $mFirstCall =
true;
137 # Initialised by initialiseVariables()
148 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised
in constructor
150 # Cleared with clearState():
155 var $mAutonumber, $mDTopen;
162 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
169 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
171 var $mTplExpandCache; # empty-frame expansion
cache
172 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
173 var $mExpensiveFunctionCount; # number
of expensive parser
function calls
174 var $mShowToc, $mForceTocPosition;
182 # These are variables reset at least once per parse regardless of $clearState
192 var $mTitle; #
Title context,
used for self-link rendering and similar
things
193 var $mOutputType; # Output
type, one
of the OT_xxx constants
194 var $ot; # Shortcut alias,
see setOutputType()
195 var $mRevisionObject;
# The revision object of the specified revision ID
196 var $mRevisionId; #
ID to display
in {{REVISIONID}}
tags
197 var $mRevisionTimestamp; # The timestamp
of the specified revision
ID
198 var $mRevisionUser; #
User to display
in {{REVISIONUSER}} tag
199 var $mRevisionSize; # Size to display
in {{REVISIONSIZE}}
variable
200 var $mRevIdForTs; # The revision
ID which was
used to fetch the timestamp
201 var $mInputSize =
false; # For {{PAGESIZE}}
on current
page.
213 var $mLangLinkLanguages;
220 public function __construct( $conf =
array() ) {
221 $this->mConf = $conf;
223 $this->mExtLinkBracketedRegex =
'/\[(((?i)' . $this->mUrlProtocols .
')' .
224 self::EXT_LINK_URL_CLASS .
'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
225 if ( isset( $conf[
'preprocessorClass'] ) ) {
226 $this->mPreprocessorClass = $conf[
'preprocessorClass'];
227 } elseif ( defined(
'HPHP_VERSION' ) ) {
228 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
229 $this->mPreprocessorClass =
'Preprocessor_Hash';
230 } elseif ( extension_loaded(
'domxml' ) ) {
231 # PECL extension that conflicts with the core DOM extension (bug 13770)
232 wfDebug(
"Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
233 $this->mPreprocessorClass =
'Preprocessor_Hash';
234 } elseif ( extension_loaded(
'dom' ) ) {
235 $this->mPreprocessorClass =
'Preprocessor_DOM';
237 $this->mPreprocessorClass =
'Preprocessor_Hash';
239 wfDebug( __CLASS__ .
": using preprocessor: {$this->mPreprocessorClass}\n" );
245 function __destruct() {
246 if ( isset( $this->mLinkHolders ) ) {
247 unset( $this->mLinkHolders );
250 unset( $this->$name );
264 function firstCallInit() {
265 if ( !$this->mFirstCall ) {
268 $this->mFirstCall =
false;
274 $this->initialiseVariables();
285 function clearState() {
287 if ( $this->mFirstCall ) {
288 $this->firstCallInit();
291 $this->mOptions->registerWatcher(
array( $this->mOutput,
'recordOption' ) );
292 $this->mAutonumber = 0;
293 $this->mLastSection =
'';
294 $this->mDTopen =
false;
295 $this->mIncludeCount =
array();
296 $this->mArgStack =
false;
297 $this->mInPre =
false;
300 $this->mRevisionObject = $this->mRevisionTimestamp =
301 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize =
null;
302 $this->mVarCache =
array();
304 $this->mLangLinkLanguages =
array();
316 $this->mUniqPrefix =
"\x7f'\"`UNIQ" . self::getRandomString();
317 $this->mStripState =
new StripState( $this->mUniqPrefix );
319 # Clear these on every parse, bug 4549
320 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache =
array();
322 $this->mShowToc =
true;
323 $this->mForceTocPosition =
false;
324 $this->mIncludeSizes =
array(
328 $this->mPPNodeCount = 0;
329 $this->mGeneratedPPNodeCount = 0;
330 $this->mHighestExpansionDepth = 0;
331 $this->mDefaultSort =
false;
332 $this->mHeadings =
array();
333 $this->mDoubleUnderscores =
array();
334 $this->mExpensiveFunctionCount = 0;
337 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
338 $this->mPreprocessor =
null;
363 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
370 $this->mInputSize = strlen( $text );
371 if ( $this->mOptions->getEnableLimitReport() ) {
372 $this->mOutput->resetParseStartTime();
375 # Remove the strip marker tag prefix from the input, if present.
377 $text = str_replace( $this->mUniqPrefix,
'', $text );
380 $oldRevisionId = $this->mRevisionId;
381 $oldRevisionObject = $this->mRevisionObject;
382 $oldRevisionTimestamp = $this->mRevisionTimestamp;
383 $oldRevisionUser = $this->mRevisionUser;
384 $oldRevisionSize = $this->mRevisionSize;
385 if ( $revid !==
null ) {
386 $this->mRevisionId = $revid;
387 $this->mRevisionObject =
null;
388 $this->mRevisionTimestamp =
null;
389 $this->mRevisionUser =
null;
390 $this->mRevisionSize =
null;
393 wfRunHooks(
'ParserBeforeStrip',
array( &$this, &$text, &$this->mStripState ) );
395 wfRunHooks(
'ParserAfterStrip',
array( &$this, &$text, &$this->mStripState ) );
396 $text = $this->internalParse( $text );
397 wfRunHooks(
'ParserAfterParse',
array( &$this, &$text, &$this->mStripState ) );
399 $text = $this->mStripState->unstripGeneral( $text );
401 # Clean up special characters, only run once, next-to-last before doBlockLevels
403 # french spaces, last one Guillemet-left
405 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' =>
'\\1 ',
406 # french spaces, Guillemet-right
407 '/(\\302\\253) /' =>
'\\1 ',
408 '/ (!\s*important)/' =>
' \\1', # Beware
of CSS magic word !important, bug #11874.
410 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
412 $text = $this->doBlockLevels( $text, $linestart );
414 $this->replaceLinkHolders( $text );
423 if ( !(
$options->getDisableContentConversion()
424 || isset( $this->mDoubleUnderscores[
'nocontentconvert'] ) )
426 if ( !$this->mOptions->getInterfaceMessage() ) {
427 # The position of the convert() call should not be changed. it
428 # assumes that the links are all replaced and the only thing left
429 # is the <nowiki> mark.
430 $text = $this->getConverterLanguage()->convert( $text );
441 if ( !(
$options->getDisableTitleConversion()
442 || isset( $this->mDoubleUnderscores[
'nocontentconvert'] )
443 || isset( $this->mDoubleUnderscores[
'notitleconvert'] )
444 || $this->mOutput->getDisplayTitle() !==
false )
446 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
447 if ( $convruletitle ) {
448 $this->mOutput->setTitleText( $convruletitle );
450 $titleText = $this->getConverterLanguage()->convertTitle(
$title );
451 $this->mOutput->setTitleText( $titleText );
455 $text = $this->mStripState->unstripNoWiki( $text );
459 $text = $this->replaceTransparentTags( $text );
460 $text = $this->mStripState->unstripGeneral( $text );
464 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
467 # attempt to sanitize at least some nesting problems
468 # (bug #2702 and quite a few others)
471 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
472 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
473 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
474 # fix
up an anchor inside another anchor,
only
475 # at least
for a single single nested link (bug 3695)
476 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
477 '\\1\\2</a>\\3</a>\\1\\4</a>',
478 # fix div inside
inline elements- doBlockLevels won
't wrap a line which
479 # contains a div, so fix it up here; replace
480 # div with escaped text
481 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/
' =>
482 '\\1\\3&
lt;div\\5&
gt;\\6&
lt;/div&
gt;\\8\\9
',
483 # remove empty italic or bold tag pairs, some
484 # introduced by rules above
485 '/<([bi])><\/\\1>/
' => '',
488 $text = preg_replace(
489 array_keys( $tidyregs ),
490 array_values( $tidyregs ),
494 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
495 $this->limitationWarn( 'expensive-parserfunction
',
496 $this->mExpensiveFunctionCount,
497 $this->mOptions->getExpensiveParserFunctionLimit()
501 wfRunHooks( 'ParserAfterTidy
', array( &$this, &$text ) );
503 # Information on include size limits, for the benefit of users who try to skirt them
504 if ( $this->mOptions->getEnableLimitReport() ) {
505 $max = $this->mOptions->getMaxIncludeSize();
507 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu
' );
508 if ( $cpuTime !== null ) {
509 $this->mOutput->setLimitReportData( 'limitreport-cputime
',
510 sprintf( "%.3f", $cpuTime )
514 $wallTime = $this->mOutput->getTimeSinceStart( 'wall
' );
515 $this->mOutput->setLimitReportData( 'limitreport-walltime
',
516 sprintf( "%.3f", $wallTime )
519 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes
',
520 array( $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() )
522 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes
',
523 array( $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() )
525 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize
',
526 array( $this->mIncludeSizes['post-expand
'], $max )
528 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize
',
529 array( $this->mIncludeSizes['arg
'], $max )
531 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth
',
532 array( $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() )
534 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount
',
535 array( $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() )
539 $limitReport = "NewPP limit report\n";
540 if ( $wgShowHostnames ) {
541 $limitReport .= 'Parsed by
' . wfHostname() . "\n";
543 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
544 if ( wfRunHooks( 'ParserLimitReportFormat
',
545 array( $key, &$value, &$limitReport, false, false )
547 $keyMsg = wfMessage( $key )->inLanguage( 'en
' )->useDatabase( false );
548 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
549 ->inLanguage( 'en
' )->useDatabase( false );
550 if ( !$valueMsg->exists() ) {
551 $valueMsg = new RawMessage( '$1
' );
553 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
554 $valueMsg->params( $value );
555 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
559 // Since we're not really outputting HTML, decode the entities and
561 $limitReport = htmlspecialchars_decode( $limitReport );
566 $limitReport = str_replace(
array(
'-',
'&' ),
array(
'‐',
'&' ), $limitReport );
567 $text .=
"\n<!-- \n$limitReport-->\n";
569 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
570 wfDebugLog(
'generated-pp-node-count', $this->mGeneratedPPNodeCount .
' ' .
571 $this->mTitle->getPrefixedDBkey() );
574 $this->mOutput->setText( $text );
576 $this->mRevisionId = $oldRevisionId;
577 $this->mRevisionObject = $oldRevisionObject;
578 $this->mRevisionTimestamp = $oldRevisionTimestamp;
579 $this->mRevisionUser = $oldRevisionUser;
580 $this->mRevisionSize = $oldRevisionSize;
581 $this->mInputSize =
false;
585 return $this->mOutput;
599 function recursiveTagParse( $text, $frame =
false ) {
601 wfRunHooks(
'ParserBeforeStrip',
array( &$this, &$text, &$this->mStripState ) );
602 wfRunHooks(
'ParserAfterStrip',
array( &$this, &$text, &$this->mStripState ) );
603 $text = $this->internalParse( $text,
false, $frame );
616 if ( $revid !==
null ) {
617 $this->mRevisionId = $revid;
619 wfRunHooks(
'ParserBeforeStrip',
array( &$this, &$text, &$this->mStripState ) );
620 wfRunHooks(
'ParserAfterStrip',
array( &$this, &$text, &$this->mStripState ) );
621 $text = $this->replaceVariables( $text );
622 $text = $this->mStripState->unstripBoth( $text );
636 public function recursivePreprocess( $text, $frame =
false ) {
638 $text = $this->replaceVariables( $text, $frame );
639 $text = $this->mStripState->unstripBoth( $text );
658 $msg =
new RawMessage( $text );
659 $text = $msg->params(
$params )->plain();
661 # Parser (re)initialisation
665 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
666 $text = $this->getPreprocessor()->newFrame()->expand( $dom,
$flags );
667 $text = $this->mStripState->unstripBoth( $text );
676 public static function getRandomString() {
686 function setUser(
$user ) {
687 $this->mUser =
$user;
695 public function uniqPrefix() {
696 if ( !isset( $this->mUniqPrefix ) ) {
697 # @todo FIXME: This is probably *horribly wrong*
698 # LanguageConverter seems to want $wgParser's uniqPrefix, however
699 # if this is called for a parser cache hit, the parser may not
700 # have ever been initialized in the first place.
701 # Not really sure what the heck is supposed to be going on here.
703 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
705 return $this->mUniqPrefix;
713 function setTitle(
$t ) {
718 if (
$t->hasFragment() ) {
719 # Strip the fragment to avoid various odd effects
720 $this->mTitle = clone
$t;
721 $this->mTitle->setFragment(
'' );
732 function getTitle() {
733 return $this->mTitle;
742 function Title( $x =
null ) {
743 return wfSetVar( $this->mTitle, $x );
751 function setOutputType( $ot ) {
752 $this->mOutputType = $ot;
768 function OutputType( $x =
null ) {
769 return wfSetVar( $this->mOutputType, $x );
777 function getOutput() {
778 return $this->mOutput;
786 function getOptions() {
787 return $this->mOptions;
796 function Options( $x =
null ) {
797 return wfSetVar( $this->mOptions, $x );
803 function nextLinkID() {
804 return $this->mLinkID++;
810 function setLinkID( $id ) {
811 $this->mLinkID = $id;
818 function getFunctionLang() {
819 return $this->getTargetLanguage();
831 public function getTargetLanguage() {
832 $target = $this->mOptions->getTargetLanguage();
834 if ( $target !==
null ) {
836 } elseif ( $this->mOptions->getInterfaceMessage() ) {
837 return $this->mOptions->getUserLangObj();
838 } elseif ( is_null( $this->mTitle ) ) {
839 throw new MWException( __METHOD__ .
': $this->mTitle is null' );
842 return $this->mTitle->getPageLanguage();
848 function getConverterLanguage() {
849 return $this->getTargetLanguage();
859 if ( !is_null( $this->mUser ) ) {
862 return $this->mOptions->getUser();
870 function getPreprocessor() {
871 if ( !isset( $this->mPreprocessor ) ) {
872 $class = $this->mPreprocessorClass;
873 $this->mPreprocessor =
new $class( $this );
875 return $this->mPreprocessor;
898 public static function extractTagsAndParams( $elements, $text, &
$matches, $uniq_prefix =
'' ) {
903 $taglist = implode(
'|', $elements );
904 $start =
"/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" .
">)|<(!--)/i";
906 while ( $text !=
'' ) {
907 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
909 if ( count( $p ) < 5 ) {
912 if ( count( $p ) > 5 ) {
926 $marker =
"$uniq_prefix-$element-" . sprintf(
'%08X',
$n++ ) . self::MARKER_SUFFIX;
927 $stripped .= $marker;
929 if ( $close ===
'/>' ) {
930 # Empty element tag, <tag />
935 if ( $element ===
'!--' ) {
938 $end =
"/(<\\/$element\\s*>)/i";
940 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
942 if ( count( $q ) < 3 ) {
943 # No end tag -- let it run out to the end of the text.
955 "<$element$attributes$close$content$tail" );
965 function getStripList() {
966 return $this->mStripList;
978 function insertStripItem( $text ) {
979 $rnd =
"{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
980 $this->mMarkerIndex++;
981 $this->mStripState->addGeneral( $rnd, $text );
991 function doTableStuff( $text ) {
996 $td_history =
array(); # Is currently a td tag
open?
997 $last_tag_history =
array(); # Save history
of last lag activated (td, th or caption)
998 $tr_history =
array(); # Is currently a tr tag
open?
999 $tr_attributes =
array(); # history
of tr attributes
1001 $indent_level = 0; # indent level
of the
table
1004 $line = trim( $outLine );
1007 $out .= $outLine .
"\n";
1011 $first_character =
$line[0];
1015 # First check if we are starting a new table
1016 $indent_level = strlen(
$matches[1] );
1018 $attributes = $this->mStripState->unstripBoth(
$matches[2] );
1021 $outLine = str_repeat(
'<dl><dd>', $indent_level ) .
"<table{$attributes}>";
1022 array_push( $td_history,
false );
1023 array_push( $last_tag_history,
'' );
1024 array_push( $tr_history,
false );
1025 array_push( $tr_attributes,
'' );
1026 array_push( $has_opened_tr,
false );
1027 } elseif ( count( $td_history ) == 0 ) {
1028 # Don't do any of the following
1029 $out .= $outLine .
"\n";
1031 } elseif ( substr(
$line, 0, 2 ) ===
'|}' ) {
1032 # We are ending a table
1034 $last_tag = array_pop( $last_tag_history );
1036 if ( !array_pop( $has_opened_tr ) ) {
1037 $line =
"<tr><td></td></tr>{$line}";
1040 if ( array_pop( $tr_history ) ) {
1041 $line =
"</tr>{$line}";
1044 if ( array_pop( $td_history ) ) {
1045 $line =
"</{$last_tag}>{$line}";
1047 array_pop( $tr_attributes );
1048 $outLine =
$line . str_repeat(
'</dd></dl>', $indent_level );
1049 } elseif ( substr(
$line, 0, 2 ) ===
'|-' ) {
1050 # Now we have a table row
1051 $line = preg_replace(
'#^\|-+#',
'',
$line );
1053 # Whats after the tag is now only attributes
1054 $attributes = $this->mStripState->unstripBoth(
$line );
1056 array_pop( $tr_attributes );
1057 array_push( $tr_attributes, $attributes );
1060 $last_tag = array_pop( $last_tag_history );
1061 array_pop( $has_opened_tr );
1062 array_push( $has_opened_tr,
true );
1064 if ( array_pop( $tr_history ) ) {
1068 if ( array_pop( $td_history ) ) {
1069 $line =
"</{$last_tag}>{$line}";
1073 array_push( $tr_history,
false );
1074 array_push( $td_history,
false );
1075 array_push( $last_tag_history,
'' );
1076 } elseif ( $first_character ===
'|' || $first_character ===
'!' || substr(
$line, 0, 2 ) ===
'|+' ) {
1077 # This might be cell elements, td, th or captions
1078 if ( substr(
$line, 0, 2 ) ===
'|+' ) {
1079 $first_character =
'+';
1085 if ( $first_character ===
'!' ) {
1089 # Split up multiple cells on the same line.
1090 # FIXME : This can result in improper nesting of tags processed
1091 # by earlier parser steps, but should avoid splitting up eg
1092 # attribute values containing literal "||".
1097 # Loop through each table cell
1098 foreach ( $cells
as $cell ) {
1100 if ( $first_character !==
'+' ) {
1101 $tr_after = array_pop( $tr_attributes );
1102 if ( !array_pop( $tr_history ) ) {
1103 $previous =
"<tr{$tr_after}>\n";
1105 array_push( $tr_history,
true );
1106 array_push( $tr_attributes,
'' );
1107 array_pop( $has_opened_tr );
1108 array_push( $has_opened_tr,
true );
1111 $last_tag = array_pop( $last_tag_history );
1113 if ( array_pop( $td_history ) ) {
1114 $previous =
"</{$last_tag}>\n{$previous}";
1117 if ( $first_character ===
'|' ) {
1119 } elseif ( $first_character ===
'!' ) {
1121 } elseif ( $first_character ===
'+' ) {
1122 $last_tag =
'caption';
1127 array_push( $last_tag_history, $last_tag );
1129 # A cell could contain both parameters and data
1130 $cell_data = explode(
'|', $cell, 2 );
1132 # Bug 553: Note that a '|' inside an invalid link should not
1133 # be mistaken as delimiting cell parameters
1134 if ( strpos( $cell_data[0],
'[[' ) !==
false ) {
1135 $cell =
"{$previous}<{$last_tag}>{$cell}";
1136 } elseif ( count( $cell_data ) == 1 ) {
1137 $cell =
"{$previous}<{$last_tag}>{$cell_data[0]}";
1139 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1141 $cell =
"{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1145 array_push( $td_history,
true );
1148 $out .= $outLine .
"\n";
1151 # Closing open td, tr && table
1152 while ( count( $td_history ) > 0 ) {
1153 if ( array_pop( $td_history ) ) {
1156 if ( array_pop( $tr_history ) ) {
1159 if ( !array_pop( $has_opened_tr ) ) {
1160 $out .=
"<tr><td></td></tr>\n";
1163 $out .=
"</table>\n";
1166 # Remove trailing line-ending (b/c)
1167 if ( substr(
$out, -1 ) ===
"\n" ) {
1171 # special case: don't return empty table
1172 if (
$out ===
"<table>\n<tr><td></td></tr>\n</table>" ) {
1193 function internalParse( $text, $isMain =
true, $frame =
false ) {
1198 # Hook to suspend the parser in this state
1199 if ( !
wfRunHooks(
'ParserBeforeInternalParse',
array( &$this, &$text, &$this->mStripState ) ) ) {
1204 # if $frame is provided, then use $frame for replacing any variables
1206 # use frame depth to infer how include/noinclude tags should be handled
1207 # depth=0 means this is the top-level document; otherwise it's an included document
1208 if ( !$frame->depth ) {
1211 $flag = Parser::PTD_FOR_INCLUSION;
1213 $dom = $this->preprocessToDom( $text, $flag );
1214 $text = $frame->expand( $dom );
1216 # if $frame is not provided, then use old-style replaceVariables
1217 $text = $this->replaceVariables( $text );
1220 wfRunHooks(
'InternalParseBeforeSanitize',
array( &$this, &$text, &$this->mStripState ) );
1222 wfRunHooks(
'InternalParseBeforeLinks',
array( &$this, &$text, &$this->mStripState ) );
1224 # Tables need to come after variable replacement for things to work
1225 # properly; putting them before other transformations should keep
1226 # exciting things like link expansions from showing up in surprising
1228 $text = $this->doTableStuff( $text );
1230 $text = preg_replace(
'/(^|\n)-----*/',
'\\1<hr />', $text );
1232 $text = $this->doDoubleUnderscore( $text );
1234 $text = $this->doHeadings( $text );
1235 $text = $this->replaceInternalLinks( $text );
1236 $text = $this->doAllQuotes( $text );
1237 $text = $this->replaceExternalLinks( $text );
1239 # replaceInternalLinks may sometimes leave behind
1240 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1241 $text = str_replace( $this->mUniqPrefix .
'NOPARSE',
'', $text );
1243 $text = $this->doMagicLinks( $text );
1244 $text = $this->formatHeadings( $text, $origText, $isMain );
1261 function doMagicLinks( $text ) {
1264 $urlChar = self::EXT_LINK_URL_CLASS;
1265 $text = preg_replace_callback(
1267 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1268 (<.*?>) | # m[2]: Skip stuff inside HTML elements' .
"
1269 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" .
'
1270 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1271 ISBN\s+(\b # m[5]: ISBN, capture number
1272 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1273 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1274 [0-9Xx] # check digit
1276 )!xu',
array( &$this,
'magicLinkCallback' ), $text );
1286 function magicLinkCallback( $m ) {
1287 if ( isset( $m[1] ) && $m[1] !==
'' ) {
1290 } elseif ( isset( $m[2] ) && $m[2] !==
'' ) {
1293 } elseif ( isset( $m[3] ) && $m[3] !==
'' ) {
1294 # Free external link
1295 return $this->makeFreeExternalLink( $m[0] );
1296 } elseif ( isset( $m[4] ) && $m[4] !==
'' ) {
1298 if ( substr( $m[0], 0, 3 ) ===
'RFC' ) {
1301 $cssClass =
'mw-magiclink-rfc';
1303 } elseif ( substr( $m[0], 0, 4 ) ===
'PMID' ) {
1305 $urlmsg =
'pubmedurl';
1306 $cssClass =
'mw-magiclink-pmid';
1309 throw new MWException( __METHOD__ .
': unrecognised match type "' .
1310 substr( $m[0], 0, 20 ) .
'"' );
1312 $url =
wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1314 } elseif ( isset( $m[5] ) && $m[5] !==
'' ) {
1317 $num = strtr( $isbn,
array(
1323 return '<a href="' .
1324 htmlspecialchars( $titleObj->getLocalURL() ) .
1325 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1339 function makeFreeExternalLink( $url ) {
1344 # The characters '<' and '>' (which were escaped by
1345 # removeHTMLtags()) should not be included in
1346 # URLs, per RFC 2396.
1348 if ( preg_match(
'/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1349 $trail = substr( $url, $m2[0][1] ) . $trail;
1350 $url = substr( $url, 0, $m2[0][1] );
1353 # Move trailing punctuation to $trail
1355 # If there is no left bracket, then consider right brackets fair game too
1356 if ( strpos( $url,
'(' ) ===
false ) {
1360 $numSepChars = strspn( strrev( $url ), $sep );
1361 if ( $numSepChars ) {
1362 $trail = substr( $url, -$numSepChars ) . $trail;
1363 $url = substr( $url, 0, -$numSepChars );
1368 # Is this an external image?
1369 $text = $this->maybeMakeExternalImage( $url );
1370 if ( $text ===
false ) {
1371 # Not an image, make a link
1373 $this->getConverterLanguage()->markNoConversion( $url,
true ),
1375 $this->getExternalLinkAttribs( $url ) );
1376 # Register it in the output object...
1377 $this->mOutput->addExternalLink( $url );
1380 return $text . $trail;
1392 function doHeadings( $text ) {
1394 for ( $i = 6; $i >= 1; --$i ) {
1395 $h = str_repeat(
'=', $i );
1396 $text = preg_replace(
"/^$h(.+)$h\\s*$/m",
"<h$i>\\1</h$i>", $text );
1410 function doAllQuotes( $text ) {
1415 $outtext .= $this->doQuotes(
$line ) .
"\n";
1417 $outtext = substr( $outtext, 0, -1 );
1429 public function doQuotes( $text ) {
1430 $arr = preg_split(
"/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1431 $countarr = count( $arr );
1432 if ( $countarr == 1 ) {
1441 for ( $i = 1; $i < $countarr; $i += 2 ) {
1442 $thislen = strlen( $arr[$i] );
1446 if ( $thislen == 4 ) {
1447 $arr[$i - 1] .=
"'";
1450 } elseif ( $thislen > 5 ) {
1454 $arr[$i - 1] .= str_repeat(
"'", $thislen - 5 );
1459 if ( $thislen == 2 ) {
1461 } elseif ( $thislen == 3 ) {
1463 } elseif ( $thislen == 5 ) {
1473 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1474 $firstsingleletterword = -1;
1475 $firstmultiletterword = -1;
1477 for ( $i = 1; $i < $countarr; $i += 2 ) {
1478 if ( strlen( $arr[$i] ) == 3 ) {
1479 $x1 = substr( $arr[$i - 1], -1 );
1480 $x2 = substr( $arr[$i - 1], -2, 1 );
1481 if ( $x1 ===
' ' ) {
1482 if ( $firstspace == -1 ) {
1485 } elseif ( $x2 ===
' ' ) {
1486 if ( $firstsingleletterword == -1 ) {
1487 $firstsingleletterword = $i;
1493 if ( $firstmultiletterword == -1 ) {
1494 $firstmultiletterword = $i;
1501 if ( $firstsingleletterword > -1 ) {
1502 $arr[$firstsingleletterword] =
"''";
1503 $arr[$firstsingleletterword - 1] .=
"'";
1504 } elseif ( $firstmultiletterword > -1 ) {
1506 $arr[$firstmultiletterword] =
"''";
1507 $arr[$firstmultiletterword - 1] .=
"'";
1508 } elseif ( $firstspace > -1 ) {
1512 $arr[$firstspace] =
"''";
1513 $arr[$firstspace - 1] .=
"'";
1522 foreach ( $arr
as $r ) {
1523 if ( ( $i % 2 ) == 0 ) {
1524 if ( $state ===
'both' ) {
1530 $thislen = strlen( $r );
1531 if ( $thislen == 2 ) {
1532 if ( $state ===
'i' ) {
1535 } elseif ( $state ===
'bi' ) {
1538 } elseif ( $state ===
'ib' ) {
1541 } elseif ( $state ===
'both' ) {
1542 $output .=
'<b><i>' . $buffer .
'</i>';
1548 } elseif ( $thislen == 3 ) {
1549 if ( $state ===
'b' ) {
1552 } elseif ( $state ===
'bi' ) {
1555 } elseif ( $state ===
'ib' ) {
1558 } elseif ( $state ===
'both' ) {
1559 $output .=
'<i><b>' . $buffer .
'</b>';
1565 } elseif ( $thislen == 5 ) {
1566 if ( $state ===
'b' ) {
1569 } elseif ( $state ===
'i' ) {
1572 } elseif ( $state ===
'bi' ) {
1575 } elseif ( $state ===
'ib' ) {
1578 } elseif ( $state ===
'both' ) {
1579 $output .=
'<i><b>' . $buffer .
'</b></i>';
1590 if ( $state ===
'b' || $state ===
'ib' ) {
1593 if ( $state ===
'i' || $state ===
'bi' || $state ===
'ib' ) {
1596 if ( $state ===
'bi' ) {
1600 if ( $state ===
'both' && $buffer ) {
1601 $output .=
'<b><i>' . $buffer .
'</i></b>';
1619 function replaceExternalLinks( $text ) {
1622 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1623 if ( $bits ===
false ) {
1625 throw new MWException(
"PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1627 $s = array_shift( $bits );
1630 while ( $i < count( $bits ) ) {
1633 $text = $bits[$i++];
1634 $trail = $bits[$i++];
1636 # The characters '<' and '>' (which were escaped by
1637 # removeHTMLtags()) should not be included in
1638 # URLs, per RFC 2396.
1640 if ( preg_match(
'/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1641 $text = substr( $url, $m2[0][1] ) .
' ' . $text;
1642 $url = substr( $url, 0, $m2[0][1] );
1645 # If the link text is an image URL, replace it with an <img> tag
1646 # This happened by accident in the original parser, but some people used it extensively
1647 $img = $this->maybeMakeExternalImage( $text );
1648 if ( $img !==
false ) {
1654 # Set linktype for CSS - if URL==text, link is essentially free
1655 $linktype = ( $text === $url ) ?
'free' :
'text';
1657 # No link text, e.g. [http://domain.tld/some.link]
1658 if ( $text ==
'' ) {
1660 $langObj = $this->getTargetLanguage();
1661 $text =
'[' . $langObj->formatNum( ++$this->mAutonumber ) .
']';
1662 $linktype =
'autonumber';
1664 # Have link text, e.g. [http://domain.tld/some.link text]s
1669 $text = $this->getConverterLanguage()->markNoConversion( $text );
1673 # Use the encoded URL
1674 # This means that users can paste URLs directly into the text
1675 # Funny characters like ö aren't valid in URLs anyway
1676 # This was changed in August 2004
1678 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1680 # Register link in the output object.
1681 $this->mOutput->addExternalLink( $url );
1697 public static function getExternalLinkRel( $url =
false,
$title =
null ) {
1698 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1700 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1718 function getExternalLinkAttribs( $url =
false ) {
1720 $rel = self::getExternalLinkRel( $url, $this->mTitle );
1722 $target = $this->mOptions->getExternalLinkTarget();
1725 if ( !in_array( $target,
array(
'_self',
'_parent',
'_top' ) ) ) {
1729 if ( $rel !==
'' ) {
1732 $rel .=
'noreferrer noopener';
1750 static function replaceUnusualEscapes( $url ) {
1751 return preg_replace_callback(
'/%[0-9A-Fa-f]{2}/',
1752 array( __CLASS__,
'replaceUnusualEscapesCallback' ), $url );
1763 private static function replaceUnusualEscapesCallback(
$matches ) {
1765 $ord = ord( $char );
1766 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1767 if ( $ord > 32 && $ord < 127 && strpos(
'<>"#{}|\^~[]`;/?', $char ) ===
false ) {
1768 # No, shouldn't be escaped
1771 # Yes, leave it escaped
1785 function maybeMakeExternalImage( $url ) {
1786 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1787 $imagesexception = !empty( $imagesfrom );
1789 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1790 if ( $imagesexception && is_array( $imagesfrom ) ) {
1791 $imagematch =
false;
1792 foreach ( $imagesfrom
as $match ) {
1793 if ( strpos( $url, $match ) === 0 ) {
1798 } elseif ( $imagesexception ) {
1799 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1801 $imagematch =
false;
1803 if ( $this->mOptions->getAllowExternalImages()
1804 || ( $imagesexception && $imagematch ) ) {
1805 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1810 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1811 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1812 $whitelist = explode(
"\n",
wfMessage(
'external_image_whitelist' )->inContentLanguage()->
text() );
1813 foreach ( $whitelist
as $entry ) {
1814 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1815 if ( strpos( $entry,
'#' ) === 0 || $entry ===
'' ) {
1818 if ( preg_match(
'/' . str_replace(
'/',
'\\/', $entry ) .
'/i', $url ) ) {
1819 # Image matches a whitelist entry
1837 function replaceInternalLinks(
$s ) {
1838 $this->mLinkHolders->merge( $this->replaceInternalLinks2(
$s ) );
1850 function replaceInternalLinks2( &
$s ) {
1854 static $tc =
false, $e1, $e1_img;
1855 # the % is needed to support urlencoded titles as well
1858 # Match a link having the form [[namespace:link|alternate]]trail
1859 $e1 =
"/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1860 # Match cases where there is no "]]", which might still be images
1861 $e1_img =
"/^([{$tc}]+)\\|(.*)\$/sD";
1866 # split the entire text string on occurrences of [[
1868 # get the first element (all text up to first [[), and remove the space we added
1871 $line = $a->current(); # Workaround
for broken ArrayIterator::next()
that returns "
void"
1872 $s = substr(
$s, 1 );
1874 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1876 if ( $useLinkPrefixExtension ) {
1877 # Match the end of a line for a word that's not followed by whitespace,
1878 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1881 $e2 =
"/^((?>.*[^$charset]|))(.+)$/sDu";
1884 if ( is_null( $this->mTitle ) ) {
1887 throw new MWException( __METHOD__ .
": \$this->mTitle is null\n" );
1889 $nottalk = !$this->mTitle->isTalkPage();
1891 if ( $useLinkPrefixExtension ) {
1893 if ( preg_match( $e2,
$s, $m ) ) {
1894 $first_prefix = $m[2];
1896 $first_prefix =
false;
1902 $useSubpages = $this->areSubpagesAllowed();
1905 # Loop for each link
1906 for ( ;
$line !==
false &&
$line !==
null; $a->next(),
$line = $a->current() ) {
1907 # Check for excessive memory usage
1908 if ( $holders->isBig() ) {
1910 # Do the existence check, replace the link holders and clear the array
1911 $holders->replace(
$s );
1915 if ( $useLinkPrefixExtension ) {
1917 if ( preg_match( $e2,
$s, $m ) ) {
1924 if ( $first_prefix ) {
1925 $prefix = $first_prefix;
1926 $first_prefix =
false;
1931 $might_be_img =
false;
1936 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1937 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1938 # the real problem is with the $e1 regex
1941 # Still some problems for cases where the ] is meant to be outside punctuation,
1942 # and no image is in sight. See bug 2095.
1945 && substr( $m[3], 0, 1 ) ===
']'
1946 && strpos( $text,
'[' ) !==
false
1948 $text .=
']'; #
so that replaceExternalLinks($text) works
later
1949 $m[3] = substr( $m[3], 1 );
1951 # fix up urlencoded title texts
1952 if ( strpos( $m[1],
'%' ) !==
false ) {
1953 # Should anchors '#' also be rejected?
1954 $m[1] = str_replace(
array(
'<',
'>' ),
array(
'<',
'>' ), rawurldecode( $m[1] ) );
1957 } elseif ( preg_match( $e1_img,
$line, $m ) ) { # Invalid, but might be an image with a link
in its caption
1958 $might_be_img =
true;
1960 if ( strpos( $m[1],
'%' ) !==
false ) {
1961 $m[1] = str_replace(
array(
'<',
'>' ),
array(
'<',
'>' ), rawurldecode( $m[1] ) );
1972 # Don't allow internal links to pages containing
1973 # PROTO: where PROTO is a valid URL protocol; these
1974 # should be external links.
1975 if ( preg_match(
'/^(?i:' . $this->mUrlProtocols .
')/', $m[1] ) ) {
1981 # Make subpage if necessary
1982 if ( $useSubpages ) {
1983 $link = $this->maybeDoSubpageLink( $m[1], $text );
1988 $noforce = ( substr( $m[1], 0, 1 ) !==
':' );
1990 # Strip off leading ':'
1997 if ( $nt ===
null ) {
2003 $ns = $nt->getNamespace();
2004 $iw = $nt->getInterwiki();
2007 if ( $might_be_img ) { #
if this is actually an invalid link
2009 if ( $ns ==
NS_FILE && $noforce ) { # but might be an image
2012 # look at the next 'line' to see if we can close it there
2014 $next_line = $a->current();
2015 if ( $next_line ===
false || $next_line ===
null ) {
2018 $m = explode(
']]', $next_line, 3 );
2019 if ( count( $m ) == 3 ) {
2020 # the first ]] closes the inner link, the second the image
2022 $text .=
"[[{$m[0]}]]{$m[1]}";
2025 } elseif ( count( $m ) == 2 ) {
2026 # if there's exactly one ]] that's fine, we'll keep looking
2027 $text .=
"[[{$m[0]}]]{$m[1]}";
2029 # if $next_line is invalid too, we need look no further
2030 $text .=
'[[' . $next_line;
2035 # we couldn't find the end of this imageLink, so output it raw
2036 # but don't ignore what might be perfectly normal links in the text we've examined
2037 $holders->merge( $this->replaceInternalLinks2( $text ) );
2038 $s .=
"{$prefix}[[$link|$text";
2039 # note: no $trail, because without an end, there *is* no trail
2043 }
else { #
it's not an image, so output it raw
2044 $s .= "{$prefix}[[$link|$text";
2045 # note: no $trail, because without an end, there *is* no trail
2046 wfProfileOut( __METHOD__ . "-might_be_img" );
2049 wfProfileOut( __METHOD__ . "-might_be_img" );
2052 $wasblank = ( $text == '' );
2056 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2057 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2058 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2059 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2060 $text = $this->doQuotes( $text );
2063 # Link not escaped by : , create the various objects
2066 wfProfileIn( __METHOD__ . "-interwiki" );
2067 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw
' ) ) {
2068 // XXX: the above check prevents links to sites with identifiers that are not language codes
2070 # Bug 24502: filter duplicates
2071 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2072 $this->mLangLinkLanguages[$iw] = true;
2073 $this->mOutput->addLanguageLink( $nt->getFullText() );
2076 $s = rtrim( $s . $prefix );
2077 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2078 wfProfileOut( __METHOD__ . "-interwiki" );
2081 wfProfileOut( __METHOD__ . "-interwiki" );
2083 if ( $ns == NS_FILE ) {
2084 wfProfileIn( __METHOD__ . "-image" );
2085 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2087 # if no parameters were passed, $text
2088 # becomes something like "File:Foo.png",
2089 # which we don't want to pass
on to the
2093 # recursively parse links inside the image caption
2094 # actually, this will parse them in any other parameters, too,
2095 # but it might be hard to fix that, and it doesn't matter ATM
2096 $text = $this->replaceExternalLinks( $text );
2097 $holders->merge( $this->replaceInternalLinks2( $text ) );
2099 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2100 $s .= $prefix . $this->armorLinks(
2101 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2103 $s .= $prefix . $trail;
2111 $s = rtrim(
$s .
"\n" ); # bug 87
2114 $sortkey = $this->getDefaultSort();
2119 $sortkey = str_replace(
"\n",
'', $sortkey );
2120 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2121 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2126 $s .= trim( $prefix . $trail,
"\n" ) ==
'' ?
'' : $prefix . $trail;
2133 # Self-link checking. For some languages, variants of the title are checked in
2134 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2135 # for linking to a different variant.
2136 if ( $ns !=
NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2141 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2142 # @todo FIXME: Should do batch file existence checks, see comment below
2145 # Give extensions a chance to select the file revision for us
2150 # Fetch and register the file (file title may be different via hooks)
2152 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2153 $s .= $prefix . $this->armorLinks(
2160 # Some titles, such as valid special pages or files in foreign repos, should
2161 # be shown as bluelinks even though they're not included in the page table
2163 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2164 # batch file existence checks for NS_FILE and NS_MEDIA
2165 if ( $iw ==
'' && $nt->isAlwaysKnown() ) {
2166 $this->mOutput->addLink( $nt );
2167 $s .= $this->makeKnownLinkHolder( $nt, $text,
array(), $trail, $prefix );
2169 # Links will be added to the output link list after checking
2170 $s .= $holders->makeHolder( $nt, $text,
array(), $trail, $prefix );
2192 function makeKnownLinkHolder( $nt, $text =
'',
$query =
array(), $trail =
'', $prefix =
'' ) {
2195 if ( is_string(
$query ) ) {
2198 if ( $text ==
'' ) {
2199 $text = htmlspecialchars( $nt->getPrefixedText() );
2204 return $this->armorLinks(
$link ) . $trail;
2217 function armorLinks( $text ) {
2218 return preg_replace(
'/\b((?i)' . $this->mUrlProtocols .
')/',
2219 "{$this->mUniqPrefix}NOPARSE$1", $text );
2226 function areSubpagesAllowed() {
2227 # Some namespaces don't allow subpages
2239 function maybeDoSubpageLink( $target, &$text ) {
2249 function closeParagraph() {
2251 if ( $this->mLastSection !=
'' ) {
2252 $result =
'</' . $this->mLastSection .
">\n";
2254 $this->mInPre =
false;
2255 $this->mLastSection =
'';
2269 function getCommon( $st1, $st2 ) {
2270 $fl = strlen( $st1 );
2271 $shorter = strlen( $st2 );
2272 if ( $fl < $shorter ) {
2276 for ( $i = 0; $i < $shorter; ++$i ) {
2277 if ( $st1[$i] != $st2[$i] ) {
2293 function openList( $char ) {
2294 $result = $this->closeParagraph();
2296 if (
'*' === $char ) {
2298 } elseif (
'#' === $char ) {
2300 } elseif (
':' === $char ) {
2302 } elseif (
';' === $char ) {
2304 $this->mDTopen =
true;
2319 function nextItem( $char ) {
2320 if (
'*' === $char ||
'#' === $char ) {
2321 return "</li>\n<li>";
2322 } elseif (
':' === $char ||
';' === $char ) {
2324 if ( $this->mDTopen ) {
2327 if (
';' === $char ) {
2328 $this->mDTopen =
true;
2329 return $close .
'<dt>';
2331 $this->mDTopen =
false;
2332 return $close .
'<dd>';
2335 return '<!-- ERR 2 -->';
2345 function closeList( $char ) {
2346 if (
'*' === $char ) {
2347 $text =
"</li>\n</ul>";
2348 } elseif (
'#' === $char ) {
2349 $text =
"</li>\n</ol>";
2350 } elseif (
':' === $char ) {
2351 if ( $this->mDTopen ) {
2352 $this->mDTopen =
false;
2353 $text =
"</dt>\n</dl>";
2355 $text =
"</dd>\n</dl>";
2358 return '<!-- ERR 3 -->';
2360 return $text .
"\n";
2372 function doBlockLevels( $text, $linestart ) {
2375 # Parsing through the text line by line. The main thing
2376 # happening here is handling of block-level elements p, pre,
2377 # and making lists from lines starting with * # : etc.
2382 $this->mDTopen = $inBlockElem =
false;
2384 $paragraphStack =
false;
2385 $inBlockquote =
false;
2387 foreach ( $textLines
as $oLine ) {
2389 if ( !$linestart ) {
2399 $lastPrefixLength = strlen( $lastPrefix );
2400 $preCloseMatch = preg_match(
'/<\\/pre/i', $oLine );
2401 $preOpenMatch = preg_match(
'/<pre/i', $oLine );
2402 # If not in a <pre> element, scan for and figure out what prefixes are there.
2403 if ( !$this->mInPre ) {
2404 # Multiple prefixes may abut each other for nested lists.
2405 $prefixLength = strspn( $oLine,
'*#:;' );
2406 $prefix = substr( $oLine, 0, $prefixLength );
2409 # ; and : are both from definition-lists, so they're equivalent
2410 # for the purposes of determining whether or not we need to open/close
2412 $prefix2 = str_replace(
';',
':', $prefix );
2413 $t = substr( $oLine, $prefixLength );
2414 $this->mInPre = (bool)$preOpenMatch;
2416 # Don't interpret any other prefixes in preformatted text
2418 $prefix = $prefix2 =
'';
2423 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2424 # Same as the last item, so no need to deal with nesting or opening stuff
2425 $output .= $this->nextItem( substr( $prefix, -1 ) );
2426 $paragraphStack =
false;
2428 if ( substr( $prefix, -1 ) ===
';' ) {
2429 # The one nasty exception: definition lists work like this:
2430 # ; title : definition text
2431 # So we check for : in the remainder text to split up the
2432 # title and definition, without b0rking links.
2434 if ( $this->findColonNoLinks(
$t,
$term, $t2 ) !==
false ) {
2439 } elseif ( $prefixLength || $lastPrefixLength ) {
2440 # We need to open or close prefixes, or both.
2442 # Either open or close a level...
2443 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2444 $paragraphStack =
false;
2446 # Close all the prefixes which aren't shared.
2447 while ( $commonPrefixLength < $lastPrefixLength ) {
2448 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2449 --$lastPrefixLength;
2452 # Continue the current prefix if appropriate.
2453 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2454 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2457 # Open prefixes where appropriate.
2458 while ( $prefixLength > $commonPrefixLength ) {
2459 $char = substr( $prefix, $commonPrefixLength, 1 );
2460 $output .= $this->openList( $char );
2462 if (
';' === $char ) {
2463 # @todo FIXME: This is dupe of code above
2464 if ( $this->findColonNoLinks(
$t,
$term, $t2 ) !==
false ) {
2469 ++$commonPrefixLength;
2471 $lastPrefix = $prefix2;
2474 # If we have no prefixes, go to paragraph mode.
2475 if ( 0 == $prefixLength ) {
2477 # No prefix (not in list)--go to paragraph mode
2478 # XXX: use a stack for nestable elements like span, table and div
2479 $openmatch = preg_match(
'/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
$t );
2480 $closematch = preg_match(
2481 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2482 '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|' . $this->mUniqPrefix .
'-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
$t );
2483 if ( $openmatch or $closematch ) {
2484 $paragraphStack =
false;
2485 # TODO bug 5718: paragraph closed
2486 $output .= $this->closeParagraph();
2487 if ( $preOpenMatch and !$preCloseMatch ) {
2488 $this->mInPre =
true;
2491 while ( preg_match(
'/<(\\/?)blockquote[\s>]/i',
$t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) {
2492 $inBlockquote = !$bqMatch[1][0];
2493 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
2495 $inBlockElem = !$closematch;
2496 } elseif ( !$inBlockElem && !$this->mInPre ) {
2497 if (
' ' == substr(
$t, 0, 1 ) and ( $this->mLastSection ===
'pre' || trim(
$t ) !=
'' ) and !$inBlockquote ) {
2499 if ( $this->mLastSection !==
'pre' ) {
2500 $paragraphStack =
false;
2501 $output .= $this->closeParagraph() .
'<pre>';
2502 $this->mLastSection =
'pre';
2504 $t = substr(
$t, 1 );
2507 if ( trim(
$t ) ===
'' ) {
2508 if ( $paragraphStack ) {
2509 $output .= $paragraphStack .
'<br />';
2510 $paragraphStack =
false;
2511 $this->mLastSection =
'p';
2513 if ( $this->mLastSection !==
'p' ) {
2514 $output .= $this->closeParagraph();
2515 $this->mLastSection =
'';
2516 $paragraphStack =
'<p>';
2518 $paragraphStack =
'</p><p>';
2522 if ( $paragraphStack ) {
2524 $paragraphStack =
false;
2525 $this->mLastSection =
'p';
2526 } elseif ( $this->mLastSection !==
'p' ) {
2527 $output .= $this->closeParagraph() .
'<p>';
2528 $this->mLastSection =
'p';
2535 # somewhere above we forget to get out of pre block (bug 785)
2536 if ( $preCloseMatch && $this->mInPre ) {
2537 $this->mInPre =
false;
2539 if ( $paragraphStack ===
false ) {
2543 while ( $prefixLength ) {
2544 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2547 if ( $this->mLastSection !=
'' ) {
2548 $output .=
'</' . $this->mLastSection .
'>';
2549 $this->mLastSection =
'';
2566 function findColonNoLinks( $str, &$before, &$after ) {
2569 $pos = strpos( $str,
':' );
2570 if ( $pos ===
false ) {
2576 $lt = strpos( $str,
'<' );
2577 if ( $lt ===
false || $lt > $pos ) {
2578 # Easy; no tag nesting to worry about
2579 $before = substr( $str, 0, $pos );
2580 $after = substr( $str, $pos + 1 );
2585 # Ugly state machine to walk through avoiding tags.
2586 $state = self::COLON_STATE_TEXT;
2588 $len = strlen( $str );
2589 for ( $i = 0; $i < $len; $i++ ) {
2593 # (Using the number is a performance hack for common cases)
2594 case 0: # self::COLON_STATE_TEXT:
2597 # Could be either a <start> tag or an </end> tag
2598 $state = self::COLON_STATE_TAGSTART;
2601 if ( $stack == 0 ) {
2603 $before = substr( $str, 0, $i );
2604 $after = substr( $str, $i + 1 );
2608 # Embedded in a tag; don't break it.
2611 # Skip ahead looking for something interesting
2612 $colon = strpos( $str,
':', $i );
2613 if ( $colon ===
false ) {
2614 # Nothing else interesting
2618 $lt = strpos( $str,
'<', $i );
2619 if ( $stack === 0 ) {
2620 if ( $lt ===
false || $colon < $lt ) {
2622 $before = substr( $str, 0, $colon );
2623 $after = substr( $str, $colon + 1 );
2628 if ( $lt ===
false ) {
2629 # Nothing else interesting to find; abort!
2630 # We're nested, but there's no close tags left. Abort!
2633 # Skip ahead to next tag start
2635 $state = self::COLON_STATE_TAGSTART;
2638 case 1: # self::COLON_STATE_TAG:
2643 $state = self::COLON_STATE_TEXT;
2646 # Slash may be followed by >?
2647 $state = self::COLON_STATE_TAGSLASH;
2653 case 2: # self::COLON_STATE_TAGSTART:
2656 $state = self::COLON_STATE_CLOSETAG;
2659 $state = self::COLON_STATE_COMMENT;
2662 # Illegal early close? This shouldn't happen D:
2663 $state = self::COLON_STATE_TEXT;
2666 $state = self::COLON_STATE_TAG;
2669 case 3: # self::COLON_STATE_CLOSETAG:
2674 wfDebug( __METHOD__ .
": Invalid input; too many close tags\n" );
2678 $state = self::COLON_STATE_TEXT;
2681 case self::COLON_STATE_TAGSLASH:
2683 # Yes, a self-closed tag <blah/>
2684 $state = self::COLON_STATE_TEXT;
2686 # Probably we're jumping the gun, and this is an attribute
2687 $state = self::COLON_STATE_TAG;
2690 case 5: # self::COLON_STATE_COMMENT:
2692 $state = self::COLON_STATE_COMMENTDASH;
2695 case self::COLON_STATE_COMMENTDASH:
2697 $state = self::COLON_STATE_COMMENTDASHDASH;
2699 $state = self::COLON_STATE_COMMENT;
2702 case self::COLON_STATE_COMMENTDASHDASH:
2704 $state = self::COLON_STATE_TEXT;
2706 $state = self::COLON_STATE_COMMENT;
2711 throw new MWException(
"State machine error in " . __METHOD__ );
2715 wfDebug( __METHOD__ .
": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2734 function getVariableValue( $index, $frame =
false ) {
2738 if ( is_null( $this->mTitle ) ) {
2743 throw new MWException( __METHOD__ .
' Should only be '
2744 .
' called while parsing (no title set)' );
2751 if (
wfRunHooks(
'ParserGetVariableValueVarCache',
array( &$this, &$this->mVarCache ) ) ) {
2752 if ( isset( $this->mVarCache[$index] ) ) {
2753 return $this->mVarCache[$index];
2760 $pageLang = $this->getFunctionLang();
2763 case 'currentmonth':
2766 case 'currentmonth1':
2769 case 'currentmonthname':
2772 case 'currentmonthnamegen':
2775 case 'currentmonthabbrev':
2790 case 'localmonthname':
2793 case 'localmonthnamegen':
2796 case 'localmonthabbrev':
2811 case 'fullpagename':
2814 case 'fullpagenamee':
2820 case 'subpagenamee':
2823 case 'rootpagename':
2826 case 'rootpagenamee':
2829 case 'basepagename':
2832 case 'basepagenamee':
2835 case 'talkpagename':
2836 if ( $this->mTitle->canTalk() ) {
2837 $talkPage = $this->mTitle->getTalkPage();
2843 case 'talkpagenamee':
2844 if ( $this->mTitle->canTalk() ) {
2845 $talkPage = $this->mTitle->getTalkPage();
2851 case 'subjectpagename':
2852 $subjPage = $this->mTitle->getSubjectPage();
2855 case 'subjectpagenamee':
2856 $subjPage = $this->mTitle->getSubjectPage();
2860 $pageid = $this->getTitle()->getArticleID();
2861 if ( $pageid == 0 ) {
2862 # 0 means the page doesn't exist in the database,
2863 # which means the user is previewing a new page.
2864 # The vary-revision flag must be set, because the magic word
2865 # will have a different value once the page is saved.
2866 $this->mOutput->setFlag(
'vary-revision' );
2867 wfDebug( __METHOD__ .
": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2869 $value = $pageid ? $pageid :
null;
2872 # Let the edit saving system know we should parse the page
2873 # *after* a revision ID has been assigned.
2874 $this->mOutput->setFlag(
'vary-revision' );
2875 wfDebug( __METHOD__ .
": {{REVISIONID}} used, setting vary-revision...\n" );
2876 $value = $this->mRevisionId;
2879 # Let the edit saving system know we should parse the page
2880 # *after* a revision ID has been assigned. This is for null edits.
2881 $this->mOutput->setFlag(
'vary-revision' );
2882 wfDebug( __METHOD__ .
": {{REVISIONDAY}} used, setting vary-revision...\n" );
2883 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2885 case 'revisionday2':
2886 # Let the edit saving system know we should parse the page
2887 # *after* a revision ID has been assigned. This is for null edits.
2888 $this->mOutput->setFlag(
'vary-revision' );
2889 wfDebug( __METHOD__ .
": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2890 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2892 case 'revisionmonth':
2893 # Let the edit saving system know we should parse the page
2894 # *after* a revision ID has been assigned. This is for null edits.
2895 $this->mOutput->setFlag(
'vary-revision' );
2896 wfDebug( __METHOD__ .
": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2897 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2899 case 'revisionmonth1':
2900 # Let the edit saving system know we should parse the page
2901 # *after* a revision ID has been assigned. This is for null edits.
2902 $this->mOutput->setFlag(
'vary-revision' );
2903 wfDebug( __METHOD__ .
": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2904 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2906 case 'revisionyear':
2907 # Let the edit saving system know we should parse the page
2908 # *after* a revision ID has been assigned. This is for null edits.
2909 $this->mOutput->setFlag(
'vary-revision' );
2910 wfDebug( __METHOD__ .
": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2911 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2913 case 'revisiontimestamp':
2914 # Let the edit saving system know we should parse the page
2915 # *after* a revision ID has been assigned. This is for null edits.
2916 $this->mOutput->setFlag(
'vary-revision' );
2917 wfDebug( __METHOD__ .
": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2918 $value = $this->getRevisionTimestamp();
2920 case 'revisionuser':
2921 # Let the edit saving system know we should parse the page
2922 # *after* a revision ID has been assigned. This is for null edits.
2923 $this->mOutput->setFlag(
'vary-revision' );
2924 wfDebug( __METHOD__ .
": {{REVISIONUSER}} used, setting vary-revision...\n" );
2925 $value = $this->getRevisionUser();
2927 case 'revisionsize':
2928 # Let the edit saving system know we should parse the page
2929 # *after* a revision ID has been assigned. This is for null edits.
2930 $this->mOutput->setFlag(
'vary-revision' );
2931 wfDebug( __METHOD__ .
": {{REVISIONSIZE}} used, setting vary-revision...\n" );
2932 $value = $this->getRevisionSize();
2935 $value = str_replace(
'_',
' ',
$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2940 case 'namespacenumber':
2941 $value = $this->mTitle->getNamespace();
2944 $value = $this->mTitle->canTalk() ? str_replace(
'_',
' ', $this->mTitle->getTalkNsText() ) :
'';
2947 $value = $this->mTitle->canTalk() ?
wfUrlencode( $this->mTitle->getTalkNsText() ) :
'';
2949 case 'subjectspace':
2950 $value = str_replace(
'_',
' ', $this->mTitle->getSubjectNsText() );
2952 case 'subjectspacee':
2955 case 'currentdayname':
2968 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2969 # int to remove the padding
2975 case 'localdayname':
2988 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2989 # int to remove the padding
2995 case 'numberofarticles':
2998 case 'numberoffiles':
3001 case 'numberofusers':
3004 case 'numberofactiveusers':
3007 case 'numberofpages':
3010 case 'numberofadmins':
3013 case 'numberofedits':
3016 case 'numberofviews':
3017 global $wgDisableCounters;
3020 case 'currenttimestamp':
3023 case 'localtimestamp':
3026 case 'currentversion':
3037 return $serverParts && isset( $serverParts[
'host'] ) ? $serverParts[
'host'] : $wgServer;
3039 return $wgScriptPath;
3041 return $wgStylePath;
3042 case 'directionmark':
3043 return $pageLang->getDirMark();
3044 case 'contentlanguage':
3046 return $wgLanguageCode;
3047 case 'cascadingsources':
3052 wfRunHooks(
'ParserGetVariableValueSwitch',
array( &$this, &$this->mVarCache, &$index, &
$ret, &$frame ) );
3057 $this->mVarCache[$index] =
$value;
3068 function initialiseVariables() {
3100 function preprocessToDom( $text,
$flags = 0 ) {
3101 $dom = $this->getPreprocessor()->preprocessToObj( $text,
$flags );
3112 public static function splitWhitespace(
$s ) {
3113 $ltrimmed = ltrim(
$s );
3114 $w1 = substr(
$s, 0, strlen(
$s ) - strlen( $ltrimmed ) );
3115 $trimmed = rtrim( $ltrimmed );
3116 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3118 $w2 = substr( $ltrimmed, -$diff );
3122 return array( $w1, $trimmed, $w2 );
3144 function replaceVariables( $text, $frame =
false, $argsOnly =
false ) {
3145 # Is there any text? Also, Prevent too big inclusions!
3146 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3151 if ( $frame ===
false ) {
3152 $frame = $this->getPreprocessor()->newFrame();
3153 } elseif ( !( $frame instanceof
PPFrame ) ) {
3154 wfDebug( __METHOD__ .
" called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3155 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3158 $dom = $this->preprocessToDom( $text );
3160 $text = $frame->expand( $dom,
$flags );
3173 static function createAssocArgs(
$args ) {
3174 $assocArgs =
array();
3177 $eqpos = strpos( $arg,
'=' );
3178 if ( $eqpos ===
false ) {
3179 $assocArgs[$index++] = $arg;
3181 $name = trim( substr( $arg, 0, $eqpos ) );
3182 $value = trim( substr( $arg, $eqpos + 1 ) );
3183 if (
$value ===
false ) {
3186 if (
$name !==
false ) {
3219 function limitationWarn( $limitationType, $current =
'', $max =
'' ) {
3220 # does no harm if $current and $max are present but are unnecessary for the message
3221 $warning =
wfMessage(
"$limitationType-warning" )->numParams( $current, $max )
3222 ->inLanguage( $this->mOptions->getUserLangObj() )->
text();
3223 $this->mOutput->addWarning( $warning );
3224 $this->addTrackingCategory(
"$limitationType-category" );
3240 function braceSubstitution( $piece, $frame ) {
3245 $found =
false; # $text has been filled
3246 $nowiki =
false; #
wiki markup
in $text should be escaped
3247 $isHTML =
false; # $text
is HTML, armour
it against wikitext transformation
3248 $forceRawInterwiki =
false; # Force interwiki transclusion to be done
in raw mode not rendered
3249 $isChildObj =
false; # $text
is a DOM node needing expansion
in a child frame
3250 $isLocalObj =
false; # $text
is a DOM node needing expansion
in the current frame
3252 # Title object, where $text came from
3255 # $part1 is the bit before the first |, and must contain only title characters.
3256 # Various prefixes will be stripped from it later.
3257 $titleWithSpaces = $frame->expand( $piece[
'title'] );
3258 $part1 = trim( $titleWithSpaces );
3261 # Original title text preserved for various purposes
3262 $originalTitle = $part1;
3264 # $args is a list of argument nodes, starting from index 0, not including $part1
3265 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3266 $args = (
null == $piece[
'parts'] ) ?
array() : $piece[
'parts'];
3269 $titleProfileIn =
null;
3275 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3277 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3278 # Decide whether to expand template or keep wikitext as-is.
3279 if ( $this->ot[
'wiki'] ) {
3280 if ( $substMatch ===
false ) {
3281 $literal =
true; # literal when
in PST with no prefix
3283 $literal =
false; # expand when
in PST with subst: or safesubst:
3286 if ( $substMatch ==
'subst' ) {
3287 $literal =
true; # literal when not
in PST with plain subst:
3289 $literal =
false; # expand when not
in PST with safesubst: or no prefix
3293 $text = $frame->virtualBracketedImplode(
'{{',
'|',
'}}', $titleWithSpaces,
$args );
3300 if ( !$found &&
$args->getLength() == 0 ) {
3301 $id = $this->mVariables->matchStartToEnd( $part1 );
3302 if ( $id !==
false ) {
3303 $text = $this->getVariableValue( $id, $frame );
3311 # MSG, MSGNW and RAW
3315 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3318 # Remove obsolete MSG:
3320 $mwMsg->matchStartAndRemove( $part1 );
3325 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3326 $forceRawInterwiki =
true;
3335 $colonPos = strpos( $part1,
':' );
3336 if ( $colonPos !==
false ) {
3337 $func = substr( $part1, 0, $colonPos );
3338 $funcArgs =
array( trim( substr( $part1, $colonPos + 1 ) ) );
3339 for ( $i = 0; $i <
$args->getLength(); $i++ ) {
3340 $funcArgs[] =
$args->item( $i );
3343 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3344 }
catch ( Exception $ex ) {
3350 # The interface for parser functions allows for extracting
3351 # flags into the local scope. Extract any forwarded flags
3358 # Finish mangling title and then check for loops.
3359 # Set $title to a Title object and $titleText to the PDBK
3362 # Split the title into page and subpage
3364 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3365 if ( $part1 !== $relative ) {
3367 $ns = $this->mTitle->getNamespace();
3371 $titleText =
$title->getPrefixedText();
3372 # Check for language variants if the template is not found
3373 if ( $this->getConverterLanguage()->hasVariants() &&
$title->getArticleID() == 0 ) {
3374 $this->getConverterLanguage()->findVariantLink( $part1,
$title,
true );
3376 # Do recursion depth check
3377 $limit = $this->mOptions->getMaxTemplateDepth();
3378 if ( $frame->depth >=
$limit ) {
3380 $text =
'<span class="error">'
3381 .
wfMessage(
'parser-template-recursion-depth-warning' )
3382 ->numParams(
$limit )->inContentLanguage()->text()
3388 # Load from database
3389 if ( !$found &&
$title ) {
3391 # Too many unique items can kill profiling DBs/collectors
3392 $titleProfileIn = __METHOD__ .
"-title-" .
$title->getPrefixedDBkey();
3396 if ( !
$title->isExternal() ) {
3397 if (
$title->isSpecialPage()
3398 && $this->mOptions->getAllowSpecialInclusion()
3399 && $this->ot[
'html']
3404 $pageArgs =
array();
3405 for ( $i = 0; $i <
$args->getLength(); $i++ ) {
3406 $bits =
$args->item( $i )->splitArg();
3407 if ( strval( $bits[
'index'] ) ===
'' ) {
3409 $value = trim( $frame->expand( $bits[
'value'] ) );
3417 $context->setRequest(
new FauxRequest( $pageArgs ) );
3418 $context->setUser( $this->getUser() );
3419 $context->setLanguage( $this->mOptions->getUserLangObj() );
3422 $text = $context->getOutput()->getHTML();
3423 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3426 $this->disableCache();
3429 $found =
false; # access denied
3430 wfDebug( __METHOD__ .
": template inclusion denied for " .
3431 $title->getPrefixedDBkey() .
"\n" );
3434 if ( $text !==
false ) {
3440 # If the title is valid but undisplayable, make a link to it
3441 if ( !$found && ( $this->ot[
'html'] || $this->ot[
'pre'] ) ) {
3442 $text =
"[[:$titleText]]";
3445 } elseif (
$title->isTrans() ) {
3446 # Interwiki transclusion
3447 if ( $this->ot[
'html'] && !$forceRawInterwiki ) {
3448 $text = $this->interwikiTransclude(
$title,
'render' );
3451 $text = $this->interwikiTransclude(
$title,
'raw' );
3452 # Preprocess it like a template
3453 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3459 # Do infinite loop check
3460 # This has to be done after redirect resolution to avoid infinite loops via redirects
3461 if ( !$frame->loopCheck(
$title ) ) {
3463 $text =
'<span class="error">'
3464 .
wfMessage(
'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3466 wfDebug( __METHOD__ .
": template loop broken at '$titleText'\n" );
3471 # If we haven't found text to substitute by now, we're done
3472 # Recover the source wikitext and return it
3474 $text = $frame->virtualBracketedImplode(
'{{',
'|',
'}}', $titleWithSpaces,
$args );
3475 if ( $titleProfileIn ) {
3479 return array(
'object' => $text );
3482 # Expand DOM-style return values in a child frame
3483 if ( $isChildObj ) {
3484 # Clean up argument array
3489 } elseif ( $titleText !==
false && $newFrame->isEmpty() ) {
3490 # Expansion is eligible for the empty-frame cache
3491 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3492 $text = $this->mTplExpandCache[$titleText];
3494 $text = $newFrame->expand( $text );
3495 $this->mTplExpandCache[$titleText] = $text;
3498 # Uncached expansion
3499 $text = $newFrame->expand( $text );
3502 if ( $isLocalObj && $nowiki ) {
3504 $isLocalObj =
false;
3507 if ( $titleProfileIn ) {
3511 # Replace raw HTML by a placeholder
3513 $text = $this->insertStripItem( $text );
3514 } elseif ( $nowiki && ( $this->ot[
'html'] || $this->ot[
'pre'] ) ) {
3515 # Escape nowiki-style return values
3517 } elseif ( is_string( $text )
3518 && !$piece[
'lineStart']
3519 && preg_match(
'/^(?:{\\||:|;|#|\*)/', $text )
3521 # Bug 529: if the template begins with a table or block-level
3522 # element, it should be treated as beginning a new line.
3523 # This behavior is somewhat controversial.
3524 $text =
"\n" . $text;
3527 if ( is_string( $text ) && !$this->incrementIncludeSize(
'post-expand', strlen( $text ) ) ) {
3528 # Error, oversize inclusion
3529 if ( $titleText !==
false ) {
3530 # Make a working, properly escaped link if possible (bug 23588)
3531 $text =
"[[:$titleText]]";
3533 # This will probably not be a working link, but at least it may
3534 # provide some hint of where the problem is
3535 preg_replace(
'/^:/',
'', $originalTitle );
3536 $text =
"[[:$originalTitle]]";
3538 $text .= $this->insertStripItem(
'<!-- WARNING: template omitted, post-expand include size too large -->' );
3539 $this->limitationWarn(
'post-expand-template-inclusion' );
3542 if ( $isLocalObj ) {
3570 public function callParserFunction( $frame, $function,
array $args =
array() ) {
3575 # Case sensitive functions
3576 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3577 $function = $this->mFunctionSynonyms[1][$function];
3579 # Case insensitive functions
3581 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3582 $function = $this->mFunctionSynonyms[0][$function];
3585 return array(
'found' =>
false );
3589 wfProfileIn( __METHOD__ .
'-pfunc-' . $function );
3590 list( $callback,
$flags ) = $this->mFunctionHooks[$function];
3592 # Workaround for PHP bug 35229 and similar
3593 if ( !is_callable( $callback ) ) {
3596 throw new MWException(
"Tag hook for $function is not callable\n" );
3599 $allArgs =
array( &$this );
3601 # Convert arguments to PPNodes and collect for appending to $allArgs
3602 $funcArgs =
array();
3603 foreach (
$args as $k => $v ) {
3604 if ( $v instanceof
PPNode || $k === 0 ) {
3607 $funcArgs[] = $this->mPreprocessor->newPartNodeArray(
array( $k => $v ) )->item( 0 );
3611 # Add a frame parameter, and pass the arguments as an array
3612 $allArgs[] = $frame;
3613 $allArgs[] = $funcArgs;
3615 # Convert arguments to plain text and append to $allArgs
3616 foreach (
$args as $k => $v ) {
3617 if ( $v instanceof
PPNode ) {
3618 $allArgs[] = trim( $frame->expand( $v ) );
3619 } elseif ( is_int( $k ) && $k >= 0 ) {
3620 $allArgs[] = trim( $v );
3622 $allArgs[] = trim(
"$k=$v" );
3627 $result = call_user_func_array( $callback, $allArgs );
3629 # The interface for function hooks allows them to return a wikitext
3630 # string or an array containing the string and any flags. This mungs
3631 # things around to match what this method should return.
3648 $preprocessFlags = 0;
3649 if ( isset(
$result[
'noparse'] ) ) {
3650 $noparse =
$result[
'noparse'];
3652 if ( isset(
$result[
'preprocessFlags'] ) ) {
3653 $preprocessFlags =
$result[
'preprocessFlags'];
3657 $result[
'text'] = $this->preprocessToDom(
$result[
'text'], $preprocessFlags );
3674 function getTemplateDom(
$title ) {
3676 $titleText =
$title->getPrefixedDBkey();
3678 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3679 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3681 $titleText =
$title->getPrefixedDBkey();
3683 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3684 return array( $this->mTplDomCache[$titleText],
$title );
3687 # Cache miss, go to the database
3690 if ( $text ===
false ) {
3691 $this->mTplDomCache[$titleText] =
false;
3695 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3696 $this->mTplDomCache[$titleText] = $dom;
3698 if ( !
$title->equals( $cacheTitle ) ) {
3699 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3711 function fetchTemplateAndTitle(
$title ) {
3712 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3713 $stuff = call_user_func( $templateCb,
$title, $this );
3714 $text = $stuff['
text'];
3715 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] :
$title;
3716 if ( isset( $stuff['deps'] ) ) {
3717 foreach ( $stuff[
'deps']
as $dep ) {
3718 $this->mOutput->addTemplate( $dep[
'title'], $dep[
'page_id'], $dep[
'rev_id'] );
3719 if ( $dep[
'title']->equals( $this->getTitle() ) ) {
3722 $this->mOutput->setFlag(
'vary-revision' );
3726 return array( $text, $finalTitle );
3734 function fetchTemplate(
$title ) {
3735 $rv = $this->fetchTemplateAndTitle(
$title );
3748 static function statelessFetchTemplate(
$title,
$parser =
false ) {
3749 $text = $skip =
false;
3753 # Loop to fetch the article, with up to 1 redirect
3754 for ( $i = 0; $i < 2 && is_object(
$title ); $i++ ) {
3755 # Give extensions a chance to select the revision instead
3756 $id =
false; # Assume current
3757 wfRunHooks(
'BeforeParserFetchTemplateAndtitle',
3764 'page_id' =>
$title->getArticleID(),
3773 $rev_id =
$rev ?
$rev->getId() : 0;
3774 # If there is no current revision, there is no page
3775 if ( $id ===
false && !
$rev ) {
3777 $linkCache->addBadLinkObj(
$title );
3782 'page_id' =>
$title->getArticleID(),
3783 'rev_id' => $rev_id );
3785 # We fetched a rev from a different title; register it too...
3787 'title' =>
$rev->getTitle(),
3788 'page_id' =>
$rev->getPage(),
3789 'rev_id' => $rev_id );
3793 $content =
$rev->getContent();
3794 $text = $content ? $content->getWikitextForTransclusion() :
null;
3796 if ( $text ===
false || $text ===
null ) {
3803 if ( !$message->exists() ) {
3807 $content = $message->content();
3808 $text = $message->plain();
3817 $title = $content->getRedirectTarget();
3821 'finalTitle' => $finalTitle,
3849 # Register the file as a dependency...
3850 $this->mOutput->addImage(
$title->getDBkey(),
$time, $sha1 );
3852 # Update fetched file title
3854 $this->mOutput->addImage(
$title->getDBkey(),
$time, $sha1 );
3870 if ( isset(
$options[
'broken'] ) ) {
3872 } elseif ( isset(
$options[
'sha1'] ) ) {
3888 function interwikiTransclude(
$title, $action ) {
3889 global $wgEnableScaryTranscluding;
3891 if ( !$wgEnableScaryTranscluding ) {
3892 return wfMessage(
'scarytranscludedisabled' )->inContentLanguage()->text();
3895 $url =
$title->getFullURL(
array(
'action' => $action ) );
3897 if ( strlen( $url ) > 255 ) {
3898 return wfMessage(
'scarytranscludetoolong' )->inContentLanguage()->text();
3900 return $this->fetchScaryTemplateMaybeFromCache( $url );
3907 function fetchScaryTemplateMaybeFromCache( $url ) {
3908 global $wgTranscludeCacheExpiry;
3910 $tsCond =
$dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3911 $obj =
$dbr->selectRow(
'transcache',
array(
'tc_time',
'tc_contents' ),
3912 array(
'tc_url' => $url,
"tc_time >= " .
$dbr->addQuotes( $tsCond ) ) );
3914 return $obj->tc_contents;
3918 $status = $req->execute();
3919 if ( $status->isOK() ) {
3920 $text = $req->getContent();
3921 } elseif ( $req->getStatus() != 200 ) {
3922 return wfMessage(
'scarytranscludefailed-httpstatus', $url, $req->getStatus() )->inContentLanguage()->text();
3924 return wfMessage(
'scarytranscludefailed', $url )->inContentLanguage()->text();
3928 $dbw->replace(
'transcache',
array(
'tc_url' ),
array(
3930 'tc_time' => $dbw->timestamp( time() ),
3931 'tc_contents' => $text
3945 function argSubstitution( $piece, $frame ) {
3949 $parts = $piece[
'parts'];
3950 $nameWithSpaces = $frame->expand( $piece[
'title'] );
3951 $argName = trim( $nameWithSpaces );
3953 $text = $frame->getArgument( $argName );
3954 if ( $text ===
false && $parts->getLength() > 0
3955 && ( $this->ot[
'html']
3957 || ( $this->ot[
'wiki'] && $frame->isTemplate() )
3960 # No match in frame, use the supplied default
3961 $object = $parts->item( 0 )->getChildren();
3963 if ( !$this->incrementIncludeSize(
'arg', strlen( $text ) ) ) {
3964 $error =
'<!-- WARNING: argument omitted, expansion size too large -->';
3965 $this->limitationWarn(
'post-expand-template-argument' );
3968 if ( $text ===
false && $object ===
false ) {
3970 $object = $frame->virtualBracketedImplode(
'{{{',
'|',
'}}}', $nameWithSpaces, $parts );
3972 if (
$error !==
false ) {
3975 if ( $object !==
false ) {
4000 function extensionSubstitution(
$params, $frame ) {
4002 $attrText = !isset(
$params[
'attr'] ) ? null : $frame->expand(
$params[
'attr'] );
4003 $content = !isset(
$params[
'inner'] ) ? null : $frame->expand(
$params[
'inner'] );
4004 $marker =
"{$this->mUniqPrefix}-$name-" . sprintf(
'%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
4006 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower(
$name )] ) &&
4007 ( $this->ot[
'html'] || $this->ot[
'pre'] );
4008 if ( $isFunctionTag ) {
4009 $markerType =
'none';
4011 $markerType =
'general';
4013 if ( $this->ot[
'html'] || $isFunctionTag ) {
4016 if ( isset(
$params[
'attributes'] ) ) {
4017 $attributes = $attributes +
$params[
'attributes'];
4020 if ( isset( $this->mTagHooks[
$name] ) ) {
4021 # Workaround for PHP bug 35229 and similar
4022 if ( !is_callable( $this->mTagHooks[
$name] ) ) {
4023 throw new MWException(
"Tag hook for $name is not callable\n" );
4025 $output = call_user_func_array( $this->mTagHooks[
$name],
4026 array( $content, $attributes, $this, $frame ) );
4027 } elseif ( isset( $this->mFunctionTagHooks[
$name] ) ) {
4028 list( $callback, ) = $this->mFunctionTagHooks[
$name];
4029 if ( !is_callable( $callback ) ) {
4030 throw new MWException(
"Tag hook for $name is not callable\n" );
4033 $output = call_user_func_array( $callback,
array( &$this, $frame, $content, $attributes ) );
4035 $output =
'<span class="error">Invalid tag extension name: ' .
4036 htmlspecialchars(
$name ) .
'</span>';
4040 # Extract flags to local scope (to override $markerType)
4047 if ( is_null( $attrText ) ) {
4050 if ( isset(
$params[
'attributes'] ) ) {
4051 foreach (
$params[
'attributes']
as $attrName => $attrValue ) {
4052 $attrText .=
' ' . htmlspecialchars( $attrName ) .
'="' .
4053 htmlspecialchars( $attrValue ) .
'"';
4056 if ( $content ===
null ) {
4057 $output =
"<$name$attrText/>";
4059 $close = is_null(
$params[
'close'] ) ?
'' : $frame->expand(
$params[
'close'] );
4060 $output =
"<$name$attrText>$content$close";
4064 if ( $markerType ===
'none' ) {
4066 } elseif ( $markerType ===
'nowiki' ) {
4067 $this->mStripState->addNoWiki( $marker,
$output );
4068 } elseif ( $markerType ===
'general' ) {
4069 $this->mStripState->addGeneral( $marker,
$output );
4071 throw new MWException( __METHOD__ .
': invalid marker type' );
4083 function incrementIncludeSize(
$type,
$size ) {
4084 if ( $this->mIncludeSizes[
$type] +
$size > $this->mOptions->getMaxIncludeSize() ) {
4097 function incrementExpensiveFunctionCount() {
4098 $this->mExpensiveFunctionCount++;
4099 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4110 function doDoubleUnderscore( $text ) {
4113 # The position of __TOC__ needs to be recorded
4115 if ( $mw->match( $text ) ) {
4116 $this->mShowToc =
true;
4117 $this->mForceTocPosition =
true;
4119 # Set a placeholder. At the end we'll fill it in with the TOC.
4120 $text = $mw->replace(
'<!--MWTOC-->', $text, 1 );
4122 # Only keep the first one.
4123 $text = $mw->replace(
'', $text );
4126 # Now match and remove the rest of them
4128 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4130 if ( isset( $this->mDoubleUnderscores[
'nogallery'] ) ) {
4131 $this->mOutput->mNoGallery =
true;
4133 if ( isset( $this->mDoubleUnderscores[
'notoc'] ) && !$this->mForceTocPosition ) {
4134 $this->mShowToc =
false;
4136 if ( isset( $this->mDoubleUnderscores[
'hiddencat'] ) && $this->mTitle->getNamespace() ==
NS_CATEGORY ) {
4137 $this->addTrackingCategory(
'hidden-category-category' );
4139 # (bug 8068) Allow control over whether robots index a page.
4141 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4142 # is not desirable, the last one on the page should win.
4143 if ( isset( $this->mDoubleUnderscores[
'noindex'] ) && $this->mTitle->canUseNoindex() ) {
4144 $this->mOutput->setIndexPolicy(
'noindex' );
4145 $this->addTrackingCategory(
'noindex-category' );
4147 if ( isset( $this->mDoubleUnderscores[
'index'] ) && $this->mTitle->canUseNoindex() ) {
4148 $this->mOutput->setIndexPolicy(
'index' );
4149 $this->addTrackingCategory(
'index-category' );
4152 # Cache all double underscores in the database
4153 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4154 $this->mOutput->setProperty( $key,
'' );
4172 public function addTrackingCategory( $msg ) {
4173 if ( $this->mTitle->getNamespace() ===
NS_SPECIAL ) {
4174 wfDebug( __METHOD__ .
": Not adding tracking category $msg to special page!\n" );
4179 ->title( $this->getTitle() )
4180 ->inContentLanguage()
4183 # Allow tracking categories to be disabled by setting them to "-"
4184 if ( $cat ===
'-' ) {
4189 if ( $containerCategory ) {
4190 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4193 wfDebug( __METHOD__ .
": [[MediaWiki:$msg]] is not a valid title!\n" );
4214 function formatHeadings( $text, $origText, $isMain =
true ) {
4215 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4217 # Inhibit editsection links if requested in the page
4218 if ( isset( $this->mDoubleUnderscores[
'noeditsection'] ) ) {
4219 $maybeShowEditLink = $showEditLink =
false;
4221 $maybeShowEditLink =
true;
4222 $showEditLink = $this->mOptions->getEditSection();
4224 if ( $showEditLink ) {
4225 $this->mOutput->setEditSectionTokens(
true );
4228 # Get all headlines for numbering them and adding funky stuff like [edit]
4229 # links - this is for later, but we need the number of headlines right now
4231 $numMatches = preg_match_all(
'/<H(?P<level>[1-6])(?P<attrib>.*?' .
'>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text,
$matches );
4233 # if there are fewer than 4 headlines in the article, do not show TOC
4234 # unless it's been explicitly enabled.
4235 $enoughToc = $this->mShowToc &&
4236 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4238 # Allow user to stipulate that a page should have a "new section"
4239 # link added via __NEWSECTIONLINK__
4240 if ( isset( $this->mDoubleUnderscores[
'newsectionlink'] ) ) {
4241 $this->mOutput->setNewSection(
true );
4244 # Allow user to remove the "new section"
4245 # link via __NONEWSECTIONLINK__
4246 if ( isset( $this->mDoubleUnderscores[
'nonewsectionlink'] ) ) {
4247 $this->mOutput->hideNewSection(
true );
4250 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4251 # override above conditions and always show TOC above first header
4252 if ( isset( $this->mDoubleUnderscores[
'forcetoc'] ) ) {
4253 $this->mShowToc =
true;
4261 # Ugh .. the TOC should have neat indentation levels which can be
4262 # passed to the skin functions. These are determined here
4266 $sublevelCount =
array();
4267 $levelCount =
array();
4272 $markerRegex =
"{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4273 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4274 $oldType = $this->mOutputType;
4276 $frame = $this->getPreprocessor()->newFrame();
4277 $root = $this->preprocessToDom( $origText );
4278 $node = $root->getFirstChild();
4284 $isTemplate =
false;
4286 $sectionIndex =
false;
4288 $markerMatches =
array();
4289 if ( preg_match(
"/^$markerRegex/", $headline, $markerMatches ) ) {
4290 $serial = $markerMatches[1];
4291 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4292 $isTemplate = ( $titleText != $baseTitleText );
4293 $headline = preg_replace(
"/^$markerRegex\\s*/",
"", $headline );
4297 $prevlevel = $level;
4299 $level =
$matches[1][$headlineCount];
4301 if ( $level > $prevlevel ) {
4302 # Increase TOC level
4304 $sublevelCount[$toclevel] = 0;
4305 if ( $toclevel < $wgMaxTocLevel ) {
4306 $prevtoclevel = $toclevel;
4310 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4311 # Decrease TOC level, find level to jump to
4313 for ( $i = $toclevel; $i > 0; $i-- ) {
4314 if ( $levelCount[$i] == $level ) {
4315 # Found last matching level
4318 } elseif ( $levelCount[$i] < $level ) {
4319 # Found first matching level below current level
4327 if ( $toclevel < $wgMaxTocLevel ) {
4328 if ( $prevtoclevel < $wgMaxTocLevel ) {
4329 # Unindent only if the previous toc level was shown :p
4331 $prevtoclevel = $toclevel;
4337 # No change in level, end TOC line
4338 if ( $toclevel < $wgMaxTocLevel ) {
4343 $levelCount[$toclevel] = $level;
4345 # count number of headlines for each level
4346 $sublevelCount[$toclevel]++;
4348 for ( $i = 1; $i <= $toclevel; $i++ ) {
4349 if ( !empty( $sublevelCount[$i] ) ) {
4353 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4358 # The safe header is a version of the header text safe to use for links
4360 # Remove link placeholders by the link text.
4361 # <!--LINK number-->
4363 # link text with suffix
4364 # Do this before unstrip since link text can contain strip markers
4365 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4367 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4368 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4370 # Strip out HTML (first regex removes any tag not allowed)
4372 # * <sup> and <sub> (bug 8393)
4375 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4377 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4378 # to allow setting directionality in toc items.
4379 $tocline = preg_replace(
4380 array(
'#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' .
'>#',
'#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' .
'>#' ),
4381 array(
'',
'<$1>' ),
4384 $tocline = trim( $tocline );
4386 # For the anchor, strip out HTML-y stuff period
4387 $safeHeadline = preg_replace(
'/<.*?' .
'>/',
'', $safeHeadline );
4390 # Save headline for section edit hint before it's escaped
4391 $headlineHint = $safeHeadline;
4393 if ( $wgExperimentalHtmlIds ) {
4394 # For reverse compatibility, provide an id that's
4395 # HTML4-compatible, like we used to.
4397 # It may be worth noting, academically, that it's possible for
4398 # the legacy anchor to conflict with a non-legacy headline
4399 # anchor on the page. In this case likely the "correct" thing
4400 # would be to either drop the legacy anchors or make sure
4401 # they're numbered first. However, this would require people
4402 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4403 # manually, so let's not bother worrying about it.
4405 array(
'noninitial',
'legacy' ) );
4408 if ( $legacyHeadline == $safeHeadline ) {
4409 # No reason to have both (in fact, we can't)
4410 $legacyHeadline =
false;
4413 $legacyHeadline =
false;
4418 # HTML names must be case-insensitively unique (bug 10721).
4419 # This does not apply to Unicode characters per
4420 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4421 # @todo FIXME: We may be changing them depending on the current locale.
4422 $arrayKey = strtolower( $safeHeadline );
4423 if ( $legacyHeadline ===
false ) {
4424 $legacyArrayKey =
false;
4426 $legacyArrayKey = strtolower( $legacyHeadline );
4429 # count how many in assoc. array so we can track dupes in anchors
4430 if ( isset( $refers[$arrayKey] ) ) {
4431 $refers[$arrayKey]++;
4433 $refers[$arrayKey] = 1;
4435 if ( isset( $refers[$legacyArrayKey] ) ) {
4436 $refers[$legacyArrayKey]++;
4438 $refers[$legacyArrayKey] = 1;
4441 # Don't number the heading if it is the only one (looks silly)
4442 if ( count(
$matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4443 # the two are different if the line contains a link
4444 $headline =
Html::element(
'span',
array(
'class' =>
'mw-headline-number' ), $numbering ) .
' ' . $headline;
4447 # Create the anchor for linking from the TOC to the section
4448 $anchor = $safeHeadline;
4449 $legacyAnchor = $legacyHeadline;
4450 if ( $refers[$arrayKey] > 1 ) {
4451 $anchor .=
'_' . $refers[$arrayKey];
4453 if ( $legacyHeadline !==
false && $refers[$legacyArrayKey] > 1 ) {
4454 $legacyAnchor .=
'_' . $refers[$legacyArrayKey];
4456 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4458 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4461 # Add the section to the section tree
4462 # Find the DOM node for this header
4463 $noOffset = ( $isTemplate || $sectionIndex ===
false );
4464 while ( $node && !$noOffset ) {
4465 if ( $node->getName() ===
'h' ) {
4466 $bits = $node->splitHeading();
4467 if ( $bits[
'i'] == $sectionIndex ) {
4471 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4473 $node = $node->getNextSibling();
4476 'toclevel' => $toclevel,
4479 'number' => $numbering,
4480 'index' => ( $isTemplate ?
'T-' :
'' ) . $sectionIndex,
4481 'fromtitle' => $titleText,
4482 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4483 'anchor' => $anchor,
4486 # give headline the correct <h#> tag
4487 if ( $maybeShowEditLink && $sectionIndex !==
false ) {
4489 if ( $isTemplate ) {
4490 # Put a T flag in the section identifier, to indicate to extractSections()
4491 # that sections inside <includeonly> should be counted.
4492 $editlinkArgs =
array( $titleText,
"T-$sectionIndex" );
4494 $editlinkArgs =
array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4503 $editlink =
'<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4504 $editlink .=
'" section="' . htmlspecialchars( $editlinkArgs[1] ) .
'"';
4505 if ( isset( $editlinkArgs[2] ) ) {
4506 $editlink .=
'>' . $editlinkArgs[2] .
'</mw:editsection>';
4514 $matches[
'attrib'][$headlineCount], $anchor, $headline,
4515 $editlink, $legacyAnchor );
4520 $this->setOutputType( $oldType );
4522 # Never ever show TOC if no headers
4523 if ( $numVisible < 1 ) {
4528 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4532 $this->mOutput->setTOCHTML( $toc );
4533 $toc = self::TOC_START . $toc . self::TOC_END;
4537 $this->mOutput->setSections( $tocraw );
4540 # split up and insert constructed headlines
4541 $blocks = preg_split(
'/<H[1-6].*?' .
'>[\s\S]*?<\/H[1-6]>/i', $text );
4545 $sections =
array();
4546 foreach ( $blocks
as $block ) {
4548 if ( empty( $head[$i - 1] ) ) {
4549 $sections[$i] = $block;
4551 $sections[$i] = $head[$i - 1] . $block;
4564 wfRunHooks(
'ParserSectionCreate',
array( $this, $i, &$sections[$i], $showEditLink ) );
4569 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4572 $sections[0] = $sections[0] . $toc .
"\n";
4575 $full .= join(
'', $sections );
4577 if ( $this->mForceTocPosition ) {
4578 return str_replace(
'<!--MWTOC-->', $toc, $full );
4597 $this->setUser(
$user );
4602 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4603 if (
$options->getPreSaveTransform() ) {
4604 $text = $this->pstPass2( $text,
$user );
4606 $text = $this->mStripState->unstripBoth( $text );
4608 $this->setUser(
null ); #Reset
4621 private function pstPass2( $text,
$user ) {
4624 # Note: This is the timestamp saved as hardcoded wikitext to
4625 # the database, we use $wgContLang here in order to give
4626 # everyone the same signature and use the default one rather
4627 # than the one selected in each user's preferences.
4628 # (see also bug 12815)
4629 $ts = $this->mOptions->getTimestamp();
4632 $tzMsg =
$timestamp->format(
'T' ); # might vary
on DST changeover!
4634 # Allow translation of timezones through wiki. format() can return
4635 # whatever crap the system uses, localised or not, so we cannot
4636 # ship premade translations.
4637 $key =
'timezone-' . strtolower( trim( $tzMsg ) );
4638 $msg =
wfMessage( $key )->inContentLanguage();
4639 if ( $msg->exists() ) {
4640 $tzMsg = $msg->text();
4643 $d =
$wgContLang->timeanddate( $ts,
false,
false ) .
" ($tzMsg)";
4645 # Variable replacement
4646 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4647 $text = $this->replaceVariables( $text );
4649 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4650 # which may corrupt this parser instance via its wfMessage()->text() call-
4653 $sigText = $this->getUserSig(
$user );
4654 $text = strtr( $text,
array(
4656 '~~~~' =>
"$sigText $d",
4660 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4662 $nc =
'[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4664 $p1 =
"/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:
page (context)|]]
4665 $p4 =
"/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (
double-width brackets, added
in r40257)
4666 $p3 =
"/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:
page (context), context|]] (
using either single or
double-width comma)
4669 #
try $p1 first, to turn
"[[A, B (C)|]]" into
"[[A, B (C)|A, B]]"
4670 $text = preg_replace( $p1,
'[[\\1\\2\\3|\\2]]', $text );
4671 $text = preg_replace( $p4,
'[[\\1\\2\\3|\\2]]', $text );
4672 $text = preg_replace( $p3,
'[[\\1\\2\\3\\4|\\2]]', $text );
4674 $t = $this->mTitle->getText();
4676 if ( preg_match(
"/^($nc+:|)$tc+?( \\($tc+\\))$/",
$t, $m ) ) {
4677 $text = preg_replace( $p2,
"[[$m[1]\\1$m[2]|\\1]]", $text );
4678 } elseif ( preg_match(
"/^($nc+:|)$tc+?(, $tc+|)$/",
$t, $m ) &&
"$m[1]$m[2]" !=
'' ) {
4679 $text = preg_replace( $p2,
"[[$m[1]\\1$m[2]|\\1]]", $text );
4681 # if there's no context, don't bother duplicating the title
4682 $text = preg_replace( $p2,
'[[\\1]]', $text );
4685 # Trim trailing whitespace
4686 $text = rtrim( $text );
4705 function getUserSig( &
$user, $nickname =
false, $fancySig =
null ) {
4708 $username =
$user->getName();
4710 # If not given, retrieve from the user object.
4711 if ( $nickname ===
false ) {
4712 $nickname =
$user->getOption(
'nickname' );
4715 if ( is_null( $fancySig ) ) {
4716 $fancySig =
$user->getBoolOption(
'fancysig' );
4719 $nickname = $nickname ==
null ? $username : $nickname;
4721 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4722 $nickname = $username;
4723 wfDebug( __METHOD__ .
": $username has overlong signature.\n" );
4724 } elseif ( $fancySig !==
false ) {
4725 # Sig. might contain markup; validate this
4726 if ( $this->validateSig( $nickname ) !==
false ) {
4727 # Validated; clean up (if needed) and return it
4728 return $this->cleanSig( $nickname,
true );
4730 # Failed to validate; fall back to the default
4731 $nickname = $username;
4732 wfDebug( __METHOD__ .
": $username has bad XML tags in signature.\n" );
4736 # Make sure nickname doesnt get a sig in a sig
4737 $nickname = self::cleanSigInSig( $nickname );
4739 # If we're still here, make it a link to the user page
4742 $msgName =
$user->isAnon() ?
'signature-anon' :
'signature';
4744 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4753 function validateSig( $text ) {
4767 public function cleanSig( $text, $parsing =
false ) {
4773 # Option to disable this feature
4774 if ( !$this->mOptions->getCleanSignatures() ) {
4778 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4779 # => Move this logic to braceSubstitution()
4781 $substRegex =
'/\{\{(?!(?:' . $substWord->getBaseRegex() .
'))/x' . $substWord->getRegexCase();
4782 $substText =
'{{' . $substWord->getSynonym( 0 );
4784 $text = preg_replace( $substRegex, $substText, $text );
4785 $text = self::cleanSigInSig( $text );
4786 $dom = $this->preprocessToDom( $text );
4787 $frame = $this->getPreprocessor()->newFrame();
4788 $text = $frame->expand( $dom );
4791 $text = $this->mStripState->unstripBoth( $text );
4803 public static function cleanSigInSig( $text ) {
4804 $text = preg_replace(
'/~{3,5}/',
'', $text );
4828 $this->setTitle(
$title );
4830 $this->setOutputType( $outputType );
4831 if ( $clearState ) {
4832 $this->clearState();
4845 static $executing =
false;
4847 # Guard against infinite recursion
4890 public function setHook( $tag, $callback ) {
4891 $tag = strtolower( $tag );
4892 if ( preg_match(
'/[<>\r\n]/', $tag, $m ) ) {
4893 throw new MWException(
"Invalid character {$m[0]} in setHook('$tag', ...) call" );
4895 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] :
null;
4896 $this->mTagHooks[$tag] = $callback;
4897 if ( !in_array( $tag, $this->mStripList ) ) {
4898 $this->mStripList[] = $tag;
4921 function setTransparentTagHook( $tag, $callback ) {
4922 $tag = strtolower( $tag );
4923 if ( preg_match(
'/[<>\r\n]/', $tag, $m ) ) {
4924 throw new MWException(
"Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4926 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] :
null;
4927 $this->mTransparentTagHooks[$tag] = $callback;
4935 function clearTagHooks() {
4936 $this->mTagHooks =
array();
4937 $this->mFunctionTagHooks =
array();
4938 $this->mStripList = $this->mDefaultStripList;
4984 public function setFunctionHook( $id, $callback,
$flags = 0 ) {
4987 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] :
null;
4988 $this->mFunctionHooks[$id] =
array( $callback,
$flags );
4990 # Add to function cache
4993 throw new MWException( __METHOD__ .
'() expecting a magic word identifier.' );
4996 $synonyms = $mw->getSynonyms();
4997 $sensitive = intval( $mw->isCaseSensitive() );
4999 foreach ( $synonyms
as $syn ) {
5001 if ( !$sensitive ) {
5008 # Remove trailing colon
5009 if ( substr( $syn, -1, 1 ) ===
':' ) {
5010 $syn = substr( $syn, 0, -1 );
5012 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
5022 function getFunctionHooks() {
5023 return array_keys( $this->mFunctionHooks );
5036 function setFunctionTagHook( $tag, $callback,
$flags ) {
5037 $tag = strtolower( $tag );
5038 if ( preg_match(
'/[<>\r\n]/', $tag, $m ) ) {
5039 throw new MWException(
"Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5041 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
5042 $this->mFunctionTagHooks[$tag] :
null;
5043 $this->mFunctionTagHooks[$tag] =
array( $callback,
$flags );
5045 if ( !in_array( $tag, $this->mStripList ) ) {
5046 $this->mStripList[] = $tag;
5062 function replaceLinkHolders( &$text,
$options = 0 ) {
5063 return $this->mLinkHolders->replace( $text );
5073 function replaceLinkHoldersText( $text ) {
5074 return $this->mLinkHolders->replaceText( $text );
5090 function renderImageGallery( $text,
$params ) {
5094 if ( isset(
$params[
'mode'] ) ) {
5105 $ig->setContextTitle( $this->mTitle );
5106 $ig->setShowBytes(
false );
5107 $ig->setShowFilename(
false );
5108 $ig->setParser( $this );
5109 $ig->setHideBadImages();
5112 if ( isset(
$params[
'showfilename'] ) ) {
5113 $ig->setShowFilename(
true );
5115 $ig->setShowFilename(
false );
5117 if ( isset(
$params[
'caption'] ) ) {
5118 $caption =
$params[
'caption'];
5119 $caption = htmlspecialchars( $caption );
5120 $caption = $this->replaceInternalLinks( $caption );
5121 $ig->setCaptionHtml( $caption );
5123 if ( isset(
$params[
'perrow'] ) ) {
5124 $ig->setPerRow(
$params[
'perrow'] );
5126 if ( isset(
$params[
'widths'] ) ) {
5127 $ig->setWidths(
$params[
'widths'] );
5129 if ( isset(
$params[
'heights'] ) ) {
5130 $ig->setHeights(
$params[
'heights'] );
5132 $ig->setAdditionalOptions(
$params );
5134 wfRunHooks(
'BeforeParserrenderImageGallery',
array( &$this, &$ig ) );
5138 # match lines like these:
5139 # Image:someimage.jpg|This is some image
5147 if ( strpos(
$matches[0],
'%' ) !==
false ) {
5151 if ( is_null(
$title ) ) {
5152 # Bogus title. Ignore these so we don't bomb out later.
5156 # We need to get what handler the file uses, to figure out parameters.
5157 # Note, a hook can overide the file name, and chose an entirely different
5158 # file (which potentially could be of a different type and have different handler).
5163 # Don't register it now, as ImageGallery does that later.
5165 $handler =
$file ?
$file->getHandler() :
false;
5169 'img_alt' =>
'gallery-internal-alt',
5170 'img_link' =>
'gallery-internal-link',
5173 $paramMap = $paramMap + $handler->getParamMap();
5176 unset( $paramMap[
'img_width'] );
5185 $handlerOptions =
array();
5196 foreach ( $parameterMatches
as $parameterMatch ) {
5197 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5199 $paramName = $paramMap[$magicName];
5201 switch ( $paramName ) {
5202 case 'gallery-internal-alt':
5203 $alt = $this->stripAltText( $match,
false );
5205 case 'gallery-internal-link':
5206 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5207 $chars = self::EXT_LINK_URL_CLASS;
5208 $prots = $this->mUrlProtocols;
5210 if ( preg_match(
"/^($prots)$chars+$/u", $linkValue ) ) {
5212 $this->mOutput->addExternalLink(
$link );
5215 if ( $localLinkTitle !==
null ) {
5216 $this->mOutput->addLink( $localLinkTitle );
5217 $link = $localLinkTitle->getLinkURL();
5223 if ( $handler->validateParam( $paramName, $match ) ) {
5224 $handlerOptions[$paramName] = $match;
5227 wfDebug(
"$parameterMatch failed parameter validation\n" );
5228 $label .=
'|' . $parameterMatch;
5234 $label .=
'|' . $parameterMatch;
5238 $label = substr( $label, 1 );
5241 $ig->add(
$title, $label, $alt,
$link, $handlerOptions );
5243 $html = $ig->toHTML();
5252 function getImageParams( $handler ) {
5254 $handlerClass = get_class( $handler );
5258 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5259 # Initialise static lists
5260 static $internalParamNames =
array(
5261 'horizAlign' =>
array(
'left',
'right',
'center',
'none' ),
5262 'vertAlign' =>
array(
'baseline',
'sub',
'super',
'top',
'text-top',
'middle',
5263 'bottom',
'text-bottom' ),
5264 'frame' =>
array(
'thumbnail',
'manualthumb',
'framed',
'frameless',
5265 'upright',
'border',
'link',
'alt',
'class' ),
5267 static $internalParamMap;
5268 if ( !$internalParamMap ) {
5269 $internalParamMap =
array();
5270 foreach ( $internalParamNames
as $type => $names ) {
5272 $magicName = str_replace(
'-',
'_',
"img_$name" );
5278 # Add handler params
5279 $paramMap = $internalParamMap;
5281 $handlerParamMap = $handler->getParamMap();
5282 foreach ( $handlerParamMap
as $magic => $paramName ) {
5283 $paramMap[$magic] =
array(
'handler', $paramName );
5286 $this->mImageParams[$handlerClass] = $paramMap;
5287 $this->mImageParamsMagicArray[$handlerClass] =
new MagicWordArray( array_keys( $paramMap ) );
5289 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5301 # Check if the options text is of the form "options|alt text"
5303 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5304 # * left no resizing, just left align. label is used for alt= only
5305 # * right same, but right aligned
5306 # * none same, but not aligned
5307 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5308 # * center center the image
5309 # * frame Keep original image size, no magnify-button.
5310 # * framed Same as "frame"
5311 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5312 # * upright reduce width for upright images, rounded to full __0 px
5313 # * border draw a 1px border around the image
5314 # * alt Text for HTML alt attribute (defaults to empty)
5315 # * class Set a class for img node
5316 # * link Set the target of the image link. Can be external, interwiki, or local
5317 # vertical-align values (no % or length right now):
5329 # Give extensions a chance to select the file revision for us
5334 # Fetch and register the file (file title may be different via hooks)
5338 $handler =
$file ?
$file->getHandler() :
false;
5340 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5343 $this->addTrackingCategory(
'broken-file-category' );
5346 # Process the input parameters
5349 'horizAlign' =>
array(),
'vertAlign' =>
array() );
5350 foreach ( $parts
as $part ) {
5351 $part = trim( $part );
5352 list( $magicName,
$value ) = $mwArray->matchVariableStartToEnd( $part );
5354 if ( isset( $paramMap[$magicName] ) ) {
5355 list(
$type, $paramName ) = $paramMap[$magicName];
5357 # Special case; width and height come in one variable together
5358 if (
$type ===
'handler' && $paramName ===
'width' ) {
5359 $parsedWidthParam = $this->parseWidthParam(
$value );
5360 if ( isset( $parsedWidthParam[
'width'] ) ) {
5361 $width = $parsedWidthParam[
'width'];
5362 if ( $handler->validateParam(
'width', $width ) ) {
5367 if ( isset( $parsedWidthParam[
'height'] ) ) {
5368 $height = $parsedWidthParam[
'height'];
5369 if ( $handler->validateParam(
'height', $height ) ) {
5374 # else no validation -- bug 13436
5376 if (
$type ===
'handler' ) {
5377 # Validate handler parameter
5378 $validated = $handler->validateParam( $paramName,
$value );
5380 # Validate internal parameters
5381 switch ( $paramName ) {
5385 # @todo FIXME: Possibly check validity here for
5386 # manualthumb? downstream behavior seems odd with
5387 # missing manual thumbs.
5392 $chars = self::EXT_LINK_URL_CLASS;
5393 $prots = $this->mUrlProtocols;
5395 $paramName =
'no-link';
5398 } elseif ( preg_match(
"/^(?i)$prots/",
$value ) ) {
5399 if ( preg_match(
"/^((?i)$prots)$chars+$/u",
$value, $m ) ) {
5400 $paramName =
'link-url';
5401 $this->mOutput->addExternalLink(
$value );
5402 if ( $this->mOptions->getExternalLinkTarget() ) {
5403 $params[
$type][
'link-target'] = $this->mOptions->getExternalLinkTarget();
5410 $paramName =
'link-title';
5412 $this->mOutput->addLink( $linkTitle );
5418 # Most other things appear to be empty or numeric...
5419 $validated = (
$value ===
false || is_numeric( trim(
$value ) ) );
5428 if ( !$validated ) {
5433 # Process alignment parameters
5434 if (
$params[
'horizAlign'] ) {
5441 $params[
'frame'][
'caption'] = $caption;
5443 # Will the image be presented in a frame, with the caption below?
5444 $imageIsFramed = isset(
$params[
'frame'][
'frame'] )
5445 || isset(
$params[
'frame'][
'framed'] )
5446 || isset(
$params[
'frame'][
'thumbnail'] )
5447 || isset(
$params[
'frame'][
'manualthumb'] );
5449 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5450 # came to also set the caption, ordinary text after the image -- which
5451 # makes no sense, because that just repeats the text multiple times in
5452 # screen readers. It *also* came to set the title attribute.
5454 # Now that we have an alt attribute, we should not set the alt text to
5455 # equal the caption: that's worse than useless, it just repeats the
5456 # text. This is the framed/thumbnail case. If there's no caption, we
5457 # use the unnamed parameter for alt text as well, just for the time be-
5458 # ing, if the unnamed param is set and the alt param is not.
5460 # For the future, we need to figure out if we want to tweak this more,
5461 # e.g., introducing a title= parameter for the title; ignoring the un-
5462 # named parameter entirely for images without a caption; adding an ex-
5463 # plicit caption= parameter and preserving the old magic unnamed para-
5465 if ( $imageIsFramed ) { # Framed image
5466 if ( $caption ===
'' && !isset(
$params[
'frame'][
'alt'] ) ) {
5467 # No caption or alt text, add the filename as the alt text so
5468 # that screen readers at least get some description of the image
5471 # Do not set $params['frame']['title'] because tooltips don't make sense
5473 }
else { # Inline image
5474 if ( !isset(
$params[
'frame'][
'alt'] ) ) {
5475 # No alt text, use the "caption" for the alt text
5476 if ( $caption !==
'' ) {
5477 $params[
'frame'][
'alt'] = $this->stripAltText( $caption, $holders );
5479 # No caption, fall back to using the filename for the
5484 # Use the "caption" for the tooltip text
5485 $params[
'frame'][
'title'] = $this->stripAltText( $caption, $holders );
5490 # Linker does the rest
5493 $time, $descQuery, $this->mOptions->getThumbSize() );
5495 # Give the handler a chance to modify the parser object
5497 $handler->parserTransformHook( $this,
$file );
5508 protected function stripAltText( $caption, $holders ) {
5509 # Strip bad stuff out of the title (tooltip). We can't just use
5510 # replaceLinkHoldersText() here, because if this function is called
5511 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5513 $tooltip = $holders->replaceText( $caption );
5515 $tooltip = $this->replaceLinkHoldersText( $caption );
5518 # make sure there are no placeholders in thumbnail attributes
5519 # that are later expanded to html- so expand them now and
5521 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5531 function disableCache() {
5532 wfDebug(
"Parser output marked as uncacheable.\n" );
5533 if ( !$this->mOutput ) {
5535 " can only be called when actually parsing something" );
5537 $this->mOutput->setCacheTime( -1 );
5538 $this->mOutput->updateCacheExpiry( 0 );
5549 function attributeStripCallback( &$text, $frame =
false ) {
5550 $text = $this->replaceVariables( $text, $frame );
5551 $text = $this->mStripState->unstripBoth( $text );
5560 function getTags() {
5561 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
5574 function replaceTransparentTags( $text ) {
5576 $elements = array_keys( $this->mTransparentTagHooks );
5577 $text = self::extractTagsAndParams( $elements, $text,
$matches, $this->mUniqPrefix );
5578 $replacements =
array();
5581 list( $element, $content,
$params, $tag ) = $data;
5582 $tagName = strtolower( $element );
5583 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5584 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
array( $content,
$params, $this ) );
5588 $replacements[$marker] =
$output;
5590 return strtr( $text, $replacements );
5622 private function extractSections( $text,
$section, $mode, $newText =
'' ) {
5626 $frame = $this->getPreprocessor()->newFrame();
5628 # Process section extraction flags
5630 $sectionParts = explode(
'-',
$section );
5631 $sectionIndex = array_pop( $sectionParts );
5632 foreach ( $sectionParts
as $part ) {
5633 if ( $part ===
'T' ) {
5634 $flags |= self::PTD_FOR_INCLUSION;
5638 # Check for empty input
5639 if ( strval( $text ) ===
'' ) {
5640 # Only sections 0 and T-0 exist in an empty document
5641 if ( $sectionIndex == 0 ) {
5642 if ( $mode ===
'get' ) {
5648 if ( $mode ===
'get' ) {
5656 # Preprocess the text
5657 $root = $this->preprocessToDom( $text,
$flags );
5659 # <h> nodes indicate section breaks
5660 # They can only occur at the top level, so we can find them by iterating the root's children
5661 $node = $root->getFirstChild();
5663 # Find the target section
5664 if ( $sectionIndex == 0 ) {
5665 # Section zero doesn't nest, level=big
5666 $targetLevel = 1000;
5669 if ( $node->getName() ===
'h' ) {
5670 $bits = $node->splitHeading();
5671 if ( $bits[
'i'] == $sectionIndex ) {
5672 $targetLevel = $bits[
'level'];
5676 if ( $mode ===
'replace' ) {
5679 $node = $node->getNextSibling();
5685 if ( $mode ===
'get' ) {
5692 # Find the end of the section, including nested sections
5694 if ( $node->getName() ===
'h' ) {
5695 $bits = $node->splitHeading();
5696 $curLevel = $bits[
'level'];
5697 if ( $bits[
'i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5701 if ( $mode ===
'get' ) {
5704 $node = $node->getNextSibling();
5707 # Write out the remainder (in replace mode only)
5708 if ( $mode ===
'replace' ) {
5709 # Output the replacement text
5710 # Add two newlines on -- trailing whitespace in $newText is conventionally
5711 # stripped by the editor, so we need both newlines to restore the paragraph gap
5712 # Only add trailing whitespace if there is newText
5713 if ( $newText !=
"" ) {
5714 $outText .= $newText .
"\n\n";
5719 $node = $node->getNextSibling();
5723 if ( is_string( $outText ) ) {
5724 # Re-insert stripped tags
5725 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5743 public function getSection( $text,
$section, $deftext =
'' ) {
5744 return $this->extractSections( $text,
$section,
"get", $deftext );
5757 public function replaceSection( $oldtext,
$section, $text ) {
5758 return $this->extractSections( $oldtext,
$section,
"replace", $text );
5766 function getRevisionId() {
5767 return $this->mRevisionId;
5776 public function getRevisionObject() {
5777 if ( !is_null( $this->mRevisionObject ) ) {
5778 return $this->mRevisionObject;
5780 if ( is_null( $this->mRevisionId ) ) {
5785 return $this->mRevisionObject;
5792 function getRevisionTimestamp() {
5793 if ( is_null( $this->mRevisionTimestamp ) ) {
5798 $revObject = $this->getRevisionObject();
5801 # The cryptic '' timezone parameter tells to use the site-default
5802 # timezone offset instead of the user settings.
5804 # Since this value will be saved into the parser cache, served
5805 # to other users, and potentially even used inside links and such,
5806 # it needs to be consistent for all visitors.
5811 return $this->mRevisionTimestamp;
5819 function getRevisionUser() {
5820 if ( is_null( $this->mRevisionUser ) ) {
5821 $revObject = $this->getRevisionObject();
5823 # if this template is subst: the revision id will be blank,
5824 # so just use the current user's name
5826 $this->mRevisionUser = $revObject->getUserText();
5827 } elseif ( $this->ot[
'wiki'] || $this->mOptions->getIsPreview() ) {
5828 $this->mRevisionUser = $this->getUser()->getName();
5831 return $this->mRevisionUser;
5839 function getRevisionSize() {
5840 if ( is_null( $this->mRevisionSize ) ) {
5841 $revObject = $this->getRevisionObject();
5843 # if this variable is subst: the revision id will be blank,
5844 # so just use the parser input size, because the own substituation
5845 # will change the size.
5847 $this->mRevisionSize = $revObject->getSize();
5848 } elseif ( $this->ot[
'wiki'] || $this->mOptions->getIsPreview() ) {
5849 $this->mRevisionSize = $this->mInputSize;
5852 return $this->mRevisionSize;
5860 public function setDefaultSort(
$sort ) {
5861 $this->mDefaultSort =
$sort;
5862 $this->mOutput->setProperty(
'defaultsort',
$sort );
5875 public function getDefaultSort() {
5876 if ( $this->mDefaultSort !==
false ) {
5877 return $this->mDefaultSort;
5889 public function getCustomDefaultSort() {
5890 return $this->mDefaultSort;
5902 public function guessSectionNameFromWikiText( $text ) {
5903 # Strip out wikitext links(they break the anchor)
5904 $text = $this->stripSectionName( $text );
5917 public function guessLegacySectionNameFromWikiText( $text ) {
5918 # Strip out wikitext links(they break the anchor)
5919 $text = $this->stripSectionName( $text );
5938 public function stripSectionName( $text ) {
5939 # Strip internal link markup
5940 $text = preg_replace(
'/\[\[:?([^[|]+)\|([^[]+)\]\]/',
'$2', $text );
5941 $text = preg_replace(
'/\[\[:?([^[]+)\|?\]\]/',
'$1', $text );
5943 # Strip external link markup
5944 # @todo FIXME: Not tolerant to blank link text
5945 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5946 # on how many empty links there are on the page - need to figure that out.
5947 $text = preg_replace(
'/\[(?i:' . $this->mUrlProtocols .
')([^ ]+?) ([^[]+)\]/',
'$2', $text );
5949 # Parse wikitext quotes (italics & bold)
5950 $text = $this->doQuotes( $text );
5970 $text = $this->replaceVariables( $text );
5971 $text = $this->mStripState->unstripBoth( $text );
6012 function markerSkipCallback(
$s, $callback ) {
6015 while ( $i < strlen(
$s ) ) {
6016 $markerStart = strpos(
$s, $this->mUniqPrefix, $i );
6017 if ( $markerStart ===
false ) {
6018 $out .= call_user_func( $callback, substr(
$s, $i ) );
6021 $out .= call_user_func( $callback, substr(
$s, $i, $markerStart - $i ) );
6022 $markerEnd = strpos(
$s, self::MARKER_SUFFIX, $markerStart );
6023 if ( $markerEnd ===
false ) {
6024 $out .= substr(
$s, $markerStart );
6027 $markerEnd += strlen( self::MARKER_SUFFIX );
6028 $out .= substr(
$s, $markerStart, $markerEnd - $markerStart );
6042 function killMarkers( $text ) {
6043 return $this->mStripState->killMarkers( $text );
6062 function serializeHalfParsedText( $text ) {
6066 'version' => self::HALF_PARSED_VERSION,
6067 'stripState' => $this->mStripState->getSubState( $text ),
6068 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6089 function unserializeHalfParsedText( $data ) {
6090 if ( !isset( $data[
'version'] ) || $data[
'version'] != self::HALF_PARSED_VERSION ) {
6091 throw new MWException( __METHOD__ .
': invalid version' );
6094 # First, extract the strip state.
6095 $texts =
array( $data[
'text'] );
6096 $texts = $this->mStripState->merge( $data[
'stripState'], $texts );
6098 # Now renumber links
6099 $texts = $this->mLinkHolders->mergeForeign( $data[
'linkHolders'], $texts );
6101 # Should be good to go.
6114 function isValidHalfParsedText( $data ) {
6115 return isset( $data[
'version'] ) && $data[
'version'] == self::HALF_PARSED_VERSION;
6126 public function parseWidthParam(
$value ) {
6127 $parsedWidthParam =
array();
6129 return $parsedWidthParam;
6132 # (bug 13500) In both cases (width/height and width only),
6133 # permit trailing "px" for backward compatibility.
6134 if ( preg_match(
'/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/',
$value, $m ) ) {
6135 $width = intval( $m[1] );
6136 $height = intval( $m[2] );
6137 $parsedWidthParam[
'width'] = $width;
6138 $parsedWidthParam[
'height'] = $height;
6139 } elseif ( preg_match(
'/^[0-9]*\s*(?:px)?\s*$/',
$value ) ) {
6140 $width = intval(
$value );
6141 $parsedWidthParam[
'width'] = $width;
6143 return $parsedWidthParam;