25 use Wikimedia\ScopedCallback;
76 const VERSION =
'1.6.4';
82 const HALF_PARSED_VERSION = 2;
84 # Flags for Parser::setFunctionHook
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for T21052
92 # \x{FFFD} is the Unicode replacement character, which Preprocessor_DOM
93 # uses to replace invalid HTML characters.
94 const EXT_LINK_URL_CLASS =
'[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]';
95 # Simplified expression to match an IPv4 or IPv6 address, or
96 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
97 const EXT_LINK_ADDR =
'(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}])';
98 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
100 const EXT_IMAGE_REGEX =
'/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}\x{FFFD}]+)
101 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
103 # Regular expression for a non-newline space
104 const SPACE_NOT_NL =
'(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION = 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
112 const
OT_WIKI = 2;
# like preSaveTransform()
115 const
OT_PLAIN = 4;
# like extractSections() - portions of the original are returned unchanged.
134 const MARKER_SUFFIX =
"-QINU`\"'\x7f";
135 const MARKER_PREFIX =
"\x7f'\"`UNIQ-";
137 # Markers used for wrapping the table of contents
138 const TOC_START =
'<mw:toc>';
139 const TOC_END =
'</mw:toc>';
142 public $mTagHooks = [];
143 public $mTransparentTagHooks = [];
144 public $mFunctionHooks = [];
145 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
146 public $mFunctionTagHooks = [];
147 public $mStripList = [];
148 public $mDefaultStripList = [];
149 public $mVarCache = [];
150 public $mImageParams = [];
151 public $mImageParamsMagicArray = [];
152 public $mMarkerIndex = 0;
153 public $mFirstCall =
true;
155 # Initialised by initialiseVariables()
166 # Initialised in constructor
167 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
169 # Initialized in getPreprocessor()
171 public $mPreprocessor;
173 # Cleared with clearState():
185 public $mIncludeCount;
189 public $mLinkHolders;
192 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
193 public $mDefaultSort;
194 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
195 public $mExpensiveFunctionCount; # number
of expensive
parser function calls
196 public $mShowToc, $mForceTocPosition;
204 # These are variables reset at least once per parse regardless of $clearState
215 public $mOutputType; # Output
type, one
of the OT_xxx constants
216 public $ot; # Shortcut alias,
see setOutputType()
217 public $mRevisionObject;
# The revision object of the specified revision ID
218 public $mRevisionId; # ID to
display in {{REVISIONID}} tags
219 public $mRevisionTimestamp; # The timestamp
of the
specified revision ID
222 public $mRevIdForTs; # The revision ID which was
used to fetch the timestamp
223 public $mInputSize =
false; # For {{PAGESIZE}}
on current
page.
229 public $mUniqPrefix = self::MARKER_PREFIX;
236 public $mLangLinkLanguages;
244 public $currentRevisionCache;
250 public $mInParse =
false;
253 protected $mProfiler;
258 protected $mLinkRenderer;
263 public function __construct( $conf = [] ) {
264 $this->mConf = $conf;
266 $this->mExtLinkBracketedRegex =
'/\[(((?i)' . $this->mUrlProtocols .
')' .
267 self::EXT_LINK_ADDR .
268 self::EXT_LINK_URL_CLASS .
'*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
269 if ( isset( $conf[
'preprocessorClass'] ) ) {
270 $this->mPreprocessorClass = $conf[
'preprocessorClass'];
271 } elseif ( defined(
'HPHP_VERSION' ) ) {
272 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
274 } elseif ( extension_loaded(
'domxml' ) ) {
275 # PECL extension that conflicts with the core DOM extension (T15770)
276 wfDebug(
"Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
278 } elseif ( extension_loaded(
'dom' ) ) {
283 wfDebug( __CLASS__ .
": using preprocessor: {$this->mPreprocessorClass}\n" );
289 public function __destruct() {
290 if ( isset( $this->mLinkHolders ) ) {
291 unset( $this->mLinkHolders );
294 unset( $this->$name );
301 public function __clone() {
302 $this->mInParse =
false;
310 foreach ( [
'mStripState',
'mVarCache' ]
as $k ) {
324 public function firstCallInit() {
325 if ( !$this->mFirstCall ) {
328 $this->mFirstCall =
false;
332 $this->initialiseVariables();
344 public function clearState() {
345 if ( $this->mFirstCall ) {
346 $this->firstCallInit();
348 $this->mOutput =
new ParserOutput;
349 $this->mOptions->registerWatcher( [ $this->mOutput,
'recordOption' ] );
350 $this->mAutonumber = 0;
351 $this->mIncludeCount = [];
354 $this->mRevisionObject = $this->mRevisionTimestamp =
355 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize =
null;
356 $this->mVarCache = [];
358 $this->mLangLinkLanguages = [];
359 $this->currentRevisionCache =
null;
363 # Clear these on every parse, T6549
364 $this->mTplRedirCache = $this->mTplDomCache = [];
366 $this->mShowToc =
true;
367 $this->mForceTocPosition =
false;
368 $this->mIncludeSizes = [
372 $this->mPPNodeCount = 0;
373 $this->mGeneratedPPNodeCount = 0;
374 $this->mHighestExpansionDepth = 0;
375 $this->mDefaultSort =
false;
376 $this->mHeadings = [];
377 $this->mDoubleUnderscores = [];
378 $this->mExpensiveFunctionCount = 0;
381 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
382 $this->mPreprocessor =
null;
404 public function parse(
406 $linestart =
true, $clearState =
true, $revid =
null
411 $text = strtr( $text,
"\x7f",
"?" );
412 $magicScopeVariable = $this->lock();
415 $text = str_replace(
"\000",
'', $text );
419 $this->currentRevisionCache =
null;
420 $this->mInputSize = strlen( $text );
421 if ( $this->mOptions->getEnableLimitReport() ) {
422 $this->mOutput->resetParseStartTime();
425 $oldRevisionId = $this->mRevisionId;
426 $oldRevisionObject = $this->mRevisionObject;
427 $oldRevisionTimestamp = $this->mRevisionTimestamp;
428 $oldRevisionUser = $this->mRevisionUser;
429 $oldRevisionSize = $this->mRevisionSize;
430 if ( $revid !==
null ) {
431 $this->mRevisionId = $revid;
432 $this->mRevisionObject =
null;
433 $this->mRevisionTimestamp =
null;
434 $this->mRevisionUser =
null;
435 $this->mRevisionSize =
null;
443 $text = $this->internalParse( $text );
446 $text = $this->internalParseHalfParsed( $text,
true, $linestart );
455 if ( !(
$options->getDisableTitleConversion()
456 || isset( $this->mDoubleUnderscores[
'nocontentconvert'] )
457 || isset( $this->mDoubleUnderscores[
'notitleconvert'] )
458 || $this->mOutput->getDisplayTitle() !==
false )
460 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
461 if ( $convruletitle ) {
462 $this->mOutput->setTitleText( $convruletitle );
464 $titleText = $this->getConverterLanguage()->convertTitle(
$title );
465 $this->mOutput->setTitleText( $titleText );
469 # Compute runtime adaptive expiry if set
470 $this->mOutput->finalizeAdaptiveCacheExpiry();
472 # Warn if too many heavyweight parser functions were used
473 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
474 $this->limitationWarn(
'expensive-parserfunction',
475 $this->mExpensiveFunctionCount,
476 $this->mOptions->getExpensiveParserFunctionLimit()
480 # Information on limits, for the benefit of users who try to skirt them
481 if ( $this->mOptions->getEnableLimitReport() ) {
482 $text .= $this->makeLimitReport();
485 # Wrap non-interface parser output in a <div> so it can be targeted
487 $class = $this->mOptions->getWrapOutputClass();
488 if ( $class !==
false && !$this->mOptions->getInterfaceMessage() ) {
492 $this->mOutput->setText( $text );
494 $this->mRevisionId = $oldRevisionId;
495 $this->mRevisionObject = $oldRevisionObject;
496 $this->mRevisionTimestamp = $oldRevisionTimestamp;
497 $this->mRevisionUser = $oldRevisionUser;
498 $this->mRevisionSize = $oldRevisionSize;
499 $this->mInputSize =
false;
500 $this->currentRevisionCache =
null;
502 return $this->mOutput;
511 protected function makeLimitReport() {
514 $maxIncludeSize = $this->mOptions->getMaxIncludeSize();
516 $cpuTime = $this->mOutput->getTimeSinceStart(
'cpu' );
517 if ( $cpuTime !==
null ) {
518 $this->mOutput->setLimitReportData(
'limitreport-cputime',
519 sprintf(
"%.3f", $cpuTime )
523 $wallTime = $this->mOutput->getTimeSinceStart(
'wall' );
524 $this->mOutput->setLimitReportData(
'limitreport-walltime',
525 sprintf(
"%.3f", $wallTime )
528 $this->mOutput->setLimitReportData(
'limitreport-ppvisitednodes',
529 [ $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() ]
531 $this->mOutput->setLimitReportData(
'limitreport-ppgeneratednodes',
532 [ $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() ]
534 $this->mOutput->setLimitReportData(
'limitreport-postexpandincludesize',
535 [ $this->mIncludeSizes[
'post-expand'], $maxIncludeSize ]
537 $this->mOutput->setLimitReportData(
'limitreport-templateargumentsize',
538 [ $this->mIncludeSizes[
'arg'], $maxIncludeSize ]
540 $this->mOutput->setLimitReportData(
'limitreport-expansiondepth',
541 [ $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() ]
543 $this->mOutput->setLimitReportData(
'limitreport-expensivefunctioncount',
544 [ $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() ]
547 foreach ( $this->mStripState->getLimitReport()
as list( $key,
$value ) ) {
548 $this->mOutput->setLimitReportData( $key,
$value );
551 Hooks::run(
'ParserLimitReportPrepare', [ $this, $this->mOutput ] );
553 $limitReport =
"NewPP limit report\n";
555 $limitReport .=
'Parsed by ' .
wfHostname() .
"\n";
557 $limitReport .=
'Cached time: ' . $this->mOutput->getCacheTime() .
"\n";
558 $limitReport .=
'Cache expiry: ' . $this->mOutput->getCacheExpiry() .
"\n";
559 $limitReport .=
'Dynamic content: ' .
560 ( $this->mOutput->hasDynamicContent() ?
'true' :
'false' ) .
563 foreach ( $this->mOutput->getLimitReportData()
as $key =>
$value ) {
565 [ $key, &
$value, &$limitReport,
false,
false ]
567 $keyMsg =
wfMessage( $key )->inLanguage(
'en' )->useDatabase(
false );
568 $valueMsg =
wfMessage( [
"$key-value-text",
"$key-value" ] )
569 ->inLanguage(
'en' )->useDatabase(
false );
570 if ( !$valueMsg->exists() ) {
573 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
574 $valueMsg->params(
$value );
575 $limitReport .=
"{$keyMsg->text()}: {$valueMsg->text()}\n";
581 $limitReport = htmlspecialchars_decode( $limitReport );
583 Hooks::run(
'ParserLimitReport', [ $this, &$limitReport ],
'1.22' );
587 $limitReport = str_replace( [
'-',
'&' ], [
'‐',
'&' ], $limitReport );
588 $text =
"\n<!-- \n$limitReport-->\n";
591 $dataByFunc = $this->mProfiler->getFunctionStats();
592 uasort( $dataByFunc,
function ( $a, $b ) {
593 return $a[
'real'] < $b[
'real'];
596 foreach ( array_slice( $dataByFunc, 0, 10 )
as $item ) {
597 $profileReport[] = sprintf(
"%6.2f%% %8.3f %6d %s",
598 $item[
'%real'], $item[
'real'], $item[
'calls'],
599 htmlspecialchars( $item[
'name'] ) );
601 $text .=
"<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
602 $text .= implode(
"\n", $profileReport ) .
"\n-->\n";
604 $this->mOutput->setLimitReportData(
'limitreport-timingprofile', $profileReport );
608 $this->mOutput->setLimitReportData(
'cachereport-origin',
wfHostname() );
610 $this->mOutput->setLimitReportData(
'cachereport-timestamp',
611 $this->mOutput->getCacheTime() );
612 $this->mOutput->setLimitReportData(
'cachereport-ttl',
613 $this->mOutput->getCacheExpiry() );
614 $this->mOutput->setLimitReportData(
'cachereport-transientcontent',
615 $this->mOutput->hasDynamicContent() );
617 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
618 wfDebugLog(
'generated-pp-node-count', $this->mGeneratedPPNodeCount .
' ' .
619 $this->mTitle->getPrefixedDBkey() );
646 public function recursiveTagParse( $text, $frame =
false ) {
651 $text = $this->internalParse( $text,
false, $frame );
672 public function recursiveTagParseFully( $text, $frame =
false ) {
673 $text = $this->recursiveTagParse( $text, $frame );
674 $text = $this->internalParseHalfParsed( $text,
false );
689 public function preprocess( $text,
Title $title =
null,
692 $magicScopeVariable = $this->lock();
694 if ( $revid !==
null ) {
695 $this->mRevisionId = $revid;
701 $text = $this->replaceVariables( $text, $frame );
702 $text = $this->mStripState->unstripBoth( $text );
715 public function recursivePreprocess( $text, $frame =
false ) {
716 $text = $this->replaceVariables( $text, $frame );
717 $text = $this->mStripState->unstripBoth( $text );
736 $text = $msg->params(
$params )->plain();
738 # Parser (re)initialisation
739 $magicScopeVariable = $this->lock();
743 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
744 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
745 $text = $this->mStripState->unstripBoth( $text );
755 public function setUser(
$user ) {
756 $this->mUser =
$user;
764 public function setTitle(
$t ) {
769 if (
$t->hasFragment() ) {
770 # Strip the fragment to avoid various odd effects
771 $this->mTitle =
$t->createFragmentTarget(
'' );
782 public function getTitle() {
783 return $this->mTitle;
792 public function Title( $x =
null ) {
793 return wfSetVar( $this->mTitle, $x );
801 public function setOutputType( $ot ) {
802 $this->mOutputType = $ot;
818 public function OutputType( $x =
null ) {
819 return wfSetVar( $this->mOutputType, $x );
827 public function getOutput() {
828 return $this->mOutput;
836 public function getOptions() {
837 return $this->mOptions;
846 public function Options( $x =
null ) {
847 return wfSetVar( $this->mOptions, $x );
853 public function nextLinkID() {
854 return $this->mLinkID++;
860 public function setLinkID( $id ) {
861 $this->mLinkID = $id;
868 public function getFunctionLang() {
869 return $this->getTargetLanguage();
881 public function getTargetLanguage() {
882 $target = $this->mOptions->getTargetLanguage();
884 if ( $target !==
null ) {
886 } elseif ( $this->mOptions->getInterfaceMessage() ) {
887 return $this->mOptions->getUserLangObj();
888 } elseif ( is_null( $this->mTitle ) ) {
889 throw new MWException( __METHOD__ .
': $this->mTitle is null' );
892 return $this->mTitle->getPageLanguage();
899 public function getConverterLanguage() {
900 return $this->getTargetLanguage();
909 public function getUser() {
910 if ( !is_null( $this->mUser ) ) {
913 return $this->mOptions->getUser();
921 public function getPreprocessor() {
922 if ( !isset( $this->mPreprocessor ) ) {
923 $class = $this->mPreprocessorClass;
924 $this->mPreprocessor =
new $class( $this );
926 return $this->mPreprocessor;
935 public function getLinkRenderer() {
936 if ( !$this->mLinkRenderer ) {
937 $this->mLinkRenderer = MediaWikiServices::getInstance()
938 ->getLinkRendererFactory()->create();
939 $this->mLinkRenderer->setStubThreshold(
940 $this->getOptions()->getStubThreshold()
944 return $this->mLinkRenderer;
966 public static function extractTagsAndParams( $elements, $text, &
$matches ) {
971 $taglist = implode(
'|', $elements );
972 $start =
"/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" .
">)|<(!--)/i";
974 while ( $text !=
'' ) {
975 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
977 if (
count( $p ) < 5 ) {
980 if (
count( $p ) > 5 ) {
994 $marker = self::MARKER_PREFIX .
"-$element-" . sprintf(
'%08X', $n++ ) . self::MARKER_SUFFIX;
995 $stripped .= $marker;
997 if ( $close ===
'/>' ) {
998 # Empty element tag, <tag />
1003 if ( $element ===
'!--' ) {
1006 $end =
"/(<\\/$element\\s*>)/i";
1008 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
1010 if (
count( $q ) < 3 ) {
1011 # No end tag -- let it run out to the end of the text.
1022 Sanitizer::decodeTagAttributes( $attributes ),
1023 "<$element$attributes$close$content$tail" ];
1033 public function getStripList() {
1034 return $this->mStripList;
1046 public function insertStripItem( $text ) {
1047 $marker = self::MARKER_PREFIX .
"-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
1048 $this->mMarkerIndex++;
1049 $this->mStripState->addGeneral( $marker, $text );
1060 public function doTableStuff( $text ) {
1063 $td_history = []; # Is currently
a td
tag open?
1064 $last_tag_history = []; # Save
history of last lag activated (td, th
or caption)
1065 $tr_history = []; # Is currently
a tr
tag open?
1066 $tr_attributes = []; #
history of tr attributes
1067 $has_opened_tr = []; # Did
this table open a <tr> element?
1068 $indent_level = 0; # indent level
of the
table
1071 $line = trim( $outLine );
1074 $out .= $outLine .
"\n";
1078 $first_character =
$line[0];
1079 $first_two = substr(
$line, 0, 2 );
1082 if ( preg_match(
'/^(:*)\s*\{\|(.*)$/',
$line,
$matches ) ) {
1083 # First check if we are starting a new table
1084 $indent_level = strlen(
$matches[1] );
1086 $attributes = $this->mStripState->unstripBoth(
$matches[2] );
1087 $attributes = Sanitizer::fixTagAttributes( $attributes,
'table' );
1089 $outLine = str_repeat(
'<dl><dd>', $indent_level ) .
"<table{$attributes}>";
1090 array_push( $td_history,
false );
1091 array_push( $last_tag_history,
'' );
1092 array_push( $tr_history,
false );
1093 array_push( $tr_attributes,
'' );
1094 array_push( $has_opened_tr,
false );
1095 } elseif (
count( $td_history ) == 0 ) {
1096 # Don't do any of the following
1097 $out .= $outLine .
"\n";
1099 } elseif ( $first_two ===
'|}' ) {
1100 # We are ending a table
1102 $last_tag = array_pop( $last_tag_history );
1104 if ( !array_pop( $has_opened_tr ) ) {
1105 $line =
"<tr><td></td></tr>{$line}";
1108 if ( array_pop( $tr_history ) ) {
1109 $line =
"</tr>{$line}";
1112 if ( array_pop( $td_history ) ) {
1113 $line =
"</{$last_tag}>{$line}";
1115 array_pop( $tr_attributes );
1116 if ( $indent_level > 0 ) {
1117 $outLine = rtrim(
$line ) . str_repeat(
'</dd></dl>', $indent_level );
1121 } elseif ( $first_two ===
'|-' ) {
1122 # Now we have a table row
1123 $line = preg_replace(
'#^\|-+#',
'',
$line );
1125 # Whats after the tag is now only attributes
1126 $attributes = $this->mStripState->unstripBoth(
$line );
1127 $attributes = Sanitizer::fixTagAttributes( $attributes,
'tr' );
1128 array_pop( $tr_attributes );
1129 array_push( $tr_attributes, $attributes );
1132 $last_tag = array_pop( $last_tag_history );
1133 array_pop( $has_opened_tr );
1134 array_push( $has_opened_tr,
true );
1136 if ( array_pop( $tr_history ) ) {
1140 if ( array_pop( $td_history ) ) {
1141 $line =
"</{$last_tag}>{$line}";
1145 array_push( $tr_history,
false );
1146 array_push( $td_history,
false );
1147 array_push( $last_tag_history,
'' );
1148 } elseif ( $first_character ===
'|'
1149 || $first_character ===
'!'
1150 || $first_two ===
'|+'
1152 # This might be cell elements, td, th or captions
1153 if ( $first_two ===
'|+' ) {
1154 $first_character =
'+';
1161 if ( $first_character ===
'!' ) {
1165 # Split up multiple cells on the same line.
1166 # FIXME : This can result in improper nesting of tags processed
1167 # by earlier parser steps.
1168 $cells = explode(
'||',
$line );
1172 # Loop through each table cell
1173 foreach ( $cells
as $cell ) {
1175 if ( $first_character !==
'+' ) {
1176 $tr_after = array_pop( $tr_attributes );
1177 if ( !array_pop( $tr_history ) ) {
1178 $previous =
"<tr{$tr_after}>\n";
1180 array_push( $tr_history,
true );
1181 array_push( $tr_attributes,
'' );
1182 array_pop( $has_opened_tr );
1183 array_push( $has_opened_tr,
true );
1186 $last_tag = array_pop( $last_tag_history );
1188 if ( array_pop( $td_history ) ) {
1189 $previous =
"</{$last_tag}>\n{$previous}";
1192 if ( $first_character ===
'|' ) {
1194 } elseif ( $first_character ===
'!' ) {
1196 } elseif ( $first_character ===
'+' ) {
1197 $last_tag =
'caption';
1202 array_push( $last_tag_history, $last_tag );
1204 # A cell could contain both parameters and data
1205 $cell_data = explode(
'|', $cell, 2 );
1207 # T2553: Note that a '|' inside an invalid link should not
1208 # be mistaken as delimiting cell parameters
1209 # Bug T153140: Neither should language converter markup.
1210 if ( preg_match(
'/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1211 $cell =
"{$previous}<{$last_tag}>" . trim( $cell );
1212 } elseif (
count( $cell_data ) == 1 ) {
1214 $cell =
"{$previous}<{$last_tag}>" . trim( $cell_data[0] );
1216 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1217 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1219 $cell =
"{$previous}<{$last_tag}{$attributes}>" . trim( $cell_data[1] );
1223 array_push( $td_history,
true );
1226 $out .= $outLine .
"\n";
1229 # Closing open td, tr && table
1230 while (
count( $td_history ) > 0 ) {
1231 if ( array_pop( $td_history ) ) {
1234 if ( array_pop( $tr_history ) ) {
1237 if ( !array_pop( $has_opened_tr ) ) {
1238 $out .=
"<tr><td></td></tr>\n";
1241 $out .=
"</table>\n";
1244 # Remove trailing line-ending (b/c)
1245 if ( substr(
$out, -1 ) ===
"\n" ) {
1249 # special case: don't return empty table
1250 if (
$out ===
"<table>\n<tr><td></td></tr>\n</table>" ) {
1269 public function internalParse( $text, $isMain =
true, $frame =
false ) {
1275 # Hook to suspend the parser in this state
1276 if ( !
Hooks::run(
'ParserBeforeInternalParse', [ &
$parser, &$text, &$this->mStripState ] ) ) {
1280 # if $frame is provided, then use $frame for replacing any variables
1282 # use frame depth to infer how include/noinclude tags should be handled
1283 # depth=0 means this is the top-level document; otherwise it's an included document
1284 if ( !$frame->depth ) {
1287 $flag = self::PTD_FOR_INCLUSION;
1289 $dom = $this->preprocessToDom( $text, $flag );
1290 $text = $frame->expand( $dom );
1292 # if $frame is not provided, then use old-style replaceVariables
1293 $text = $this->replaceVariables( $text );
1296 Hooks::run(
'InternalParseBeforeSanitize', [ &
$parser, &$text, &$this->mStripState ] );
1297 $text = Sanitizer::removeHTMLtags(
1299 [ $this,
'attributeStripCallback' ],
1301 array_keys( $this->mTransparentTagHooks ),
1303 [ $this,
'addTrackingCategory' ]
1305 Hooks::run(
'InternalParseBeforeLinks', [ &
$parser, &$text, &$this->mStripState ] );
1307 # Tables need to come after variable replacement for things to work
1308 # properly; putting them before other transformations should keep
1309 # exciting things like link expansions from showing up in surprising
1311 $text = $this->doTableStuff( $text );
1313 $text = preg_replace(
'/(^|\n)-----*/',
'\\1<hr />', $text );
1315 $text = $this->doDoubleUnderscore( $text );
1317 $text = $this->doHeadings( $text );
1318 $text = $this->replaceInternalLinks( $text );
1319 $text = $this->doAllQuotes( $text );
1320 $text = $this->replaceExternalLinks( $text );
1322 # replaceInternalLinks may sometimes leave behind
1323 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1324 $text = str_replace( self::MARKER_PREFIX .
'NOPARSE',
'', $text );
1326 $text = $this->doMagicLinks( $text );
1327 $text = $this->formatHeadings( $text, $origText, $isMain );
1341 private function internalParseHalfParsed( $text, $isMain =
true, $linestart =
true ) {
1342 $text = $this->mStripState->unstripGeneral( $text );
1351 # Clean up special characters, only run once, next-to-last before doBlockLevels
1353 # French spaces, last one Guillemet-left
1354 # only if there is something before the space
1355 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' =>
'\\1 ',
1356 # french spaces, Guillemet-right
1357 '/(\\302\\253) /' =>
'\\1 ',
1358 '/ (!\s*important)/' =>
' \\1', # Beware
of CSS magic word !important, T13874.
1360 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1362 $text = $this->doBlockLevels( $text, $linestart );
1364 $this->replaceLinkHolders( $text );
1373 if ( !( $this->mOptions->getDisableContentConversion()
1374 || isset( $this->mDoubleUnderscores[
'nocontentconvert'] ) )
1376 if ( !$this->mOptions->getInterfaceMessage() ) {
1377 # The position of the convert() call should not be changed. it
1378 # assumes that the links are all replaced and the only thing left
1379 # is the <nowiki> mark.
1380 $text = $this->getConverterLanguage()->convert( $text );
1384 $text = $this->mStripState->unstripNoWiki( $text );
1390 $text = $this->replaceTransparentTags( $text );
1391 $text = $this->mStripState->unstripGeneral( $text );
1393 $text = Sanitizer::normalizeCharReferences( $text );
1396 if ( $this->mOptions->getTidy() ) {
1400 # attempt to sanitize at least some nesting problems
1401 # (T4702 and quite a few others)
1403 # ''Something [http://www.cool.com cool''] -->
1404 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1405 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1406 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1407 # fix up an anchor inside another anchor, only
1408 # at least for a single single nested link (T5695)
1409 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1410 '\\1\\2</a>\\3</a>\\1\\4</a>',
1411 # fix div inside inline elements- doBlockLevels won't wrap a line which
1412 # contains a div, so fix it up here; replace
1413 # div with escaped text
1414 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1415 '\\1\\3<div\\5>\\6</div>\\8\\9',
1416 # remove empty italic or bold tag pairs, some
1417 # introduced by rules above
1418 '/<([bi])><\/\\1>/' =>
'',
1421 $text = preg_replace(
1422 array_keys( $tidyregs ),
1423 array_values( $tidyregs ),
1445 public function doMagicLinks( $text ) {
1447 $urlChar = self::EXT_LINK_URL_CLASS;
1448 $addr = self::EXT_LINK_ADDR;
1449 $space = self::SPACE_NOT_NL; # non-newline space
1450 $spdash =
"(?:-|$space)"; #
a dash
or a non-newline space
1451 $spaces =
"$space++"; # possessive match
of 1
or more spaces
1452 $text = preg_replace_callback(
1454 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1455 (<.*?>) | # m[2]: Skip stuff inside HTML elements' .
"
1456 (\b # m[3]: Free external links
1458 ($addr$urlChar*) # m[4]: Post-protocol path
1460 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1462 \bISBN $spaces ( # m[6]: ISBN, capture number
1463 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1464 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1465 [0-9Xx] # check digit
1467 )!xu", [ $this,
'magicLinkCallback' ], $text );
1476 public function magicLinkCallback( $m ) {
1477 if ( isset( $m[1] ) && $m[1] !==
'' ) {
1480 } elseif ( isset( $m[2] ) && $m[2] !==
'' ) {
1483 } elseif ( isset( $m[3] ) && $m[3] !==
'' ) {
1484 # Free external link
1485 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1486 } elseif ( isset( $m[5] ) && $m[5] !==
'' ) {
1488 if ( substr( $m[0], 0, 3 ) ===
'RFC' ) {
1489 if ( !$this->mOptions->getMagicRFCLinks() ) {
1494 $cssClass =
'mw-magiclink-rfc';
1495 $trackingCat =
'magiclink-tracking-rfc';
1497 } elseif ( substr( $m[0], 0, 4 ) ===
'PMID' ) {
1498 if ( !$this->mOptions->getMagicPMIDLinks() ) {
1502 $urlmsg =
'pubmedurl';
1503 $cssClass =
'mw-magiclink-pmid';
1504 $trackingCat =
'magiclink-tracking-pmid';
1507 throw new MWException( __METHOD__ .
': unrecognised match type "' .
1508 substr( $m[0], 0, 20 ) .
'"' );
1510 $url =
wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1511 $this->addTrackingCategory( $trackingCat );
1513 } elseif ( isset( $m[6] ) && $m[6] !==
''
1514 && $this->mOptions->getMagicISBNLinks()
1518 $space = self::SPACE_NOT_NL; # non-newline space
1519 $isbn = preg_replace(
"/$space/",
' ', $isbn );
1520 $num = strtr( $isbn, [
1525 $this->addTrackingCategory(
'magiclink-tracking-isbn' );
1526 return $this->getLinkRenderer()->makeKnownLink(
1530 'class' =>
'internal mw-magiclink-isbn',
1548 public function makeFreeExternalLink( $url, $numPostProto ) {
1551 # The characters '<' and '>' (which were escaped by
1552 # removeHTMLtags()) should not be included in
1553 # URLs, per RFC 2396.
1554 # Make terminate a URL as well (bug T84937)
1557 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1562 $trail = substr( $url, $m2[0][1] ) . $trail;
1563 $url = substr( $url, 0, $m2[0][1] );
1566 # Move trailing punctuation to $trail
1568 # If there is no left bracket, then consider right brackets fair game too
1569 if ( strpos( $url,
'(' ) ===
false ) {
1573 $urlRev = strrev( $url );
1574 $numSepChars = strspn( $urlRev, $sep );
1575 # Don't break a trailing HTML entity by moving the ; into $trail
1576 # This is in hot code, so use substr_compare to avoid having to
1577 # create a new string object for the comparison
1578 if ( $numSepChars && substr_compare( $url,
";", -$numSepChars, 1 ) === 0 ) {
1579 # more optimization: instead of running preg_match with a $
1580 # anchor, which can be slow, do the match on the reversed
1581 # string starting at the desired offset.
1582 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1583 if ( preg_match(
'/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1587 if ( $numSepChars ) {
1588 $trail = substr( $url, -$numSepChars ) . $trail;
1589 $url = substr( $url, 0, -$numSepChars );
1592 # Verify that we still have a real URL after trail removal, and
1593 # not just lone protocol
1594 if ( strlen( $trail ) >= $numPostProto ) {
1595 return $url . $trail;
1598 $url = Sanitizer::cleanUrl( $url );
1600 # Is this an external image?
1601 $text = $this->maybeMakeExternalImage( $url );
1602 if ( $text ===
false ) {
1603 # Not an image, make a link
1605 $this->getConverterLanguage()->markNoConversion( $url,
true ),
1607 $this->getExternalLinkAttribs( $url ), $this->mTitle );
1608 # Register it in the output object...
1609 $this->mOutput->addExternalLink( $url );
1611 return $text . $trail;
1623 public function doHeadings( $text ) {
1624 for ( $i = 6; $i >= 1; --$i ) {
1625 $h = str_repeat(
'=', $i );
1628 $text = preg_replace(
"/^(?:$h)[ \\t]*(.+?)[ \\t]*(?:$h)\\s*$/m",
"<h$i>\\1</h$i>", $text );
1641 public function doAllQuotes( $text ) {
1645 $outtext .= $this->doQuotes(
$line ) .
"\n";
1647 $outtext = substr( $outtext, 0, -1 );
1658 public function doQuotes( $text ) {
1659 $arr = preg_split(
"/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1660 $countarr =
count( $arr );
1661 if ( $countarr == 1 ) {
1670 for ( $i = 1; $i < $countarr; $i += 2 ) {
1671 $thislen = strlen( $arr[$i] );
1675 if ( $thislen == 4 ) {
1676 $arr[$i - 1] .=
"'";
1679 } elseif ( $thislen > 5 ) {
1683 $arr[$i - 1] .= str_repeat(
"'", $thislen - 5 );
1688 if ( $thislen == 2 ) {
1690 } elseif ( $thislen == 3 ) {
1692 } elseif ( $thislen == 5 ) {
1702 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1703 $firstsingleletterword = -1;
1704 $firstmultiletterword = -1;
1706 for ( $i = 1; $i < $countarr; $i += 2 ) {
1707 if ( strlen( $arr[$i] ) == 3 ) {
1708 $x1 = substr( $arr[$i - 1], -1 );
1709 $x2 = substr( $arr[$i - 1], -2, 1 );
1710 if ( $x1 ===
' ' ) {
1711 if ( $firstspace == -1 ) {
1714 } elseif ( $x2 ===
' ' ) {
1715 $firstsingleletterword = $i;
1720 if ( $firstmultiletterword == -1 ) {
1721 $firstmultiletterword = $i;
1728 if ( $firstsingleletterword > -1 ) {
1729 $arr[$firstsingleletterword] =
"''";
1730 $arr[$firstsingleletterword - 1] .=
"'";
1731 } elseif ( $firstmultiletterword > -1 ) {
1733 $arr[$firstmultiletterword] =
"''";
1734 $arr[$firstmultiletterword - 1] .=
"'";
1735 } elseif ( $firstspace > -1 ) {
1739 $arr[$firstspace] =
"''";
1740 $arr[$firstspace - 1] .=
"'";
1749 foreach ( $arr
as $r ) {
1750 if ( ( $i % 2 ) == 0 ) {
1751 if ( $state ===
'both' ) {
1757 $thislen = strlen( $r );
1758 if ( $thislen == 2 ) {
1759 if ( $state ===
'i' ) {
1762 } elseif ( $state ===
'bi' ) {
1765 } elseif ( $state ===
'ib' ) {
1768 } elseif ( $state ===
'both' ) {
1775 } elseif ( $thislen == 3 ) {
1776 if ( $state ===
'b' ) {
1779 } elseif ( $state ===
'bi' ) {
1782 } elseif ( $state ===
'ib' ) {
1785 } elseif ( $state ===
'both' ) {
1792 } elseif ( $thislen == 5 ) {
1793 if ( $state ===
'b' ) {
1796 } elseif ( $state ===
'i' ) {
1799 } elseif ( $state ===
'bi' ) {
1802 } elseif ( $state ===
'ib' ) {
1805 } elseif ( $state ===
'both' ) {
1817 if ( $state ===
'b' || $state ===
'ib' ) {
1820 if ( $state ===
'i' || $state ===
'bi' || $state ===
'ib' ) {
1823 if ( $state ===
'bi' ) {
1827 if ( $state ===
'both' &&
$buffer ) {
1846 public function replaceExternalLinks( $text ) {
1847 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1848 if ( $bits ===
false ) {
1849 throw new MWException(
"PCRE needs to be compiled with "
1850 .
"--enable-unicode-properties in order for MediaWiki to function" );
1852 $s = array_shift( $bits );
1855 while ( $i <
count( $bits ) ) {
1858 $text = $bits[$i++];
1859 $trail = $bits[$i++];
1861 # The characters '<' and '>' (which were escaped by
1862 # removeHTMLtags()) should not be included in
1863 # URLs, per RFC 2396.
1865 if ( preg_match(
'/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1866 $text = substr( $url, $m2[0][1] ) .
' ' . $text;
1867 $url = substr( $url, 0, $m2[0][1] );
1870 # If the link text is an image URL, replace it with an <img> tag
1871 # This happened by accident in the original parser, but some people used it extensively
1872 $img = $this->maybeMakeExternalImage( $text );
1873 if ( $img !==
false ) {
1879 # Set linktype for CSS
1882 # No link text, e.g. [http://domain.tld/some.link]
1883 if ( $text ==
'' ) {
1885 $langObj = $this->getTargetLanguage();
1886 $text =
'[' . $langObj->formatNum( ++$this->mAutonumber ) .
']';
1887 $linktype =
'autonumber';
1889 # Have link text, e.g. [http://domain.tld/some.link text]s
1894 $text = $this->getConverterLanguage()->markNoConversion( $text );
1896 $url = Sanitizer::cleanUrl( $url );
1898 # Use the encoded URL
1899 # This means that users can paste URLs directly into the text
1900 # Funny characters like ö aren't valid in URLs anyway
1901 # This was changed in August 2004
1903 $this->getExternalLinkAttribs( $url ), $this->mTitle ) . $dtrail . $trail;
1905 # Register link in the output object.
1906 $this->mOutput->addExternalLink( $url );
1921 public static function getExternalLinkRel( $url =
false,
$title =
null ) {
1942 public function getExternalLinkAttribs( $url ) {
1944 $rel = self::getExternalLinkRel( $url, $this->mTitle );
1946 $target = $this->mOptions->getExternalLinkTarget();
1949 if ( !in_array( $target, [
'_self',
'_parent',
'_top' ] ) ) {
1953 if ( $rel !==
'' ) {
1956 $rel .=
'noreferrer noopener';
1972 public static function normalizeLinkUrl( $url ) {
1973 # First, make sure unsafe characters are encoded
1974 $url = preg_replace_callback(
'/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1976 return rawurlencode( $m[0] );
1982 $end = strlen( $url );
1984 # Fragment part - 'fragment'
1985 $start = strpos( $url,
'#' );
1986 if ( $start !==
false && $start < $end ) {
1987 $ret = self::normalizeUrlComponent(
1988 substr( $url, $start, $end - $start ),
'"#%<>[\]^`{|}' ) .
$ret;
1992 # Query part - 'query' minus &=+;
1993 $start = strpos( $url,
'?' );
1994 if ( $start !==
false && $start < $end ) {
1995 $ret = self::normalizeUrlComponent(
1996 substr( $url, $start, $end - $start ),
'"#%<>[\]^`{|}&=+;' ) .
$ret;
2000 # Scheme and path part - 'pchar'
2001 # (we assume no userinfo or encoded colons in the host)
2002 $ret = self::normalizeUrlComponent(
2003 substr( $url, 0, $end ),
'"#%<>[\]^`{|}/?' ) .
$ret;
2008 private static function normalizeUrlComponent( $component, $unsafe ) {
2009 $callback =
function (
$matches )
use ( $unsafe ) {
2011 $ord = ord( $char );
2012 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) ===
false ) {
2016 # Leave it escaped, but use uppercase for a-f
2020 return preg_replace_callback(
'/%[0-9A-Fa-f]{2}/', $callback, $component );
2031 private function maybeMakeExternalImage( $url ) {
2032 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
2033 $imagesexception = !empty( $imagesfrom );
2035 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2036 if ( $imagesexception && is_array( $imagesfrom ) ) {
2037 $imagematch =
false;
2038 foreach ( $imagesfrom
as $match ) {
2039 if ( strpos( $url, $match ) === 0 ) {
2044 } elseif ( $imagesexception ) {
2045 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2047 $imagematch =
false;
2050 if ( $this->mOptions->getAllowExternalImages()
2051 || ( $imagesexception && $imagematch )
2053 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
2058 if ( !$text && $this->mOptions->getEnableImageWhitelist()
2059 && preg_match( self::EXT_IMAGE_REGEX, $url )
2061 $whitelist = explode(
2063 wfMessage(
'external_image_whitelist' )->inContentLanguage()->
text()
2066 foreach ( $whitelist
as $entry ) {
2067 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2068 if ( strpos( $entry,
'#' ) === 0 || $entry ===
'' ) {
2071 if ( preg_match(
'/' . str_replace(
'/',
'\\/', $entry ) .
'/i', $url ) ) {
2072 # Image matches a whitelist entry
2090 public function replaceInternalLinks(
$s ) {
2091 $this->mLinkHolders->merge( $this->replaceInternalLinks2(
$s ) );
2103 public function replaceInternalLinks2( &
$s ) {
2106 static $tc =
false, $e1, $e1_img;
2107 # the % is needed to support urlencoded titles as well
2110 # Match a link having the form [[namespace:link|alternate]]trail
2111 $e1 =
"/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2112 # Match cases where there is no "]]", which might still be images
2113 $e1_img =
"/^([{$tc}]+)\\|(.*)\$/sD";
2118 # split the entire text string on occurrences of [[
2120 # get the first element (all text up to first [[), and remove the space we added
2123 $line = $a->current(); # Workaround
for broken ArrayIterator::next()
that returns "
void"
2124 $s = substr(
$s, 1 );
2126 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2128 if ( $useLinkPrefixExtension ) {
2129 # Match the end of a line for a word that's not followed by whitespace,
2130 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2133 $e2 =
"/^((?>.*[^$charset]|))(.+)$/sDu";
2136 if ( is_null( $this->mTitle ) ) {
2137 throw new MWException( __METHOD__ .
": \$this->mTitle is null\n" );
2139 $nottalk = !$this->mTitle->isTalkPage();
2141 if ( $useLinkPrefixExtension ) {
2143 if ( preg_match( $e2,
$s, $m ) ) {
2144 $first_prefix = $m[2];
2146 $first_prefix =
false;
2152 $useSubpages = $this->areSubpagesAllowed();
2154 # Loop for each link
2155 for ( ;
$line !==
false &&
$line !==
null; $a->next(),
$line = $a->current() ) {
2156 # Check for excessive memory usage
2157 if ( $holders->isBig() ) {
2159 # Do the existence check, replace the link holders and clear the array
2160 $holders->replace(
$s );
2164 if ( $useLinkPrefixExtension ) {
2165 if ( preg_match( $e2,
$s, $m ) ) {
2172 if ( $first_prefix ) {
2173 $prefix = $first_prefix;
2174 $first_prefix =
false;
2178 $might_be_img =
false;
2182 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2183 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2184 # the real problem is with the $e1 regex
2186 # Still some problems for cases where the ] is meant to be outside punctuation,
2187 # and no image is in sight. See T4095.
2189 && substr( $m[3], 0, 1 ) ===
']'
2190 && strpos( $text,
'[' ) !==
false
2192 $text .=
']'; #
so that replaceExternalLinks($text) works
later
2193 $m[3] = substr( $m[3], 1 );
2195 # fix up urlencoded title texts
2196 if ( strpos( $m[1],
'%' ) !==
false ) {
2197 # Should anchors '#' also be rejected?
2198 $m[1] = str_replace( [
'<',
'>' ], [
'<',
'>' ], rawurldecode( $m[1] ) );
2201 } elseif ( preg_match( $e1_img,
$line, $m ) ) {
2202 # Invalid, but might be an image with a link in its caption
2203 $might_be_img =
true;
2205 if ( strpos( $m[1],
'%' ) !==
false ) {
2206 $m[1] = str_replace( [
'<',
'>' ], [
'<',
'>' ], rawurldecode( $m[1] ) );
2214 $origLink = ltrim( $m[1],
' ' );
2216 # Don't allow internal links to pages containing
2217 # PROTO: where PROTO is a valid URL protocol; these
2218 # should be external links.
2219 if ( preg_match(
'/^(?i:' . $this->mUrlProtocols .
')/', $origLink ) ) {
2224 # Make subpage if necessary
2225 if ( $useSubpages ) {
2226 $link = $this->maybeDoSubpageLink( $origLink, $text );
2235 $unstrip = $this->mStripState->killMarkers(
$link );
2236 $noMarkers = ( $unstrip ===
$link );
2239 if ( $nt ===
null ) {
2244 $ns = $nt->getNamespace();
2245 $iw = $nt->getInterwiki();
2247 $noforce = ( substr( $origLink, 0, 1 ) !==
':' );
2249 if ( $might_be_img ) { #
if this is actually an invalid
link
2250 if ( $ns ==
NS_FILE && $noforce ) { # but might be an image
2253 # look at the next 'line' to see if we can close it there
2255 $next_line = $a->current();
2256 if ( $next_line ===
false || $next_line ===
null ) {
2259 $m = explode(
']]', $next_line, 3 );
2260 if (
count( $m ) == 3 ) {
2261 # the first ]] closes the inner link, the second the image
2263 $text .=
"[[{$m[0]}]]{$m[1]}";
2266 } elseif (
count( $m ) == 2 ) {
2267 # if there's exactly one ]] that's fine, we'll keep looking
2268 $text .=
"[[{$m[0]}]]{$m[1]}";
2270 # if $next_line is invalid too, we need look no further
2271 $text .=
'[[' . $next_line;
2276 # we couldn't find the end of this imageLink, so output it raw
2277 # but don't ignore what might be perfectly normal links in the text we've examined
2278 $holders->merge( $this->replaceInternalLinks2( $text ) );
2279 $s .=
"{$prefix}[[$link|$text";
2280 # note: no $trail, because without an end, there *is* no trail
2283 }
else { #
it's not an image, so output it raw
2284 $s .= "{$prefix}[[$link|$text";
2285 # note: no $trail, because without an end, there *is* no trail
2290 $wasblank = ( $text == '' );
2294 # Strip off leading ':
'
2295 $text = substr( $text, 1 );
2298 # T6598 madness. Handle the quotes only if they come from the alternate part
2299 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2300 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2301 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2302 $text = $this->doQuotes( $text );
2305 # Link not escaped by : , create the various objects
2306 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2309 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2310 Language::fetchLanguageName( $iw, null, 'mw
' ) ||
2311 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2314 # T26502: filter duplicates
2315 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2316 $this->mLangLinkLanguages[$iw] = true;
2317 $this->mOutput->addLanguageLink( $nt->getFullText() );
2323 $s = rtrim( $s . $prefix ) . $trail; # T175416
2327 if ( $ns == NS_FILE ) {
2328 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2330 # if no parameters were passed, $text
2331 # becomes something like "File:Foo.png",
2332 # which we don't want to pass
on to the
2336 # recursively parse links inside the image caption
2337 # actually, this will parse them in any other parameters, too,
2338 # but it might be hard to fix that, and it doesn't matter ATM
2339 $text = $this->replaceExternalLinks( $text );
2340 $holders->merge( $this->replaceInternalLinks2( $text ) );
2342 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2343 $s .= $prefix . $this->armorLinks(
2344 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2351 $s = rtrim(
$s . $prefix ) . $trail; # T2087, T87753
2354 $sortkey = $this->getDefaultSort();
2358 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2359 $sortkey = str_replace(
"\n",
'', $sortkey );
2360 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2361 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2367 # Self-link checking. For some languages, variants of the title are checked in
2368 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2369 # for linking to a different variant.
2370 if ( $ns !=
NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2375 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2376 # @todo FIXME: Should do batch file existence checks, see comment below
2378 # Give extensions a chance to select the file revision for us
2382 [ $this, $nt, &
$options, &$descQuery ] );
2383 # Fetch and register the file (file title may be different via hooks)
2384 list( $file, $nt ) = $this->fetchFileAndTitle( $nt,
$options );
2385 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2386 $s .= $prefix . $this->armorLinks(
2391 # Some titles, such as valid special pages or files in foreign repos, should
2392 # be shown as bluelinks even though they're not included in the page table
2393 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2394 # batch file existence checks for NS_FILE and NS_MEDIA
2395 if ( $iw ==
'' && $nt->isAlwaysKnown() ) {
2396 $this->mOutput->addLink( $nt );
2397 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2399 # Links will be added to the output link list after checking
2400 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2419 protected function makeKnownLinkHolder( $nt, $text =
'', $trail =
'', $prefix =
'' ) {
2422 if ( $text ==
'' ) {
2423 $text = htmlspecialchars( $nt->getPrefixedText() );
2426 $link = $this->getLinkRenderer()->makeKnownLink(
2427 $nt,
new HtmlArmor(
"$prefix$text$inside" )
2430 return $this->armorLinks(
$link ) . $trail;
2443 public function armorLinks( $text ) {
2444 return preg_replace(
'/\b((?i)' . $this->mUrlProtocols .
')/',
2445 self::MARKER_PREFIX .
"NOPARSE$1", $text );
2452 public function areSubpagesAllowed() {
2453 # Some namespaces don't allow subpages
2465 public function maybeDoSubpageLink( $target, &$text ) {
2477 public function doBlockLevels( $text, $linestart ) {
2492 public function getVariableValue( $index, $frame =
false ) {
2496 if ( is_null( $this->mTitle ) ) {
2501 throw new MWException( __METHOD__ .
' Should only be '
2502 .
' called while parsing (no title set)' );
2512 if (
Hooks::run(
'ParserGetVariableValueVarCache', [ &
$parser, &$this->mVarCache ] ) ) {
2513 if ( isset( $this->mVarCache[$index] ) ) {
2514 return $this->mVarCache[$index];
2518 $ts =
wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2521 $pageLang = $this->getFunctionLang();
2527 case 'currentmonth':
2530 case 'currentmonth1':
2533 case 'currentmonthname':
2536 case 'currentmonthnamegen':
2539 case 'currentmonthabbrev':
2554 case 'localmonthname':
2557 case 'localmonthnamegen':
2560 case 'localmonthabbrev':
2575 case 'fullpagename':
2578 case 'fullpagenamee':
2584 case 'subpagenamee':
2587 case 'rootpagename':
2590 case 'rootpagenamee':
2594 $this->mTitle->getRootText()
2597 case 'basepagename':
2600 case 'basepagenamee':
2604 $this->mTitle->getBaseText()
2607 case 'talkpagename':
2608 if ( $this->mTitle->canHaveTalkPage() ) {
2609 $talkPage = $this->mTitle->getTalkPage();
2615 case 'talkpagenamee':
2616 if ( $this->mTitle->canHaveTalkPage() ) {
2617 $talkPage = $this->mTitle->getTalkPage();
2623 case 'subjectpagename':
2624 $subjPage = $this->mTitle->getSubjectPage();
2627 case 'subjectpagenamee':
2628 $subjPage = $this->mTitle->getSubjectPage();
2632 $pageid = $this->getTitle()->getArticleID();
2633 if ( $pageid == 0 ) {
2634 # 0 means the page doesn't exist in the database,
2635 # which means the user is previewing a new page.
2636 # The vary-revision flag must be set, because the magic word
2637 # will have a different value once the page is saved.
2638 $this->mOutput->setFlag(
'vary-revision' );
2639 wfDebug( __METHOD__ .
": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2641 $value = $pageid ? $pageid :
null;
2644 # Let the edit saving system know we should parse the page
2645 # *after* a revision ID has been assigned.
2646 $this->mOutput->setFlag(
'vary-revision-id' );
2647 wfDebug( __METHOD__ .
": {{REVISIONID}} used, setting vary-revision-id...\n" );
2648 $value = $this->mRevisionId;
2649 if ( !
$value && $this->mOptions->getSpeculativeRevIdCallback() ) {
2650 $value = call_user_func( $this->mOptions->getSpeculativeRevIdCallback() );
2651 $this->mOutput->setSpeculativeRevIdUsed(
$value );
2655 # Let the edit saving system know we should parse the page
2656 # *after* a revision ID has been assigned. This is for null edits.
2657 $this->mOutput->setFlag(
'vary-revision' );
2658 wfDebug( __METHOD__ .
": {{REVISIONDAY}} used, setting vary-revision...\n" );
2659 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2661 case 'revisionday2':
2662 # Let the edit saving system know we should parse the page
2663 # *after* a revision ID has been assigned. This is for null edits.
2664 $this->mOutput->setFlag(
'vary-revision' );
2665 wfDebug( __METHOD__ .
": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2666 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2668 case 'revisionmonth':
2669 # Let the edit saving system know we should parse the page
2670 # *after* a revision ID has been assigned. This is for null edits.
2671 $this->mOutput->setFlag(
'vary-revision' );
2672 wfDebug( __METHOD__ .
": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2673 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2675 case 'revisionmonth1':
2676 # Let the edit saving system know we should parse the page
2677 # *after* a revision ID has been assigned. This is for null edits.
2678 $this->mOutput->setFlag(
'vary-revision' );
2679 wfDebug( __METHOD__ .
": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2680 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2682 case 'revisionyear':
2683 # Let the edit saving system know we should parse the page
2684 # *after* a revision ID has been assigned. This is for null edits.
2685 $this->mOutput->setFlag(
'vary-revision' );
2686 wfDebug( __METHOD__ .
": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2687 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2689 case 'revisiontimestamp':
2690 # Let the edit saving system know we should parse the page
2691 # *after* a revision ID has been assigned. This is for null edits.
2692 $this->mOutput->setFlag(
'vary-revision' );
2693 wfDebug( __METHOD__ .
": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2694 $value = $this->getRevisionTimestamp();
2696 case 'revisionuser':
2697 # Let the edit saving system know we should parse the page
2698 # *after* a revision ID has been assigned for null edits.
2699 $this->mOutput->setFlag(
'vary-user' );
2700 wfDebug( __METHOD__ .
": {{REVISIONUSER}} used, setting vary-user...\n" );
2701 $value = $this->getRevisionUser();
2703 case 'revisionsize':
2704 $value = $this->getRevisionSize();
2707 $value = str_replace(
'_',
' ',
$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2712 case 'namespacenumber':
2713 $value = $this->mTitle->getNamespace();
2716 $value = $this->mTitle->canHaveTalkPage()
2717 ? str_replace(
'_',
' ', $this->mTitle->getTalkNsText() )
2721 $value = $this->mTitle->canHaveTalkPage() ?
wfUrlencode( $this->mTitle->getTalkNsText() ) :
'';
2723 case 'subjectspace':
2724 $value = str_replace(
'_',
' ', $this->mTitle->getSubjectNsText() );
2726 case 'subjectspacee':
2729 case 'currentdayname':
2742 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2743 # int to remove the padding
2749 case 'localdayname':
2750 $value = $pageLang->getWeekdayName(
2758 $value = $pageLang->time(
2768 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2769 # int to remove the padding
2775 case 'numberofarticles':
2778 case 'numberoffiles':
2781 case 'numberofusers':
2784 case 'numberofactiveusers':
2787 case 'numberofpages':
2790 case 'numberofadmins':
2793 case 'numberofedits':
2796 case 'currenttimestamp':
2799 case 'localtimestamp':
2802 case 'currentversion':
2817 case 'directionmark':
2818 return $pageLang->getDirMark();
2819 case 'contentlanguage':
2822 case 'pagelanguage':
2823 $value = $pageLang->getCode();
2825 case 'cascadingsources':
2831 'ParserGetVariableValueSwitch',
2832 [ &
$parser, &$this->mVarCache, &$index, &
$ret, &$frame ]
2839 $this->mVarCache[$index] =
$value;
2850 public function initialiseVariables() {
2880 public function preprocessToDom( $text, $flags = 0 ) {
2881 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2892 public static function splitWhitespace(
$s ) {
2893 $ltrimmed = ltrim(
$s );
2894 $w1 = substr(
$s, 0, strlen(
$s ) - strlen( $ltrimmed ) );
2895 $trimmed = rtrim( $ltrimmed );
2896 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2898 $w2 = substr( $ltrimmed, -$diff );
2902 return [ $w1, $trimmed, $w2 ];
2925 public function replaceVariables( $text, $frame =
false, $argsOnly =
false ) {
2926 # Is there any text? Also, Prevent too big inclusions!
2927 $textSize = strlen( $text );
2928 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
2932 if ( $frame ===
false ) {
2933 $frame = $this->getPreprocessor()->newFrame();
2934 } elseif ( !( $frame instanceof
PPFrame ) ) {
2935 wfDebug( __METHOD__ .
" called using plain parameters instead of "
2936 .
"a PPFrame instance. Creating custom frame.\n" );
2937 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2940 $dom = $this->preprocessToDom( $text );
2942 $text = $frame->expand( $dom, $flags );
2954 public static function createAssocArgs(
$args ) {
2958 $eqpos = strpos( $arg,
'=' );
2959 if ( $eqpos ===
false ) {
2960 $assocArgs[$index++] = $arg;
2962 $name = trim( substr( $arg, 0, $eqpos ) );
2963 $value = trim( substr( $arg, $eqpos + 1 ) );
2964 if (
$value ===
false ) {
2967 if (
$name !==
false ) {
3002 public function limitationWarn( $limitationType, $current =
'', $max =
'' ) {
3003 # does no harm if $current and $max are present but are unnecessary for the message
3004 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3005 # only during preview, and that would split the parser cache unnecessarily.
3006 $warning =
wfMessage(
"$limitationType-warning" )->numParams( $current, $max )
3008 $this->mOutput->addWarning( $warning );
3009 $this->addTrackingCategory(
"$limitationType-category" );
3024 public function braceSubstitution( $piece, $frame ) {
3034 $forceRawInterwiki =
false;
3036 $isChildObj =
false;
3038 $isLocalObj =
false;
3040 # Title object, where $text came from
3043 # $part1 is the bit before the first |, and must contain only title characters.
3044 # Various prefixes will be stripped from it later.
3045 $titleWithSpaces = $frame->expand( $piece[
'title'] );
3046 $part1 = trim( $titleWithSpaces );
3049 # Original title text preserved for various purposes
3050 $originalTitle = $part1;
3052 # $args is a list of argument nodes, starting from index 0, not including $part1
3053 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3054 # below won't work b/c this $args isn't an object
3055 $args = (
null == $piece[
'parts'] ) ? [] : $piece[
'parts'];
3057 $profileSection =
null;
3061 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3063 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3064 # Decide whether to expand template or keep wikitext as-is.
3065 if ( $this->ot[
'wiki'] ) {
3066 if ( $substMatch ===
false ) {
3067 $literal =
true; # literal when
in PST with no prefix
3069 $literal =
false; # expand when
in PST with subst:
or safesubst:
3072 if ( $substMatch ==
'subst' ) {
3073 $literal =
true; # literal when
not in PST with
plain subst:
3075 $literal =
false; # expand when
not in PST with safesubst:
or no prefix
3079 $text = $frame->virtualBracketedImplode(
'{{',
'|',
'}}', $titleWithSpaces,
$args );
3086 if ( !$found &&
$args->getLength() == 0 ) {
3087 $id = $this->mVariables->matchStartToEnd( $part1 );
3088 if ( $id !==
false ) {
3089 $text = $this->getVariableValue( $id, $frame );
3097 # MSG, MSGNW and RAW
3101 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3104 # Remove obsolete MSG:
3106 $mwMsg->matchStartAndRemove( $part1 );
3111 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3112 $forceRawInterwiki =
true;
3118 $colonPos = strpos( $part1,
':' );
3119 if ( $colonPos !==
false ) {
3120 $func = substr( $part1, 0, $colonPos );
3121 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3122 $argsLength =
$args->getLength();
3123 for ( $i = 0; $i < $argsLength; $i++ ) {
3124 $funcArgs[] =
$args->item( $i );
3127 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3128 }
catch ( Exception $ex ) {
3133 if ( isset(
$result[
'title'] ) ) {
3136 if ( isset(
$result[
'found'] ) ) {
3139 if ( array_key_exists(
'text',
$result ) ) {
3143 if ( isset(
$result[
'nowiki'] ) ) {
3146 if ( isset(
$result[
'isHTML'] ) ) {
3149 if ( isset(
$result[
'forceRawInterwiki'] ) ) {
3150 $forceRawInterwiki =
$result[
'forceRawInterwiki'];
3152 if ( isset(
$result[
'isChildObj'] ) ) {
3153 $isChildObj =
$result[
'isChildObj'];
3155 if ( isset(
$result[
'isLocalObj'] ) ) {
3156 $isLocalObj =
$result[
'isLocalObj'];
3161 # Finish mangling title and then check for loops.
3162 # Set $title to a Title object and $titleText to the PDBK
3165 # Split the title into page and subpage
3167 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3168 if ( $part1 !== $relative ) {
3170 $ns = $this->mTitle->getNamespace();
3174 $titleText =
$title->getPrefixedText();
3175 # Check for language variants if the template is not found
3176 if ( $this->getConverterLanguage()->hasVariants() &&
$title->getArticleID() == 0 ) {
3177 $this->getConverterLanguage()->findVariantLink( $part1,
$title,
true );
3179 # Do recursion depth check
3180 $limit = $this->mOptions->getMaxTemplateDepth();
3181 if ( $frame->depth >= $limit ) {
3183 $text =
'<span class="error">'
3184 .
wfMessage(
'parser-template-recursion-depth-warning' )
3185 ->numParams( $limit )->inContentLanguage()->text()
3191 # Load from database
3192 if ( !$found &&
$title ) {
3193 $profileSection = $this->mProfiler->scopedProfileIn(
$title->getPrefixedDBkey() );
3194 if ( !
$title->isExternal() ) {
3195 if (
$title->isSpecialPage()
3196 && $this->mOptions->getAllowSpecialInclusion()
3197 && $this->ot[
'html']
3204 $argsLength =
$args->getLength();
3205 for ( $i = 0; $i < $argsLength; $i++ ) {
3206 $bits =
$args->item( $i )->splitArg();
3207 if ( strval( $bits[
'index'] ) ===
'' ) {
3209 $value = trim( $frame->expand( $bits[
'value'] ) );
3218 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3219 $context->setUser( $this->getUser() );
3224 $context->setLanguage( $this->mOptions->getUserLangObj() );
3228 $text =
$context->getOutput()->getHTML();
3229 $this->mOutput->addOutputPageMetadata(
$context->getOutput() );
3232 if ( $specialPage && $specialPage->maxIncludeCacheTime() !==
false ) {
3233 $this->mOutput->updateRuntimeAdaptiveExpiry(
3234 $specialPage->maxIncludeCacheTime()
3239 $found =
false; # access denied
3240 wfDebug( __METHOD__ .
": template inclusion denied for " .
3241 $title->getPrefixedDBkey() .
"\n" );
3244 if ( $text !==
false ) {
3250 # If the title is valid but undisplayable, make a link to it
3251 if ( !$found && ( $this->ot[
'html'] || $this->ot[
'pre'] ) ) {
3252 $text =
"[[:$titleText]]";
3255 } elseif (
$title->isTrans() ) {
3256 # Interwiki transclusion
3257 if ( $this->ot[
'html'] && !$forceRawInterwiki ) {
3258 $text = $this->interwikiTransclude(
$title,
'render' );
3261 $text = $this->interwikiTransclude(
$title,
'raw' );
3262 # Preprocess it like a template
3263 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3269 # Do infinite loop check
3270 # This has to be done after redirect resolution to avoid infinite loops via redirects
3271 if ( !$frame->loopCheck(
$title ) ) {
3273 $text =
'<span class="error">'
3274 .
wfMessage(
'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3276 $this->addTrackingCategory(
'template-loop-category' );
3277 $this->mOutput->addWarning(
wfMessage(
'template-loop-warning',
3279 wfDebug( __METHOD__ .
": template loop broken at '$titleText'\n" );
3283 # If we haven't found text to substitute by now, we're done
3284 # Recover the source wikitext and return it
3286 $text = $frame->virtualBracketedImplode(
'{{',
'|',
'}}', $titleWithSpaces,
$args );
3287 if ( $profileSection ) {
3288 $this->mProfiler->scopedProfileOut( $profileSection );
3290 return [
'object' => $text ];
3293 # Expand DOM-style return values in a child frame
3294 if ( $isChildObj ) {
3295 # Clean up argument array
3300 } elseif ( $titleText !==
false && $newFrame->isEmpty() ) {
3301 # Expansion is eligible for the empty-frame cache
3302 $text = $newFrame->cachedExpand( $titleText, $text );
3304 # Uncached expansion
3305 $text = $newFrame->expand( $text );
3308 if ( $isLocalObj && $nowiki ) {
3310 $isLocalObj =
false;
3313 if ( $profileSection ) {
3314 $this->mProfiler->scopedProfileOut( $profileSection );
3317 # Replace raw HTML by a placeholder
3319 $text = $this->insertStripItem( $text );
3320 } elseif ( $nowiki && ( $this->ot[
'html'] || $this->ot[
'pre'] ) ) {
3321 # Escape nowiki-style return values
3323 } elseif ( is_string( $text )
3324 && !$piece[
'lineStart']
3325 && preg_match(
'/^(?:{\\||:|;|#|\*)/', $text )
3327 # T2529: if the template begins with a table or block-level
3328 # element, it should be treated as beginning a new line.
3329 # This behavior is somewhat controversial.
3330 $text =
"\n" . $text;
3333 if ( is_string( $text ) && !$this->incrementIncludeSize(
'post-expand', strlen( $text ) ) ) {
3334 # Error, oversize inclusion
3335 if ( $titleText !==
false ) {
3336 # Make a working, properly escaped link if possible (T25588)
3337 $text =
"[[:$titleText]]";
3339 # This will probably not be a working link, but at least it may
3340 # provide some hint of where the problem is
3341 preg_replace(
'/^:/',
'', $originalTitle );
3342 $text =
"[[:$originalTitle]]";
3344 $text .= $this->insertStripItem(
'<!-- WARNING: template omitted, '
3345 .
'post-expand include size too large -->' );
3346 $this->limitationWarn(
'post-expand-template-inclusion' );
3349 if ( $isLocalObj ) {
3350 $ret = [
'object' => $text ];
3352 $ret = [
'text' => $text ];
3377 public function callParserFunction( $frame, $function,
array $args = [] ) {
3380 # Case sensitive functions
3381 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3382 $function = $this->mFunctionSynonyms[1][$function];
3384 # Case insensitive functions
3386 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3387 $function = $this->mFunctionSynonyms[0][$function];
3389 return [
'found' =>
false ];
3393 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3400 # Convert arguments to PPNodes and collect for appending to $allArgs
3402 foreach (
$args as $k => $v ) {
3403 if ( $v instanceof
PPNode || $k === 0 ) {
3406 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3410 # Add a frame parameter, and pass the arguments as an array
3411 $allArgs[] = $frame;
3412 $allArgs[] = $funcArgs;
3414 # Convert arguments to plain text and append to $allArgs
3415 foreach (
$args as $k => $v ) {
3416 if ( $v instanceof
PPNode ) {
3417 $allArgs[] = trim( $frame->expand( $v ) );
3418 } elseif ( is_int( $k ) && $k >= 0 ) {
3419 $allArgs[] = trim( $v );
3421 $allArgs[] = trim(
"$k=$v" );
3426 $result = call_user_func_array( $callback, $allArgs );
3428 # The interface for function hooks allows them to return a wikitext
3429 # string or an array containing the string and any flags. This mungs
3430 # things around to match what this method should return.
3447 $preprocessFlags = 0;
3448 if ( isset(
$result[
'noparse'] ) ) {
3449 $noparse =
$result[
'noparse'];
3451 if ( isset(
$result[
'preprocessFlags'] ) ) {
3452 $preprocessFlags =
$result[
'preprocessFlags'];
3456 $result[
'text'] = $this->preprocessToDom(
$result[
'text'], $preprocessFlags );
3471 public function getTemplateDom(
$title ) {
3473 $titleText =
$title->getPrefixedDBkey();
3475 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3476 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3478 $titleText =
$title->getPrefixedDBkey();
3480 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3481 return [ $this->mTplDomCache[$titleText],
$title ];
3484 # Cache miss, go to the database
3487 if ( $text ===
false ) {
3488 $this->mTplDomCache[$titleText] =
false;
3489 return [
false,
$title ];
3492 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3493 $this->mTplDomCache[$titleText] = $dom;
3495 if ( !
$title->equals( $cacheTitle ) ) {
3496 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3514 public function fetchCurrentRevisionOfTitle(
$title ) {
3515 $cacheKey =
$title->getPrefixedDBkey();
3516 if ( !$this->currentRevisionCache ) {
3517 $this->currentRevisionCache =
new MapCacheLRU( 100 );
3519 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3520 $this->currentRevisionCache->set( $cacheKey,
3522 call_user_func( $this->mOptions->getCurrentRevisionCallback(),
$title, $this )
3525 return $this->currentRevisionCache->get( $cacheKey );
3548 public function fetchTemplateAndTitle(
$title ) {
3550 $templateCb = $this->mOptions->getTemplateCallback();
3551 $stuff = call_user_func( $templateCb,
$title, $this );
3553 $text = $stuff[
'text'];
3554 if ( is_string( $stuff[
'text'] ) ) {
3555 $text = strtr( $text,
"\x7f",
"?" );
3557 $finalTitle = isset( $stuff[
'finalTitle'] ) ? $stuff[
'finalTitle'] :
$title;
3558 if ( isset( $stuff[
'deps'] ) ) {
3559 foreach ( $stuff[
'deps']
as $dep ) {
3560 $this->mOutput->addTemplate( $dep[
'title'], $dep[
'page_id'], $dep[
'rev_id'] );
3561 if ( $dep[
'title']->equals( $this->getTitle() ) ) {
3564 $this->mOutput->setFlag(
'vary-revision' );
3568 return [ $text, $finalTitle ];
3576 public function fetchTemplate(
$title ) {
3577 return $this->fetchTemplateAndTitle(
$title )[0];
3589 public static function statelessFetchTemplate(
$title,
$parser =
false ) {
3590 $text = $skip =
false;
3594 # Loop to fetch the article, with up to 1 redirect
3596 for ( $i = 0; $i < 2 && is_object(
$title ); $i++ ) {
3597 # Give extensions a chance to select the revision instead
3598 $id =
false; # Assume current
3599 Hooks::run(
'BeforeParserFetchTemplateAndtitle',
3606 'page_id' =>
$title->getArticleID(),
3619 $rev_id =
$rev ?
$rev->getId() : 0;
3620 # If there is no current revision, there is no page
3621 if ( $id ===
false && !
$rev ) {
3623 $linkCache->addBadLinkObj(
$title );
3628 'page_id' =>
$title->getArticleID(),
3629 'rev_id' => $rev_id ];
3631 # We fetched a rev from a different title; register it too...
3633 'title' =>
$rev->getTitle(),
3634 'page_id' =>
$rev->getPage(),
3635 'rev_id' => $rev_id ];
3639 $content =
$rev->getContent();
3640 $text = $content ? $content->getWikitextForTransclusion() :
null;
3645 if ( $text ===
false || $text ===
null ) {
3652 if ( !$message->exists() ) {
3656 $content = $message->content();
3657 $text = $message->plain();
3666 $title = $content->getRedirectTarget();
3670 'finalTitle' => $finalTitle,
3695 $time = $file ? $file->getTimestamp() :
false;
3696 $sha1 = $file ? $file->getSha1() :
false;
3697 # Register the file as a dependency...
3698 $this->mOutput->addImage(
$title->getDBkey(),
$time, $sha1 );
3699 if ( $file && !
$title->equals( $file->getTitle() ) ) {
3700 # Update fetched file title
3701 $title = $file->getTitle();
3702 $this->mOutput->addImage(
$title->getDBkey(),
$time, $sha1 );
3704 return [ $file,
$title ];
3717 protected function fetchFileNoRegister(
$title,
$options = [] ) {
3718 if ( isset(
$options[
'broken'] ) ) {
3720 } elseif ( isset(
$options[
'sha1'] ) ) {
3736 public function interwikiTransclude(
$title, $action ) {
3740 return wfMessage(
'scarytranscludedisabled' )->inContentLanguage()->text();
3743 $url =
$title->getFullURL( [
'action' => $action ] );
3745 if ( strlen( $url ) > 255 ) {
3746 return wfMessage(
'scarytranscludetoolong' )->inContentLanguage()->text();
3748 return $this->fetchScaryTemplateMaybeFromCache( $url );
3755 public function fetchScaryTemplateMaybeFromCache( $url ) {
3759 $obj =
$dbr->selectRow(
'transcache', [
'tc_time',
'tc_contents' ],
3760 [
'tc_url' => $url,
"tc_time >= " .
$dbr->addQuotes( $tsCond ) ] );
3762 return $obj->tc_contents;
3768 $text =
$req->getContent();
3769 } elseif (
$req->getStatus() != 200 ) {
3771 return wfMessage(
'scarytranscludefailed-httpstatus' )
3772 ->params( $url,
$req->getStatus() )->inContentLanguage()->text();
3774 return wfMessage(
'scarytranscludefailed', $url )->inContentLanguage()->text();
3778 $dbw->replace(
'transcache', [
'tc_url' ], [
3780 'tc_time' => $dbw->timestamp( time() ),
3781 'tc_contents' => $text
3795 public function argSubstitution( $piece, $frame ) {
3797 $parts = $piece[
'parts'];
3798 $nameWithSpaces = $frame->expand( $piece[
'title'] );
3799 $argName = trim( $nameWithSpaces );
3801 $text = $frame->getArgument( $argName );
3802 if ( $text ===
false && $parts->getLength() > 0
3803 && ( $this->ot[
'html']
3805 || ( $this->ot[
'wiki'] && $frame->isTemplate() )
3808 # No match in frame, use the supplied default
3809 $object = $parts->item( 0 )->getChildren();
3811 if ( !$this->incrementIncludeSize(
'arg', strlen( $text ) ) ) {
3812 $error =
'<!-- WARNING: argument omitted, expansion size too large -->';
3813 $this->limitationWarn(
'post-expand-template-argument' );
3816 if ( $text ===
false && $object ===
false ) {
3818 $object = $frame->virtualBracketedImplode(
'{{{',
'|',
'}}}', $nameWithSpaces, $parts );
3820 if ( $error !==
false ) {
3823 if ( $object !==
false ) {
3824 $ret = [
'object' => $object ];
3826 $ret = [
'text' => $text ];
3847 public function extensionSubstitution(
$params, $frame ) {
3848 static $errorStr =
'<span class="error">';
3849 static $errorLen = 20;
3852 if ( substr(
$name, 0, $errorLen ) === $errorStr ) {
3858 $attrText = !isset(
$params[
'attr'] ) ? null : $frame->expand(
$params[
'attr'] );
3859 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3867 $content = !isset(
$params[
'inner'] ) ? null : $frame->expand(
$params[
'inner'] );
3869 $marker = self::MARKER_PREFIX .
"-$name-"
3870 . sprintf(
'%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3872 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower(
$name )] ) &&
3873 ( $this->ot[
'html'] || $this->ot[
'pre'] );
3874 if ( $isFunctionTag ) {
3875 $markerType =
'none';
3877 $markerType =
'general';
3879 if ( $this->ot[
'html'] || $isFunctionTag ) {
3881 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3882 if ( isset(
$params[
'attributes'] ) ) {
3883 $attributes = $attributes +
$params[
'attributes'];
3886 if ( isset( $this->mTagHooks[
$name] ) ) {
3887 $output = call_user_func_array( $this->mTagHooks[
$name],
3888 [ $content, $attributes, $this, $frame ] );
3889 } elseif ( isset( $this->mFunctionTagHooks[
$name] ) ) {
3890 list( $callback, ) = $this->mFunctionTagHooks[
$name];
3894 $output = call_user_func_array( $callback, [ &
$parser, $frame, $content, $attributes ] );
3896 $output =
'<span class="error">Invalid tag extension name: ' .
3897 htmlspecialchars(
$name ) .
'</span>';
3904 if ( isset( $flags[
'markerType'] ) ) {
3905 $markerType = $flags[
'markerType'];
3909 if ( is_null( $attrText ) ) {
3912 if ( isset(
$params[
'attributes'] ) ) {
3913 foreach (
$params[
'attributes']
as $attrName => $attrValue ) {
3914 $attrText .=
' ' . htmlspecialchars( $attrName ) .
'="' .
3915 htmlspecialchars( $attrValue ) .
'"';
3918 if ( $content ===
null ) {
3919 $output =
"<$name$attrText/>";
3921 $close = is_null(
$params[
'close'] ) ?
'' : $frame->expand(
$params[
'close'] );
3922 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3926 $output =
"<$name$attrText>$content$close";
3930 if ( $markerType ===
'none' ) {
3932 } elseif ( $markerType ===
'nowiki' ) {
3933 $this->mStripState->addNoWiki( $marker,
$output );
3934 } elseif ( $markerType ===
'general' ) {
3935 $this->mStripState->addGeneral( $marker,
$output );
3937 throw new MWException( __METHOD__ .
': invalid marker type' );
3949 public function incrementIncludeSize(
$type, $size ) {
3950 if ( $this->mIncludeSizes[
$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3953 $this->mIncludeSizes[
$type] += $size;
3963 public function incrementExpensiveFunctionCount() {
3964 $this->mExpensiveFunctionCount++;
3965 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
3976 public function doDoubleUnderscore( $text ) {
3977 # The position of __TOC__ needs to be recorded
3979 if ( $mw->match( $text ) ) {
3980 $this->mShowToc =
true;
3981 $this->mForceTocPosition =
true;
3983 # Set a placeholder. At the end we'll fill it in with the TOC.
3984 $text = $mw->replace(
'<!--MWTOC\'"-->', $text, 1 );
3986 # Only keep the first one.
3987 $text = $mw->replace(
'', $text );
3990 # Now match and remove the rest of them
3992 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3994 if ( isset( $this->mDoubleUnderscores[
'nogallery'] ) ) {
3995 $this->mOutput->mNoGallery =
true;
3997 if ( isset( $this->mDoubleUnderscores[
'notoc'] ) && !$this->mForceTocPosition ) {
3998 $this->mShowToc =
false;
4000 if ( isset( $this->mDoubleUnderscores[
'hiddencat'] )
4003 $this->addTrackingCategory(
'hidden-category-category' );
4005 # (T10068) Allow control over whether robots index a page.
4006 # __INDEX__ always overrides __NOINDEX__, see T16899
4007 if ( isset( $this->mDoubleUnderscores[
'noindex'] ) && $this->mTitle->canUseNoindex() ) {
4008 $this->mOutput->setIndexPolicy(
'noindex' );
4009 $this->addTrackingCategory(
'noindex-category' );
4011 if ( isset( $this->mDoubleUnderscores[
'index'] ) && $this->mTitle->canUseNoindex() ) {
4012 $this->mOutput->setIndexPolicy(
'index' );
4013 $this->addTrackingCategory(
'index-category' );
4016 # Cache all double underscores in the database
4017 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4018 $this->mOutput->setProperty( $key,
'' );
4029 public function addTrackingCategory( $msg ) {
4030 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4049 public function formatHeadings( $text, $origText, $isMain =
true ) {
4052 # Inhibit editsection links if requested in the page
4053 if ( isset( $this->mDoubleUnderscores[
'noeditsection'] ) ) {
4054 $maybeShowEditLink =
false;
4056 $maybeShowEditLink =
true;
4059 # Get all headlines for numbering them and adding funky stuff like [edit]
4060 # links - this is for later, but we need the number of headlines right now
4061 # NOTE: white space in headings have been trimmed in doHeadings. They shouldn't
4062 # be trimmed here since whitespace in HTML headings is significant.
4064 $numMatches = preg_match_all(
4065 '/<H(?P<level>[1-6])(?P<attrib>.*?>)(?P<header>[\s\S]*?)<\/H[1-6] *>/i',
4070 # if there are fewer than 4 headlines in the article, do not show TOC
4071 # unless it's been explicitly enabled.
4072 $enoughToc = $this->mShowToc &&
4073 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4075 # Allow user to stipulate that a page should have a "new section"
4076 # link added via __NEWSECTIONLINK__
4077 if ( isset( $this->mDoubleUnderscores[
'newsectionlink'] ) ) {
4078 $this->mOutput->setNewSection(
true );
4081 # Allow user to remove the "new section"
4082 # link via __NONEWSECTIONLINK__
4083 if ( isset( $this->mDoubleUnderscores[
'nonewsectionlink'] ) ) {
4084 $this->mOutput->hideNewSection(
true );
4087 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4088 # override above conditions and always show TOC above first header
4089 if ( isset( $this->mDoubleUnderscores[
'forcetoc'] ) ) {
4090 $this->mShowToc =
true;
4098 # Ugh .. the TOC should have neat indentation levels which can be
4099 # passed to the skin functions. These are determined here
4103 $sublevelCount = [];
4109 $markerRegex = self::MARKER_PREFIX .
"-h-(\d+)-" . self::MARKER_SUFFIX;
4110 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4111 $oldType = $this->mOutputType;
4113 $frame = $this->getPreprocessor()->newFrame();
4114 $root = $this->preprocessToDom( $origText );
4115 $node = $root->getFirstChild();
4120 $headlines = $numMatches !==
false ?
$matches[3] : [];
4122 foreach ( $headlines
as $headline ) {
4123 $isTemplate =
false;
4125 $sectionIndex =
false;
4127 $markerMatches = [];
4128 if ( preg_match(
"/^$markerRegex/", $headline, $markerMatches ) ) {
4129 $serial = $markerMatches[1];
4130 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4131 $isTemplate = ( $titleText != $baseTitleText );
4132 $headline = preg_replace(
"/^$markerRegex\\s*/",
"", $headline );
4136 $prevlevel = $level;
4138 $level =
$matches[1][$headlineCount];
4140 if ( $level > $prevlevel ) {
4141 # Increase TOC level
4143 $sublevelCount[$toclevel] = 0;
4145 $prevtoclevel = $toclevel;
4149 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4150 # Decrease TOC level, find level to jump to
4152 for ( $i = $toclevel; $i > 0; $i-- ) {
4153 if ( $levelCount[$i] == $level ) {
4154 # Found last matching level
4157 } elseif ( $levelCount[$i] < $level ) {
4158 # Found first matching level below current level
4168 # Unindent only if the previous toc level was shown :p
4170 $prevtoclevel = $toclevel;
4176 # No change in level, end TOC line
4182 $levelCount[$toclevel] = $level;
4184 # count number of headlines for each level
4185 $sublevelCount[$toclevel]++;
4187 for ( $i = 1; $i <= $toclevel; $i++ ) {
4188 if ( !empty( $sublevelCount[$i] ) ) {
4192 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4197 # The safe header is a version of the header text safe to use for links
4199 # Remove link placeholders by the link text.
4200 # <!--LINK number-->
4202 # link text with suffix
4203 # Do this before unstrip since link text can contain strip markers
4204 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4206 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4207 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4209 # Strip out HTML (first regex removes any tag not allowed)
4211 # * <sup> and <sub> (T10393)
4215 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4216 # * <s> and <strike> (T35715)
4217 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4218 # to allow setting directionality in toc items.
4219 $tocline = preg_replace(
4221 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4222 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4228 # Strip '<span></span>', which is the result from the above if
4229 # <span id="foo"></span> is used to produce an additional anchor
4231 $tocline = str_replace(
'<span></span>',
'', $tocline );
4233 $tocline = trim( $tocline );
4235 # For the anchor, strip out HTML-y stuff period
4236 $safeHeadline = preg_replace(
'/<.*?>/',
'', $safeHeadline );
4237 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4239 # Save headline for section edit hint before it's escaped
4240 $headlineHint = $safeHeadline;
4242 # Decode HTML entities
4243 $safeHeadline = Sanitizer::decodeCharReferences( $safeHeadline );
4245 $safeHeadline = self::normalizeSectionName( $safeHeadline );
4247 $fallbackHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_FALLBACK );
4248 $linkAnchor = Sanitizer::escapeIdForLink( $safeHeadline );
4249 $safeHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_PRIMARY );
4250 if ( $fallbackHeadline === $safeHeadline ) {
4251 # No reason to have both (in fact, we can't)
4252 $fallbackHeadline =
false;
4255 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4256 # @todo FIXME: We may be changing them depending on the current locale.
4257 $arrayKey = strtolower( $safeHeadline );
4258 if ( $fallbackHeadline ===
false ) {
4259 $fallbackArrayKey =
false;
4261 $fallbackArrayKey = strtolower( $fallbackHeadline );
4264 # Create the anchor for linking from the TOC to the section
4265 $anchor = $safeHeadline;
4266 $fallbackAnchor = $fallbackHeadline;
4267 if ( isset( $refers[$arrayKey] ) ) {
4269 for ( $i = 2; isset( $refers[
"${arrayKey}_$i"] ); ++$i );
4271 $linkAnchor .=
"_$i";
4272 $refers[
"${arrayKey}_$i"] =
true;
4274 $refers[$arrayKey] =
true;
4276 if ( $fallbackHeadline !==
false && isset( $refers[$fallbackArrayKey] ) ) {
4278 for ( $i = 2; isset( $refers[
"${fallbackArrayKey}_$i"] ); ++$i );
4279 $fallbackAnchor .=
"_$i";
4280 $refers[
"${fallbackArrayKey}_$i"] =
true;
4282 $refers[$fallbackArrayKey] =
true;
4285 # Don't number the heading if it is the only one (looks silly)
4286 if (
count(
$matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4287 # the two are different if the line contains a link
4290 [
'class' =>
'mw-headline-number' ],
4292 ) .
' ' . $headline;
4297 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4300 # Add the section to the section tree
4301 # Find the DOM node for this header
4302 $noOffset = ( $isTemplate || $sectionIndex ===
false );
4303 while ( $node && !$noOffset ) {
4304 if ( $node->getName() ===
'h' ) {
4305 $bits = $node->splitHeading();
4306 if ( $bits[
'i'] == $sectionIndex ) {
4310 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4312 $node = $node->getNextSibling();
4315 'toclevel' => $toclevel,
4318 'number' => $numbering,
4319 'index' => ( $isTemplate ?
'T-' :
'' ) . $sectionIndex,
4320 'fromtitle' => $titleText,
4321 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4322 'anchor' => $anchor,
4325 # give headline the correct <h#> tag
4326 if ( $maybeShowEditLink && $sectionIndex !==
false ) {
4328 if ( $isTemplate ) {
4329 # Put a T flag in the section identifier, to indicate to extractSections()
4330 # that sections inside <includeonly> should be counted.
4331 $editsectionPage = $titleText;
4332 $editsectionSection =
"T-$sectionIndex";
4333 $editsectionContent =
null;
4335 $editsectionPage = $this->mTitle->getPrefixedText();
4336 $editsectionSection = $sectionIndex;
4337 $editsectionContent = $headlineHint;
4351 $editlink =
'<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4352 $editlink .=
'" section="' . htmlspecialchars( $editsectionSection ) .
'"';
4353 if ( $editsectionContent !==
null ) {
4354 $editlink .=
'>' . $editsectionContent .
'</mw:editsection>';
4362 $matches[
'attrib'][$headlineCount], $anchor, $headline,
4363 $editlink, $fallbackAnchor );
4368 $this->setOutputType( $oldType );
4370 # Never ever show TOC if no headers
4371 if ( $numVisible < 1 ) {
4380 $this->mOutput->setTOCHTML( $toc );
4381 $toc = self::TOC_START . $toc . self::TOC_END;
4385 $this->mOutput->setSections( $tocraw );
4388 # split up and insert constructed headlines
4389 $blocks = preg_split(
'/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4394 foreach ( $blocks
as $block ) {
4396 if ( empty( $head[$i - 1] ) ) {
4397 $sections[$i] = $block;
4399 $sections[$i] = $head[$i - 1] . $block;
4412 Hooks::run(
'ParserSectionCreate', [ $this, $i, &$sections[$i], $maybeShowEditLink ] );
4417 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4420 $sections[0] = $sections[0] . $toc .
"\n";
4423 $full .= implode(
'', $sections );
4425 if ( $this->mForceTocPosition ) {
4426 return str_replace(
'<!--MWTOC\'"-->', $toc, $full );
4446 if ( $clearState ) {
4447 $magicScopeVariable = $this->lock();
4450 $this->setUser(
$user );
4453 $text = str_replace(
"\000",
'', $text );
4460 if (
$options->getPreSaveTransform() ) {
4461 $text = $this->pstPass2( $text,
$user );
4463 $text = $this->mStripState->unstripBoth( $text );
4465 $this->setUser(
null ); # Reset
4478 private function pstPass2( $text,
$user ) {
4481 # Note: This is the timestamp saved as hardcoded wikitext to
4482 # the database, we use $wgContLang here in order to give
4483 # everyone the same signature and use the default one rather
4484 # than the one selected in each user's preferences.
4486 $ts = $this->mOptions->getTimestamp();
4488 $ts = $timestamp->format(
'YmdHis' );
4489 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4491 $d =
$wgContLang->timeanddate( $ts,
false,
false ) .
" ($tzMsg)";
4493 # Variable replacement
4494 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4495 $text = $this->replaceVariables( $text );
4497 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4498 # which may corrupt this parser instance via its wfMessage()->text() call-
4501 if ( strpos( $text,
'~~~' ) !==
false ) {
4502 $sigText = $this->getUserSig(
$user );
4503 $text = strtr( $text, [
4505 '~~~~' =>
"$sigText $d",
4508 # The main two signature forms used above are time-sensitive
4509 $this->mOutput->setFlag(
'user-signature' );
4512 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4514 $nc =
'[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can
use non-ascii!
4517 $p1 =
"/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4519 $p4 =
"/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4521 $p3 =
"/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4523 $p2 =
"/\[\[\\|($tc+)]]/";
4525 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4526 $text = preg_replace( $p1,
'[[\\1\\2\\3|\\2]]', $text );
4527 $text = preg_replace( $p4,
'[[\\1\\2\\3|\\2]]', $text );
4528 $text = preg_replace( $p3,
'[[\\1\\2\\3\\4|\\2]]', $text );
4530 $t = $this->mTitle->getText();
4532 if ( preg_match(
"/^($nc+:|)$tc+?( \\($tc+\\))$/",
$t, $m ) ) {
4533 $text = preg_replace( $p2,
"[[$m[1]\\1$m[2]|\\1]]", $text );
4534 } elseif ( preg_match(
"/^($nc+:|)$tc+?(, $tc+|)$/",
$t, $m ) &&
"$m[1]$m[2]" !=
'' ) {
4535 $text = preg_replace( $p2,
"[[$m[1]\\1$m[2]|\\1]]", $text );
4537 # if there's no context, don't bother duplicating the title
4538 $text = preg_replace( $p2,
'[[\\1]]', $text );
4558 public function getUserSig( &
$user, $nickname =
false, $fancySig =
null ) {
4563 # If not given, retrieve from the user object.
4564 if ( $nickname ===
false ) {
4565 $nickname =
$user->getOption(
'nickname' );
4568 if ( is_null( $fancySig ) ) {
4569 $fancySig =
$user->getBoolOption(
'fancysig' );
4572 $nickname = $nickname ==
null ?
$username : $nickname;
4576 wfDebug( __METHOD__ .
": $username has overlong signature.\n" );
4577 } elseif ( $fancySig !==
false ) {
4578 # Sig. might contain markup; validate this
4579 if ( $this->validateSig( $nickname ) !==
false ) {
4580 # Validated; clean up (if needed) and return it
4581 return $this->cleanSig( $nickname,
true );
4583 # Failed to validate; fall back to the default
4585 wfDebug( __METHOD__ .
": $username has bad XML tags in signature.\n" );
4589 # Make sure nickname doesnt get a sig in a sig
4590 $nickname = self::cleanSigInSig( $nickname );
4592 # If we're still here, make it a link to the user page
4595 $msgName =
$user->isAnon() ?
'signature-anon' :
'signature';
4597 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4598 ->title( $this->getTitle() )->text();
4607 public function validateSig( $text ) {
4621 public function cleanSig( $text, $parsing =
false ) {
4624 $magicScopeVariable = $this->lock();
4628 # Option to disable this feature
4629 if ( !$this->mOptions->getCleanSignatures() ) {
4633 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4634 # => Move this logic to braceSubstitution()
4636 $substRegex =
'/\{\{(?!(?:' . $substWord->getBaseRegex() .
'))/x' . $substWord->getRegexCase();
4637 $substText =
'{{' . $substWord->getSynonym( 0 );
4639 $text = preg_replace( $substRegex, $substText, $text );
4640 $text = self::cleanSigInSig( $text );
4641 $dom = $this->preprocessToDom( $text );
4642 $frame = $this->getPreprocessor()->newFrame();
4643 $text = $frame->expand( $dom );
4646 $text = $this->mStripState->unstripBoth( $text );
4658 public static function cleanSigInSig( $text ) {
4659 $text = preg_replace(
'/~{3,5}/',
'', $text );
4673 $outputType, $clearState =
true
4685 $outputType, $clearState =
true
4687 $this->setTitle(
$title );
4689 $this->setOutputType( $outputType );
4690 if ( $clearState ) {
4691 $this->clearState();
4704 static $executing =
false;
4706 # Guard against infinite recursion
4747 public function setHook( $tag, callable $callback ) {
4748 $tag = strtolower( $tag );
4749 if ( preg_match(
'/[<>\r\n]/', $tag, $m ) ) {
4750 throw new MWException(
"Invalid character {$m[0]} in setHook('$tag', ...) call" );
4752 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] :
null;
4753 $this->mTagHooks[$tag] = $callback;
4754 if ( !in_array( $tag, $this->mStripList ) ) {
4755 $this->mStripList[] = $tag;
4778 public function setTransparentTagHook( $tag, callable $callback ) {
4779 $tag = strtolower( $tag );
4780 if ( preg_match(
'/[<>\r\n]/', $tag, $m ) ) {
4781 throw new MWException(
"Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4783 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] :
null;
4784 $this->mTransparentTagHooks[$tag] = $callback;
4792 public function clearTagHooks() {
4793 $this->mTagHooks = [];
4794 $this->mFunctionTagHooks = [];
4795 $this->mStripList = $this->mDefaultStripList;
4841 public function setFunctionHook( $id, callable $callback, $flags = 0 ) {
4844 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] :
null;
4845 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4847 # Add to function cache
4850 throw new MWException( __METHOD__ .
'() expecting a magic word identifier.' );
4853 $synonyms = $mw->getSynonyms();
4854 $sensitive = intval( $mw->isCaseSensitive() );
4856 foreach ( $synonyms
as $syn ) {
4858 if ( !$sensitive ) {
4865 # Remove trailing colon
4866 if ( substr( $syn, -1, 1 ) ===
':' ) {
4867 $syn = substr( $syn, 0, -1 );
4869 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4879 public function getFunctionHooks() {
4880 return array_keys( $this->mFunctionHooks );
4893 public function setFunctionTagHook( $tag, callable $callback, $flags ) {
4894 $tag = strtolower( $tag );
4895 if ( preg_match(
'/[<>\r\n]/', $tag, $m ) ) {
4896 throw new MWException(
"Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4898 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4899 $this->mFunctionTagHooks[$tag] :
null;
4900 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
4902 if ( !in_array( $tag, $this->mStripList ) ) {
4903 $this->mStripList[] = $tag;
4916 public function replaceLinkHolders( &$text,
$options = 0 ) {
4917 $this->mLinkHolders->replace( $text );
4927 public function replaceLinkHoldersText( $text ) {
4928 return $this->mLinkHolders->replaceText( $text );
4944 public function renderImageGallery( $text,
$params ) {
4946 if ( isset(
$params[
'mode'] ) ) {
4952 }
catch ( Exception
$e ) {
4957 $ig->setContextTitle( $this->mTitle );
4958 $ig->setShowBytes(
false );
4959 $ig->setShowDimensions(
false );
4960 $ig->setShowFilename(
false );
4961 $ig->setParser( $this );
4962 $ig->setHideBadImages();
4963 $ig->setAttributes( Sanitizer::validateTagAttributes(
$params,
'ul' ) );
4965 if ( isset(
$params[
'showfilename'] ) ) {
4966 $ig->setShowFilename(
true );
4968 $ig->setShowFilename(
false );
4970 if ( isset(
$params[
'caption'] ) ) {
4971 $caption =
$params[
'caption'];
4972 $caption = htmlspecialchars( $caption );
4973 $caption = $this->replaceInternalLinks( $caption );
4974 $ig->setCaptionHtml( $caption );
4976 if ( isset(
$params[
'perrow'] ) ) {
4977 $ig->setPerRow(
$params[
'perrow'] );
4979 if ( isset(
$params[
'widths'] ) ) {
4980 $ig->setWidths(
$params[
'widths'] );
4982 if ( isset(
$params[
'heights'] ) ) {
4983 $ig->setHeights(
$params[
'heights'] );
4985 $ig->setAdditionalOptions(
$params );
4993 # match lines like these:
4994 # Image:someimage.jpg|This is some image
5002 if ( strpos(
$matches[0],
'%' ) !==
false ) {
5006 if ( is_null(
$title ) ) {
5007 # Bogus title. Ignore these so we don't bomb out later.
5011 # We need to get what handler the file uses, to figure out parameters.
5012 # Note, a hook can overide the file name, and chose an entirely different
5013 # file (which potentially could be of a different type and have different handler).
5018 # Don't register it now, as TraditionalImageGallery does that later.
5020 $handler = $file ? $file->getHandler() :
false;
5023 'img_alt' =>
'gallery-internal-alt',
5024 'img_link' =>
'gallery-internal-link',
5027 $paramMap = $paramMap +
$handler->getParamMap();
5030 unset( $paramMap[
'img_width'] );
5038 $handlerOptions = [];
5052 foreach ( $parameterMatches
as $parameterMatch ) {
5053 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5055 $paramName = $paramMap[$magicName];
5057 switch ( $paramName ) {
5058 case 'gallery-internal-alt':
5059 $alt = $this->stripAltText( $match,
false );
5061 case 'gallery-internal-link':
5062 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5063 $chars = self::EXT_LINK_URL_CLASS;
5064 $addr = self::EXT_LINK_ADDR;
5065 $prots = $this->mUrlProtocols;
5067 if ( preg_match(
'/^-{R|(.*)}-$/', $linkValue ) ) {
5070 $linkValue = substr( $linkValue, 4, -2 );
5072 if ( preg_match(
"/^($prots)$addr$chars*$/u", $linkValue ) ) {
5074 $this->mOutput->addExternalLink(
$link );
5077 if ( $localLinkTitle !==
null ) {
5078 $this->mOutput->addLink( $localLinkTitle );
5079 $link = $localLinkTitle->getLinkURL();
5085 if (
$handler->validateParam( $paramName, $match ) ) {
5086 $handlerOptions[$paramName] = $match;
5089 wfDebug(
"$parameterMatch failed parameter validation\n" );
5090 $label =
'|' . $parameterMatch;
5096 $label =
'|' . $parameterMatch;
5100 $label = substr( $label, 1 );
5103 $ig->add(
$title, $label, $alt,
$link, $handlerOptions );
5105 $html = $ig->toHTML();
5114 public function getImageParams(
$handler ) {
5116 $handlerClass = get_class(
$handler );
5120 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5121 # Initialise static lists
5122 static $internalParamNames = [
5123 'horizAlign' => [
'left',
'right',
'center',
'none' ],
5124 'vertAlign' => [
'baseline',
'sub',
'super',
'top',
'text-top',
'middle',
5125 'bottom',
'text-bottom' ],
5126 'frame' => [
'thumbnail',
'manualthumb',
'framed',
'frameless',
5127 'upright',
'border',
'link',
'alt',
'class' ],
5129 static $internalParamMap;
5130 if ( !$internalParamMap ) {
5131 $internalParamMap = [];
5132 foreach ( $internalParamNames
as $type => $names ) {
5139 $magicName = str_replace(
'-',
'_',
"img_$name" );
5140 $internalParamMap[$magicName] = [
$type,
$name ];
5145 # Add handler params
5146 $paramMap = $internalParamMap;
5148 $handlerParamMap =
$handler->getParamMap();
5149 foreach ( $handlerParamMap
as $magic => $paramName ) {
5150 $paramMap[$magic] = [
'handler', $paramName ];
5153 $this->mImageParams[$handlerClass] = $paramMap;
5154 $this->mImageParamsMagicArray[$handlerClass] =
new MagicWordArray( array_keys( $paramMap ) );
5156 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5167 public function makeImage(
$title,
$options, $holders =
false ) {
5168 # Check if the options text is of the form "options|alt text"
5170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5171 # * left no resizing, just left align. label is used for alt= only
5172 # * right same, but right aligned
5173 # * none same, but not aligned
5174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5175 # * center center the image
5176 # * frame Keep original image size, no magnify-button.
5177 # * framed Same as "frame"
5178 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5179 # * upright reduce width for upright images, rounded to full __0 px
5180 # * border draw a 1px border around the image
5181 # * alt Text for HTML alt attribute (defaults to empty)
5182 # * class Set a class for img node
5183 # * link Set the target of the image link. Can be external, interwiki, or local
5184 # vertical-align values (no % or length right now):
5194 # Protect LanguageConverter markup when splitting into parts
5199 # Give extensions a chance to select the file revision for us
5204 # Fetch and register the file (file title may be different via hooks)
5208 $handler = $file ? $file->getHandler() :
false;
5210 list( $paramMap, $mwArray ) = $this->getImageParams(
$handler );
5213 $this->addTrackingCategory(
'broken-file-category' );
5216 # Process the input parameters
5218 $params = [
'frame' => [],
'handler' => [],
5219 'horizAlign' => [],
'vertAlign' => [] ];
5220 $seenformat =
false;
5221 foreach ( $parts
as $part ) {
5222 $part = trim( $part );
5223 list( $magicName,
$value ) = $mwArray->matchVariableStartToEnd( $part );
5225 if ( isset( $paramMap[$magicName] ) ) {
5226 list(
$type, $paramName ) = $paramMap[$magicName];
5228 # Special case; width and height come in one variable together
5229 if (
$type ===
'handler' && $paramName ===
'width' ) {
5230 $parsedWidthParam = self::parseWidthParam(
$value );
5231 if ( isset( $parsedWidthParam[
'width'] ) ) {
5232 $width = $parsedWidthParam[
'width'];
5233 if (
$handler->validateParam(
'width', $width ) ) {
5238 if ( isset( $parsedWidthParam[
'height'] ) ) {
5239 $height = $parsedWidthParam[
'height'];
5240 if (
$handler->validateParam(
'height', $height ) ) {
5245 # else no validation -- T15436
5247 if (
$type ===
'handler' ) {
5248 # Validate handler parameter
5251 # Validate internal parameters
5252 switch ( $paramName ) {
5256 # @todo FIXME: Possibly check validity here for
5257 # manualthumb? downstream behavior seems odd with
5258 # missing manual thumbs.
5263 $chars = self::EXT_LINK_URL_CLASS;
5264 $addr = self::EXT_LINK_ADDR;
5265 $prots = $this->mUrlProtocols;
5267 $paramName =
'no-link';
5270 } elseif ( preg_match(
"/^((?i)$prots)/",
$value ) ) {
5271 if ( preg_match(
"/^((?i)$prots)$addr$chars*$/u",
$value, $m ) ) {
5272 $paramName =
'link-url';
5273 $this->mOutput->addExternalLink(
$value );
5274 if ( $this->mOptions->getExternalLinkTarget() ) {
5275 $params[
$type][
'link-target'] = $this->mOptions->getExternalLinkTarget();
5282 $paramName =
'link-title';
5284 $this->mOutput->addLink( $linkTitle );
5293 $validated = !$seenformat;
5297 # Most other things appear to be empty or numeric...
5298 $validated = (
$value ===
false || is_numeric( trim(
$value ) ) );
5307 if ( !$validated ) {
5312 # Process alignment parameters
5313 if (
$params[
'horizAlign'] ) {
5320 $params[
'frame'][
'caption'] = $caption;
5322 # Will the image be presented in a frame, with the caption below?
5323 $imageIsFramed = isset(
$params[
'frame'][
'frame'] )
5324 || isset(
$params[
'frame'][
'framed'] )
5325 || isset(
$params[
'frame'][
'thumbnail'] )
5326 || isset(
$params[
'frame'][
'manualthumb'] );
5328 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5329 # came to also set the caption, ordinary text after the image -- which
5330 # makes no sense, because that just repeats the text multiple times in
5331 # screen readers. It *also* came to set the title attribute.
5332 # Now that we have an alt attribute, we should not set the alt text to
5333 # equal the caption: that's worse than useless, it just repeats the
5334 # text. This is the framed/thumbnail case. If there's no caption, we
5335 # use the unnamed parameter for alt text as well, just for the time be-
5336 # ing, if the unnamed param is set and the alt param is not.
5337 # For the future, we need to figure out if we want to tweak this more,
5338 # e.g., introducing a title= parameter for the title; ignoring the un-
5339 # named parameter entirely for images without a caption; adding an ex-
5340 # plicit caption= parameter and preserving the old magic unnamed para-
5342 if ( $imageIsFramed ) { # Framed image
5343 if ( $caption ===
'' && !isset(
$params[
'frame'][
'alt'] ) ) {
5344 # No caption or alt text, add the filename as the alt text so
5345 # that screen readers at least get some description of the image
5348 # Do not set $params['frame']['title'] because tooltips don't make sense
5350 }
else { # Inline image
5351 if ( !isset(
$params[
'frame'][
'alt'] ) ) {
5352 # No alt text, use the "caption" for the alt text
5353 if ( $caption !==
'' ) {
5354 $params[
'frame'][
'alt'] = $this->stripAltText( $caption, $holders );
5356 # No caption, fall back to using the filename for the
5361 # Use the "caption" for the tooltip text
5362 $params[
'frame'][
'title'] = $this->stripAltText( $caption, $holders );
5367 # Linker does the rest
5370 $time, $descQuery, $this->mOptions->getThumbSize() );
5372 # Give the handler a chance to modify the parser object
5374 $handler->parserTransformHook( $this, $file );
5385 protected function stripAltText( $caption, $holders ) {
5386 # Strip bad stuff out of the title (tooltip). We can't just use
5387 # replaceLinkHoldersText() here, because if this function is called
5388 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5390 $tooltip = $holders->replaceText( $caption );
5392 $tooltip = $this->replaceLinkHoldersText( $caption );
5395 # make sure there are no placeholders in thumbnail attributes
5396 # that are later expanded to html- so expand them now and
5398 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5399 $tooltip = Sanitizer::stripAllTags( $tooltip );
5409 public function disableCache() {
5410 wfDebug(
"Parser output marked as uncacheable.\n" );
5411 if ( !$this->mOutput ) {
5413 " can only be called when actually parsing something" );
5415 $this->mOutput->updateCacheExpiry( 0 );
5426 public function attributeStripCallback( &$text, $frame =
false ) {
5427 $text = $this->replaceVariables( $text, $frame );
5428 $text = $this->mStripState->unstripBoth( $text );
5437 public function getTags() {
5439 array_keys( $this->mTransparentTagHooks ),
5440 array_keys( $this->mTagHooks ),
5441 array_keys( $this->mFunctionTagHooks )
5455 public function replaceTransparentTags( $text ) {
5457 $elements = array_keys( $this->mTransparentTagHooks );
5458 $text = self::extractTagsAndParams( $elements, $text,
$matches );
5462 list( $element, $content,
$params, $tag ) = $data;
5463 $tagName = strtolower( $element );
5464 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5465 $output = call_user_func_array(
5466 $this->mTransparentTagHooks[$tagName],
5472 $replacements[$marker] =
$output;
5474 return strtr( $text, $replacements );
5506 private function extractSections( $text, $sectionId, $mode, $newText =
'' ) {
5509 $magicScopeVariable = $this->lock();
5512 $frame = $this->getPreprocessor()->newFrame();
5514 # Process section extraction flags
5516 $sectionParts = explode(
'-', $sectionId );
5517 $sectionIndex = array_pop( $sectionParts );
5518 foreach ( $sectionParts
as $part ) {
5519 if ( $part ===
'T' ) {
5520 $flags |= self::PTD_FOR_INCLUSION;
5524 # Check for empty input
5525 if ( strval( $text ) ===
'' ) {
5526 # Only sections 0 and T-0 exist in an empty document
5527 if ( $sectionIndex == 0 ) {
5528 if ( $mode ===
'get' ) {
5534 if ( $mode ===
'get' ) {
5542 # Preprocess the text
5543 $root = $this->preprocessToDom( $text, $flags );
5545 # <h> nodes indicate section breaks
5546 # They can only occur at the top level, so we can find them by iterating the root's children
5547 $node = $root->getFirstChild();
5549 # Find the target section
5550 if ( $sectionIndex == 0 ) {
5551 # Section zero doesn't nest, level=big
5552 $targetLevel = 1000;
5555 if ( $node->getName() ===
'h' ) {
5556 $bits = $node->splitHeading();
5557 if ( $bits[
'i'] == $sectionIndex ) {
5558 $targetLevel = $bits[
'level'];
5562 if ( $mode ===
'replace' ) {
5565 $node = $node->getNextSibling();
5571 if ( $mode ===
'get' ) {
5578 # Find the end of the section, including nested sections
5580 if ( $node->getName() ===
'h' ) {
5581 $bits = $node->splitHeading();
5582 $curLevel = $bits[
'level'];
5583 if ( $bits[
'i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5587 if ( $mode ===
'get' ) {
5590 $node = $node->getNextSibling();
5593 # Write out the remainder (in replace mode only)
5594 if ( $mode ===
'replace' ) {
5595 # Output the replacement text
5596 # Add two newlines on -- trailing whitespace in $newText is conventionally
5597 # stripped by the editor, so we need both newlines to restore the paragraph gap
5598 # Only add trailing whitespace if there is newText
5599 if ( $newText !=
"" ) {
5600 $outText .= $newText .
"\n\n";
5605 $node = $node->getNextSibling();
5609 if ( is_string( $outText ) ) {
5610 # Re-insert stripped tags
5611 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5631 public function getSection( $text, $sectionId, $defaultText =
'' ) {
5632 return $this->extractSections( $text, $sectionId,
'get', $defaultText );
5647 public function replaceSection( $oldText, $sectionId, $newText ) {
5648 return $this->extractSections( $oldText, $sectionId,
'replace', $newText );
5656 public function getRevisionId() {
5657 return $this->mRevisionId;
5666 public function getRevisionObject() {
5667 if ( !is_null( $this->mRevisionObject ) ) {
5668 return $this->mRevisionObject;
5670 if ( is_null( $this->mRevisionId ) ) {
5674 $rev = call_user_func(
5675 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5678 # If the parse is for a new revision, then the callback should have
5679 # already been set to force the object and should match mRevisionId.
5680 # If not, try to fetch by mRevisionId for sanity.
5681 if (
$rev &&
$rev->getId() != $this->mRevisionId ) {
5685 $this->mRevisionObject =
$rev;
5687 return $this->mRevisionObject;
5695 public function getRevisionTimestamp() {
5696 if ( is_null( $this->mRevisionTimestamp ) ) {
5699 $revObject = $this->getRevisionObject();
5700 $timestamp = $revObject ? $revObject->getTimestamp() :
wfTimestampNow();
5702 # The cryptic '' timezone parameter tells to use the site-default
5703 # timezone offset instead of the user settings.
5704 # Since this value will be saved into the parser cache, served
5705 # to other users, and potentially even used inside links and such,
5706 # it needs to be consistent for all visitors.
5707 $this->mRevisionTimestamp =
$wgContLang->userAdjust( $timestamp,
'' );
5710 return $this->mRevisionTimestamp;
5718 public function getRevisionUser() {
5719 if ( is_null( $this->mRevisionUser ) ) {
5720 $revObject = $this->getRevisionObject();
5722 # if this template is subst: the revision id will be blank,
5723 # so just use the current user's name
5725 $this->mRevisionUser = $revObject->getUserText();
5726 } elseif ( $this->ot[
'wiki'] || $this->mOptions->getIsPreview() ) {
5727 $this->mRevisionUser = $this->getUser()->getName();
5730 return $this->mRevisionUser;
5738 public function getRevisionSize() {
5739 if ( is_null( $this->mRevisionSize ) ) {
5740 $revObject = $this->getRevisionObject();
5742 # if this variable is subst: the revision id will be blank,
5743 # so just use the parser input size, because the own substituation
5744 # will change the size.
5746 $this->mRevisionSize = $revObject->getSize();
5748 $this->mRevisionSize = $this->mInputSize;
5751 return $this->mRevisionSize;
5759 public function setDefaultSort(
$sort ) {
5760 $this->mDefaultSort =
$sort;
5761 $this->mOutput->setProperty(
'defaultsort',
$sort );
5774 public function getDefaultSort() {
5775 if ( $this->mDefaultSort !==
false ) {
5776 return $this->mDefaultSort;
5788 public function getCustomDefaultSort() {
5789 return $this->mDefaultSort;
5792 private static function getSectionNameFromStrippedText( $text ) {
5793 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5794 $text = Sanitizer::decodeCharReferences( $text );
5795 $text = self::normalizeSectionName( $text );
5799 private static function makeAnchor( $sectionName ) {
5800 return '#' . Sanitizer::escapeIdForLink( $sectionName );
5803 private static function makeLegacyAnchor( $sectionName ) {
5807 $id = Sanitizer::escapeIdForAttribute( $sectionName, Sanitizer::ID_FALLBACK );
5809 $id = Sanitizer::escapeIdForLink( $sectionName );
5823 public function guessSectionNameFromWikiText( $text ) {
5824 # Strip out wikitext links(they break the anchor)
5825 $text = $this->stripSectionName( $text );
5826 $sectionName = self::getSectionNameFromStrippedText( $text );
5827 return self::makeAnchor( $sectionName );
5839 public function guessLegacySectionNameFromWikiText( $text ) {
5840 # Strip out wikitext links(they break the anchor)
5841 $text = $this->stripSectionName( $text );
5842 $sectionName = self::getSectionNameFromStrippedText( $text );
5843 return self::makeLegacyAnchor( $sectionName );
5851 public static function guessSectionNameFromStrippedText( $text ) {
5852 $sectionName = self::getSectionNameFromStrippedText( $text );
5853 return self::makeAnchor( $sectionName );
5862 private static function normalizeSectionName( $text ) {
5863 # T90902: ensure the same normalization is applied for IDs as to links
5864 $titleParser = MediaWikiServices::getInstance()->getTitleParser();
5867 $parts = $titleParser->splitTitleString(
"#$text" );
5871 return $parts[
'fragment'];
5888 public function stripSectionName( $text ) {
5889 # Strip internal link markup
5890 $text = preg_replace(
'/\[\[:?([^[|]+)\|([^[]+)\]\]/',
'$2', $text );
5891 $text = preg_replace(
'/\[\[:?([^[]+)\|?\]\]/',
'$1', $text );
5893 # Strip external link markup
5894 # @todo FIXME: Not tolerant to blank link text
5895 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5896 # on how many empty links there are on the page - need to figure that out.
5897 $text = preg_replace(
'/\[(?i:' . $this->mUrlProtocols .
')([^ ]+?) ([^[]+)\]/',
'$2', $text );
5899 # Parse wikitext quotes (italics & bold)
5900 $text = $this->doQuotes( $text );
5920 $magicScopeVariable = $this->lock();
5923 $text = $this->replaceVariables( $text );
5924 $text = $this->mStripState->unstripBoth( $text );
5925 $text = Sanitizer::removeHTMLtags( $text );
5965 public function markerSkipCallback(
$s, $callback ) {
5968 while ( $i < strlen(
$s ) ) {
5969 $markerStart = strpos(
$s, self::MARKER_PREFIX, $i );
5970 if ( $markerStart ===
false ) {
5971 $out .= call_user_func( $callback, substr(
$s, $i ) );
5974 $out .= call_user_func( $callback, substr(
$s, $i, $markerStart - $i ) );
5975 $markerEnd = strpos(
$s, self::MARKER_SUFFIX, $markerStart );
5976 if ( $markerEnd ===
false ) {
5977 $out .= substr(
$s, $markerStart );
5980 $markerEnd += strlen( self::MARKER_SUFFIX );
5981 $out .= substr(
$s, $markerStart, $markerEnd - $markerStart );
5995 public function killMarkers( $text ) {
5996 return $this->mStripState->killMarkers( $text );
6016 public function serializeHalfParsedText( $text ) {
6020 'version' => self::HALF_PARSED_VERSION,
6021 'stripState' => $this->mStripState->getSubState( $text ),
6022 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6043 public function unserializeHalfParsedText( $data ) {
6045 if ( !isset( $data[
'version'] ) || $data[
'version'] != self::HALF_PARSED_VERSION ) {
6046 throw new MWException( __METHOD__ .
': invalid version' );
6049 # First, extract the strip state.
6050 $texts = [ $data[
'text'] ];
6051 $texts = $this->mStripState->merge( $data[
'stripState'], $texts );
6053 # Now renumber links
6054 $texts = $this->mLinkHolders->mergeForeign( $data[
'linkHolders'], $texts );
6056 # Should be good to go.
6070 public function isValidHalfParsedText( $data ) {
6072 return isset( $data[
'version'] ) && $data[
'version'] == self::HALF_PARSED_VERSION;
6084 public static function parseWidthParam(
$value, $parseHeight =
true ) {
6085 $parsedWidthParam = [];
6087 return $parsedWidthParam;
6090 # (T15500) In both cases (width/height and width only),
6091 # permit trailing "px" for backward compatibility.
6092 if ( $parseHeight && preg_match(
'/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/',
$value, $m ) ) {
6093 $width = intval( $m[1] );
6094 $height = intval( $m[2] );
6095 $parsedWidthParam[
'width'] = $width;
6096 $parsedWidthParam[
'height'] = $height;
6097 } elseif ( preg_match(
'/^[0-9]*\s*(?:px)?\s*$/',
$value ) ) {
6098 $width = intval(
$value );
6099 $parsedWidthParam[
'width'] = $width;
6101 return $parsedWidthParam;
6113 protected function lock() {
6114 if ( $this->mInParse ) {
6115 throw new MWException(
"Parser state cleared while parsing. "
6116 .
"Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse );
6122 $this->mInParse =
$e->getTraceAsString();
6124 $recursiveCheck =
new ScopedCallback(
function () {
6125 $this->mInParse =
false;
6128 return $recursiveCheck;
6141 public static function stripOuterParagraph(
$html ) {
6143 if ( preg_match(
'/^<p>(.*)\n?<\/p>\n?$/sU',
$html, $m ) ) {
6144 if ( strpos( $m[1],
'</p>' ) ===
false ) {
6162 public function getFreshParser() {
6164 if ( $this->mInParse ) {
6177 public function enableOOUI() {
6179 $this->mOutput->setEnableOOUI(
true );