Merge "Revert "registration: Only allow one extension to set a specific config setting""
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * PHP parser that converts wiki markup to HTML.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Parser
22 */
23 use MediaWiki\Linker\LinkRenderer;
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
26
27 /**
28 * @defgroup Parser Parser
29 */
30
31 /**
32 * PHP Parser - Processes wiki markup (which uses a more user-friendly
33 * syntax, such as "[[link]]" for making links), and provides a one-way
34 * transformation of that wiki markup it into (X)HTML output / markup
35 * (which in turn the browser understands, and can display).
36 *
37 * There are seven main entry points into the Parser class:
38 *
39 * - Parser::parse()
40 * produces HTML output
41 * - Parser::preSaveTransform()
42 * produces altered wiki markup
43 * - Parser::preprocess()
44 * removes HTML comments and expands templates
45 * - Parser::cleanSig() and Parser::cleanSigInSig()
46 * cleans a signature before saving it to preferences
47 * - Parser::getSection()
48 * return the content of a section from an article for section editing
49 * - Parser::replaceSection()
50 * replaces a section by number inside an article
51 * - Parser::getPreloadText()
52 * removes <noinclude> sections and <includeonly> tags
53 *
54 * Globals used:
55 * object: $wgContLang
56 *
57 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
58 *
59 * @par Settings:
60 * $wgNamespacesWithSubpages
61 *
62 * @par Settings only within ParserOptions:
63 * $wgAllowExternalImages
64 * $wgAllowSpecialInclusion
65 * $wgInterwikiMagic
66 * $wgMaxArticleSize
67 *
68 * @ingroup Parser
69 */
70 class Parser {
71 /**
72 * Update this version number when the ParserOutput format
73 * changes in an incompatible way, so the parser cache
74 * can automatically discard old data.
75 */
76 const VERSION = '1.6.4';
77
78 /**
79 * Update this version number when the output of serialiseHalfParsedText()
80 * changes in an incompatible way
81 */
82 const HALF_PARSED_VERSION = 2;
83
84 # Flags for Parser::setFunctionHook
85 const SFH_NO_HASH = 1;
86 const SFH_OBJECT_ARGS = 2;
87
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)
99 // @codingStandardsIgnoreStart Generic.Files.LineLength
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';
102 // @codingStandardsIgnoreEnd
103
104 # Regular expression for a non-newline space
105 const SPACE_NOT_NL = '(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
106
107 # Flags for preprocessToDom
108 const PTD_FOR_INCLUSION = 1;
109
110 # Allowed values for $this->mOutputType
111 # Parameter to startExternalParse().
112 const OT_HTML = 1; # like parse()
113 const OT_WIKI = 2; # like preSaveTransform()
114 const OT_PREPROCESS = 3; # like preprocess()
115 const OT_MSG = 3;
116 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
117
118 /**
119 * @var string Prefix and suffix for temporary replacement strings
120 * for the multipass parser.
121 *
122 * \x7f should never appear in input as it's disallowed in XML.
123 * Using it at the front also gives us a little extra robustness
124 * since it shouldn't match when butted up against identifier-like
125 * string constructs.
126 *
127 * Must not consist of all title characters, or else it will change
128 * the behavior of <nowiki> in a link.
129 *
130 * Must have a character that needs escaping in attributes, otherwise
131 * someone could put a strip marker in an attribute, to get around
132 * escaping quote marks, and break out of the attribute. Thus we add
133 * `'".
134 */
135 const MARKER_SUFFIX = "-QINU`\"'\x7f";
136 const MARKER_PREFIX = "\x7f'\"`UNIQ-";
137
138 # Markers used for wrapping the table of contents
139 const TOC_START = '<mw:toc>';
140 const TOC_END = '</mw:toc>';
141
142 # Persistent:
143 public $mTagHooks = [];
144 public $mTransparentTagHooks = [];
145 public $mFunctionHooks = [];
146 public $mFunctionSynonyms = [ 0 => [], 1 => [] ];
147 public $mFunctionTagHooks = [];
148 public $mStripList = [];
149 public $mDefaultStripList = [];
150 public $mVarCache = [];
151 public $mImageParams = [];
152 public $mImageParamsMagicArray = [];
153 public $mMarkerIndex = 0;
154 public $mFirstCall = true;
155
156 # Initialised by initialiseVariables()
157
158 /**
159 * @var MagicWordArray
160 */
161 public $mVariables;
162
163 /**
164 * @var MagicWordArray
165 */
166 public $mSubstWords;
167 # Initialised in constructor
168 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
169
170 # Initialized in getPreprocessor()
171 /** @var Preprocessor */
172 public $mPreprocessor;
173
174 # Cleared with clearState():
175 /**
176 * @var ParserOutput
177 */
178 public $mOutput;
179 public $mAutonumber;
180
181 /**
182 * @var StripState
183 */
184 public $mStripState;
185
186 public $mIncludeCount;
187 /**
188 * @var LinkHolderArray
189 */
190 public $mLinkHolders;
191
192 public $mLinkID;
193 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
194 public $mDefaultSort;
195 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
196 public $mExpensiveFunctionCount; # number of expensive parser function calls
197 public $mShowToc, $mForceTocPosition;
198
199 /**
200 * @var User
201 */
202 public $mUser; # User object; only used when doing pre-save transform
203
204 # Temporary
205 # These are variables reset at least once per parse regardless of $clearState
206
207 /**
208 * @var ParserOptions
209 */
210 public $mOptions;
211
212 /**
213 * @var Title
214 */
215 public $mTitle; # Title context, used for self-link rendering and similar things
216 public $mOutputType; # Output type, one of the OT_xxx constants
217 public $ot; # Shortcut alias, see setOutputType()
218 public $mRevisionObject; # The revision object of the specified revision ID
219 public $mRevisionId; # ID to display in {{REVISIONID}} tags
220 public $mRevisionTimestamp; # The timestamp of the specified revision ID
221 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
222 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
223 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
224 public $mInputSize = false; # For {{PAGESIZE}} on current page.
225
226 /**
227 * @var string Deprecated accessor for the strip marker prefix.
228 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
229 */
230 public $mUniqPrefix = self::MARKER_PREFIX;
231
232 /**
233 * @var array Array with the language name of each language link (i.e. the
234 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
235 * duplicate language links to the ParserOutput.
236 */
237 public $mLangLinkLanguages;
238
239 /**
240 * @var MapCacheLRU|null
241 * @since 1.24
242 *
243 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
244 */
245 public $currentRevisionCache;
246
247 /**
248 * @var bool|string Recursive call protection.
249 * This variable should be treated as if it were private.
250 */
251 public $mInParse = false;
252
253 /** @var SectionProfiler */
254 protected $mProfiler;
255
256 /**
257 * @var LinkRenderer
258 */
259 protected $mLinkRenderer;
260
261 /**
262 * @param array $conf
263 */
264 public function __construct( $conf = [] ) {
265 $this->mConf = $conf;
266 $this->mUrlProtocols = wfUrlProtocols();
267 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
268 self::EXT_LINK_ADDR .
269 self::EXT_LINK_URL_CLASS . '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F\\x{FFFD}]*?)\]/Su';
270 if ( isset( $conf['preprocessorClass'] ) ) {
271 $this->mPreprocessorClass = $conf['preprocessorClass'];
272 } elseif ( defined( 'HPHP_VERSION' ) ) {
273 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
274 $this->mPreprocessorClass = 'Preprocessor_Hash';
275 } elseif ( extension_loaded( 'domxml' ) ) {
276 # PECL extension that conflicts with the core DOM extension (T15770)
277 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
278 $this->mPreprocessorClass = 'Preprocessor_Hash';
279 } elseif ( extension_loaded( 'dom' ) ) {
280 $this->mPreprocessorClass = 'Preprocessor_DOM';
281 } else {
282 $this->mPreprocessorClass = 'Preprocessor_Hash';
283 }
284 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
285 }
286
287 /**
288 * Reduce memory usage to reduce the impact of circular references
289 */
290 public function __destruct() {
291 if ( isset( $this->mLinkHolders ) ) {
292 unset( $this->mLinkHolders );
293 }
294 foreach ( $this as $name => $value ) {
295 unset( $this->$name );
296 }
297 }
298
299 /**
300 * Allow extensions to clean up when the parser is cloned
301 */
302 public function __clone() {
303 $this->mInParse = false;
304
305 // T58226: When you create a reference "to" an object field, that
306 // makes the object field itself be a reference too (until the other
307 // reference goes out of scope). When cloning, any field that's a
308 // reference is copied as a reference in the new object. Both of these
309 // are defined PHP5 behaviors, as inconvenient as it is for us when old
310 // hooks from PHP4 days are passing fields by reference.
311 foreach ( [ 'mStripState', 'mVarCache' ] as $k ) {
312 // Make a non-reference copy of the field, then rebind the field to
313 // reference the new copy.
314 $tmp = $this->$k;
315 $this->$k =& $tmp;
316 unset( $tmp );
317 }
318
319 Hooks::run( 'ParserCloned', [ $this ] );
320 }
321
322 /**
323 * Do various kinds of initialisation on the first call of the parser
324 */
325 public function firstCallInit() {
326 if ( !$this->mFirstCall ) {
327 return;
328 }
329 $this->mFirstCall = false;
330
331 CoreParserFunctions::register( $this );
332 CoreTagHooks::register( $this );
333 $this->initialiseVariables();
334
335 // Avoid PHP 7.1 warning from passing $this by reference
336 $parser = $this;
337 Hooks::run( 'ParserFirstCallInit', [ &$parser ] );
338 }
339
340 /**
341 * Clear Parser state
342 *
343 * @private
344 */
345 public function clearState() {
346 if ( $this->mFirstCall ) {
347 $this->firstCallInit();
348 }
349 $this->mOutput = new ParserOutput;
350 $this->mOptions->registerWatcher( [ $this->mOutput, 'recordOption' ] );
351 $this->mAutonumber = 0;
352 $this->mIncludeCount = [];
353 $this->mLinkHolders = new LinkHolderArray( $this );
354 $this->mLinkID = 0;
355 $this->mRevisionObject = $this->mRevisionTimestamp =
356 $this->mRevisionId = $this->mRevisionUser = $this->mRevisionSize = null;
357 $this->mVarCache = [];
358 $this->mUser = null;
359 $this->mLangLinkLanguages = [];
360 $this->currentRevisionCache = null;
361
362 $this->mStripState = new StripState;
363
364 # Clear these on every parse, T6549
365 $this->mTplRedirCache = $this->mTplDomCache = [];
366
367 $this->mShowToc = true;
368 $this->mForceTocPosition = false;
369 $this->mIncludeSizes = [
370 'post-expand' => 0,
371 'arg' => 0,
372 ];
373 $this->mPPNodeCount = 0;
374 $this->mGeneratedPPNodeCount = 0;
375 $this->mHighestExpansionDepth = 0;
376 $this->mDefaultSort = false;
377 $this->mHeadings = [];
378 $this->mDoubleUnderscores = [];
379 $this->mExpensiveFunctionCount = 0;
380
381 # Fix cloning
382 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
383 $this->mPreprocessor = null;
384 }
385
386 $this->mProfiler = new SectionProfiler();
387
388 // Avoid PHP 7.1 warning from passing $this by reference
389 $parser = $this;
390 Hooks::run( 'ParserClearState', [ &$parser ] );
391 }
392
393 /**
394 * Convert wikitext to HTML
395 * Do not call this function recursively.
396 *
397 * @param string $text Text we want to parse
398 * @param Title $title
399 * @param ParserOptions $options
400 * @param bool $linestart
401 * @param bool $clearState
402 * @param int $revid Number to pass in {{REVISIONID}}
403 * @return ParserOutput A ParserOutput
404 */
405 public function parse(
406 $text, Title $title, ParserOptions $options,
407 $linestart = true, $clearState = true, $revid = null
408 ) {
409 /**
410 * First pass--just handle <nowiki> sections, pass the rest off
411 * to internalParse() which does all the real work.
412 */
413
414 global $wgShowHostnames;
415
416 if ( $clearState ) {
417 // We use U+007F DELETE to construct strip markers, so we have to make
418 // sure that this character does not occur in the input text.
419 $text = strtr( $text, "\x7f", "?" );
420 $magicScopeVariable = $this->lock();
421 }
422 // Strip U+0000 NULL (T159174)
423 $text = str_replace( "\000", '', $text );
424
425 $this->startParse( $title, $options, self::OT_HTML, $clearState );
426
427 $this->currentRevisionCache = null;
428 $this->mInputSize = strlen( $text );
429 if ( $this->mOptions->getEnableLimitReport() ) {
430 $this->mOutput->resetParseStartTime();
431 }
432
433 $oldRevisionId = $this->mRevisionId;
434 $oldRevisionObject = $this->mRevisionObject;
435 $oldRevisionTimestamp = $this->mRevisionTimestamp;
436 $oldRevisionUser = $this->mRevisionUser;
437 $oldRevisionSize = $this->mRevisionSize;
438 if ( $revid !== null ) {
439 $this->mRevisionId = $revid;
440 $this->mRevisionObject = null;
441 $this->mRevisionTimestamp = null;
442 $this->mRevisionUser = null;
443 $this->mRevisionSize = null;
444 }
445
446 // Avoid PHP 7.1 warning from passing $this by reference
447 $parser = $this;
448 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
449 # No more strip!
450 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
451 $text = $this->internalParse( $text );
452 Hooks::run( 'ParserAfterParse', [ &$parser, &$text, &$this->mStripState ] );
453
454 $text = $this->internalParseHalfParsed( $text, true, $linestart );
455
456 /**
457 * A converted title will be provided in the output object if title and
458 * content conversion are enabled, the article text does not contain
459 * a conversion-suppressing double-underscore tag, and no
460 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
461 * automatic link conversion.
462 */
463 if ( !( $options->getDisableTitleConversion()
464 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
465 || isset( $this->mDoubleUnderscores['notitleconvert'] )
466 || $this->mOutput->getDisplayTitle() !== false )
467 ) {
468 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
469 if ( $convruletitle ) {
470 $this->mOutput->setTitleText( $convruletitle );
471 } else {
472 $titleText = $this->getConverterLanguage()->convertTitle( $title );
473 $this->mOutput->setTitleText( $titleText );
474 }
475 }
476
477 # Done parsing! Compute runtime adaptive expiry if set
478 $this->mOutput->finalizeAdaptiveCacheExpiry();
479
480 # Warn if too many heavyweight parser functions were used
481 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
482 $this->limitationWarn( 'expensive-parserfunction',
483 $this->mExpensiveFunctionCount,
484 $this->mOptions->getExpensiveParserFunctionLimit()
485 );
486 }
487
488 # Information on include size limits, for the benefit of users who try to skirt them
489 if ( $this->mOptions->getEnableLimitReport() ) {
490 $max = $this->mOptions->getMaxIncludeSize();
491
492 $cpuTime = $this->mOutput->getTimeSinceStart( 'cpu' );
493 if ( $cpuTime !== null ) {
494 $this->mOutput->setLimitReportData( 'limitreport-cputime',
495 sprintf( "%.3f", $cpuTime )
496 );
497 }
498
499 $wallTime = $this->mOutput->getTimeSinceStart( 'wall' );
500 $this->mOutput->setLimitReportData( 'limitreport-walltime',
501 sprintf( "%.3f", $wallTime )
502 );
503
504 $this->mOutput->setLimitReportData( 'limitreport-ppvisitednodes',
505 [ $this->mPPNodeCount, $this->mOptions->getMaxPPNodeCount() ]
506 );
507 $this->mOutput->setLimitReportData( 'limitreport-ppgeneratednodes',
508 [ $this->mGeneratedPPNodeCount, $this->mOptions->getMaxGeneratedPPNodeCount() ]
509 );
510 $this->mOutput->setLimitReportData( 'limitreport-postexpandincludesize',
511 [ $this->mIncludeSizes['post-expand'], $max ]
512 );
513 $this->mOutput->setLimitReportData( 'limitreport-templateargumentsize',
514 [ $this->mIncludeSizes['arg'], $max ]
515 );
516 $this->mOutput->setLimitReportData( 'limitreport-expansiondepth',
517 [ $this->mHighestExpansionDepth, $this->mOptions->getMaxPPExpandDepth() ]
518 );
519 $this->mOutput->setLimitReportData( 'limitreport-expensivefunctioncount',
520 [ $this->mExpensiveFunctionCount, $this->mOptions->getExpensiveParserFunctionLimit() ]
521 );
522 Hooks::run( 'ParserLimitReportPrepare', [ $this, $this->mOutput ] );
523
524 $limitReport = "NewPP limit report\n";
525 if ( $wgShowHostnames ) {
526 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
527 }
528 $limitReport .= 'Cached time: ' . $this->mOutput->getCacheTime() . "\n";
529 $limitReport .= 'Cache expiry: ' . $this->mOutput->getCacheExpiry() . "\n";
530 $limitReport .= 'Dynamic content: ' .
531 ( $this->mOutput->hasDynamicContent() ? 'true' : 'false' ) .
532 "\n";
533
534 foreach ( $this->mOutput->getLimitReportData() as $key => $value ) {
535 if ( Hooks::run( 'ParserLimitReportFormat',
536 [ $key, &$value, &$limitReport, false, false ]
537 ) ) {
538 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
539 $valueMsg = wfMessage( [ "$key-value-text", "$key-value" ] )
540 ->inLanguage( 'en' )->useDatabase( false );
541 if ( !$valueMsg->exists() ) {
542 $valueMsg = new RawMessage( '$1' );
543 }
544 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
545 $valueMsg->params( $value );
546 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
547 }
548 }
549 }
550 // Since we're not really outputting HTML, decode the entities and
551 // then re-encode the things that need hiding inside HTML comments.
552 $limitReport = htmlspecialchars_decode( $limitReport );
553 // Run deprecated hook
554 Hooks::run( 'ParserLimitReport', [ $this, &$limitReport ], '1.22' );
555
556 // Sanitize for comment. Note '‐' in the replacement is U+2010,
557 // which looks much like the problematic '-'.
558 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&amp;' ], $limitReport );
559 $text .= "\n<!-- \n$limitReport-->\n";
560
561 // Add on template profiling data in human/machine readable way
562 $dataByFunc = $this->mProfiler->getFunctionStats();
563 uasort( $dataByFunc, function ( $a, $b ) {
564 return $a['real'] < $b['real']; // descending order
565 } );
566 $profileReport = [];
567 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
568 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
569 $item['%real'], $item['real'], $item['calls'],
570 htmlspecialchars( $item['name'] ) );
571 }
572 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
573 $text .= implode( "\n", $profileReport ) . "\n-->\n";
574
575 $this->mOutput->setLimitReportData( 'limitreport-timingprofile', $profileReport );
576
577 // Add other cache related metadata
578 if ( $wgShowHostnames ) {
579 $this->mOutput->setLimitReportData( 'cachereport-origin', wfHostname() );
580 }
581 $this->mOutput->setLimitReportData( 'cachereport-timestamp',
582 $this->mOutput->getCacheTime() );
583 $this->mOutput->setLimitReportData( 'cachereport-ttl',
584 $this->mOutput->getCacheExpiry() );
585 $this->mOutput->setLimitReportData( 'cachereport-transientcontent',
586 $this->mOutput->hasDynamicContent() );
587
588 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
589 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
590 $this->mTitle->getPrefixedDBkey() );
591 }
592 }
593
594 # Wrap non-interface parser output in a <div> so it can be targeted
595 # with CSS (T37247)
596 $class = $this->mOptions->getWrapOutputClass();
597 if ( $class !== false && !$this->mOptions->getInterfaceMessage() ) {
598 $text = Html::rawElement( 'div', [ 'class' => $class ], $text );
599 }
600
601 $this->mOutput->setText( $text );
602
603 $this->mRevisionId = $oldRevisionId;
604 $this->mRevisionObject = $oldRevisionObject;
605 $this->mRevisionTimestamp = $oldRevisionTimestamp;
606 $this->mRevisionUser = $oldRevisionUser;
607 $this->mRevisionSize = $oldRevisionSize;
608 $this->mInputSize = false;
609 $this->currentRevisionCache = null;
610
611 return $this->mOutput;
612 }
613
614 /**
615 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
616 * can be called from an extension tag hook.
617 *
618 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
619 * instead, which means that lists and links have not been fully parsed yet,
620 * and strip markers are still present.
621 *
622 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
623 *
624 * Use this function if you're a parser tag hook and you want to parse
625 * wikitext before or after applying additional transformations, and you
626 * intend to *return the result as hook output*, which will cause it to go
627 * through the rest of parsing process automatically.
628 *
629 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
630 * $text are not expanded
631 *
632 * @param string $text Text extension wants to have parsed
633 * @param bool|PPFrame $frame The frame to use for expanding any template variables
634 * @return string UNSAFE half-parsed HTML
635 */
636 public function recursiveTagParse( $text, $frame = false ) {
637 // Avoid PHP 7.1 warning from passing $this by reference
638 $parser = $this;
639 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
640 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
641 $text = $this->internalParse( $text, false, $frame );
642 return $text;
643 }
644
645 /**
646 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
647 * point can be called from an extension tag hook.
648 *
649 * The output of this function is fully-parsed HTML that is safe for output.
650 * If you're a parser tag hook, you might want to use recursiveTagParse()
651 * instead.
652 *
653 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
654 * $text are not expanded
655 *
656 * @since 1.25
657 *
658 * @param string $text Text extension wants to have parsed
659 * @param bool|PPFrame $frame The frame to use for expanding any template variables
660 * @return string Fully parsed HTML
661 */
662 public function recursiveTagParseFully( $text, $frame = false ) {
663 $text = $this->recursiveTagParse( $text, $frame );
664 $text = $this->internalParseHalfParsed( $text, false );
665 return $text;
666 }
667
668 /**
669 * Expand templates and variables in the text, producing valid, static wikitext.
670 * Also removes comments.
671 * Do not call this function recursively.
672 * @param string $text
673 * @param Title $title
674 * @param ParserOptions $options
675 * @param int|null $revid
676 * @param bool|PPFrame $frame
677 * @return mixed|string
678 */
679 public function preprocess( $text, Title $title = null,
680 ParserOptions $options, $revid = null, $frame = false
681 ) {
682 $magicScopeVariable = $this->lock();
683 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
684 if ( $revid !== null ) {
685 $this->mRevisionId = $revid;
686 }
687 // Avoid PHP 7.1 warning from passing $this by reference
688 $parser = $this;
689 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
690 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
691 $text = $this->replaceVariables( $text, $frame );
692 $text = $this->mStripState->unstripBoth( $text );
693 return $text;
694 }
695
696 /**
697 * Recursive parser entry point that can be called from an extension tag
698 * hook.
699 *
700 * @param string $text Text to be expanded
701 * @param bool|PPFrame $frame The frame to use for expanding any template variables
702 * @return string
703 * @since 1.19
704 */
705 public function recursivePreprocess( $text, $frame = false ) {
706 $text = $this->replaceVariables( $text, $frame );
707 $text = $this->mStripState->unstripBoth( $text );
708 return $text;
709 }
710
711 /**
712 * Process the wikitext for the "?preload=" feature. (T7210)
713 *
714 * "<noinclude>", "<includeonly>" etc. are parsed as for template
715 * transclusion, comments, templates, arguments, tags hooks and parser
716 * functions are untouched.
717 *
718 * @param string $text
719 * @param Title $title
720 * @param ParserOptions $options
721 * @param array $params
722 * @return string
723 */
724 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = [] ) {
725 $msg = new RawMessage( $text );
726 $text = $msg->params( $params )->plain();
727
728 # Parser (re)initialisation
729 $magicScopeVariable = $this->lock();
730 $this->startParse( $title, $options, self::OT_PLAIN, true );
731
732 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
733 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
734 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
735 $text = $this->mStripState->unstripBoth( $text );
736 return $text;
737 }
738
739 /**
740 * Get a random string
741 *
742 * @return string
743 * @deprecated since 1.26; use wfRandomString() instead.
744 */
745 public static function getRandomString() {
746 wfDeprecated( __METHOD__, '1.26' );
747 return wfRandomString( 16 );
748 }
749
750 /**
751 * Set the current user.
752 * Should only be used when doing pre-save transform.
753 *
754 * @param User|null $user User object or null (to reset)
755 */
756 public function setUser( $user ) {
757 $this->mUser = $user;
758 }
759
760 /**
761 * Accessor for mUniqPrefix.
762 *
763 * @return string
764 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
765 */
766 public function uniqPrefix() {
767 wfDeprecated( __METHOD__, '1.26' );
768 return self::MARKER_PREFIX;
769 }
770
771 /**
772 * Set the context title
773 *
774 * @param Title $t
775 */
776 public function setTitle( $t ) {
777 if ( !$t ) {
778 $t = Title::newFromText( 'NO TITLE' );
779 }
780
781 if ( $t->hasFragment() ) {
782 # Strip the fragment to avoid various odd effects
783 $this->mTitle = $t->createFragmentTarget( '' );
784 } else {
785 $this->mTitle = $t;
786 }
787 }
788
789 /**
790 * Accessor for the Title object
791 *
792 * @return Title
793 */
794 public function getTitle() {
795 return $this->mTitle;
796 }
797
798 /**
799 * Accessor/mutator for the Title object
800 *
801 * @param Title $x Title object or null to just get the current one
802 * @return Title
803 */
804 public function Title( $x = null ) {
805 return wfSetVar( $this->mTitle, $x );
806 }
807
808 /**
809 * Set the output type
810 *
811 * @param int $ot New value
812 */
813 public function setOutputType( $ot ) {
814 $this->mOutputType = $ot;
815 # Shortcut alias
816 $this->ot = [
817 'html' => $ot == self::OT_HTML,
818 'wiki' => $ot == self::OT_WIKI,
819 'pre' => $ot == self::OT_PREPROCESS,
820 'plain' => $ot == self::OT_PLAIN,
821 ];
822 }
823
824 /**
825 * Accessor/mutator for the output type
826 *
827 * @param int|null $x New value or null to just get the current one
828 * @return int
829 */
830 public function OutputType( $x = null ) {
831 return wfSetVar( $this->mOutputType, $x );
832 }
833
834 /**
835 * Get the ParserOutput object
836 *
837 * @return ParserOutput
838 */
839 public function getOutput() {
840 return $this->mOutput;
841 }
842
843 /**
844 * Get the ParserOptions object
845 *
846 * @return ParserOptions
847 */
848 public function getOptions() {
849 return $this->mOptions;
850 }
851
852 /**
853 * Accessor/mutator for the ParserOptions object
854 *
855 * @param ParserOptions $x New value or null to just get the current one
856 * @return ParserOptions Current ParserOptions object
857 */
858 public function Options( $x = null ) {
859 return wfSetVar( $this->mOptions, $x );
860 }
861
862 /**
863 * @return int
864 */
865 public function nextLinkID() {
866 return $this->mLinkID++;
867 }
868
869 /**
870 * @param int $id
871 */
872 public function setLinkID( $id ) {
873 $this->mLinkID = $id;
874 }
875
876 /**
877 * Get a language object for use in parser functions such as {{FORMATNUM:}}
878 * @return Language
879 */
880 public function getFunctionLang() {
881 return $this->getTargetLanguage();
882 }
883
884 /**
885 * Get the target language for the content being parsed. This is usually the
886 * language that the content is in.
887 *
888 * @since 1.19
889 *
890 * @throws MWException
891 * @return Language
892 */
893 public function getTargetLanguage() {
894 $target = $this->mOptions->getTargetLanguage();
895
896 if ( $target !== null ) {
897 return $target;
898 } elseif ( $this->mOptions->getInterfaceMessage() ) {
899 return $this->mOptions->getUserLangObj();
900 } elseif ( is_null( $this->mTitle ) ) {
901 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
902 }
903
904 return $this->mTitle->getPageLanguage();
905 }
906
907 /**
908 * Get the language object for language conversion
909 * @return Language|null
910 */
911 public function getConverterLanguage() {
912 return $this->getTargetLanguage();
913 }
914
915 /**
916 * Get a User object either from $this->mUser, if set, or from the
917 * ParserOptions object otherwise
918 *
919 * @return User
920 */
921 public function getUser() {
922 if ( !is_null( $this->mUser ) ) {
923 return $this->mUser;
924 }
925 return $this->mOptions->getUser();
926 }
927
928 /**
929 * Get a preprocessor object
930 *
931 * @return Preprocessor
932 */
933 public function getPreprocessor() {
934 if ( !isset( $this->mPreprocessor ) ) {
935 $class = $this->mPreprocessorClass;
936 $this->mPreprocessor = new $class( $this );
937 }
938 return $this->mPreprocessor;
939 }
940
941 /**
942 * Get a LinkRenderer instance to make links with
943 *
944 * @since 1.28
945 * @return LinkRenderer
946 */
947 public function getLinkRenderer() {
948 if ( !$this->mLinkRenderer ) {
949 $this->mLinkRenderer = MediaWikiServices::getInstance()
950 ->getLinkRendererFactory()->create();
951 $this->mLinkRenderer->setStubThreshold(
952 $this->getOptions()->getStubThreshold()
953 );
954 }
955
956 return $this->mLinkRenderer;
957 }
958
959 /**
960 * Replaces all occurrences of HTML-style comments and the given tags
961 * in the text with a random marker and returns the next text. The output
962 * parameter $matches will be an associative array filled with data in
963 * the form:
964 *
965 * @code
966 * 'UNIQ-xxxxx' => [
967 * 'element',
968 * 'tag content',
969 * [ 'param' => 'x' ],
970 * '<element param="x">tag content</element>' ]
971 * @endcode
972 *
973 * @param array $elements List of element names. Comments are always extracted.
974 * @param string $text Source text string.
975 * @param array &$matches Out parameter, Array: extracted tags
976 * @param string|null $uniq_prefix
977 * @return string Stripped text
978 * @since 1.26 The uniq_prefix argument is deprecated.
979 */
980 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
981 if ( $uniq_prefix !== null ) {
982 wfDeprecated( __METHOD__ . ' called with $prefix argument', '1.26' );
983 }
984 static $n = 1;
985 $stripped = '';
986 $matches = [];
987
988 $taglist = implode( '|', $elements );
989 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
990
991 while ( $text != '' ) {
992 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
993 $stripped .= $p[0];
994 if ( count( $p ) < 5 ) {
995 break;
996 }
997 if ( count( $p ) > 5 ) {
998 # comment
999 $element = $p[4];
1000 $attributes = '';
1001 $close = '';
1002 $inside = $p[5];
1003 } else {
1004 # tag
1005 $element = $p[1];
1006 $attributes = $p[2];
1007 $close = $p[3];
1008 $inside = $p[4];
1009 }
1010
1011 $marker = self::MARKER_PREFIX . "-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
1012 $stripped .= $marker;
1013
1014 if ( $close === '/>' ) {
1015 # Empty element tag, <tag />
1016 $content = null;
1017 $text = $inside;
1018 $tail = null;
1019 } else {
1020 if ( $element === '!--' ) {
1021 $end = '/(-->)/';
1022 } else {
1023 $end = "/(<\\/$element\\s*>)/i";
1024 }
1025 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
1026 $content = $q[0];
1027 if ( count( $q ) < 3 ) {
1028 # No end tag -- let it run out to the end of the text.
1029 $tail = '';
1030 $text = '';
1031 } else {
1032 $tail = $q[1];
1033 $text = $q[2];
1034 }
1035 }
1036
1037 $matches[$marker] = [ $element,
1038 $content,
1039 Sanitizer::decodeTagAttributes( $attributes ),
1040 "<$element$attributes$close$content$tail" ];
1041 }
1042 return $stripped;
1043 }
1044
1045 /**
1046 * Get a list of strippable XML-like elements
1047 *
1048 * @return array
1049 */
1050 public function getStripList() {
1051 return $this->mStripList;
1052 }
1053
1054 /**
1055 * Add an item to the strip state
1056 * Returns the unique tag which must be inserted into the stripped text
1057 * The tag will be replaced with the original text in unstrip()
1058 *
1059 * @param string $text
1060 *
1061 * @return string
1062 */
1063 public function insertStripItem( $text ) {
1064 $marker = self::MARKER_PREFIX . "-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
1065 $this->mMarkerIndex++;
1066 $this->mStripState->addGeneral( $marker, $text );
1067 return $marker;
1068 }
1069
1070 /**
1071 * parse the wiki syntax used to render tables
1072 *
1073 * @private
1074 * @param string $text
1075 * @return string
1076 */
1077 public function doTableStuff( $text ) {
1078 $lines = StringUtils::explode( "\n", $text );
1079 $out = '';
1080 $td_history = []; # Is currently a td tag open?
1081 $last_tag_history = []; # Save history of last lag activated (td, th or caption)
1082 $tr_history = []; # Is currently a tr tag open?
1083 $tr_attributes = []; # history of tr attributes
1084 $has_opened_tr = []; # Did this table open a <tr> element?
1085 $indent_level = 0; # indent level of the table
1086
1087 foreach ( $lines as $outLine ) {
1088 $line = trim( $outLine );
1089
1090 if ( $line === '' ) { # empty line, go to next line
1091 $out .= $outLine . "\n";
1092 continue;
1093 }
1094
1095 $first_character = $line[0];
1096 $first_two = substr( $line, 0, 2 );
1097 $matches = [];
1098
1099 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1100 # First check if we are starting a new table
1101 $indent_level = strlen( $matches[1] );
1102
1103 $attributes = $this->mStripState->unstripBoth( $matches[2] );
1104 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
1105
1106 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1107 array_push( $td_history, false );
1108 array_push( $last_tag_history, '' );
1109 array_push( $tr_history, false );
1110 array_push( $tr_attributes, '' );
1111 array_push( $has_opened_tr, false );
1112 } elseif ( count( $td_history ) == 0 ) {
1113 # Don't do any of the following
1114 $out .= $outLine . "\n";
1115 continue;
1116 } elseif ( $first_two === '|}' ) {
1117 # We are ending a table
1118 $line = '</table>' . substr( $line, 2 );
1119 $last_tag = array_pop( $last_tag_history );
1120
1121 if ( !array_pop( $has_opened_tr ) ) {
1122 $line = "<tr><td></td></tr>{$line}";
1123 }
1124
1125 if ( array_pop( $tr_history ) ) {
1126 $line = "</tr>{$line}";
1127 }
1128
1129 if ( array_pop( $td_history ) ) {
1130 $line = "</{$last_tag}>{$line}";
1131 }
1132 array_pop( $tr_attributes );
1133 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1134 } elseif ( $first_two === '|-' ) {
1135 # Now we have a table row
1136 $line = preg_replace( '#^\|-+#', '', $line );
1137
1138 # Whats after the tag is now only attributes
1139 $attributes = $this->mStripState->unstripBoth( $line );
1140 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
1141 array_pop( $tr_attributes );
1142 array_push( $tr_attributes, $attributes );
1143
1144 $line = '';
1145 $last_tag = array_pop( $last_tag_history );
1146 array_pop( $has_opened_tr );
1147 array_push( $has_opened_tr, true );
1148
1149 if ( array_pop( $tr_history ) ) {
1150 $line = '</tr>';
1151 }
1152
1153 if ( array_pop( $td_history ) ) {
1154 $line = "</{$last_tag}>{$line}";
1155 }
1156
1157 $outLine = $line;
1158 array_push( $tr_history, false );
1159 array_push( $td_history, false );
1160 array_push( $last_tag_history, '' );
1161 } elseif ( $first_character === '|'
1162 || $first_character === '!'
1163 || $first_two === '|+'
1164 ) {
1165 # This might be cell elements, td, th or captions
1166 if ( $first_two === '|+' ) {
1167 $first_character = '+';
1168 $line = substr( $line, 2 );
1169 } else {
1170 $line = substr( $line, 1 );
1171 }
1172
1173 // Implies both are valid for table headings.
1174 if ( $first_character === '!' ) {
1175 $line = StringUtils::replaceMarkup( '!!', '||', $line );
1176 }
1177
1178 # Split up multiple cells on the same line.
1179 # FIXME : This can result in improper nesting of tags processed
1180 # by earlier parser steps.
1181 $cells = explode( '||', $line );
1182
1183 $outLine = '';
1184
1185 # Loop through each table cell
1186 foreach ( $cells as $cell ) {
1187 $previous = '';
1188 if ( $first_character !== '+' ) {
1189 $tr_after = array_pop( $tr_attributes );
1190 if ( !array_pop( $tr_history ) ) {
1191 $previous = "<tr{$tr_after}>\n";
1192 }
1193 array_push( $tr_history, true );
1194 array_push( $tr_attributes, '' );
1195 array_pop( $has_opened_tr );
1196 array_push( $has_opened_tr, true );
1197 }
1198
1199 $last_tag = array_pop( $last_tag_history );
1200
1201 if ( array_pop( $td_history ) ) {
1202 $previous = "</{$last_tag}>\n{$previous}";
1203 }
1204
1205 if ( $first_character === '|' ) {
1206 $last_tag = 'td';
1207 } elseif ( $first_character === '!' ) {
1208 $last_tag = 'th';
1209 } elseif ( $first_character === '+' ) {
1210 $last_tag = 'caption';
1211 } else {
1212 $last_tag = '';
1213 }
1214
1215 array_push( $last_tag_history, $last_tag );
1216
1217 # A cell could contain both parameters and data
1218 $cell_data = explode( '|', $cell, 2 );
1219
1220 # T2553: Note that a '|' inside an invalid link should not
1221 # be mistaken as delimiting cell parameters
1222 # Bug T153140: Neither should language converter markup.
1223 if ( preg_match( '/\[\[|-\{/', $cell_data[0] ) === 1 ) {
1224 $cell = "{$previous}<{$last_tag}>{$cell}";
1225 } elseif ( count( $cell_data ) == 1 ) {
1226 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1227 } else {
1228 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1229 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1230 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1231 }
1232
1233 $outLine .= $cell;
1234 array_push( $td_history, true );
1235 }
1236 }
1237 $out .= $outLine . "\n";
1238 }
1239
1240 # Closing open td, tr && table
1241 while ( count( $td_history ) > 0 ) {
1242 if ( array_pop( $td_history ) ) {
1243 $out .= "</td>\n";
1244 }
1245 if ( array_pop( $tr_history ) ) {
1246 $out .= "</tr>\n";
1247 }
1248 if ( !array_pop( $has_opened_tr ) ) {
1249 $out .= "<tr><td></td></tr>\n";
1250 }
1251
1252 $out .= "</table>\n";
1253 }
1254
1255 # Remove trailing line-ending (b/c)
1256 if ( substr( $out, -1 ) === "\n" ) {
1257 $out = substr( $out, 0, -1 );
1258 }
1259
1260 # special case: don't return empty table
1261 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1262 $out = '';
1263 }
1264
1265 return $out;
1266 }
1267
1268 /**
1269 * Helper function for parse() that transforms wiki markup into half-parsed
1270 * HTML. Only called for $mOutputType == self::OT_HTML.
1271 *
1272 * @private
1273 *
1274 * @param string $text The text to parse
1275 * @param bool $isMain Whether this is being called from the main parse() function
1276 * @param PPFrame|bool $frame A pre-processor frame
1277 *
1278 * @return string
1279 */
1280 public function internalParse( $text, $isMain = true, $frame = false ) {
1281 $origText = $text;
1282
1283 // Avoid PHP 7.1 warning from passing $this by reference
1284 $parser = $this;
1285
1286 # Hook to suspend the parser in this state
1287 if ( !Hooks::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState ] ) ) {
1288 return $text;
1289 }
1290
1291 # if $frame is provided, then use $frame for replacing any variables
1292 if ( $frame ) {
1293 # use frame depth to infer how include/noinclude tags should be handled
1294 # depth=0 means this is the top-level document; otherwise it's an included document
1295 if ( !$frame->depth ) {
1296 $flag = 0;
1297 } else {
1298 $flag = self::PTD_FOR_INCLUSION;
1299 }
1300 $dom = $this->preprocessToDom( $text, $flag );
1301 $text = $frame->expand( $dom );
1302 } else {
1303 # if $frame is not provided, then use old-style replaceVariables
1304 $text = $this->replaceVariables( $text );
1305 }
1306
1307 Hooks::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState ] );
1308 $text = Sanitizer::removeHTMLtags(
1309 $text,
1310 [ $this, 'attributeStripCallback' ],
1311 false,
1312 array_keys( $this->mTransparentTagHooks ),
1313 [],
1314 [ $this, 'addTrackingCategory' ]
1315 );
1316 Hooks::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState ] );
1317
1318 # Tables need to come after variable replacement for things to work
1319 # properly; putting them before other transformations should keep
1320 # exciting things like link expansions from showing up in surprising
1321 # places.
1322 $text = $this->doTableStuff( $text );
1323
1324 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1325
1326 $text = $this->doDoubleUnderscore( $text );
1327
1328 $text = $this->doHeadings( $text );
1329 $text = $this->replaceInternalLinks( $text );
1330 $text = $this->doAllQuotes( $text );
1331 $text = $this->replaceExternalLinks( $text );
1332
1333 # replaceInternalLinks may sometimes leave behind
1334 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1335 $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text );
1336
1337 $text = $this->doMagicLinks( $text );
1338 $text = $this->formatHeadings( $text, $origText, $isMain );
1339
1340 return $text;
1341 }
1342
1343 /**
1344 * Helper function for parse() that transforms half-parsed HTML into fully
1345 * parsed HTML.
1346 *
1347 * @param string $text
1348 * @param bool $isMain
1349 * @param bool $linestart
1350 * @return string
1351 */
1352 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1353 $text = $this->mStripState->unstripGeneral( $text );
1354
1355 // Avoid PHP 7.1 warning from passing $this by reference
1356 $parser = $this;
1357
1358 if ( $isMain ) {
1359 Hooks::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1360 }
1361
1362 # Clean up special characters, only run once, next-to-last before doBlockLevels
1363 $fixtags = [
1364 # French spaces, last one Guillemet-left
1365 # only if there is something before the space
1366 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
1367 # french spaces, Guillemet-right
1368 '/(\\302\\253) /' => '\\1&#160;',
1369 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1370 ];
1371 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1372
1373 $text = $this->doBlockLevels( $text, $linestart );
1374
1375 $this->replaceLinkHolders( $text );
1376
1377 /**
1378 * The input doesn't get language converted if
1379 * a) It's disabled
1380 * b) Content isn't converted
1381 * c) It's a conversion table
1382 * d) it is an interface message (which is in the user language)
1383 */
1384 if ( !( $this->mOptions->getDisableContentConversion()
1385 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
1386 ) {
1387 if ( !$this->mOptions->getInterfaceMessage() ) {
1388 # The position of the convert() call should not be changed. it
1389 # assumes that the links are all replaced and the only thing left
1390 # is the <nowiki> mark.
1391 $text = $this->getConverterLanguage()->convert( $text );
1392 }
1393 }
1394
1395 $text = $this->mStripState->unstripNoWiki( $text );
1396
1397 if ( $isMain ) {
1398 Hooks::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1399 }
1400
1401 $text = $this->replaceTransparentTags( $text );
1402 $text = $this->mStripState->unstripGeneral( $text );
1403
1404 $text = Sanitizer::normalizeCharReferences( $text );
1405
1406 if ( MWTidy::isEnabled() ) {
1407 if ( $this->mOptions->getTidy() ) {
1408 $text = MWTidy::tidy( $text );
1409 }
1410 } else {
1411 # attempt to sanitize at least some nesting problems
1412 # (T4702 and quite a few others)
1413 $tidyregs = [
1414 # ''Something [http://www.cool.com cool''] -->
1415 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1416 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1417 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1418 # fix up an anchor inside another anchor, only
1419 # at least for a single single nested link (T5695)
1420 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1421 '\\1\\2</a>\\3</a>\\1\\4</a>',
1422 # fix div inside inline elements- doBlockLevels won't wrap a line which
1423 # contains a div, so fix it up here; replace
1424 # div with escaped text
1425 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1426 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1427 # remove empty italic or bold tag pairs, some
1428 # introduced by rules above
1429 '/<([bi])><\/\\1>/' => '',
1430 ];
1431
1432 $text = preg_replace(
1433 array_keys( $tidyregs ),
1434 array_values( $tidyregs ),
1435 $text );
1436 }
1437
1438 if ( $isMain ) {
1439 Hooks::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1440 }
1441
1442 return $text;
1443 }
1444
1445 /**
1446 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1447 * magic external links.
1448 *
1449 * DML
1450 * @private
1451 *
1452 * @param string $text
1453 *
1454 * @return string
1455 */
1456 public function doMagicLinks( $text ) {
1457 $prots = wfUrlProtocolsWithoutProtRel();
1458 $urlChar = self::EXT_LINK_URL_CLASS;
1459 $addr = self::EXT_LINK_ADDR;
1460 $space = self::SPACE_NOT_NL; # non-newline space
1461 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1462 $spaces = "$space++"; # possessive match of 1 or more spaces
1463 $text = preg_replace_callback(
1464 '!(?: # Start cases
1465 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1466 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1467 (\b # m[3]: Free external links
1468 (?i:$prots)
1469 ($addr$urlChar*) # m[4]: Post-protocol path
1470 ) |
1471 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1472 ([0-9]+)\b |
1473 \bISBN $spaces ( # m[6]: ISBN, capture number
1474 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1475 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1476 [0-9Xx] # check digit
1477 )\b
1478 )!xu", [ $this, 'magicLinkCallback' ], $text );
1479 return $text;
1480 }
1481
1482 /**
1483 * @throws MWException
1484 * @param array $m
1485 * @return HTML|string
1486 */
1487 public function magicLinkCallback( $m ) {
1488 if ( isset( $m[1] ) && $m[1] !== '' ) {
1489 # Skip anchor
1490 return $m[0];
1491 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1492 # Skip HTML element
1493 return $m[0];
1494 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1495 # Free external link
1496 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1497 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1498 # RFC or PMID
1499 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1500 if ( !$this->mOptions->getMagicRFCLinks() ) {
1501 return $m[0];
1502 }
1503 $keyword = 'RFC';
1504 $urlmsg = 'rfcurl';
1505 $cssClass = 'mw-magiclink-rfc';
1506 $trackingCat = 'magiclink-tracking-rfc';
1507 $id = $m[5];
1508 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1509 if ( !$this->mOptions->getMagicPMIDLinks() ) {
1510 return $m[0];
1511 }
1512 $keyword = 'PMID';
1513 $urlmsg = 'pubmedurl';
1514 $cssClass = 'mw-magiclink-pmid';
1515 $trackingCat = 'magiclink-tracking-pmid';
1516 $id = $m[5];
1517 } else {
1518 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1519 substr( $m[0], 0, 20 ) . '"' );
1520 }
1521 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1522 $this->addTrackingCategory( $trackingCat );
1523 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle );
1524 } elseif ( isset( $m[6] ) && $m[6] !== ''
1525 && $this->mOptions->getMagicISBNLinks()
1526 ) {
1527 # ISBN
1528 $isbn = $m[6];
1529 $space = self::SPACE_NOT_NL; # non-newline space
1530 $isbn = preg_replace( "/$space/", ' ', $isbn );
1531 $num = strtr( $isbn, [
1532 '-' => '',
1533 ' ' => '',
1534 'x' => 'X',
1535 ] );
1536 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1537 return $this->getLinkRenderer()->makeKnownLink(
1538 SpecialPage::getTitleFor( 'Booksources', $num ),
1539 "ISBN $isbn",
1540 [
1541 'class' => 'internal mw-magiclink-isbn',
1542 'title' => false // suppress title attribute
1543 ]
1544 );
1545 } else {
1546 return $m[0];
1547 }
1548 }
1549
1550 /**
1551 * Make a free external link, given a user-supplied URL
1552 *
1553 * @param string $url
1554 * @param int $numPostProto
1555 * The number of characters after the protocol.
1556 * @return string HTML
1557 * @private
1558 */
1559 public function makeFreeExternalLink( $url, $numPostProto ) {
1560 $trail = '';
1561
1562 # The characters '<' and '>' (which were escaped by
1563 # removeHTMLtags()) should not be included in
1564 # URLs, per RFC 2396.
1565 # Make &nbsp; terminate a URL as well (bug T84937)
1566 $m2 = [];
1567 if ( preg_match(
1568 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1569 $url,
1570 $m2,
1571 PREG_OFFSET_CAPTURE
1572 ) ) {
1573 $trail = substr( $url, $m2[0][1] ) . $trail;
1574 $url = substr( $url, 0, $m2[0][1] );
1575 }
1576
1577 # Move trailing punctuation to $trail
1578 $sep = ',;\.:!?';
1579 # If there is no left bracket, then consider right brackets fair game too
1580 if ( strpos( $url, '(' ) === false ) {
1581 $sep .= ')';
1582 }
1583
1584 $urlRev = strrev( $url );
1585 $numSepChars = strspn( $urlRev, $sep );
1586 # Don't break a trailing HTML entity by moving the ; into $trail
1587 # This is in hot code, so use substr_compare to avoid having to
1588 # create a new string object for the comparison
1589 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1590 # more optimization: instead of running preg_match with a $
1591 # anchor, which can be slow, do the match on the reversed
1592 # string starting at the desired offset.
1593 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1594 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1595 $numSepChars--;
1596 }
1597 }
1598 if ( $numSepChars ) {
1599 $trail = substr( $url, -$numSepChars ) . $trail;
1600 $url = substr( $url, 0, -$numSepChars );
1601 }
1602
1603 # Verify that we still have a real URL after trail removal, and
1604 # not just lone protocol
1605 if ( strlen( $trail ) >= $numPostProto ) {
1606 return $url . $trail;
1607 }
1608
1609 $url = Sanitizer::cleanUrl( $url );
1610
1611 # Is this an external image?
1612 $text = $this->maybeMakeExternalImage( $url );
1613 if ( $text === false ) {
1614 # Not an image, make a link
1615 $text = Linker::makeExternalLink( $url,
1616 $this->getConverterLanguage()->markNoConversion( $url, true ),
1617 true, 'free',
1618 $this->getExternalLinkAttribs( $url ), $this->mTitle );
1619 # Register it in the output object...
1620 $this->mOutput->addExternalLink( $url );
1621 }
1622 return $text . $trail;
1623 }
1624
1625 /**
1626 * Parse headers and return html
1627 *
1628 * @private
1629 *
1630 * @param string $text
1631 *
1632 * @return string
1633 */
1634 public function doHeadings( $text ) {
1635 for ( $i = 6; $i >= 1; --$i ) {
1636 $h = str_repeat( '=', $i );
1637 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1638 }
1639 return $text;
1640 }
1641
1642 /**
1643 * Replace single quotes with HTML markup
1644 * @private
1645 *
1646 * @param string $text
1647 *
1648 * @return string The altered text
1649 */
1650 public function doAllQuotes( $text ) {
1651 $outtext = '';
1652 $lines = StringUtils::explode( "\n", $text );
1653 foreach ( $lines as $line ) {
1654 $outtext .= $this->doQuotes( $line ) . "\n";
1655 }
1656 $outtext = substr( $outtext, 0, -1 );
1657 return $outtext;
1658 }
1659
1660 /**
1661 * Helper function for doAllQuotes()
1662 *
1663 * @param string $text
1664 *
1665 * @return string
1666 */
1667 public function doQuotes( $text ) {
1668 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1669 $countarr = count( $arr );
1670 if ( $countarr == 1 ) {
1671 return $text;
1672 }
1673
1674 // First, do some preliminary work. This may shift some apostrophes from
1675 // being mark-up to being text. It also counts the number of occurrences
1676 // of bold and italics mark-ups.
1677 $numbold = 0;
1678 $numitalics = 0;
1679 for ( $i = 1; $i < $countarr; $i += 2 ) {
1680 $thislen = strlen( $arr[$i] );
1681 // If there are ever four apostrophes, assume the first is supposed to
1682 // be text, and the remaining three constitute mark-up for bold text.
1683 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1684 if ( $thislen == 4 ) {
1685 $arr[$i - 1] .= "'";
1686 $arr[$i] = "'''";
1687 $thislen = 3;
1688 } elseif ( $thislen > 5 ) {
1689 // If there are more than 5 apostrophes in a row, assume they're all
1690 // text except for the last 5.
1691 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1692 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1693 $arr[$i] = "'''''";
1694 $thislen = 5;
1695 }
1696 // Count the number of occurrences of bold and italics mark-ups.
1697 if ( $thislen == 2 ) {
1698 $numitalics++;
1699 } elseif ( $thislen == 3 ) {
1700 $numbold++;
1701 } elseif ( $thislen == 5 ) {
1702 $numitalics++;
1703 $numbold++;
1704 }
1705 }
1706
1707 // If there is an odd number of both bold and italics, it is likely
1708 // that one of the bold ones was meant to be an apostrophe followed
1709 // by italics. Which one we cannot know for certain, but it is more
1710 // likely to be one that has a single-letter word before it.
1711 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1712 $firstsingleletterword = -1;
1713 $firstmultiletterword = -1;
1714 $firstspace = -1;
1715 for ( $i = 1; $i < $countarr; $i += 2 ) {
1716 if ( strlen( $arr[$i] ) == 3 ) {
1717 $x1 = substr( $arr[$i - 1], -1 );
1718 $x2 = substr( $arr[$i - 1], -2, 1 );
1719 if ( $x1 === ' ' ) {
1720 if ( $firstspace == -1 ) {
1721 $firstspace = $i;
1722 }
1723 } elseif ( $x2 === ' ' ) {
1724 $firstsingleletterword = $i;
1725 // if $firstsingleletterword is set, we don't
1726 // look at the other options, so we can bail early.
1727 break;
1728 } else {
1729 if ( $firstmultiletterword == -1 ) {
1730 $firstmultiletterword = $i;
1731 }
1732 }
1733 }
1734 }
1735
1736 // If there is a single-letter word, use it!
1737 if ( $firstsingleletterword > -1 ) {
1738 $arr[$firstsingleletterword] = "''";
1739 $arr[$firstsingleletterword - 1] .= "'";
1740 } elseif ( $firstmultiletterword > -1 ) {
1741 // If not, but there's a multi-letter word, use that one.
1742 $arr[$firstmultiletterword] = "''";
1743 $arr[$firstmultiletterword - 1] .= "'";
1744 } elseif ( $firstspace > -1 ) {
1745 // ... otherwise use the first one that has neither.
1746 // (notice that it is possible for all three to be -1 if, for example,
1747 // there is only one pentuple-apostrophe in the line)
1748 $arr[$firstspace] = "''";
1749 $arr[$firstspace - 1] .= "'";
1750 }
1751 }
1752
1753 // Now let's actually convert our apostrophic mush to HTML!
1754 $output = '';
1755 $buffer = '';
1756 $state = '';
1757 $i = 0;
1758 foreach ( $arr as $r ) {
1759 if ( ( $i % 2 ) == 0 ) {
1760 if ( $state === 'both' ) {
1761 $buffer .= $r;
1762 } else {
1763 $output .= $r;
1764 }
1765 } else {
1766 $thislen = strlen( $r );
1767 if ( $thislen == 2 ) {
1768 if ( $state === 'i' ) {
1769 $output .= '</i>';
1770 $state = '';
1771 } elseif ( $state === 'bi' ) {
1772 $output .= '</i>';
1773 $state = 'b';
1774 } elseif ( $state === 'ib' ) {
1775 $output .= '</b></i><b>';
1776 $state = 'b';
1777 } elseif ( $state === 'both' ) {
1778 $output .= '<b><i>' . $buffer . '</i>';
1779 $state = 'b';
1780 } else { // $state can be 'b' or ''
1781 $output .= '<i>';
1782 $state .= 'i';
1783 }
1784 } elseif ( $thislen == 3 ) {
1785 if ( $state === 'b' ) {
1786 $output .= '</b>';
1787 $state = '';
1788 } elseif ( $state === 'bi' ) {
1789 $output .= '</i></b><i>';
1790 $state = 'i';
1791 } elseif ( $state === 'ib' ) {
1792 $output .= '</b>';
1793 $state = 'i';
1794 } elseif ( $state === 'both' ) {
1795 $output .= '<i><b>' . $buffer . '</b>';
1796 $state = 'i';
1797 } else { // $state can be 'i' or ''
1798 $output .= '<b>';
1799 $state .= 'b';
1800 }
1801 } elseif ( $thislen == 5 ) {
1802 if ( $state === 'b' ) {
1803 $output .= '</b><i>';
1804 $state = 'i';
1805 } elseif ( $state === 'i' ) {
1806 $output .= '</i><b>';
1807 $state = 'b';
1808 } elseif ( $state === 'bi' ) {
1809 $output .= '</i></b>';
1810 $state = '';
1811 } elseif ( $state === 'ib' ) {
1812 $output .= '</b></i>';
1813 $state = '';
1814 } elseif ( $state === 'both' ) {
1815 $output .= '<i><b>' . $buffer . '</b></i>';
1816 $state = '';
1817 } else { // ($state == '')
1818 $buffer = '';
1819 $state = 'both';
1820 }
1821 }
1822 }
1823 $i++;
1824 }
1825 // Now close all remaining tags. Notice that the order is important.
1826 if ( $state === 'b' || $state === 'ib' ) {
1827 $output .= '</b>';
1828 }
1829 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1830 $output .= '</i>';
1831 }
1832 if ( $state === 'bi' ) {
1833 $output .= '</b>';
1834 }
1835 // There might be lonely ''''', so make sure we have a buffer
1836 if ( $state === 'both' && $buffer ) {
1837 $output .= '<b><i>' . $buffer . '</i></b>';
1838 }
1839 return $output;
1840 }
1841
1842 /**
1843 * Replace external links (REL)
1844 *
1845 * Note: this is all very hackish and the order of execution matters a lot.
1846 * Make sure to run tests/parser/parserTests.php if you change this code.
1847 *
1848 * @private
1849 *
1850 * @param string $text
1851 *
1852 * @throws MWException
1853 * @return string
1854 */
1855 public function replaceExternalLinks( $text ) {
1856 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1857 if ( $bits === false ) {
1858 throw new MWException( "PCRE needs to be compiled with "
1859 . "--enable-unicode-properties in order for MediaWiki to function" );
1860 }
1861 $s = array_shift( $bits );
1862
1863 $i = 0;
1864 while ( $i < count( $bits ) ) {
1865 $url = $bits[$i++];
1866 $i++; // protocol
1867 $text = $bits[$i++];
1868 $trail = $bits[$i++];
1869
1870 # The characters '<' and '>' (which were escaped by
1871 # removeHTMLtags()) should not be included in
1872 # URLs, per RFC 2396.
1873 $m2 = [];
1874 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1875 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1876 $url = substr( $url, 0, $m2[0][1] );
1877 }
1878
1879 # If the link text is an image URL, replace it with an <img> tag
1880 # This happened by accident in the original parser, but some people used it extensively
1881 $img = $this->maybeMakeExternalImage( $text );
1882 if ( $img !== false ) {
1883 $text = $img;
1884 }
1885
1886 $dtrail = '';
1887
1888 # Set linktype for CSS - if URL==text, link is essentially free
1889 $linktype = ( $text === $url ) ? 'free' : 'text';
1890
1891 # No link text, e.g. [http://domain.tld/some.link]
1892 if ( $text == '' ) {
1893 # Autonumber
1894 $langObj = $this->getTargetLanguage();
1895 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1896 $linktype = 'autonumber';
1897 } else {
1898 # Have link text, e.g. [http://domain.tld/some.link text]s
1899 # Check for trail
1900 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1901 }
1902
1903 $text = $this->getConverterLanguage()->markNoConversion( $text );
1904
1905 $url = Sanitizer::cleanUrl( $url );
1906
1907 # Use the encoded URL
1908 # This means that users can paste URLs directly into the text
1909 # Funny characters like ö aren't valid in URLs anyway
1910 # This was changed in August 2004
1911 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1912 $this->getExternalLinkAttribs( $url ), $this->mTitle ) . $dtrail . $trail;
1913
1914 # Register link in the output object.
1915 $this->mOutput->addExternalLink( $url );
1916 }
1917
1918 return $s;
1919 }
1920
1921 /**
1922 * Get the rel attribute for a particular external link.
1923 *
1924 * @since 1.21
1925 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1926 * nofollow if appropriate
1927 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1928 * @return string|null Rel attribute for $url
1929 */
1930 public static function getExternalLinkRel( $url = false, $title = null ) {
1931 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1932 $ns = $title ? $title->getNamespace() : false;
1933 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1934 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1935 ) {
1936 return 'nofollow';
1937 }
1938 return null;
1939 }
1940
1941 /**
1942 * Get an associative array of additional HTML attributes appropriate for a
1943 * particular external link. This currently may include rel => nofollow
1944 * (depending on configuration, namespace, and the URL's domain) and/or a
1945 * target attribute (depending on configuration).
1946 *
1947 * @param string $url URL to extract the domain from for rel =>
1948 * nofollow if appropriate
1949 * @return array Associative array of HTML attributes
1950 */
1951 public function getExternalLinkAttribs( $url ) {
1952 $attribs = [];
1953 $rel = self::getExternalLinkRel( $url, $this->mTitle );
1954
1955 $target = $this->mOptions->getExternalLinkTarget();
1956 if ( $target ) {
1957 $attribs['target'] = $target;
1958 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1959 // T133507. New windows can navigate parent cross-origin.
1960 // Including noreferrer due to lacking browser
1961 // support of noopener. Eventually noreferrer should be removed.
1962 if ( $rel !== '' ) {
1963 $rel .= ' ';
1964 }
1965 $rel .= 'noreferrer noopener';
1966 }
1967 }
1968 $attribs['rel'] = $rel;
1969 return $attribs;
1970 }
1971
1972 /**
1973 * Replace unusual escape codes in a URL with their equivalent characters
1974 *
1975 * This generally follows the syntax defined in RFC 3986, with special
1976 * consideration for HTTP query strings.
1977 *
1978 * @param string $url
1979 * @return string
1980 */
1981 public static function normalizeLinkUrl( $url ) {
1982 # First, make sure unsafe characters are encoded
1983 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1984 function ( $m ) {
1985 return rawurlencode( $m[0] );
1986 },
1987 $url
1988 );
1989
1990 $ret = '';
1991 $end = strlen( $url );
1992
1993 # Fragment part - 'fragment'
1994 $start = strpos( $url, '#' );
1995 if ( $start !== false && $start < $end ) {
1996 $ret = self::normalizeUrlComponent(
1997 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1998 $end = $start;
1999 }
2000
2001 # Query part - 'query' minus &=+;
2002 $start = strpos( $url, '?' );
2003 if ( $start !== false && $start < $end ) {
2004 $ret = self::normalizeUrlComponent(
2005 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2006 $end = $start;
2007 }
2008
2009 # Scheme and path part - 'pchar'
2010 # (we assume no userinfo or encoded colons in the host)
2011 $ret = self::normalizeUrlComponent(
2012 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2013
2014 return $ret;
2015 }
2016
2017 private static function normalizeUrlComponent( $component, $unsafe ) {
2018 $callback = function ( $matches ) use ( $unsafe ) {
2019 $char = urldecode( $matches[0] );
2020 $ord = ord( $char );
2021 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2022 # Unescape it
2023 return $char;
2024 } else {
2025 # Leave it escaped, but use uppercase for a-f
2026 return strtoupper( $matches[0] );
2027 }
2028 };
2029 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2030 }
2031
2032 /**
2033 * make an image if it's allowed, either through the global
2034 * option, through the exception, or through the on-wiki whitelist
2035 *
2036 * @param string $url
2037 *
2038 * @return string
2039 */
2040 private function maybeMakeExternalImage( $url ) {
2041 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
2042 $imagesexception = !empty( $imagesfrom );
2043 $text = false;
2044 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2045 if ( $imagesexception && is_array( $imagesfrom ) ) {
2046 $imagematch = false;
2047 foreach ( $imagesfrom as $match ) {
2048 if ( strpos( $url, $match ) === 0 ) {
2049 $imagematch = true;
2050 break;
2051 }
2052 }
2053 } elseif ( $imagesexception ) {
2054 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2055 } else {
2056 $imagematch = false;
2057 }
2058
2059 if ( $this->mOptions->getAllowExternalImages()
2060 || ( $imagesexception && $imagematch )
2061 ) {
2062 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
2063 # Image found
2064 $text = Linker::makeExternalImage( $url );
2065 }
2066 }
2067 if ( !$text && $this->mOptions->getEnableImageWhitelist()
2068 && preg_match( self::EXT_IMAGE_REGEX, $url )
2069 ) {
2070 $whitelist = explode(
2071 "\n",
2072 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2073 );
2074
2075 foreach ( $whitelist as $entry ) {
2076 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2077 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
2078 continue;
2079 }
2080 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2081 # Image matches a whitelist entry
2082 $text = Linker::makeExternalImage( $url );
2083 break;
2084 }
2085 }
2086 }
2087 return $text;
2088 }
2089
2090 /**
2091 * Process [[ ]] wikilinks
2092 *
2093 * @param string $s
2094 *
2095 * @return string Processed text
2096 *
2097 * @private
2098 */
2099 public function replaceInternalLinks( $s ) {
2100 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
2101 return $s;
2102 }
2103
2104 /**
2105 * Process [[ ]] wikilinks (RIL)
2106 * @param string &$s
2107 * @throws MWException
2108 * @return LinkHolderArray
2109 *
2110 * @private
2111 */
2112 public function replaceInternalLinks2( &$s ) {
2113 global $wgExtraInterlanguageLinkPrefixes;
2114
2115 static $tc = false, $e1, $e1_img;
2116 # the % is needed to support urlencoded titles as well
2117 if ( !$tc ) {
2118 $tc = Title::legalChars() . '#%';
2119 # Match a link having the form [[namespace:link|alternate]]trail
2120 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2121 # Match cases where there is no "]]", which might still be images
2122 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2123 }
2124
2125 $holders = new LinkHolderArray( $this );
2126
2127 # split the entire text string on occurrences of [[
2128 $a = StringUtils::explode( '[[', ' ' . $s );
2129 # get the first element (all text up to first [[), and remove the space we added
2130 $s = $a->current();
2131 $a->next();
2132 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2133 $s = substr( $s, 1 );
2134
2135 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2136 $e2 = null;
2137 if ( $useLinkPrefixExtension ) {
2138 # Match the end of a line for a word that's not followed by whitespace,
2139 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2140 global $wgContLang;
2141 $charset = $wgContLang->linkPrefixCharset();
2142 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2143 }
2144
2145 if ( is_null( $this->mTitle ) ) {
2146 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2147 }
2148 $nottalk = !$this->mTitle->isTalkPage();
2149
2150 if ( $useLinkPrefixExtension ) {
2151 $m = [];
2152 if ( preg_match( $e2, $s, $m ) ) {
2153 $first_prefix = $m[2];
2154 } else {
2155 $first_prefix = false;
2156 }
2157 } else {
2158 $prefix = '';
2159 }
2160
2161 $useSubpages = $this->areSubpagesAllowed();
2162
2163 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2164 # Loop for each link
2165 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2166 // @codingStandardsIgnoreEnd
2167
2168 # Check for excessive memory usage
2169 if ( $holders->isBig() ) {
2170 # Too big
2171 # Do the existence check, replace the link holders and clear the array
2172 $holders->replace( $s );
2173 $holders->clear();
2174 }
2175
2176 if ( $useLinkPrefixExtension ) {
2177 if ( preg_match( $e2, $s, $m ) ) {
2178 $prefix = $m[2];
2179 $s = $m[1];
2180 } else {
2181 $prefix = '';
2182 }
2183 # first link
2184 if ( $first_prefix ) {
2185 $prefix = $first_prefix;
2186 $first_prefix = false;
2187 }
2188 }
2189
2190 $might_be_img = false;
2191
2192 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2193 $text = $m[2];
2194 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2195 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2196 # the real problem is with the $e1 regex
2197 # See T1500.
2198 # Still some problems for cases where the ] is meant to be outside punctuation,
2199 # and no image is in sight. See T4095.
2200 if ( $text !== ''
2201 && substr( $m[3], 0, 1 ) === ']'
2202 && strpos( $text, '[' ) !== false
2203 ) {
2204 $text .= ']'; # so that replaceExternalLinks($text) works later
2205 $m[3] = substr( $m[3], 1 );
2206 }
2207 # fix up urlencoded title texts
2208 if ( strpos( $m[1], '%' ) !== false ) {
2209 # Should anchors '#' also be rejected?
2210 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2211 }
2212 $trail = $m[3];
2213 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2214 # Invalid, but might be an image with a link in its caption
2215 $might_be_img = true;
2216 $text = $m[2];
2217 if ( strpos( $m[1], '%' ) !== false ) {
2218 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2219 }
2220 $trail = "";
2221 } else { # Invalid form; output directly
2222 $s .= $prefix . '[[' . $line;
2223 continue;
2224 }
2225
2226 $origLink = ltrim( $m[1], ' ' );
2227
2228 # Don't allow internal links to pages containing
2229 # PROTO: where PROTO is a valid URL protocol; these
2230 # should be external links.
2231 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2232 $s .= $prefix . '[[' . $line;
2233 continue;
2234 }
2235
2236 # Make subpage if necessary
2237 if ( $useSubpages ) {
2238 $link = $this->maybeDoSubpageLink( $origLink, $text );
2239 } else {
2240 $link = $origLink;
2241 }
2242
2243 $unstrip = $this->mStripState->unstripNoWiki( $link );
2244 $nt = is_string( $unstrip ) ? Title::newFromText( $unstrip ) : null;
2245 if ( $nt === null ) {
2246 $s .= $prefix . '[[' . $line;
2247 continue;
2248 }
2249
2250 $ns = $nt->getNamespace();
2251 $iw = $nt->getInterwiki();
2252
2253 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2254
2255 if ( $might_be_img ) { # if this is actually an invalid link
2256 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2257 $found = false;
2258 while ( true ) {
2259 # look at the next 'line' to see if we can close it there
2260 $a->next();
2261 $next_line = $a->current();
2262 if ( $next_line === false || $next_line === null ) {
2263 break;
2264 }
2265 $m = explode( ']]', $next_line, 3 );
2266 if ( count( $m ) == 3 ) {
2267 # the first ]] closes the inner link, the second the image
2268 $found = true;
2269 $text .= "[[{$m[0]}]]{$m[1]}";
2270 $trail = $m[2];
2271 break;
2272 } elseif ( count( $m ) == 2 ) {
2273 # if there's exactly one ]] that's fine, we'll keep looking
2274 $text .= "[[{$m[0]}]]{$m[1]}";
2275 } else {
2276 # if $next_line is invalid too, we need look no further
2277 $text .= '[[' . $next_line;
2278 break;
2279 }
2280 }
2281 if ( !$found ) {
2282 # we couldn't find the end of this imageLink, so output it raw
2283 # but don't ignore what might be perfectly normal links in the text we've examined
2284 $holders->merge( $this->replaceInternalLinks2( $text ) );
2285 $s .= "{$prefix}[[$link|$text";
2286 # note: no $trail, because without an end, there *is* no trail
2287 continue;
2288 }
2289 } else { # it's not an image, so output it raw
2290 $s .= "{$prefix}[[$link|$text";
2291 # note: no $trail, because without an end, there *is* no trail
2292 continue;
2293 }
2294 }
2295
2296 $wasblank = ( $text == '' );
2297 if ( $wasblank ) {
2298 $text = $link;
2299 if ( !$noforce ) {
2300 # Strip off leading ':'
2301 $text = substr( $text, 1 );
2302 }
2303 } else {
2304 # T6598 madness. Handle the quotes only if they come from the alternate part
2305 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2306 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2307 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2308 $text = $this->doQuotes( $text );
2309 }
2310
2311 # Link not escaped by : , create the various objects
2312 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2313 # Interwikis
2314 if (
2315 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2316 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2317 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2318 )
2319 ) {
2320 # T26502: filter duplicates
2321 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2322 $this->mLangLinkLanguages[$iw] = true;
2323 $this->mOutput->addLanguageLink( $nt->getFullText() );
2324 }
2325
2326 /**
2327 * Strip the whitespace interwiki links produce, see T10897
2328 */
2329 $s = rtrim( $s . $prefix );
2330 $s .= rtrim( $trail, "\n" );
2331 continue;
2332 }
2333
2334 if ( $ns == NS_FILE ) {
2335 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2336 if ( $wasblank ) {
2337 # if no parameters were passed, $text
2338 # becomes something like "File:Foo.png",
2339 # which we don't want to pass on to the
2340 # image generator
2341 $text = '';
2342 } else {
2343 # recursively parse links inside the image caption
2344 # actually, this will parse them in any other parameters, too,
2345 # but it might be hard to fix that, and it doesn't matter ATM
2346 $text = $this->replaceExternalLinks( $text );
2347 $holders->merge( $this->replaceInternalLinks2( $text ) );
2348 }
2349 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2350 $s .= $prefix . $this->armorLinks(
2351 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2352 continue;
2353 }
2354 } elseif ( $ns == NS_CATEGORY ) {
2355 /**
2356 * Strip the whitespace Category links produce, see T2087
2357 */
2358 $s = rtrim( $s . $prefix ); # T2087, T87753
2359 $s .= rtrim( $trail, "\n" );
2360
2361 if ( $wasblank ) {
2362 $sortkey = $this->getDefaultSort();
2363 } else {
2364 $sortkey = $text;
2365 }
2366 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2367 $sortkey = str_replace( "\n", '', $sortkey );
2368 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2369 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2370
2371 continue;
2372 }
2373 }
2374
2375 # Self-link checking. For some languages, variants of the title are checked in
2376 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2377 # for linking to a different variant.
2378 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2379 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2380 continue;
2381 }
2382
2383 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2384 # @todo FIXME: Should do batch file existence checks, see comment below
2385 if ( $ns == NS_MEDIA ) {
2386 # Give extensions a chance to select the file revision for us
2387 $options = [];
2388 $descQuery = false;
2389 Hooks::run( 'BeforeParserFetchFileAndTitle',
2390 [ $this, $nt, &$options, &$descQuery ] );
2391 # Fetch and register the file (file title may be different via hooks)
2392 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2393 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2394 $s .= $prefix . $this->armorLinks(
2395 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2396 continue;
2397 }
2398
2399 # Some titles, such as valid special pages or files in foreign repos, should
2400 # be shown as bluelinks even though they're not included in the page table
2401 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2402 # batch file existence checks for NS_FILE and NS_MEDIA
2403 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2404 $this->mOutput->addLink( $nt );
2405 $s .= $this->makeKnownLinkHolder( $nt, $text, $trail, $prefix );
2406 } else {
2407 # Links will be added to the output link list after checking
2408 $s .= $holders->makeHolder( $nt, $text, [], $trail, $prefix );
2409 }
2410 }
2411 return $holders;
2412 }
2413
2414 /**
2415 * Render a forced-blue link inline; protect against double expansion of
2416 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2417 * Since this little disaster has to split off the trail text to avoid
2418 * breaking URLs in the following text without breaking trails on the
2419 * wiki links, it's been made into a horrible function.
2420 *
2421 * @param Title $nt
2422 * @param string $text
2423 * @param string $trail
2424 * @param string $prefix
2425 * @return string HTML-wikitext mix oh yuck
2426 */
2427 protected function makeKnownLinkHolder( $nt, $text = '', $trail = '', $prefix = '' ) {
2428 list( $inside, $trail ) = Linker::splitTrail( $trail );
2429
2430 if ( $text == '' ) {
2431 $text = htmlspecialchars( $nt->getPrefixedText() );
2432 }
2433
2434 $link = $this->getLinkRenderer()->makeKnownLink(
2435 $nt, new HtmlArmor( "$prefix$text$inside" )
2436 );
2437
2438 return $this->armorLinks( $link ) . $trail;
2439 }
2440
2441 /**
2442 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2443 * going to go through further parsing steps before inline URL expansion.
2444 *
2445 * Not needed quite as much as it used to be since free links are a bit
2446 * more sensible these days. But bracketed links are still an issue.
2447 *
2448 * @param string $text More-or-less HTML
2449 * @return string Less-or-more HTML with NOPARSE bits
2450 */
2451 public function armorLinks( $text ) {
2452 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2453 self::MARKER_PREFIX . "NOPARSE$1", $text );
2454 }
2455
2456 /**
2457 * Return true if subpage links should be expanded on this page.
2458 * @return bool
2459 */
2460 public function areSubpagesAllowed() {
2461 # Some namespaces don't allow subpages
2462 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2463 }
2464
2465 /**
2466 * Handle link to subpage if necessary
2467 *
2468 * @param string $target The source of the link
2469 * @param string &$text The link text, modified as necessary
2470 * @return string The full name of the link
2471 * @private
2472 */
2473 public function maybeDoSubpageLink( $target, &$text ) {
2474 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2475 }
2476
2477 /**
2478 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2479 *
2480 * @param string $text
2481 * @param bool $linestart Whether or not this is at the start of a line.
2482 * @private
2483 * @return string The lists rendered as HTML
2484 */
2485 public function doBlockLevels( $text, $linestart ) {
2486 return BlockLevelPass::doBlockLevels( $text, $linestart );
2487 }
2488
2489 /**
2490 * Return value of a magic variable (like PAGENAME)
2491 *
2492 * @private
2493 *
2494 * @param string $index Magic variable identifier as mapped in MagicWord::$mVariableIDs
2495 * @param bool|PPFrame $frame
2496 *
2497 * @throws MWException
2498 * @return string
2499 */
2500 public function getVariableValue( $index, $frame = false ) {
2501 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2502 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2503
2504 if ( is_null( $this->mTitle ) ) {
2505 // If no title set, bad things are going to happen
2506 // later. Title should always be set since this
2507 // should only be called in the middle of a parse
2508 // operation (but the unit-tests do funky stuff)
2509 throw new MWException( __METHOD__ . ' Should only be '
2510 . ' called while parsing (no title set)' );
2511 }
2512
2513 // Avoid PHP 7.1 warning from passing $this by reference
2514 $parser = $this;
2515
2516 /**
2517 * Some of these require message or data lookups and can be
2518 * expensive to check many times.
2519 */
2520 if ( Hooks::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache ] ) ) {
2521 if ( isset( $this->mVarCache[$index] ) ) {
2522 return $this->mVarCache[$index];
2523 }
2524 }
2525
2526 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2527 Hooks::run( 'ParserGetVariableValueTs', [ &$parser, &$ts ] );
2528
2529 $pageLang = $this->getFunctionLang();
2530
2531 switch ( $index ) {
2532 case '!':
2533 $value = '|';
2534 break;
2535 case 'currentmonth':
2536 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
2537 break;
2538 case 'currentmonth1':
2539 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2540 break;
2541 case 'currentmonthname':
2542 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2543 break;
2544 case 'currentmonthnamegen':
2545 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2546 break;
2547 case 'currentmonthabbrev':
2548 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2549 break;
2550 case 'currentday':
2551 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
2552 break;
2553 case 'currentday2':
2554 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
2555 break;
2556 case 'localmonth':
2557 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
2558 break;
2559 case 'localmonth1':
2560 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2561 break;
2562 case 'localmonthname':
2563 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2564 break;
2565 case 'localmonthnamegen':
2566 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2567 break;
2568 case 'localmonthabbrev':
2569 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2570 break;
2571 case 'localday':
2572 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
2573 break;
2574 case 'localday2':
2575 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
2576 break;
2577 case 'pagename':
2578 $value = wfEscapeWikiText( $this->mTitle->getText() );
2579 break;
2580 case 'pagenamee':
2581 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2582 break;
2583 case 'fullpagename':
2584 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2585 break;
2586 case 'fullpagenamee':
2587 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2588 break;
2589 case 'subpagename':
2590 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2591 break;
2592 case 'subpagenamee':
2593 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2594 break;
2595 case 'rootpagename':
2596 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2597 break;
2598 case 'rootpagenamee':
2599 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2600 ' ',
2601 '_',
2602 $this->mTitle->getRootText()
2603 ) ) );
2604 break;
2605 case 'basepagename':
2606 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2607 break;
2608 case 'basepagenamee':
2609 $value = wfEscapeWikiText( wfUrlencode( str_replace(
2610 ' ',
2611 '_',
2612 $this->mTitle->getBaseText()
2613 ) ) );
2614 break;
2615 case 'talkpagename':
2616 if ( $this->mTitle->canTalk() ) {
2617 $talkPage = $this->mTitle->getTalkPage();
2618 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2619 } else {
2620 $value = '';
2621 }
2622 break;
2623 case 'talkpagenamee':
2624 if ( $this->mTitle->canTalk() ) {
2625 $talkPage = $this->mTitle->getTalkPage();
2626 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2627 } else {
2628 $value = '';
2629 }
2630 break;
2631 case 'subjectpagename':
2632 $subjPage = $this->mTitle->getSubjectPage();
2633 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2634 break;
2635 case 'subjectpagenamee':
2636 $subjPage = $this->mTitle->getSubjectPage();
2637 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2638 break;
2639 case 'pageid': // requested in T25427
2640 $pageid = $this->getTitle()->getArticleID();
2641 if ( $pageid == 0 ) {
2642 # 0 means the page doesn't exist in the database,
2643 # which means the user is previewing a new page.
2644 # The vary-revision flag must be set, because the magic word
2645 # will have a different value once the page is saved.
2646 $this->mOutput->setFlag( 'vary-revision' );
2647 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2648 }
2649 $value = $pageid ? $pageid : null;
2650 break;
2651 case 'revisionid':
2652 # Let the edit saving system know we should parse the page
2653 # *after* a revision ID has been assigned.
2654 $this->mOutput->setFlag( 'vary-revision-id' );
2655 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision-id...\n" );
2656 $value = $this->mRevisionId;
2657 if ( !$value && $this->mOptions->getSpeculativeRevIdCallback() ) {
2658 $value = call_user_func( $this->mOptions->getSpeculativeRevIdCallback() );
2659 $this->mOutput->setSpeculativeRevIdUsed( $value );
2660 }
2661 break;
2662 case 'revisionday':
2663 # Let the edit saving system know we should parse the page
2664 # *after* a revision ID has been assigned. This is for null edits.
2665 $this->mOutput->setFlag( 'vary-revision' );
2666 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2667 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2668 break;
2669 case 'revisionday2':
2670 # Let the edit saving system know we should parse the page
2671 # *after* a revision ID has been assigned. This is for null edits.
2672 $this->mOutput->setFlag( 'vary-revision' );
2673 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2674 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2675 break;
2676 case 'revisionmonth':
2677 # Let the edit saving system know we should parse the page
2678 # *after* a revision ID has been assigned. This is for null edits.
2679 $this->mOutput->setFlag( 'vary-revision' );
2680 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2681 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2682 break;
2683 case 'revisionmonth1':
2684 # Let the edit saving system know we should parse the page
2685 # *after* a revision ID has been assigned. This is for null edits.
2686 $this->mOutput->setFlag( 'vary-revision' );
2687 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2688 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2689 break;
2690 case 'revisionyear':
2691 # Let the edit saving system know we should parse the page
2692 # *after* a revision ID has been assigned. This is for null edits.
2693 $this->mOutput->setFlag( 'vary-revision' );
2694 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2695 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2696 break;
2697 case 'revisiontimestamp':
2698 # Let the edit saving system know we should parse the page
2699 # *after* a revision ID has been assigned. This is for null edits.
2700 $this->mOutput->setFlag( 'vary-revision' );
2701 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2702 $value = $this->getRevisionTimestamp();
2703 break;
2704 case 'revisionuser':
2705 # Let the edit saving system know we should parse the page
2706 # *after* a revision ID has been assigned for null edits.
2707 $this->mOutput->setFlag( 'vary-user' );
2708 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-user...\n" );
2709 $value = $this->getRevisionUser();
2710 break;
2711 case 'revisionsize':
2712 $value = $this->getRevisionSize();
2713 break;
2714 case 'namespace':
2715 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2716 break;
2717 case 'namespacee':
2718 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2719 break;
2720 case 'namespacenumber':
2721 $value = $this->mTitle->getNamespace();
2722 break;
2723 case 'talkspace':
2724 $value = $this->mTitle->canTalk()
2725 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
2726 : '';
2727 break;
2728 case 'talkspacee':
2729 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2730 break;
2731 case 'subjectspace':
2732 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
2733 break;
2734 case 'subjectspacee':
2735 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2736 break;
2737 case 'currentdayname':
2738 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
2739 break;
2740 case 'currentyear':
2741 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
2742 break;
2743 case 'currenttime':
2744 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2745 break;
2746 case 'currenthour':
2747 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
2748 break;
2749 case 'currentweek':
2750 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2751 # int to remove the padding
2752 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
2753 break;
2754 case 'currentdow':
2755 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
2756 break;
2757 case 'localdayname':
2758 $value = $pageLang->getWeekdayName(
2759 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
2760 );
2761 break;
2762 case 'localyear':
2763 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
2764 break;
2765 case 'localtime':
2766 $value = $pageLang->time(
2767 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
2768 false,
2769 false
2770 );
2771 break;
2772 case 'localhour':
2773 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
2774 break;
2775 case 'localweek':
2776 # @bug T6594 PHP5 has it zero padded, PHP4 does not, cast to
2777 # int to remove the padding
2778 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
2779 break;
2780 case 'localdow':
2781 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
2782 break;
2783 case 'numberofarticles':
2784 $value = $pageLang->formatNum( SiteStats::articles() );
2785 break;
2786 case 'numberoffiles':
2787 $value = $pageLang->formatNum( SiteStats::images() );
2788 break;
2789 case 'numberofusers':
2790 $value = $pageLang->formatNum( SiteStats::users() );
2791 break;
2792 case 'numberofactiveusers':
2793 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2794 break;
2795 case 'numberofpages':
2796 $value = $pageLang->formatNum( SiteStats::pages() );
2797 break;
2798 case 'numberofadmins':
2799 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2800 break;
2801 case 'numberofedits':
2802 $value = $pageLang->formatNum( SiteStats::edits() );
2803 break;
2804 case 'currenttimestamp':
2805 $value = wfTimestamp( TS_MW, $ts );
2806 break;
2807 case 'localtimestamp':
2808 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
2809 break;
2810 case 'currentversion':
2811 $value = SpecialVersion::getVersion();
2812 break;
2813 case 'articlepath':
2814 return $wgArticlePath;
2815 case 'sitename':
2816 return $wgSitename;
2817 case 'server':
2818 return $wgServer;
2819 case 'servername':
2820 return $wgServerName;
2821 case 'scriptpath':
2822 return $wgScriptPath;
2823 case 'stylepath':
2824 return $wgStylePath;
2825 case 'directionmark':
2826 return $pageLang->getDirMark();
2827 case 'contentlanguage':
2828 global $wgLanguageCode;
2829 return $wgLanguageCode;
2830 case 'pagelanguage':
2831 $value = $pageLang->getCode();
2832 break;
2833 case 'cascadingsources':
2834 $value = CoreParserFunctions::cascadingsources( $this );
2835 break;
2836 default:
2837 $ret = null;
2838 Hooks::run(
2839 'ParserGetVariableValueSwitch',
2840 [ &$parser, &$this->mVarCache, &$index, &$ret, &$frame ]
2841 );
2842
2843 return $ret;
2844 }
2845
2846 if ( $index ) {
2847 $this->mVarCache[$index] = $value;
2848 }
2849
2850 return $value;
2851 }
2852
2853 /**
2854 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2855 *
2856 * @private
2857 */
2858 public function initialiseVariables() {
2859 $variableIDs = MagicWord::getVariableIDs();
2860 $substIDs = MagicWord::getSubstIDs();
2861
2862 $this->mVariables = new MagicWordArray( $variableIDs );
2863 $this->mSubstWords = new MagicWordArray( $substIDs );
2864 }
2865
2866 /**
2867 * Preprocess some wikitext and return the document tree.
2868 * This is the ghost of replace_variables().
2869 *
2870 * @param string $text The text to parse
2871 * @param int $flags Bitwise combination of:
2872 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2873 * included. Default is to assume a direct page view.
2874 *
2875 * The generated DOM tree must depend only on the input text and the flags.
2876 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2877 *
2878 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2879 * change in the DOM tree for a given text, must be passed through the section identifier
2880 * in the section edit link and thus back to extractSections().
2881 *
2882 * The output of this function is currently only cached in process memory, but a persistent
2883 * cache may be implemented at a later date which takes further advantage of these strict
2884 * dependency requirements.
2885 *
2886 * @return PPNode
2887 */
2888 public function preprocessToDom( $text, $flags = 0 ) {
2889 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2890 return $dom;
2891 }
2892
2893 /**
2894 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2895 *
2896 * @param string $s
2897 *
2898 * @return array
2899 */
2900 public static function splitWhitespace( $s ) {
2901 $ltrimmed = ltrim( $s );
2902 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2903 $trimmed = rtrim( $ltrimmed );
2904 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2905 if ( $diff > 0 ) {
2906 $w2 = substr( $ltrimmed, -$diff );
2907 } else {
2908 $w2 = '';
2909 }
2910 return [ $w1, $trimmed, $w2 ];
2911 }
2912
2913 /**
2914 * Replace magic variables, templates, and template arguments
2915 * with the appropriate text. Templates are substituted recursively,
2916 * taking care to avoid infinite loops.
2917 *
2918 * Note that the substitution depends on value of $mOutputType:
2919 * self::OT_WIKI: only {{subst:}} templates
2920 * self::OT_PREPROCESS: templates but not extension tags
2921 * self::OT_HTML: all templates and extension tags
2922 *
2923 * @param string $text The text to transform
2924 * @param bool|PPFrame $frame Object describing the arguments passed to the
2925 * template. Arguments may also be provided as an associative array, as
2926 * was the usual case before MW1.12. Providing arguments this way may be
2927 * useful for extensions wishing to perform variable replacement
2928 * explicitly.
2929 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2930 * double-brace expansion.
2931 * @return string
2932 */
2933 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2934 # Is there any text? Also, Prevent too big inclusions!
2935 $textSize = strlen( $text );
2936 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
2937 return $text;
2938 }
2939
2940 if ( $frame === false ) {
2941 $frame = $this->getPreprocessor()->newFrame();
2942 } elseif ( !( $frame instanceof PPFrame ) ) {
2943 wfDebug( __METHOD__ . " called using plain parameters instead of "
2944 . "a PPFrame instance. Creating custom frame.\n" );
2945 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2946 }
2947
2948 $dom = $this->preprocessToDom( $text );
2949 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2950 $text = $frame->expand( $dom, $flags );
2951
2952 return $text;
2953 }
2954
2955 /**
2956 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2957 *
2958 * @param array $args
2959 *
2960 * @return array
2961 */
2962 public static function createAssocArgs( $args ) {
2963 $assocArgs = [];
2964 $index = 1;
2965 foreach ( $args as $arg ) {
2966 $eqpos = strpos( $arg, '=' );
2967 if ( $eqpos === false ) {
2968 $assocArgs[$index++] = $arg;
2969 } else {
2970 $name = trim( substr( $arg, 0, $eqpos ) );
2971 $value = trim( substr( $arg, $eqpos + 1 ) );
2972 if ( $value === false ) {
2973 $value = '';
2974 }
2975 if ( $name !== false ) {
2976 $assocArgs[$name] = $value;
2977 }
2978 }
2979 }
2980
2981 return $assocArgs;
2982 }
2983
2984 /**
2985 * Warn the user when a parser limitation is reached
2986 * Will warn at most once the user per limitation type
2987 *
2988 * The results are shown during preview and run through the Parser (See EditPage.php)
2989 *
2990 * @param string $limitationType Should be one of:
2991 * 'expensive-parserfunction' (corresponding messages:
2992 * 'expensive-parserfunction-warning',
2993 * 'expensive-parserfunction-category')
2994 * 'post-expand-template-argument' (corresponding messages:
2995 * 'post-expand-template-argument-warning',
2996 * 'post-expand-template-argument-category')
2997 * 'post-expand-template-inclusion' (corresponding messages:
2998 * 'post-expand-template-inclusion-warning',
2999 * 'post-expand-template-inclusion-category')
3000 * 'node-count-exceeded' (corresponding messages:
3001 * 'node-count-exceeded-warning',
3002 * 'node-count-exceeded-category')
3003 * 'expansion-depth-exceeded' (corresponding messages:
3004 * 'expansion-depth-exceeded-warning',
3005 * 'expansion-depth-exceeded-category')
3006 * @param string|int|null $current Current value
3007 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3008 * exceeded, provide the values (optional)
3009 */
3010 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3011 # does no harm if $current and $max are present but are unnecessary for the message
3012 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3013 # only during preview, and that would split the parser cache unnecessarily.
3014 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3015 ->text();
3016 $this->mOutput->addWarning( $warning );
3017 $this->addTrackingCategory( "$limitationType-category" );
3018 }
3019
3020 /**
3021 * Return the text of a template, after recursively
3022 * replacing any variables or templates within the template.
3023 *
3024 * @param array $piece The parts of the template
3025 * $piece['title']: the title, i.e. the part before the |
3026 * $piece['parts']: the parameter array
3027 * $piece['lineStart']: whether the brace was at the start of a line
3028 * @param PPFrame $frame The current frame, contains template arguments
3029 * @throws Exception
3030 * @return string The text of the template
3031 */
3032 public function braceSubstitution( $piece, $frame ) {
3033 // Flags
3034
3035 // $text has been filled
3036 $found = false;
3037 // wiki markup in $text should be escaped
3038 $nowiki = false;
3039 // $text is HTML, armour it against wikitext transformation
3040 $isHTML = false;
3041 // Force interwiki transclusion to be done in raw mode not rendered
3042 $forceRawInterwiki = false;
3043 // $text is a DOM node needing expansion in a child frame
3044 $isChildObj = false;
3045 // $text is a DOM node needing expansion in the current frame
3046 $isLocalObj = false;
3047
3048 # Title object, where $text came from
3049 $title = false;
3050
3051 # $part1 is the bit before the first |, and must contain only title characters.
3052 # Various prefixes will be stripped from it later.
3053 $titleWithSpaces = $frame->expand( $piece['title'] );
3054 $part1 = trim( $titleWithSpaces );
3055 $titleText = false;
3056
3057 # Original title text preserved for various purposes
3058 $originalTitle = $part1;
3059
3060 # $args is a list of argument nodes, starting from index 0, not including $part1
3061 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3062 # below won't work b/c this $args isn't an object
3063 $args = ( null == $piece['parts'] ) ? [] : $piece['parts'];
3064
3065 $profileSection = null; // profile templates
3066
3067 # SUBST
3068 if ( !$found ) {
3069 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3070
3071 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3072 # Decide whether to expand template or keep wikitext as-is.
3073 if ( $this->ot['wiki'] ) {
3074 if ( $substMatch === false ) {
3075 $literal = true; # literal when in PST with no prefix
3076 } else {
3077 $literal = false; # expand when in PST with subst: or safesubst:
3078 }
3079 } else {
3080 if ( $substMatch == 'subst' ) {
3081 $literal = true; # literal when not in PST with plain subst:
3082 } else {
3083 $literal = false; # expand when not in PST with safesubst: or no prefix
3084 }
3085 }
3086 if ( $literal ) {
3087 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3088 $isLocalObj = true;
3089 $found = true;
3090 }
3091 }
3092
3093 # Variables
3094 if ( !$found && $args->getLength() == 0 ) {
3095 $id = $this->mVariables->matchStartToEnd( $part1 );
3096 if ( $id !== false ) {
3097 $text = $this->getVariableValue( $id, $frame );
3098 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3099 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3100 }
3101 $found = true;
3102 }
3103 }
3104
3105 # MSG, MSGNW and RAW
3106 if ( !$found ) {
3107 # Check for MSGNW:
3108 $mwMsgnw = MagicWord::get( 'msgnw' );
3109 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3110 $nowiki = true;
3111 } else {
3112 # Remove obsolete MSG:
3113 $mwMsg = MagicWord::get( 'msg' );
3114 $mwMsg->matchStartAndRemove( $part1 );
3115 }
3116
3117 # Check for RAW:
3118 $mwRaw = MagicWord::get( 'raw' );
3119 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3120 $forceRawInterwiki = true;
3121 }
3122 }
3123
3124 # Parser functions
3125 if ( !$found ) {
3126 $colonPos = strpos( $part1, ':' );
3127 if ( $colonPos !== false ) {
3128 $func = substr( $part1, 0, $colonPos );
3129 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3130 $argsLength = $args->getLength();
3131 for ( $i = 0; $i < $argsLength; $i++ ) {
3132 $funcArgs[] = $args->item( $i );
3133 }
3134 try {
3135 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3136 } catch ( Exception $ex ) {
3137 throw $ex;
3138 }
3139
3140 # The interface for parser functions allows for extracting
3141 # flags into the local scope. Extract any forwarded flags
3142 # here.
3143 extract( $result );
3144 }
3145 }
3146
3147 # Finish mangling title and then check for loops.
3148 # Set $title to a Title object and $titleText to the PDBK
3149 if ( !$found ) {
3150 $ns = NS_TEMPLATE;
3151 # Split the title into page and subpage
3152 $subpage = '';
3153 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3154 if ( $part1 !== $relative ) {
3155 $part1 = $relative;
3156 $ns = $this->mTitle->getNamespace();
3157 }
3158 $title = Title::newFromText( $part1, $ns );
3159 if ( $title ) {
3160 $titleText = $title->getPrefixedText();
3161 # Check for language variants if the template is not found
3162 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3163 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3164 }
3165 # Do recursion depth check
3166 $limit = $this->mOptions->getMaxTemplateDepth();
3167 if ( $frame->depth >= $limit ) {
3168 $found = true;
3169 $text = '<span class="error">'
3170 . wfMessage( 'parser-template-recursion-depth-warning' )
3171 ->numParams( $limit )->inContentLanguage()->text()
3172 . '</span>';
3173 }
3174 }
3175 }
3176
3177 # Load from database
3178 if ( !$found && $title ) {
3179 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3180 if ( !$title->isExternal() ) {
3181 if ( $title->isSpecialPage()
3182 && $this->mOptions->getAllowSpecialInclusion()
3183 && $this->ot['html']
3184 ) {
3185 $specialPage = SpecialPageFactory::getPage( $title->getDBkey() );
3186 // Pass the template arguments as URL parameters.
3187 // "uselang" will have no effect since the Language object
3188 // is forced to the one defined in ParserOptions.
3189 $pageArgs = [];
3190 $argsLength = $args->getLength();
3191 for ( $i = 0; $i < $argsLength; $i++ ) {
3192 $bits = $args->item( $i )->splitArg();
3193 if ( strval( $bits['index'] ) === '' ) {
3194 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3195 $value = trim( $frame->expand( $bits['value'] ) );
3196 $pageArgs[$name] = $value;
3197 }
3198 }
3199
3200 // Create a new context to execute the special page
3201 $context = new RequestContext;
3202 $context->setTitle( $title );
3203 $context->setRequest( new FauxRequest( $pageArgs ) );
3204 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3205 $context->setUser( $this->getUser() );
3206 } else {
3207 // If this page is cached, then we better not be per user.
3208 $context->setUser( User::newFromName( '127.0.0.1', false ) );
3209 }
3210 $context->setLanguage( $this->mOptions->getUserLangObj() );
3211 $ret = SpecialPageFactory::capturePath(
3212 $title, $context, $this->getLinkRenderer() );
3213 if ( $ret ) {
3214 $text = $context->getOutput()->getHTML();
3215 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3216 $found = true;
3217 $isHTML = true;
3218 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3219 $this->mOutput->updateRuntimeAdaptiveExpiry(
3220 $specialPage->maxIncludeCacheTime()
3221 );
3222 }
3223 }
3224 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3225 $found = false; # access denied
3226 wfDebug( __METHOD__ . ": template inclusion denied for " .
3227 $title->getPrefixedDBkey() . "\n" );
3228 } else {
3229 list( $text, $title ) = $this->getTemplateDom( $title );
3230 if ( $text !== false ) {
3231 $found = true;
3232 $isChildObj = true;
3233 }
3234 }
3235
3236 # If the title is valid but undisplayable, make a link to it
3237 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3238 $text = "[[:$titleText]]";
3239 $found = true;
3240 }
3241 } elseif ( $title->isTrans() ) {
3242 # Interwiki transclusion
3243 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3244 $text = $this->interwikiTransclude( $title, 'render' );
3245 $isHTML = true;
3246 } else {
3247 $text = $this->interwikiTransclude( $title, 'raw' );
3248 # Preprocess it like a template
3249 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3250 $isChildObj = true;
3251 }
3252 $found = true;
3253 }
3254
3255 # Do infinite loop check
3256 # This has to be done after redirect resolution to avoid infinite loops via redirects
3257 if ( !$frame->loopCheck( $title ) ) {
3258 $found = true;
3259 $text = '<span class="error">'
3260 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3261 . '</span>';
3262 $this->addTrackingCategory( 'template-loop-category' );
3263 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3264 }
3265 }
3266
3267 # If we haven't found text to substitute by now, we're done
3268 # Recover the source wikitext and return it
3269 if ( !$found ) {
3270 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3271 if ( $profileSection ) {
3272 $this->mProfiler->scopedProfileOut( $profileSection );
3273 }
3274 return [ 'object' => $text ];
3275 }
3276
3277 # Expand DOM-style return values in a child frame
3278 if ( $isChildObj ) {
3279 # Clean up argument array
3280 $newFrame = $frame->newChild( $args, $title );
3281
3282 if ( $nowiki ) {
3283 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3284 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3285 # Expansion is eligible for the empty-frame cache
3286 $text = $newFrame->cachedExpand( $titleText, $text );
3287 } else {
3288 # Uncached expansion
3289 $text = $newFrame->expand( $text );
3290 }
3291 }
3292 if ( $isLocalObj && $nowiki ) {
3293 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3294 $isLocalObj = false;
3295 }
3296
3297 if ( $profileSection ) {
3298 $this->mProfiler->scopedProfileOut( $profileSection );
3299 }
3300
3301 # Replace raw HTML by a placeholder
3302 if ( $isHTML ) {
3303 $text = $this->insertStripItem( $text );
3304 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3305 # Escape nowiki-style return values
3306 $text = wfEscapeWikiText( $text );
3307 } elseif ( is_string( $text )
3308 && !$piece['lineStart']
3309 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3310 ) {
3311 # T2529: if the template begins with a table or block-level
3312 # element, it should be treated as beginning a new line.
3313 # This behavior is somewhat controversial.
3314 $text = "\n" . $text;
3315 }
3316
3317 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3318 # Error, oversize inclusion
3319 if ( $titleText !== false ) {
3320 # Make a working, properly escaped link if possible (T25588)
3321 $text = "[[:$titleText]]";
3322 } else {
3323 # This will probably not be a working link, but at least it may
3324 # provide some hint of where the problem is
3325 preg_replace( '/^:/', '', $originalTitle );
3326 $text = "[[:$originalTitle]]";
3327 }
3328 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3329 . 'post-expand include size too large -->' );
3330 $this->limitationWarn( 'post-expand-template-inclusion' );
3331 }
3332
3333 if ( $isLocalObj ) {
3334 $ret = [ 'object' => $text ];
3335 } else {
3336 $ret = [ 'text' => $text ];
3337 }
3338
3339 return $ret;
3340 }
3341
3342 /**
3343 * Call a parser function and return an array with text and flags.
3344 *
3345 * The returned array will always contain a boolean 'found', indicating
3346 * whether the parser function was found or not. It may also contain the
3347 * following:
3348 * text: string|object, resulting wikitext or PP DOM object
3349 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3350 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3351 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3352 * nowiki: bool, wiki markup in $text should be escaped
3353 *
3354 * @since 1.21
3355 * @param PPFrame $frame The current frame, contains template arguments
3356 * @param string $function Function name
3357 * @param array $args Arguments to the function
3358 * @throws MWException
3359 * @return array
3360 */
3361 public function callParserFunction( $frame, $function, array $args = [] ) {
3362 global $wgContLang;
3363
3364 # Case sensitive functions
3365 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3366 $function = $this->mFunctionSynonyms[1][$function];
3367 } else {
3368 # Case insensitive functions
3369 $function = $wgContLang->lc( $function );
3370 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3371 $function = $this->mFunctionSynonyms[0][$function];
3372 } else {
3373 return [ 'found' => false ];
3374 }
3375 }
3376
3377 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3378
3379 // Avoid PHP 7.1 warning from passing $this by reference
3380 $parser = $this;
3381
3382 $allArgs = [ &$parser ];
3383 if ( $flags & self::SFH_OBJECT_ARGS ) {
3384 # Convert arguments to PPNodes and collect for appending to $allArgs
3385 $funcArgs = [];
3386 foreach ( $args as $k => $v ) {
3387 if ( $v instanceof PPNode || $k === 0 ) {
3388 $funcArgs[] = $v;
3389 } else {
3390 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3391 }
3392 }
3393
3394 # Add a frame parameter, and pass the arguments as an array
3395 $allArgs[] = $frame;
3396 $allArgs[] = $funcArgs;
3397 } else {
3398 # Convert arguments to plain text and append to $allArgs
3399 foreach ( $args as $k => $v ) {
3400 if ( $v instanceof PPNode ) {
3401 $allArgs[] = trim( $frame->expand( $v ) );
3402 } elseif ( is_int( $k ) && $k >= 0 ) {
3403 $allArgs[] = trim( $v );
3404 } else {
3405 $allArgs[] = trim( "$k=$v" );
3406 }
3407 }
3408 }
3409
3410 $result = call_user_func_array( $callback, $allArgs );
3411
3412 # The interface for function hooks allows them to return a wikitext
3413 # string or an array containing the string and any flags. This mungs
3414 # things around to match what this method should return.
3415 if ( !is_array( $result ) ) {
3416 $result = [
3417 'found' => true,
3418 'text' => $result,
3419 ];
3420 } else {
3421 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3422 $result['text'] = $result[0];
3423 }
3424 unset( $result[0] );
3425 $result += [
3426 'found' => true,
3427 ];
3428 }
3429
3430 $noparse = true;
3431 $preprocessFlags = 0;
3432 if ( isset( $result['noparse'] ) ) {
3433 $noparse = $result['noparse'];
3434 }
3435 if ( isset( $result['preprocessFlags'] ) ) {
3436 $preprocessFlags = $result['preprocessFlags'];
3437 }
3438
3439 if ( !$noparse ) {
3440 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3441 $result['isChildObj'] = true;
3442 }
3443
3444 return $result;
3445 }
3446
3447 /**
3448 * Get the semi-parsed DOM representation of a template with a given title,
3449 * and its redirect destination title. Cached.
3450 *
3451 * @param Title $title
3452 *
3453 * @return array
3454 */
3455 public function getTemplateDom( $title ) {
3456 $cacheTitle = $title;
3457 $titleText = $title->getPrefixedDBkey();
3458
3459 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3460 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3461 $title = Title::makeTitle( $ns, $dbk );
3462 $titleText = $title->getPrefixedDBkey();
3463 }
3464 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3465 return [ $this->mTplDomCache[$titleText], $title ];
3466 }
3467
3468 # Cache miss, go to the database
3469 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3470
3471 if ( $text === false ) {
3472 $this->mTplDomCache[$titleText] = false;
3473 return [ false, $title ];
3474 }
3475
3476 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3477 $this->mTplDomCache[$titleText] = $dom;
3478
3479 if ( !$title->equals( $cacheTitle ) ) {
3480 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3481 [ $title->getNamespace(), $title->getDBkey() ];
3482 }
3483
3484 return [ $dom, $title ];
3485 }
3486
3487 /**
3488 * Fetch the current revision of a given title. Note that the revision
3489 * (and even the title) may not exist in the database, so everything
3490 * contributing to the output of the parser should use this method
3491 * where possible, rather than getting the revisions themselves. This
3492 * method also caches its results, so using it benefits performance.
3493 *
3494 * @since 1.24
3495 * @param Title $title
3496 * @return Revision
3497 */
3498 public function fetchCurrentRevisionOfTitle( $title ) {
3499 $cacheKey = $title->getPrefixedDBkey();
3500 if ( !$this->currentRevisionCache ) {
3501 $this->currentRevisionCache = new MapCacheLRU( 100 );
3502 }
3503 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3504 $this->currentRevisionCache->set( $cacheKey,
3505 // Defaults to Parser::statelessFetchRevision()
3506 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3507 );
3508 }
3509 return $this->currentRevisionCache->get( $cacheKey );
3510 }
3511
3512 /**
3513 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3514 * without passing them on to it.
3515 *
3516 * @since 1.24
3517 * @param Title $title
3518 * @param Parser|bool $parser
3519 * @return Revision|bool False if missing
3520 */
3521 public static function statelessFetchRevision( Title $title, $parser = false ) {
3522 $pageId = $title->getArticleID();
3523 $revId = $title->getLatestRevID();
3524
3525 $rev = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $pageId, $revId );
3526 if ( $rev ) {
3527 $rev->setTitle( $title );
3528 }
3529
3530 return $rev;
3531 }
3532
3533 /**
3534 * Fetch the unparsed text of a template and register a reference to it.
3535 * @param Title $title
3536 * @return array ( string or false, Title )
3537 */
3538 public function fetchTemplateAndTitle( $title ) {
3539 // Defaults to Parser::statelessFetchTemplate()
3540 $templateCb = $this->mOptions->getTemplateCallback();
3541 $stuff = call_user_func( $templateCb, $title, $this );
3542 // We use U+007F DELETE to distinguish strip markers from regular text.
3543 $text = $stuff['text'];
3544 if ( is_string( $stuff['text'] ) ) {
3545 $text = strtr( $text, "\x7f", "?" );
3546 }
3547 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3548 if ( isset( $stuff['deps'] ) ) {
3549 foreach ( $stuff['deps'] as $dep ) {
3550 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3551 if ( $dep['title']->equals( $this->getTitle() ) ) {
3552 // If we transclude ourselves, the final result
3553 // will change based on the new version of the page
3554 $this->mOutput->setFlag( 'vary-revision' );
3555 }
3556 }
3557 }
3558 return [ $text, $finalTitle ];
3559 }
3560
3561 /**
3562 * Fetch the unparsed text of a template and register a reference to it.
3563 * @param Title $title
3564 * @return string|bool
3565 */
3566 public function fetchTemplate( $title ) {
3567 return $this->fetchTemplateAndTitle( $title )[0];
3568 }
3569
3570 /**
3571 * Static function to get a template
3572 * Can be overridden via ParserOptions::setTemplateCallback().
3573 *
3574 * @param Title $title
3575 * @param bool|Parser $parser
3576 *
3577 * @return array
3578 */
3579 public static function statelessFetchTemplate( $title, $parser = false ) {
3580 $text = $skip = false;
3581 $finalTitle = $title;
3582 $deps = [];
3583
3584 # Loop to fetch the article, with up to 1 redirect
3585 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3586 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3587 // @codingStandardsIgnoreEnd
3588 # Give extensions a chance to select the revision instead
3589 $id = false; # Assume current
3590 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3591 [ $parser, $title, &$skip, &$id ] );
3592
3593 if ( $skip ) {
3594 $text = false;
3595 $deps[] = [
3596 'title' => $title,
3597 'page_id' => $title->getArticleID(),
3598 'rev_id' => null
3599 ];
3600 break;
3601 }
3602 # Get the revision
3603 if ( $id ) {
3604 $rev = Revision::newFromId( $id );
3605 } elseif ( $parser ) {
3606 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3607 } else {
3608 $rev = Revision::newFromTitle( $title );
3609 }
3610 $rev_id = $rev ? $rev->getId() : 0;
3611 # If there is no current revision, there is no page
3612 if ( $id === false && !$rev ) {
3613 $linkCache = LinkCache::singleton();
3614 $linkCache->addBadLinkObj( $title );
3615 }
3616
3617 $deps[] = [
3618 'title' => $title,
3619 'page_id' => $title->getArticleID(),
3620 'rev_id' => $rev_id ];
3621 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3622 # We fetched a rev from a different title; register it too...
3623 $deps[] = [
3624 'title' => $rev->getTitle(),
3625 'page_id' => $rev->getPage(),
3626 'rev_id' => $rev_id ];
3627 }
3628
3629 if ( $rev ) {
3630 $content = $rev->getContent();
3631 $text = $content ? $content->getWikitextForTransclusion() : null;
3632
3633 Hooks::run( 'ParserFetchTemplate',
3634 [ $parser, $title, $rev, &$text, &$deps ] );
3635
3636 if ( $text === false || $text === null ) {
3637 $text = false;
3638 break;
3639 }
3640 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3641 global $wgContLang;
3642 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3643 if ( !$message->exists() ) {
3644 $text = false;
3645 break;
3646 }
3647 $content = $message->content();
3648 $text = $message->plain();
3649 } else {
3650 break;
3651 }
3652 if ( !$content ) {
3653 break;
3654 }
3655 # Redirect?
3656 $finalTitle = $title;
3657 $title = $content->getRedirectTarget();
3658 }
3659 return [
3660 'text' => $text,
3661 'finalTitle' => $finalTitle,
3662 'deps' => $deps ];
3663 }
3664
3665 /**
3666 * Fetch a file and its title and register a reference to it.
3667 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3668 * @param Title $title
3669 * @param array $options Array of options to RepoGroup::findFile
3670 * @return File|bool
3671 */
3672 public function fetchFile( $title, $options = [] ) {
3673 return $this->fetchFileAndTitle( $title, $options )[0];
3674 }
3675
3676 /**
3677 * Fetch a file and its title and register a reference to it.
3678 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3679 * @param Title $title
3680 * @param array $options Array of options to RepoGroup::findFile
3681 * @return array ( File or false, Title of file )
3682 */
3683 public function fetchFileAndTitle( $title, $options = [] ) {
3684 $file = $this->fetchFileNoRegister( $title, $options );
3685
3686 $time = $file ? $file->getTimestamp() : false;
3687 $sha1 = $file ? $file->getSha1() : false;
3688 # Register the file as a dependency...
3689 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3690 if ( $file && !$title->equals( $file->getTitle() ) ) {
3691 # Update fetched file title
3692 $title = $file->getTitle();
3693 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3694 }
3695 return [ $file, $title ];
3696 }
3697
3698 /**
3699 * Helper function for fetchFileAndTitle.
3700 *
3701 * Also useful if you need to fetch a file but not use it yet,
3702 * for example to get the file's handler.
3703 *
3704 * @param Title $title
3705 * @param array $options Array of options to RepoGroup::findFile
3706 * @return File|bool
3707 */
3708 protected function fetchFileNoRegister( $title, $options = [] ) {
3709 if ( isset( $options['broken'] ) ) {
3710 $file = false; // broken thumbnail forced by hook
3711 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3712 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3713 } else { // get by (name,timestamp)
3714 $file = wfFindFile( $title, $options );
3715 }
3716 return $file;
3717 }
3718
3719 /**
3720 * Transclude an interwiki link.
3721 *
3722 * @param Title $title
3723 * @param string $action
3724 *
3725 * @return string
3726 */
3727 public function interwikiTransclude( $title, $action ) {
3728 global $wgEnableScaryTranscluding;
3729
3730 if ( !$wgEnableScaryTranscluding ) {
3731 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3732 }
3733
3734 $url = $title->getFullURL( [ 'action' => $action ] );
3735
3736 if ( strlen( $url ) > 255 ) {
3737 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3738 }
3739 return $this->fetchScaryTemplateMaybeFromCache( $url );
3740 }
3741
3742 /**
3743 * @param string $url
3744 * @return mixed|string
3745 */
3746 public function fetchScaryTemplateMaybeFromCache( $url ) {
3747 global $wgTranscludeCacheExpiry;
3748 $dbr = wfGetDB( DB_REPLICA );
3749 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3750 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3751 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3752 if ( $obj ) {
3753 return $obj->tc_contents;
3754 }
3755
3756 $req = MWHttpRequest::factory( $url, [], __METHOD__ );
3757 $status = $req->execute(); // Status object
3758 if ( $status->isOK() ) {
3759 $text = $req->getContent();
3760 } elseif ( $req->getStatus() != 200 ) {
3761 // Though we failed to fetch the content, this status is useless.
3762 return wfMessage( 'scarytranscludefailed-httpstatus' )
3763 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3764 } else {
3765 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3766 }
3767
3768 $dbw = wfGetDB( DB_MASTER );
3769 $dbw->replace( 'transcache', [ 'tc_url' ], [
3770 'tc_url' => $url,
3771 'tc_time' => $dbw->timestamp( time() ),
3772 'tc_contents' => $text
3773 ] );
3774 return $text;
3775 }
3776
3777 /**
3778 * Triple brace replacement -- used for template arguments
3779 * @private
3780 *
3781 * @param array $piece
3782 * @param PPFrame $frame
3783 *
3784 * @return array
3785 */
3786 public function argSubstitution( $piece, $frame ) {
3787 $error = false;
3788 $parts = $piece['parts'];
3789 $nameWithSpaces = $frame->expand( $piece['title'] );
3790 $argName = trim( $nameWithSpaces );
3791 $object = false;
3792 $text = $frame->getArgument( $argName );
3793 if ( $text === false && $parts->getLength() > 0
3794 && ( $this->ot['html']
3795 || $this->ot['pre']
3796 || ( $this->ot['wiki'] && $frame->isTemplate() )
3797 )
3798 ) {
3799 # No match in frame, use the supplied default
3800 $object = $parts->item( 0 )->getChildren();
3801 }
3802 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3803 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3804 $this->limitationWarn( 'post-expand-template-argument' );
3805 }
3806
3807 if ( $text === false && $object === false ) {
3808 # No match anywhere
3809 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3810 }
3811 if ( $error !== false ) {
3812 $text .= $error;
3813 }
3814 if ( $object !== false ) {
3815 $ret = [ 'object' => $object ];
3816 } else {
3817 $ret = [ 'text' => $text ];
3818 }
3819
3820 return $ret;
3821 }
3822
3823 /**
3824 * Return the text to be used for a given extension tag.
3825 * This is the ghost of strip().
3826 *
3827 * @param array $params Associative array of parameters:
3828 * name PPNode for the tag name
3829 * attr PPNode for unparsed text where tag attributes are thought to be
3830 * attributes Optional associative array of parsed attributes
3831 * inner Contents of extension element
3832 * noClose Original text did not have a close tag
3833 * @param PPFrame $frame
3834 *
3835 * @throws MWException
3836 * @return string
3837 */
3838 public function extensionSubstitution( $params, $frame ) {
3839 static $errorStr = '<span class="error">';
3840 static $errorLen = 20;
3841
3842 $name = $frame->expand( $params['name'] );
3843 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3844 // Probably expansion depth or node count exceeded. Just punt the
3845 // error up.
3846 return $name;
3847 }
3848
3849 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3850 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3851 // See above
3852 return $attrText;
3853 }
3854
3855 // We can't safely check if the expansion for $content resulted in an
3856 // error, because the content could happen to be the error string
3857 // (T149622).
3858 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3859
3860 $marker = self::MARKER_PREFIX . "-$name-"
3861 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3862
3863 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3864 ( $this->ot['html'] || $this->ot['pre'] );
3865 if ( $isFunctionTag ) {
3866 $markerType = 'none';
3867 } else {
3868 $markerType = 'general';
3869 }
3870 if ( $this->ot['html'] || $isFunctionTag ) {
3871 $name = strtolower( $name );
3872 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3873 if ( isset( $params['attributes'] ) ) {
3874 $attributes = $attributes + $params['attributes'];
3875 }
3876
3877 if ( isset( $this->mTagHooks[$name] ) ) {
3878 $output = call_user_func_array( $this->mTagHooks[$name],
3879 [ $content, $attributes, $this, $frame ] );
3880 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3881 list( $callback, ) = $this->mFunctionTagHooks[$name];
3882
3883 // Avoid PHP 7.1 warning from passing $this by reference
3884 $parser = $this;
3885 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3886 } else {
3887 $output = '<span class="error">Invalid tag extension name: ' .
3888 htmlspecialchars( $name ) . '</span>';
3889 }
3890
3891 if ( is_array( $output ) ) {
3892 # Extract flags to local scope (to override $markerType)
3893 $flags = $output;
3894 $output = $flags[0];
3895 unset( $flags[0] );
3896 extract( $flags );
3897 }
3898 } else {
3899 if ( is_null( $attrText ) ) {
3900 $attrText = '';
3901 }
3902 if ( isset( $params['attributes'] ) ) {
3903 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3904 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3905 htmlspecialchars( $attrValue ) . '"';
3906 }
3907 }
3908 if ( $content === null ) {
3909 $output = "<$name$attrText/>";
3910 } else {
3911 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3912 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3913 // See above
3914 return $close;
3915 }
3916 $output = "<$name$attrText>$content$close";
3917 }
3918 }
3919
3920 if ( $markerType === 'none' ) {
3921 return $output;
3922 } elseif ( $markerType === 'nowiki' ) {
3923 $this->mStripState->addNoWiki( $marker, $output );
3924 } elseif ( $markerType === 'general' ) {
3925 $this->mStripState->addGeneral( $marker, $output );
3926 } else {
3927 throw new MWException( __METHOD__ . ': invalid marker type' );
3928 }
3929 return $marker;
3930 }
3931
3932 /**
3933 * Increment an include size counter
3934 *
3935 * @param string $type The type of expansion
3936 * @param int $size The size of the text
3937 * @return bool False if this inclusion would take it over the maximum, true otherwise
3938 */
3939 public function incrementIncludeSize( $type, $size ) {
3940 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3941 return false;
3942 } else {
3943 $this->mIncludeSizes[$type] += $size;
3944 return true;
3945 }
3946 }
3947
3948 /**
3949 * Increment the expensive function count
3950 *
3951 * @return bool False if the limit has been exceeded
3952 */
3953 public function incrementExpensiveFunctionCount() {
3954 $this->mExpensiveFunctionCount++;
3955 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
3956 }
3957
3958 /**
3959 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3960 * Fills $this->mDoubleUnderscores, returns the modified text
3961 *
3962 * @param string $text
3963 *
3964 * @return string
3965 */
3966 public function doDoubleUnderscore( $text ) {
3967 # The position of __TOC__ needs to be recorded
3968 $mw = MagicWord::get( 'toc' );
3969 if ( $mw->match( $text ) ) {
3970 $this->mShowToc = true;
3971 $this->mForceTocPosition = true;
3972
3973 # Set a placeholder. At the end we'll fill it in with the TOC.
3974 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3975
3976 # Only keep the first one.
3977 $text = $mw->replace( '', $text );
3978 }
3979
3980 # Now match and remove the rest of them
3981 $mwa = MagicWord::getDoubleUnderscoreArray();
3982 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3983
3984 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3985 $this->mOutput->mNoGallery = true;
3986 }
3987 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3988 $this->mShowToc = false;
3989 }
3990 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
3991 && $this->mTitle->getNamespace() == NS_CATEGORY
3992 ) {
3993 $this->addTrackingCategory( 'hidden-category-category' );
3994 }
3995 # (T10068) Allow control over whether robots index a page.
3996 # __INDEX__ always overrides __NOINDEX__, see T16899
3997 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3998 $this->mOutput->setIndexPolicy( 'noindex' );
3999 $this->addTrackingCategory( 'noindex-category' );
4000 }
4001 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4002 $this->mOutput->setIndexPolicy( 'index' );
4003 $this->addTrackingCategory( 'index-category' );
4004 }
4005
4006 # Cache all double underscores in the database
4007 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4008 $this->mOutput->setProperty( $key, '' );
4009 }
4010
4011 return $text;
4012 }
4013
4014 /**
4015 * @see ParserOutput::addTrackingCategory()
4016 * @param string $msg Message key
4017 * @return bool Whether the addition was successful
4018 */
4019 public function addTrackingCategory( $msg ) {
4020 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4021 }
4022
4023 /**
4024 * This function accomplishes several tasks:
4025 * 1) Auto-number headings if that option is enabled
4026 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4027 * 3) Add a Table of contents on the top for users who have enabled the option
4028 * 4) Auto-anchor headings
4029 *
4030 * It loops through all headlines, collects the necessary data, then splits up the
4031 * string and re-inserts the newly formatted headlines.
4032 *
4033 * @param string $text
4034 * @param string $origText Original, untouched wikitext
4035 * @param bool $isMain
4036 * @return mixed|string
4037 * @private
4038 */
4039 public function formatHeadings( $text, $origText, $isMain = true ) {
4040 global $wgMaxTocLevel;
4041
4042 # Inhibit editsection links if requested in the page
4043 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4044 $maybeShowEditLink = $showEditLink = false;
4045 } else {
4046 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4047 $showEditLink = $this->mOptions->getEditSection();
4048 }
4049 if ( $showEditLink ) {
4050 $this->mOutput->setEditSectionTokens( true );
4051 }
4052
4053 # Get all headlines for numbering them and adding funky stuff like [edit]
4054 # links - this is for later, but we need the number of headlines right now
4055 $matches = [];
4056 $numMatches = preg_match_all(
4057 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4058 $text,
4059 $matches
4060 );
4061
4062 # if there are fewer than 4 headlines in the article, do not show TOC
4063 # unless it's been explicitly enabled.
4064 $enoughToc = $this->mShowToc &&
4065 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4066
4067 # Allow user to stipulate that a page should have a "new section"
4068 # link added via __NEWSECTIONLINK__
4069 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4070 $this->mOutput->setNewSection( true );
4071 }
4072
4073 # Allow user to remove the "new section"
4074 # link via __NONEWSECTIONLINK__
4075 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4076 $this->mOutput->hideNewSection( true );
4077 }
4078
4079 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4080 # override above conditions and always show TOC above first header
4081 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4082 $this->mShowToc = true;
4083 $enoughToc = true;
4084 }
4085
4086 # headline counter
4087 $headlineCount = 0;
4088 $numVisible = 0;
4089
4090 # Ugh .. the TOC should have neat indentation levels which can be
4091 # passed to the skin functions. These are determined here
4092 $toc = '';
4093 $full = '';
4094 $head = [];
4095 $sublevelCount = [];
4096 $levelCount = [];
4097 $level = 0;
4098 $prevlevel = 0;
4099 $toclevel = 0;
4100 $prevtoclevel = 0;
4101 $markerRegex = self::MARKER_PREFIX . "-h-(\d+)-" . self::MARKER_SUFFIX;
4102 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4103 $oldType = $this->mOutputType;
4104 $this->setOutputType( self::OT_WIKI );
4105 $frame = $this->getPreprocessor()->newFrame();
4106 $root = $this->preprocessToDom( $origText );
4107 $node = $root->getFirstChild();
4108 $byteOffset = 0;
4109 $tocraw = [];
4110 $refers = [];
4111
4112 $headlines = $numMatches !== false ? $matches[3] : [];
4113
4114 foreach ( $headlines as $headline ) {
4115 $isTemplate = false;
4116 $titleText = false;
4117 $sectionIndex = false;
4118 $numbering = '';
4119 $markerMatches = [];
4120 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4121 $serial = $markerMatches[1];
4122 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4123 $isTemplate = ( $titleText != $baseTitleText );
4124 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4125 }
4126
4127 if ( $toclevel ) {
4128 $prevlevel = $level;
4129 }
4130 $level = $matches[1][$headlineCount];
4131
4132 if ( $level > $prevlevel ) {
4133 # Increase TOC level
4134 $toclevel++;
4135 $sublevelCount[$toclevel] = 0;
4136 if ( $toclevel < $wgMaxTocLevel ) {
4137 $prevtoclevel = $toclevel;
4138 $toc .= Linker::tocIndent();
4139 $numVisible++;
4140 }
4141 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4142 # Decrease TOC level, find level to jump to
4143
4144 for ( $i = $toclevel; $i > 0; $i-- ) {
4145 if ( $levelCount[$i] == $level ) {
4146 # Found last matching level
4147 $toclevel = $i;
4148 break;
4149 } elseif ( $levelCount[$i] < $level ) {
4150 # Found first matching level below current level
4151 $toclevel = $i + 1;
4152 break;
4153 }
4154 }
4155 if ( $i == 0 ) {
4156 $toclevel = 1;
4157 }
4158 if ( $toclevel < $wgMaxTocLevel ) {
4159 if ( $prevtoclevel < $wgMaxTocLevel ) {
4160 # Unindent only if the previous toc level was shown :p
4161 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4162 $prevtoclevel = $toclevel;
4163 } else {
4164 $toc .= Linker::tocLineEnd();
4165 }
4166 }
4167 } else {
4168 # No change in level, end TOC line
4169 if ( $toclevel < $wgMaxTocLevel ) {
4170 $toc .= Linker::tocLineEnd();
4171 }
4172 }
4173
4174 $levelCount[$toclevel] = $level;
4175
4176 # count number of headlines for each level
4177 $sublevelCount[$toclevel]++;
4178 $dot = 0;
4179 for ( $i = 1; $i <= $toclevel; $i++ ) {
4180 if ( !empty( $sublevelCount[$i] ) ) {
4181 if ( $dot ) {
4182 $numbering .= '.';
4183 }
4184 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4185 $dot = 1;
4186 }
4187 }
4188
4189 # The safe header is a version of the header text safe to use for links
4190
4191 # Remove link placeholders by the link text.
4192 # <!--LINK number-->
4193 # turns into
4194 # link text with suffix
4195 # Do this before unstrip since link text can contain strip markers
4196 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4197
4198 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4199 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4200
4201 # Strip out HTML (first regex removes any tag not allowed)
4202 # Allowed tags are:
4203 # * <sup> and <sub> (T10393)
4204 # * <i> (T28375)
4205 # * <b> (r105284)
4206 # * <bdi> (T74884)
4207 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4208 # * <s> and <strike> (T35715)
4209 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4210 # to allow setting directionality in toc items.
4211 $tocline = preg_replace(
4212 [
4213 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4214 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4215 ],
4216 [ '', '<$1>' ],
4217 $safeHeadline
4218 );
4219
4220 # Strip '<span></span>', which is the result from the above if
4221 # <span id="foo"></span> is used to produce an additional anchor
4222 # for a section.
4223 $tocline = str_replace( '<span></span>', '', $tocline );
4224
4225 $tocline = trim( $tocline );
4226
4227 # For the anchor, strip out HTML-y stuff period
4228 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4229 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4230
4231 # Save headline for section edit hint before it's escaped
4232 $headlineHint = $safeHeadline;
4233
4234 $fallbackHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_FALLBACK );
4235 $linkAnchor = Sanitizer::escapeIdForLink( $safeHeadline );
4236 $safeHeadline = Sanitizer::escapeIdForAttribute( $safeHeadline, Sanitizer::ID_PRIMARY );
4237 if ( $fallbackHeadline === $safeHeadline ) {
4238 # No reason to have both (in fact, we can't)
4239 $fallbackHeadline = false;
4240 }
4241
4242 # HTML IDs must be case-insensitively unique for IE compatibility (T12721).
4243 # @todo FIXME: We may be changing them depending on the current locale.
4244 $arrayKey = strtolower( $safeHeadline );
4245 if ( $fallbackHeadline === false ) {
4246 $fallbackArrayKey = false;
4247 } else {
4248 $fallbackArrayKey = strtolower( $fallbackHeadline );
4249 }
4250
4251 # Create the anchor for linking from the TOC to the section
4252 $anchor = $safeHeadline;
4253 $fallbackAnchor = $fallbackHeadline;
4254 if ( isset( $refers[$arrayKey] ) ) {
4255 // @codingStandardsIgnoreStart
4256 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4257 // @codingStandardsIgnoreEnd
4258 $anchor .= "_$i";
4259 $linkAnchor .= "_$i";
4260 $refers["${arrayKey}_$i"] = true;
4261 } else {
4262 $refers[$arrayKey] = true;
4263 }
4264 if ( $fallbackHeadline !== false && isset( $refers[$fallbackArrayKey] ) ) {
4265 // @codingStandardsIgnoreStart
4266 for ( $i = 2; isset( $refers["${fallbackArrayKey}_$i"] ); ++$i );
4267 // @codingStandardsIgnoreEnd
4268 $fallbackAnchor .= "_$i";
4269 $refers["${fallbackArrayKey}_$i"] = true;
4270 } else {
4271 $refers[$fallbackArrayKey] = true;
4272 }
4273
4274 # Don't number the heading if it is the only one (looks silly)
4275 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4276 # the two are different if the line contains a link
4277 $headline = Html::element(
4278 'span',
4279 [ 'class' => 'mw-headline-number' ],
4280 $numbering
4281 ) . ' ' . $headline;
4282 }
4283
4284 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4285 $toc .= Linker::tocLine( $linkAnchor, $tocline,
4286 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4287 }
4288
4289 # Add the section to the section tree
4290 # Find the DOM node for this header
4291 $noOffset = ( $isTemplate || $sectionIndex === false );
4292 while ( $node && !$noOffset ) {
4293 if ( $node->getName() === 'h' ) {
4294 $bits = $node->splitHeading();
4295 if ( $bits['i'] == $sectionIndex ) {
4296 break;
4297 }
4298 }
4299 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4300 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4301 $node = $node->getNextSibling();
4302 }
4303 $tocraw[] = [
4304 'toclevel' => $toclevel,
4305 'level' => $level,
4306 'line' => $tocline,
4307 'number' => $numbering,
4308 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4309 'fromtitle' => $titleText,
4310 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4311 'anchor' => $anchor,
4312 ];
4313
4314 # give headline the correct <h#> tag
4315 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4316 // Output edit section links as markers with styles that can be customized by skins
4317 if ( $isTemplate ) {
4318 # Put a T flag in the section identifier, to indicate to extractSections()
4319 # that sections inside <includeonly> should be counted.
4320 $editsectionPage = $titleText;
4321 $editsectionSection = "T-$sectionIndex";
4322 $editsectionContent = null;
4323 } else {
4324 $editsectionPage = $this->mTitle->getPrefixedText();
4325 $editsectionSection = $sectionIndex;
4326 $editsectionContent = $headlineHint;
4327 }
4328 // We use a bit of pesudo-xml for editsection markers. The
4329 // language converter is run later on. Using a UNIQ style marker
4330 // leads to the converter screwing up the tokens when it
4331 // converts stuff. And trying to insert strip tags fails too. At
4332 // this point all real inputted tags have already been escaped,
4333 // so we don't have to worry about a user trying to input one of
4334 // these markers directly. We use a page and section attribute
4335 // to stop the language converter from converting these
4336 // important bits of data, but put the headline hint inside a
4337 // content block because the language converter is supposed to
4338 // be able to convert that piece of data.
4339 // Gets replaced with html in ParserOutput::getText
4340 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4341 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4342 if ( $editsectionContent !== null ) {
4343 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4344 } else {
4345 $editlink .= '/>';
4346 }
4347 } else {
4348 $editlink = '';
4349 }
4350 $head[$headlineCount] = Linker::makeHeadline( $level,
4351 $matches['attrib'][$headlineCount], $anchor, $headline,
4352 $editlink, $fallbackAnchor );
4353
4354 $headlineCount++;
4355 }
4356
4357 $this->setOutputType( $oldType );
4358
4359 # Never ever show TOC if no headers
4360 if ( $numVisible < 1 ) {
4361 $enoughToc = false;
4362 }
4363
4364 if ( $enoughToc ) {
4365 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4366 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4367 }
4368 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4369 $this->mOutput->setTOCHTML( $toc );
4370 $toc = self::TOC_START . $toc . self::TOC_END;
4371 }
4372
4373 if ( $isMain ) {
4374 $this->mOutput->setSections( $tocraw );
4375 }
4376
4377 # split up and insert constructed headlines
4378 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4379 $i = 0;
4380
4381 // build an array of document sections
4382 $sections = [];
4383 foreach ( $blocks as $block ) {
4384 // $head is zero-based, sections aren't.
4385 if ( empty( $head[$i - 1] ) ) {
4386 $sections[$i] = $block;
4387 } else {
4388 $sections[$i] = $head[$i - 1] . $block;
4389 }
4390
4391 /**
4392 * Send a hook, one per section.
4393 * The idea here is to be able to make section-level DIVs, but to do so in a
4394 * lower-impact, more correct way than r50769
4395 *
4396 * $this : caller
4397 * $section : the section number
4398 * &$sectionContent : ref to the content of the section
4399 * $showEditLinks : boolean describing whether this section has an edit link
4400 */
4401 Hooks::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $showEditLink ] );
4402
4403 $i++;
4404 }
4405
4406 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4407 // append the TOC at the beginning
4408 // Top anchor now in skin
4409 $sections[0] = $sections[0] . $toc . "\n";
4410 }
4411
4412 $full .= implode( '', $sections );
4413
4414 if ( $this->mForceTocPosition ) {
4415 return str_replace( '<!--MWTOC-->', $toc, $full );
4416 } else {
4417 return $full;
4418 }
4419 }
4420
4421 /**
4422 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4423 * conversion, substituting signatures, {{subst:}} templates, etc.
4424 *
4425 * @param string $text The text to transform
4426 * @param Title $title The Title object for the current article
4427 * @param User $user The User object describing the current user
4428 * @param ParserOptions $options Parsing options
4429 * @param bool $clearState Whether to clear the parser state first
4430 * @return string The altered wiki markup
4431 */
4432 public function preSaveTransform( $text, Title $title, User $user,
4433 ParserOptions $options, $clearState = true
4434 ) {
4435 if ( $clearState ) {
4436 $magicScopeVariable = $this->lock();
4437 }
4438 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4439 $this->setUser( $user );
4440
4441 // Strip U+0000 NULL (T159174)
4442 $text = str_replace( "\000", '', $text );
4443
4444 // We still normalize line endings for backwards-compatibility
4445 // with other code that just calls PST, but this should already
4446 // be handled in TextContent subclasses
4447 $text = TextContent::normalizeLineEndings( $text );
4448
4449 if ( $options->getPreSaveTransform() ) {
4450 $text = $this->pstPass2( $text, $user );
4451 }
4452 $text = $this->mStripState->unstripBoth( $text );
4453
4454 $this->setUser( null ); # Reset
4455
4456 return $text;
4457 }
4458
4459 /**
4460 * Pre-save transform helper function
4461 *
4462 * @param string $text
4463 * @param User $user
4464 *
4465 * @return string
4466 */
4467 private function pstPass2( $text, $user ) {
4468 global $wgContLang;
4469
4470 # Note: This is the timestamp saved as hardcoded wikitext to
4471 # the database, we use $wgContLang here in order to give
4472 # everyone the same signature and use the default one rather
4473 # than the one selected in each user's preferences.
4474 # (see also T14815)
4475 $ts = $this->mOptions->getTimestamp();
4476 $timestamp = MWTimestamp::getLocalInstance( $ts );
4477 $ts = $timestamp->format( 'YmdHis' );
4478 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4479
4480 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4481
4482 # Variable replacement
4483 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4484 $text = $this->replaceVariables( $text );
4485
4486 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4487 # which may corrupt this parser instance via its wfMessage()->text() call-
4488
4489 # Signatures
4490 if ( strpos( $text, '~~~' ) !== false ) {
4491 $sigText = $this->getUserSig( $user );
4492 $text = strtr( $text, [
4493 '~~~~~' => $d,
4494 '~~~~' => "$sigText $d",
4495 '~~~' => $sigText
4496 ] );
4497 # The main two signature forms used above are time-sensitive
4498 $this->mOutput->setFlag( 'user-signature' );
4499 }
4500
4501 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4502 $tc = '[' . Title::legalChars() . ']';
4503 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4504
4505 // [[ns:page (context)|]]
4506 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4507 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4508 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4509 // [[ns:page (context), context|]] (using either single or double-width comma)
4510 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4511 // [[|page]] (reverse pipe trick: add context from page title)
4512 $p2 = "/\[\[\\|($tc+)]]/";
4513
4514 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4515 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4516 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4517 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4518
4519 $t = $this->mTitle->getText();
4520 $m = [];
4521 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4522 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4523 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4524 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4525 } else {
4526 # if there's no context, don't bother duplicating the title
4527 $text = preg_replace( $p2, '[[\\1]]', $text );
4528 }
4529
4530 return $text;
4531 }
4532
4533 /**
4534 * Fetch the user's signature text, if any, and normalize to
4535 * validated, ready-to-insert wikitext.
4536 * If you have pre-fetched the nickname or the fancySig option, you can
4537 * specify them here to save a database query.
4538 * Do not reuse this parser instance after calling getUserSig(),
4539 * as it may have changed if it's the $wgParser.
4540 *
4541 * @param User &$user
4542 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4543 * @param bool|null $fancySig whether the nicknname is the complete signature
4544 * or null to use default value
4545 * @return string
4546 */
4547 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4548 global $wgMaxSigChars;
4549
4550 $username = $user->getName();
4551
4552 # If not given, retrieve from the user object.
4553 if ( $nickname === false ) {
4554 $nickname = $user->getOption( 'nickname' );
4555 }
4556
4557 if ( is_null( $fancySig ) ) {
4558 $fancySig = $user->getBoolOption( 'fancysig' );
4559 }
4560
4561 $nickname = $nickname == null ? $username : $nickname;
4562
4563 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4564 $nickname = $username;
4565 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4566 } elseif ( $fancySig !== false ) {
4567 # Sig. might contain markup; validate this
4568 if ( $this->validateSig( $nickname ) !== false ) {
4569 # Validated; clean up (if needed) and return it
4570 return $this->cleanSig( $nickname, true );
4571 } else {
4572 # Failed to validate; fall back to the default
4573 $nickname = $username;
4574 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4575 }
4576 }
4577
4578 # Make sure nickname doesnt get a sig in a sig
4579 $nickname = self::cleanSigInSig( $nickname );
4580
4581 # If we're still here, make it a link to the user page
4582 $userText = wfEscapeWikiText( $username );
4583 $nickText = wfEscapeWikiText( $nickname );
4584 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4585
4586 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4587 ->title( $this->getTitle() )->text();
4588 }
4589
4590 /**
4591 * Check that the user's signature contains no bad XML
4592 *
4593 * @param string $text
4594 * @return string|bool An expanded string, or false if invalid.
4595 */
4596 public function validateSig( $text ) {
4597 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4598 }
4599
4600 /**
4601 * Clean up signature text
4602 *
4603 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4604 * 2) Substitute all transclusions
4605 *
4606 * @param string $text
4607 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4608 * @return string Signature text
4609 */
4610 public function cleanSig( $text, $parsing = false ) {
4611 if ( !$parsing ) {
4612 global $wgTitle;
4613 $magicScopeVariable = $this->lock();
4614 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4615 }
4616
4617 # Option to disable this feature
4618 if ( !$this->mOptions->getCleanSignatures() ) {
4619 return $text;
4620 }
4621
4622 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4623 # => Move this logic to braceSubstitution()
4624 $substWord = MagicWord::get( 'subst' );
4625 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4626 $substText = '{{' . $substWord->getSynonym( 0 );
4627
4628 $text = preg_replace( $substRegex, $substText, $text );
4629 $text = self::cleanSigInSig( $text );
4630 $dom = $this->preprocessToDom( $text );
4631 $frame = $this->getPreprocessor()->newFrame();
4632 $text = $frame->expand( $dom );
4633
4634 if ( !$parsing ) {
4635 $text = $this->mStripState->unstripBoth( $text );
4636 }
4637
4638 return $text;
4639 }
4640
4641 /**
4642 * Strip 3, 4 or 5 tildes out of signatures.
4643 *
4644 * @param string $text
4645 * @return string Signature text with /~{3,5}/ removed
4646 */
4647 public static function cleanSigInSig( $text ) {
4648 $text = preg_replace( '/~{3,5}/', '', $text );
4649 return $text;
4650 }
4651
4652 /**
4653 * Set up some variables which are usually set up in parse()
4654 * so that an external function can call some class members with confidence
4655 *
4656 * @param Title|null $title
4657 * @param ParserOptions $options
4658 * @param int $outputType
4659 * @param bool $clearState
4660 */
4661 public function startExternalParse( Title $title = null, ParserOptions $options,
4662 $outputType, $clearState = true
4663 ) {
4664 $this->startParse( $title, $options, $outputType, $clearState );
4665 }
4666
4667 /**
4668 * @param Title|null $title
4669 * @param ParserOptions $options
4670 * @param int $outputType
4671 * @param bool $clearState
4672 */
4673 private function startParse( Title $title = null, ParserOptions $options,
4674 $outputType, $clearState = true
4675 ) {
4676 $this->setTitle( $title );
4677 $this->mOptions = $options;
4678 $this->setOutputType( $outputType );
4679 if ( $clearState ) {
4680 $this->clearState();
4681 }
4682 }
4683
4684 /**
4685 * Wrapper for preprocess()
4686 *
4687 * @param string $text The text to preprocess
4688 * @param ParserOptions $options Options
4689 * @param Title|null $title Title object or null to use $wgTitle
4690 * @return string
4691 */
4692 public function transformMsg( $text, $options, $title = null ) {
4693 static $executing = false;
4694
4695 # Guard against infinite recursion
4696 if ( $executing ) {
4697 return $text;
4698 }
4699 $executing = true;
4700
4701 if ( !$title ) {
4702 global $wgTitle;
4703 $title = $wgTitle;
4704 }
4705
4706 $text = $this->preprocess( $text, $title, $options );
4707
4708 $executing = false;
4709 return $text;
4710 }
4711
4712 /**
4713 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4714 * The callback should have the following form:
4715 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4716 *
4717 * Transform and return $text. Use $parser for any required context, e.g. use
4718 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4719 *
4720 * Hooks may return extended information by returning an array, of which the
4721 * first numbered element (index 0) must be the return string, and all other
4722 * entries are extracted into local variables within an internal function
4723 * in the Parser class.
4724 *
4725 * This interface (introduced r61913) appears to be undocumented, but
4726 * 'markerType' is used by some core tag hooks to override which strip
4727 * array their results are placed in. **Use great caution if attempting
4728 * this interface, as it is not documented and injudicious use could smash
4729 * private variables.**
4730 *
4731 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4732 * @param callable $callback The callback function (and object) to use for the tag
4733 * @throws MWException
4734 * @return callable|null The old value of the mTagHooks array associated with the hook
4735 */
4736 public function setHook( $tag, callable $callback ) {
4737 $tag = strtolower( $tag );
4738 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4739 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4740 }
4741 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4742 $this->mTagHooks[$tag] = $callback;
4743 if ( !in_array( $tag, $this->mStripList ) ) {
4744 $this->mStripList[] = $tag;
4745 }
4746
4747 return $oldVal;
4748 }
4749
4750 /**
4751 * As setHook(), but letting the contents be parsed.
4752 *
4753 * Transparent tag hooks are like regular XML-style tag hooks, except they
4754 * operate late in the transformation sequence, on HTML instead of wikitext.
4755 *
4756 * This is probably obsoleted by things dealing with parser frames?
4757 * The only extension currently using it is geoserver.
4758 *
4759 * @since 1.10
4760 * @todo better document or deprecate this
4761 *
4762 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4763 * @param callable $callback The callback function (and object) to use for the tag
4764 * @throws MWException
4765 * @return callable|null The old value of the mTagHooks array associated with the hook
4766 */
4767 public function setTransparentTagHook( $tag, callable $callback ) {
4768 $tag = strtolower( $tag );
4769 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4770 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4771 }
4772 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4773 $this->mTransparentTagHooks[$tag] = $callback;
4774
4775 return $oldVal;
4776 }
4777
4778 /**
4779 * Remove all tag hooks
4780 */
4781 public function clearTagHooks() {
4782 $this->mTagHooks = [];
4783 $this->mFunctionTagHooks = [];
4784 $this->mStripList = $this->mDefaultStripList;
4785 }
4786
4787 /**
4788 * Create a function, e.g. {{sum:1|2|3}}
4789 * The callback function should have the form:
4790 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4791 *
4792 * Or with Parser::SFH_OBJECT_ARGS:
4793 * function myParserFunction( $parser, $frame, $args ) { ... }
4794 *
4795 * The callback may either return the text result of the function, or an array with the text
4796 * in element 0, and a number of flags in the other elements. The names of the flags are
4797 * specified in the keys. Valid flags are:
4798 * found The text returned is valid, stop processing the template. This
4799 * is on by default.
4800 * nowiki Wiki markup in the return value should be escaped
4801 * isHTML The returned text is HTML, armour it against wikitext transformation
4802 *
4803 * @param string $id The magic word ID
4804 * @param callable $callback The callback function (and object) to use
4805 * @param int $flags A combination of the following flags:
4806 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4807 *
4808 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4809 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4810 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4811 * the arguments, and to control the way they are expanded.
4812 *
4813 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4814 * arguments, for instance:
4815 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4816 *
4817 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4818 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4819 * working if/when this is changed.
4820 *
4821 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4822 * expansion.
4823 *
4824 * Please read the documentation in includes/parser/Preprocessor.php for more information
4825 * about the methods available in PPFrame and PPNode.
4826 *
4827 * @throws MWException
4828 * @return string|callable The old callback function for this name, if any
4829 */
4830 public function setFunctionHook( $id, callable $callback, $flags = 0 ) {
4831 global $wgContLang;
4832
4833 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4834 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4835
4836 # Add to function cache
4837 $mw = MagicWord::get( $id );
4838 if ( !$mw ) {
4839 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4840 }
4841
4842 $synonyms = $mw->getSynonyms();
4843 $sensitive = intval( $mw->isCaseSensitive() );
4844
4845 foreach ( $synonyms as $syn ) {
4846 # Case
4847 if ( !$sensitive ) {
4848 $syn = $wgContLang->lc( $syn );
4849 }
4850 # Add leading hash
4851 if ( !( $flags & self::SFH_NO_HASH ) ) {
4852 $syn = '#' . $syn;
4853 }
4854 # Remove trailing colon
4855 if ( substr( $syn, -1, 1 ) === ':' ) {
4856 $syn = substr( $syn, 0, -1 );
4857 }
4858 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4859 }
4860 return $oldVal;
4861 }
4862
4863 /**
4864 * Get all registered function hook identifiers
4865 *
4866 * @return array
4867 */
4868 public function getFunctionHooks() {
4869 return array_keys( $this->mFunctionHooks );
4870 }
4871
4872 /**
4873 * Create a tag function, e.g. "<test>some stuff</test>".
4874 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4875 * Unlike parser functions, their content is not preprocessed.
4876 * @param string $tag
4877 * @param callable $callback
4878 * @param int $flags
4879 * @throws MWException
4880 * @return null
4881 */
4882 public function setFunctionTagHook( $tag, callable $callback, $flags ) {
4883 $tag = strtolower( $tag );
4884 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4885 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4886 }
4887 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4888 $this->mFunctionTagHooks[$tag] : null;
4889 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
4890
4891 if ( !in_array( $tag, $this->mStripList ) ) {
4892 $this->mStripList[] = $tag;
4893 }
4894
4895 return $old;
4896 }
4897
4898 /**
4899 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4900 * Placeholders created in Linker::link()
4901 *
4902 * @param string &$text
4903 * @param int $options
4904 */
4905 public function replaceLinkHolders( &$text, $options = 0 ) {
4906 $this->mLinkHolders->replace( $text );
4907 }
4908
4909 /**
4910 * Replace "<!--LINK-->" link placeholders with plain text of links
4911 * (not HTML-formatted).
4912 *
4913 * @param string $text
4914 * @return string
4915 */
4916 public function replaceLinkHoldersText( $text ) {
4917 return $this->mLinkHolders->replaceText( $text );
4918 }
4919
4920 /**
4921 * Renders an image gallery from a text with one line per image.
4922 * text labels may be given by using |-style alternative text. E.g.
4923 * Image:one.jpg|The number "1"
4924 * Image:tree.jpg|A tree
4925 * given as text will return the HTML of a gallery with two images,
4926 * labeled 'The number "1"' and
4927 * 'A tree'.
4928 *
4929 * @param string $text
4930 * @param array $params
4931 * @return string HTML
4932 */
4933 public function renderImageGallery( $text, $params ) {
4934 $mode = false;
4935 if ( isset( $params['mode'] ) ) {
4936 $mode = $params['mode'];
4937 }
4938
4939 try {
4940 $ig = ImageGalleryBase::factory( $mode );
4941 } catch ( Exception $e ) {
4942 // If invalid type set, fallback to default.
4943 $ig = ImageGalleryBase::factory( false );
4944 }
4945
4946 $ig->setContextTitle( $this->mTitle );
4947 $ig->setShowBytes( false );
4948 $ig->setShowDimensions( false );
4949 $ig->setShowFilename( false );
4950 $ig->setParser( $this );
4951 $ig->setHideBadImages();
4952 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'ul' ) );
4953
4954 if ( isset( $params['showfilename'] ) ) {
4955 $ig->setShowFilename( true );
4956 } else {
4957 $ig->setShowFilename( false );
4958 }
4959 if ( isset( $params['caption'] ) ) {
4960 $caption = $params['caption'];
4961 $caption = htmlspecialchars( $caption );
4962 $caption = $this->replaceInternalLinks( $caption );
4963 $ig->setCaptionHtml( $caption );
4964 }
4965 if ( isset( $params['perrow'] ) ) {
4966 $ig->setPerRow( $params['perrow'] );
4967 }
4968 if ( isset( $params['widths'] ) ) {
4969 $ig->setWidths( $params['widths'] );
4970 }
4971 if ( isset( $params['heights'] ) ) {
4972 $ig->setHeights( $params['heights'] );
4973 }
4974 $ig->setAdditionalOptions( $params );
4975
4976 // Avoid PHP 7.1 warning from passing $this by reference
4977 $parser = $this;
4978 Hooks::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
4979
4980 $lines = StringUtils::explode( "\n", $text );
4981 foreach ( $lines as $line ) {
4982 # match lines like these:
4983 # Image:someimage.jpg|This is some image
4984 $matches = [];
4985 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4986 # Skip empty lines
4987 if ( count( $matches ) == 0 ) {
4988 continue;
4989 }
4990
4991 if ( strpos( $matches[0], '%' ) !== false ) {
4992 $matches[1] = rawurldecode( $matches[1] );
4993 }
4994 $title = Title::newFromText( $matches[1], NS_FILE );
4995 if ( is_null( $title ) ) {
4996 # Bogus title. Ignore these so we don't bomb out later.
4997 continue;
4998 }
4999
5000 # We need to get what handler the file uses, to figure out parameters.
5001 # Note, a hook can overide the file name, and chose an entirely different
5002 # file (which potentially could be of a different type and have different handler).
5003 $options = [];
5004 $descQuery = false;
5005 Hooks::run( 'BeforeParserFetchFileAndTitle',
5006 [ $this, $title, &$options, &$descQuery ] );
5007 # Don't register it now, as TraditionalImageGallery does that later.
5008 $file = $this->fetchFileNoRegister( $title, $options );
5009 $handler = $file ? $file->getHandler() : false;
5010
5011 $paramMap = [
5012 'img_alt' => 'gallery-internal-alt',
5013 'img_link' => 'gallery-internal-link',
5014 ];
5015 if ( $handler ) {
5016 $paramMap = $paramMap + $handler->getParamMap();
5017 // We don't want people to specify per-image widths.
5018 // Additionally the width parameter would need special casing anyhow.
5019 unset( $paramMap['img_width'] );
5020 }
5021
5022 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5023
5024 $label = '';
5025 $alt = '';
5026 $link = '';
5027 $handlerOptions = [];
5028 if ( isset( $matches[3] ) ) {
5029 // look for an |alt= definition while trying not to break existing
5030 // captions with multiple pipes (|) in it, until a more sensible grammar
5031 // is defined for images in galleries
5032
5033 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5034 // splitting on '|' is a bit odd, and different from makeImage.
5035 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5036 // Protect LanguageConverter markup
5037 $parameterMatches = StringUtils::delimiterExplode(
5038 '-{', '}-', '|', $matches[3], true /* nested */
5039 );
5040
5041 foreach ( $parameterMatches as $parameterMatch ) {
5042 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5043 if ( $magicName ) {
5044 $paramName = $paramMap[$magicName];
5045
5046 switch ( $paramName ) {
5047 case 'gallery-internal-alt':
5048 $alt = $this->stripAltText( $match, false );
5049 break;
5050 case 'gallery-internal-link':
5051 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5052 $chars = self::EXT_LINK_URL_CLASS;
5053 $addr = self::EXT_LINK_ADDR;
5054 $prots = $this->mUrlProtocols;
5055 // check to see if link matches an absolute url, if not then it must be a wiki link.
5056 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5057 // Result of LanguageConverter::markNoConversion
5058 // invoked on an external link.
5059 $linkValue = substr( $linkValue, 4, -2 );
5060 }
5061 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5062 $link = $linkValue;
5063 $this->mOutput->addExternalLink( $link );
5064 } else {
5065 $localLinkTitle = Title::newFromText( $linkValue );
5066 if ( $localLinkTitle !== null ) {
5067 $this->mOutput->addLink( $localLinkTitle );
5068 $link = $localLinkTitle->getLinkURL();
5069 }
5070 }
5071 break;
5072 default:
5073 // Must be a handler specific parameter.
5074 if ( $handler->validateParam( $paramName, $match ) ) {
5075 $handlerOptions[$paramName] = $match;
5076 } else {
5077 // Guess not, consider it as caption.
5078 wfDebug( "$parameterMatch failed parameter validation\n" );
5079 $label = '|' . $parameterMatch;
5080 }
5081 }
5082
5083 } else {
5084 // Last pipe wins.
5085 $label = '|' . $parameterMatch;
5086 }
5087 }
5088 // Remove the pipe.
5089 $label = substr( $label, 1 );
5090 }
5091
5092 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5093 }
5094 $html = $ig->toHTML();
5095 Hooks::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5096 return $html;
5097 }
5098
5099 /**
5100 * @param MediaHandler $handler
5101 * @return array
5102 */
5103 public function getImageParams( $handler ) {
5104 if ( $handler ) {
5105 $handlerClass = get_class( $handler );
5106 } else {
5107 $handlerClass = '';
5108 }
5109 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5110 # Initialise static lists
5111 static $internalParamNames = [
5112 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5113 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5114 'bottom', 'text-bottom' ],
5115 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5116 'upright', 'border', 'link', 'alt', 'class' ],
5117 ];
5118 static $internalParamMap;
5119 if ( !$internalParamMap ) {
5120 $internalParamMap = [];
5121 foreach ( $internalParamNames as $type => $names ) {
5122 foreach ( $names as $name ) {
5123 // For grep: img_left, img_right, img_center, img_none,
5124 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5125 // img_bottom, img_text_bottom,
5126 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5127 // img_border, img_link, img_alt, img_class
5128 $magicName = str_replace( '-', '_', "img_$name" );
5129 $internalParamMap[$magicName] = [ $type, $name ];
5130 }
5131 }
5132 }
5133
5134 # Add handler params
5135 $paramMap = $internalParamMap;
5136 if ( $handler ) {
5137 $handlerParamMap = $handler->getParamMap();
5138 foreach ( $handlerParamMap as $magic => $paramName ) {
5139 $paramMap[$magic] = [ 'handler', $paramName ];
5140 }
5141 }
5142 $this->mImageParams[$handlerClass] = $paramMap;
5143 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5144 }
5145 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5146 }
5147
5148 /**
5149 * Parse image options text and use it to make an image
5150 *
5151 * @param Title $title
5152 * @param string $options
5153 * @param LinkHolderArray|bool $holders
5154 * @return string HTML
5155 */
5156 public function makeImage( $title, $options, $holders = false ) {
5157 # Check if the options text is of the form "options|alt text"
5158 # Options are:
5159 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5160 # * left no resizing, just left align. label is used for alt= only
5161 # * right same, but right aligned
5162 # * none same, but not aligned
5163 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5164 # * center center the image
5165 # * frame Keep original image size, no magnify-button.
5166 # * framed Same as "frame"
5167 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5168 # * upright reduce width for upright images, rounded to full __0 px
5169 # * border draw a 1px border around the image
5170 # * alt Text for HTML alt attribute (defaults to empty)
5171 # * class Set a class for img node
5172 # * link Set the target of the image link. Can be external, interwiki, or local
5173 # vertical-align values (no % or length right now):
5174 # * baseline
5175 # * sub
5176 # * super
5177 # * top
5178 # * text-top
5179 # * middle
5180 # * bottom
5181 # * text-bottom
5182
5183 # Protect LanguageConverter markup when splitting into parts
5184 $parts = StringUtils::delimiterExplode(
5185 '-{', '}-', '|', $options, true /* allow nesting */
5186 );
5187
5188 # Give extensions a chance to select the file revision for us
5189 $options = [];
5190 $descQuery = false;
5191 Hooks::run( 'BeforeParserFetchFileAndTitle',
5192 [ $this, $title, &$options, &$descQuery ] );
5193 # Fetch and register the file (file title may be different via hooks)
5194 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5195
5196 # Get parameter map
5197 $handler = $file ? $file->getHandler() : false;
5198
5199 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5200
5201 if ( !$file ) {
5202 $this->addTrackingCategory( 'broken-file-category' );
5203 }
5204
5205 # Process the input parameters
5206 $caption = '';
5207 $params = [ 'frame' => [], 'handler' => [],
5208 'horizAlign' => [], 'vertAlign' => [] ];
5209 $seenformat = false;
5210 foreach ( $parts as $part ) {
5211 $part = trim( $part );
5212 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5213 $validated = false;
5214 if ( isset( $paramMap[$magicName] ) ) {
5215 list( $type, $paramName ) = $paramMap[$magicName];
5216
5217 # Special case; width and height come in one variable together
5218 if ( $type === 'handler' && $paramName === 'width' ) {
5219 $parsedWidthParam = $this->parseWidthParam( $value );
5220 if ( isset( $parsedWidthParam['width'] ) ) {
5221 $width = $parsedWidthParam['width'];
5222 if ( $handler->validateParam( 'width', $width ) ) {
5223 $params[$type]['width'] = $width;
5224 $validated = true;
5225 }
5226 }
5227 if ( isset( $parsedWidthParam['height'] ) ) {
5228 $height = $parsedWidthParam['height'];
5229 if ( $handler->validateParam( 'height', $height ) ) {
5230 $params[$type]['height'] = $height;
5231 $validated = true;
5232 }
5233 }
5234 # else no validation -- T15436
5235 } else {
5236 if ( $type === 'handler' ) {
5237 # Validate handler parameter
5238 $validated = $handler->validateParam( $paramName, $value );
5239 } else {
5240 # Validate internal parameters
5241 switch ( $paramName ) {
5242 case 'manualthumb':
5243 case 'alt':
5244 case 'class':
5245 # @todo FIXME: Possibly check validity here for
5246 # manualthumb? downstream behavior seems odd with
5247 # missing manual thumbs.
5248 $validated = true;
5249 $value = $this->stripAltText( $value, $holders );
5250 break;
5251 case 'link':
5252 $chars = self::EXT_LINK_URL_CLASS;
5253 $addr = self::EXT_LINK_ADDR;
5254 $prots = $this->mUrlProtocols;
5255 if ( $value === '' ) {
5256 $paramName = 'no-link';
5257 $value = true;
5258 $validated = true;
5259 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5260 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5261 $paramName = 'link-url';
5262 $this->mOutput->addExternalLink( $value );
5263 if ( $this->mOptions->getExternalLinkTarget() ) {
5264 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5265 }
5266 $validated = true;
5267 }
5268 } else {
5269 $linkTitle = Title::newFromText( $value );
5270 if ( $linkTitle ) {
5271 $paramName = 'link-title';
5272 $value = $linkTitle;
5273 $this->mOutput->addLink( $linkTitle );
5274 $validated = true;
5275 }
5276 }
5277 break;
5278 case 'frameless':
5279 case 'framed':
5280 case 'thumbnail':
5281 // use first appearing option, discard others.
5282 $validated = !$seenformat;
5283 $seenformat = true;
5284 break;
5285 default:
5286 # Most other things appear to be empty or numeric...
5287 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5288 }
5289 }
5290
5291 if ( $validated ) {
5292 $params[$type][$paramName] = $value;
5293 }
5294 }
5295 }
5296 if ( !$validated ) {
5297 $caption = $part;
5298 }
5299 }
5300
5301 # Process alignment parameters
5302 if ( $params['horizAlign'] ) {
5303 $params['frame']['align'] = key( $params['horizAlign'] );
5304 }
5305 if ( $params['vertAlign'] ) {
5306 $params['frame']['valign'] = key( $params['vertAlign'] );
5307 }
5308
5309 $params['frame']['caption'] = $caption;
5310
5311 # Will the image be presented in a frame, with the caption below?
5312 $imageIsFramed = isset( $params['frame']['frame'] )
5313 || isset( $params['frame']['framed'] )
5314 || isset( $params['frame']['thumbnail'] )
5315 || isset( $params['frame']['manualthumb'] );
5316
5317 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5318 # came to also set the caption, ordinary text after the image -- which
5319 # makes no sense, because that just repeats the text multiple times in
5320 # screen readers. It *also* came to set the title attribute.
5321 # Now that we have an alt attribute, we should not set the alt text to
5322 # equal the caption: that's worse than useless, it just repeats the
5323 # text. This is the framed/thumbnail case. If there's no caption, we
5324 # use the unnamed parameter for alt text as well, just for the time be-
5325 # ing, if the unnamed param is set and the alt param is not.
5326 # For the future, we need to figure out if we want to tweak this more,
5327 # e.g., introducing a title= parameter for the title; ignoring the un-
5328 # named parameter entirely for images without a caption; adding an ex-
5329 # plicit caption= parameter and preserving the old magic unnamed para-
5330 # meter for BC; ...
5331 if ( $imageIsFramed ) { # Framed image
5332 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5333 # No caption or alt text, add the filename as the alt text so
5334 # that screen readers at least get some description of the image
5335 $params['frame']['alt'] = $title->getText();
5336 }
5337 # Do not set $params['frame']['title'] because tooltips don't make sense
5338 # for framed images
5339 } else { # Inline image
5340 if ( !isset( $params['frame']['alt'] ) ) {
5341 # No alt text, use the "caption" for the alt text
5342 if ( $caption !== '' ) {
5343 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5344 } else {
5345 # No caption, fall back to using the filename for the
5346 # alt text
5347 $params['frame']['alt'] = $title->getText();
5348 }
5349 }
5350 # Use the "caption" for the tooltip text
5351 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5352 }
5353
5354 Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5355
5356 # Linker does the rest
5357 $time = isset( $options['time'] ) ? $options['time'] : false;
5358 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5359 $time, $descQuery, $this->mOptions->getThumbSize() );
5360
5361 # Give the handler a chance to modify the parser object
5362 if ( $handler ) {
5363 $handler->parserTransformHook( $this, $file );
5364 }
5365
5366 return $ret;
5367 }
5368
5369 /**
5370 * @param string $caption
5371 * @param LinkHolderArray|bool $holders
5372 * @return mixed|string
5373 */
5374 protected function stripAltText( $caption, $holders ) {
5375 # Strip bad stuff out of the title (tooltip). We can't just use
5376 # replaceLinkHoldersText() here, because if this function is called
5377 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5378 if ( $holders ) {
5379 $tooltip = $holders->replaceText( $caption );
5380 } else {
5381 $tooltip = $this->replaceLinkHoldersText( $caption );
5382 }
5383
5384 # make sure there are no placeholders in thumbnail attributes
5385 # that are later expanded to html- so expand them now and
5386 # remove the tags
5387 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5388 $tooltip = Sanitizer::stripAllTags( $tooltip );
5389
5390 return $tooltip;
5391 }
5392
5393 /**
5394 * Set a flag in the output object indicating that the content is dynamic and
5395 * shouldn't be cached.
5396 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5397 */
5398 public function disableCache() {
5399 wfDebug( "Parser output marked as uncacheable.\n" );
5400 if ( !$this->mOutput ) {
5401 throw new MWException( __METHOD__ .
5402 " can only be called when actually parsing something" );
5403 }
5404 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5405 }
5406
5407 /**
5408 * Callback from the Sanitizer for expanding items found in HTML attribute
5409 * values, so they can be safely tested and escaped.
5410 *
5411 * @param string &$text
5412 * @param bool|PPFrame $frame
5413 * @return string
5414 */
5415 public function attributeStripCallback( &$text, $frame = false ) {
5416 $text = $this->replaceVariables( $text, $frame );
5417 $text = $this->mStripState->unstripBoth( $text );
5418 return $text;
5419 }
5420
5421 /**
5422 * Accessor
5423 *
5424 * @return array
5425 */
5426 public function getTags() {
5427 return array_merge(
5428 array_keys( $this->mTransparentTagHooks ),
5429 array_keys( $this->mTagHooks ),
5430 array_keys( $this->mFunctionTagHooks )
5431 );
5432 }
5433
5434 /**
5435 * Replace transparent tags in $text with the values given by the callbacks.
5436 *
5437 * Transparent tag hooks are like regular XML-style tag hooks, except they
5438 * operate late in the transformation sequence, on HTML instead of wikitext.
5439 *
5440 * @param string $text
5441 *
5442 * @return string
5443 */
5444 public function replaceTransparentTags( $text ) {
5445 $matches = [];
5446 $elements = array_keys( $this->mTransparentTagHooks );
5447 $text = self::extractTagsAndParams( $elements, $text, $matches );
5448 $replacements = [];
5449
5450 foreach ( $matches as $marker => $data ) {
5451 list( $element, $content, $params, $tag ) = $data;
5452 $tagName = strtolower( $element );
5453 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5454 $output = call_user_func_array(
5455 $this->mTransparentTagHooks[$tagName],
5456 [ $content, $params, $this ]
5457 );
5458 } else {
5459 $output = $tag;
5460 }
5461 $replacements[$marker] = $output;
5462 }
5463 return strtr( $text, $replacements );
5464 }
5465
5466 /**
5467 * Break wikitext input into sections, and either pull or replace
5468 * some particular section's text.
5469 *
5470 * External callers should use the getSection and replaceSection methods.
5471 *
5472 * @param string $text Page wikitext
5473 * @param string|int $sectionId A section identifier string of the form:
5474 * "<flag1> - <flag2> - ... - <section number>"
5475 *
5476 * Currently the only recognised flag is "T", which means the target section number
5477 * was derived during a template inclusion parse, in other words this is a template
5478 * section edit link. If no flags are given, it was an ordinary section edit link.
5479 * This flag is required to avoid a section numbering mismatch when a section is
5480 * enclosed by "<includeonly>" (T8563).
5481 *
5482 * The section number 0 pulls the text before the first heading; other numbers will
5483 * pull the given section along with its lower-level subsections. If the section is
5484 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5485 *
5486 * Section 0 is always considered to exist, even if it only contains the empty
5487 * string. If $text is the empty string and section 0 is replaced, $newText is
5488 * returned.
5489 *
5490 * @param string $mode One of "get" or "replace"
5491 * @param string $newText Replacement text for section data.
5492 * @return string For "get", the extracted section text.
5493 * for "replace", the whole page with the section replaced.
5494 */
5495 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5496 global $wgTitle; # not generally used but removes an ugly failure mode
5497
5498 $magicScopeVariable = $this->lock();
5499 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5500 $outText = '';
5501 $frame = $this->getPreprocessor()->newFrame();
5502
5503 # Process section extraction flags
5504 $flags = 0;
5505 $sectionParts = explode( '-', $sectionId );
5506 $sectionIndex = array_pop( $sectionParts );
5507 foreach ( $sectionParts as $part ) {
5508 if ( $part === 'T' ) {
5509 $flags |= self::PTD_FOR_INCLUSION;
5510 }
5511 }
5512
5513 # Check for empty input
5514 if ( strval( $text ) === '' ) {
5515 # Only sections 0 and T-0 exist in an empty document
5516 if ( $sectionIndex == 0 ) {
5517 if ( $mode === 'get' ) {
5518 return '';
5519 } else {
5520 return $newText;
5521 }
5522 } else {
5523 if ( $mode === 'get' ) {
5524 return $newText;
5525 } else {
5526 return $text;
5527 }
5528 }
5529 }
5530
5531 # Preprocess the text
5532 $root = $this->preprocessToDom( $text, $flags );
5533
5534 # <h> nodes indicate section breaks
5535 # They can only occur at the top level, so we can find them by iterating the root's children
5536 $node = $root->getFirstChild();
5537
5538 # Find the target section
5539 if ( $sectionIndex == 0 ) {
5540 # Section zero doesn't nest, level=big
5541 $targetLevel = 1000;
5542 } else {
5543 while ( $node ) {
5544 if ( $node->getName() === 'h' ) {
5545 $bits = $node->splitHeading();
5546 if ( $bits['i'] == $sectionIndex ) {
5547 $targetLevel = $bits['level'];
5548 break;
5549 }
5550 }
5551 if ( $mode === 'replace' ) {
5552 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5553 }
5554 $node = $node->getNextSibling();
5555 }
5556 }
5557
5558 if ( !$node ) {
5559 # Not found
5560 if ( $mode === 'get' ) {
5561 return $newText;
5562 } else {
5563 return $text;
5564 }
5565 }
5566
5567 # Find the end of the section, including nested sections
5568 do {
5569 if ( $node->getName() === 'h' ) {
5570 $bits = $node->splitHeading();
5571 $curLevel = $bits['level'];
5572 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5573 break;
5574 }
5575 }
5576 if ( $mode === 'get' ) {
5577 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5578 }
5579 $node = $node->getNextSibling();
5580 } while ( $node );
5581
5582 # Write out the remainder (in replace mode only)
5583 if ( $mode === 'replace' ) {
5584 # Output the replacement text
5585 # Add two newlines on -- trailing whitespace in $newText is conventionally
5586 # stripped by the editor, so we need both newlines to restore the paragraph gap
5587 # Only add trailing whitespace if there is newText
5588 if ( $newText != "" ) {
5589 $outText .= $newText . "\n\n";
5590 }
5591
5592 while ( $node ) {
5593 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5594 $node = $node->getNextSibling();
5595 }
5596 }
5597
5598 if ( is_string( $outText ) ) {
5599 # Re-insert stripped tags
5600 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5601 }
5602
5603 return $outText;
5604 }
5605
5606 /**
5607 * This function returns the text of a section, specified by a number ($section).
5608 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5609 * the first section before any such heading (section 0).
5610 *
5611 * If a section contains subsections, these are also returned.
5612 *
5613 * @param string $text Text to look in
5614 * @param string|int $sectionId Section identifier as a number or string
5615 * (e.g. 0, 1 or 'T-1').
5616 * @param string $defaultText Default to return if section is not found
5617 *
5618 * @return string Text of the requested section
5619 */
5620 public function getSection( $text, $sectionId, $defaultText = '' ) {
5621 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5622 }
5623
5624 /**
5625 * This function returns $oldtext after the content of the section
5626 * specified by $section has been replaced with $text. If the target
5627 * section does not exist, $oldtext is returned unchanged.
5628 *
5629 * @param string $oldText Former text of the article
5630 * @param string|int $sectionId Section identifier as a number or string
5631 * (e.g. 0, 1 or 'T-1').
5632 * @param string $newText Replacing text
5633 *
5634 * @return string Modified text
5635 */
5636 public function replaceSection( $oldText, $sectionId, $newText ) {
5637 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5638 }
5639
5640 /**
5641 * Get the ID of the revision we are parsing
5642 *
5643 * @return int|null
5644 */
5645 public function getRevisionId() {
5646 return $this->mRevisionId;
5647 }
5648
5649 /**
5650 * Get the revision object for $this->mRevisionId
5651 *
5652 * @return Revision|null Either a Revision object or null
5653 * @since 1.23 (public since 1.23)
5654 */
5655 public function getRevisionObject() {
5656 if ( !is_null( $this->mRevisionObject ) ) {
5657 return $this->mRevisionObject;
5658 }
5659 if ( is_null( $this->mRevisionId ) ) {
5660 return null;
5661 }
5662
5663 $rev = call_user_func(
5664 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5665 );
5666
5667 # If the parse is for a new revision, then the callback should have
5668 # already been set to force the object and should match mRevisionId.
5669 # If not, try to fetch by mRevisionId for sanity.
5670 if ( $rev && $rev->getId() != $this->mRevisionId ) {
5671 $rev = Revision::newFromId( $this->mRevisionId );
5672 }
5673
5674 $this->mRevisionObject = $rev;
5675
5676 return $this->mRevisionObject;
5677 }
5678
5679 /**
5680 * Get the timestamp associated with the current revision, adjusted for
5681 * the default server-local timestamp
5682 * @return string
5683 */
5684 public function getRevisionTimestamp() {
5685 if ( is_null( $this->mRevisionTimestamp ) ) {
5686 global $wgContLang;
5687
5688 $revObject = $this->getRevisionObject();
5689 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5690
5691 # The cryptic '' timezone parameter tells to use the site-default
5692 # timezone offset instead of the user settings.
5693 # Since this value will be saved into the parser cache, served
5694 # to other users, and potentially even used inside links and such,
5695 # it needs to be consistent for all visitors.
5696 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5697
5698 }
5699 return $this->mRevisionTimestamp;
5700 }
5701
5702 /**
5703 * Get the name of the user that edited the last revision
5704 *
5705 * @return string User name
5706 */
5707 public function getRevisionUser() {
5708 if ( is_null( $this->mRevisionUser ) ) {
5709 $revObject = $this->getRevisionObject();
5710
5711 # if this template is subst: the revision id will be blank,
5712 # so just use the current user's name
5713 if ( $revObject ) {
5714 $this->mRevisionUser = $revObject->getUserText();
5715 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5716 $this->mRevisionUser = $this->getUser()->getName();
5717 }
5718 }
5719 return $this->mRevisionUser;
5720 }
5721
5722 /**
5723 * Get the size of the revision
5724 *
5725 * @return int|null Revision size
5726 */
5727 public function getRevisionSize() {
5728 if ( is_null( $this->mRevisionSize ) ) {
5729 $revObject = $this->getRevisionObject();
5730
5731 # if this variable is subst: the revision id will be blank,
5732 # so just use the parser input size, because the own substituation
5733 # will change the size.
5734 if ( $revObject ) {
5735 $this->mRevisionSize = $revObject->getSize();
5736 } else {
5737 $this->mRevisionSize = $this->mInputSize;
5738 }
5739 }
5740 return $this->mRevisionSize;
5741 }
5742
5743 /**
5744 * Mutator for $mDefaultSort
5745 *
5746 * @param string $sort New value
5747 */
5748 public function setDefaultSort( $sort ) {
5749 $this->mDefaultSort = $sort;
5750 $this->mOutput->setProperty( 'defaultsort', $sort );
5751 }
5752
5753 /**
5754 * Accessor for $mDefaultSort
5755 * Will use the empty string if none is set.
5756 *
5757 * This value is treated as a prefix, so the
5758 * empty string is equivalent to sorting by
5759 * page name.
5760 *
5761 * @return string
5762 */
5763 public function getDefaultSort() {
5764 if ( $this->mDefaultSort !== false ) {
5765 return $this->mDefaultSort;
5766 } else {
5767 return '';
5768 }
5769 }
5770
5771 /**
5772 * Accessor for $mDefaultSort
5773 * Unlike getDefaultSort(), will return false if none is set
5774 *
5775 * @return string|bool
5776 */
5777 public function getCustomDefaultSort() {
5778 return $this->mDefaultSort;
5779 }
5780
5781 /**
5782 * Try to guess the section anchor name based on a wikitext fragment
5783 * presumably extracted from a heading, for example "Header" from
5784 * "== Header ==".
5785 *
5786 * @param string $text
5787 *
5788 * @return string
5789 */
5790 public function guessSectionNameFromWikiText( $text ) {
5791 # Strip out wikitext links(they break the anchor)
5792 $text = $this->stripSectionName( $text );
5793 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5794 return '#' . Sanitizer::escapeIdForLink( $text );
5795 }
5796
5797 /**
5798 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5799 * instead, if possible. For use in redirects, since various versions
5800 * of Microsoft browsers interpret Location: headers as something other
5801 * than UTF-8, resulting in breakage.
5802 *
5803 * @param string $text The section name
5804 * @return string An anchor
5805 */
5806 public function guessLegacySectionNameFromWikiText( $text ) {
5807 global $wgFragmentMode;
5808
5809 # Strip out wikitext links(they break the anchor)
5810 $text = $this->stripSectionName( $text );
5811 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5812
5813 if ( isset( $wgFragmentMode[1] ) && $wgFragmentMode[1] === 'legacy' ) {
5814 // ForAttribute() and ForLink() are the same for legacy encoding
5815 $id = Sanitizer::escapeIdForAttribute( $text, Sanitizer::ID_FALLBACK );
5816 } else {
5817 $id = Sanitizer::escapeIdForLink( $text );
5818 }
5819
5820 return "#$id";
5821 }
5822
5823 /**
5824 * Strips a text string of wikitext for use in a section anchor
5825 *
5826 * Accepts a text string and then removes all wikitext from the
5827 * string and leaves only the resultant text (i.e. the result of
5828 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5829 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5830 * to create valid section anchors by mimicing the output of the
5831 * parser when headings are parsed.
5832 *
5833 * @param string $text Text string to be stripped of wikitext
5834 * for use in a Section anchor
5835 * @return string Filtered text string
5836 */
5837 public function stripSectionName( $text ) {
5838 # Strip internal link markup
5839 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5840 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5841
5842 # Strip external link markup
5843 # @todo FIXME: Not tolerant to blank link text
5844 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5845 # on how many empty links there are on the page - need to figure that out.
5846 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5847
5848 # Parse wikitext quotes (italics & bold)
5849 $text = $this->doQuotes( $text );
5850
5851 # Strip HTML tags
5852 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5853 return $text;
5854 }
5855
5856 /**
5857 * strip/replaceVariables/unstrip for preprocessor regression testing
5858 *
5859 * @param string $text
5860 * @param Title $title
5861 * @param ParserOptions $options
5862 * @param int $outputType
5863 *
5864 * @return string
5865 */
5866 public function testSrvus( $text, Title $title, ParserOptions $options,
5867 $outputType = self::OT_HTML
5868 ) {
5869 $magicScopeVariable = $this->lock();
5870 $this->startParse( $title, $options, $outputType, true );
5871
5872 $text = $this->replaceVariables( $text );
5873 $text = $this->mStripState->unstripBoth( $text );
5874 $text = Sanitizer::removeHTMLtags( $text );
5875 return $text;
5876 }
5877
5878 /**
5879 * @param string $text
5880 * @param Title $title
5881 * @param ParserOptions $options
5882 * @return string
5883 */
5884 public function testPst( $text, Title $title, ParserOptions $options ) {
5885 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5886 }
5887
5888 /**
5889 * @param string $text
5890 * @param Title $title
5891 * @param ParserOptions $options
5892 * @return string
5893 */
5894 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
5895 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5896 }
5897
5898 /**
5899 * Call a callback function on all regions of the given text that are not
5900 * inside strip markers, and replace those regions with the return value
5901 * of the callback. For example, with input:
5902 *
5903 * aaa<MARKER>bbb
5904 *
5905 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5906 * two strings will be replaced with the value returned by the callback in
5907 * each case.
5908 *
5909 * @param string $s
5910 * @param callable $callback
5911 *
5912 * @return string
5913 */
5914 public function markerSkipCallback( $s, $callback ) {
5915 $i = 0;
5916 $out = '';
5917 while ( $i < strlen( $s ) ) {
5918 $markerStart = strpos( $s, self::MARKER_PREFIX, $i );
5919 if ( $markerStart === false ) {
5920 $out .= call_user_func( $callback, substr( $s, $i ) );
5921 break;
5922 } else {
5923 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5924 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5925 if ( $markerEnd === false ) {
5926 $out .= substr( $s, $markerStart );
5927 break;
5928 } else {
5929 $markerEnd += strlen( self::MARKER_SUFFIX );
5930 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5931 $i = $markerEnd;
5932 }
5933 }
5934 }
5935 return $out;
5936 }
5937
5938 /**
5939 * Remove any strip markers found in the given text.
5940 *
5941 * @param string $text Input string
5942 * @return string
5943 */
5944 public function killMarkers( $text ) {
5945 return $this->mStripState->killMarkers( $text );
5946 }
5947
5948 /**
5949 * Save the parser state required to convert the given half-parsed text to
5950 * HTML. "Half-parsed" in this context means the output of
5951 * recursiveTagParse() or internalParse(). This output has strip markers
5952 * from replaceVariables (extensionSubstitution() etc.), and link
5953 * placeholders from replaceLinkHolders().
5954 *
5955 * Returns an array which can be serialized and stored persistently. This
5956 * array can later be loaded into another parser instance with
5957 * unserializeHalfParsedText(). The text can then be safely incorporated into
5958 * the return value of a parser hook.
5959 *
5960 * @param string $text
5961 *
5962 * @return array
5963 */
5964 public function serializeHalfParsedText( $text ) {
5965 $data = [
5966 'text' => $text,
5967 'version' => self::HALF_PARSED_VERSION,
5968 'stripState' => $this->mStripState->getSubState( $text ),
5969 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5970 ];
5971 return $data;
5972 }
5973
5974 /**
5975 * Load the parser state given in the $data array, which is assumed to
5976 * have been generated by serializeHalfParsedText(). The text contents is
5977 * extracted from the array, and its markers are transformed into markers
5978 * appropriate for the current Parser instance. This transformed text is
5979 * returned, and can be safely included in the return value of a parser
5980 * hook.
5981 *
5982 * If the $data array has been stored persistently, the caller should first
5983 * check whether it is still valid, by calling isValidHalfParsedText().
5984 *
5985 * @param array $data Serialized data
5986 * @throws MWException
5987 * @return string
5988 */
5989 public function unserializeHalfParsedText( $data ) {
5990 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5991 throw new MWException( __METHOD__ . ': invalid version' );
5992 }
5993
5994 # First, extract the strip state.
5995 $texts = [ $data['text'] ];
5996 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5997
5998 # Now renumber links
5999 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6000
6001 # Should be good to go.
6002 return $texts[0];
6003 }
6004
6005 /**
6006 * Returns true if the given array, presumed to be generated by
6007 * serializeHalfParsedText(), is compatible with the current version of the
6008 * parser.
6009 *
6010 * @param array $data
6011 *
6012 * @return bool
6013 */
6014 public function isValidHalfParsedText( $data ) {
6015 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6016 }
6017
6018 /**
6019 * Parsed a width param of imagelink like 300px or 200x300px
6020 *
6021 * @param string $value
6022 *
6023 * @return array
6024 * @since 1.20
6025 */
6026 public function parseWidthParam( $value ) {
6027 $parsedWidthParam = [];
6028 if ( $value === '' ) {
6029 return $parsedWidthParam;
6030 }
6031 $m = [];
6032 # (T15500) In both cases (width/height and width only),
6033 # permit trailing "px" for backward compatibility.
6034 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6035 $width = intval( $m[1] );
6036 $height = intval( $m[2] );
6037 $parsedWidthParam['width'] = $width;
6038 $parsedWidthParam['height'] = $height;
6039 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6040 $width = intval( $value );
6041 $parsedWidthParam['width'] = $width;
6042 }
6043 return $parsedWidthParam;
6044 }
6045
6046 /**
6047 * Lock the current instance of the parser.
6048 *
6049 * This is meant to stop someone from calling the parser
6050 * recursively and messing up all the strip state.
6051 *
6052 * @throws MWException If parser is in a parse
6053 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6054 */
6055 protected function lock() {
6056 if ( $this->mInParse ) {
6057 throw new MWException( "Parser state cleared while parsing. "
6058 . "Did you call Parser::parse recursively? Lock is held by: " . $this->mInParse );
6059 }
6060
6061 // Save the backtrace when locking, so that if some code tries locking again,
6062 // we can print the lock owner's backtrace for easier debugging
6063 $e = new Exception;
6064 $this->mInParse = $e->getTraceAsString();
6065
6066 $recursiveCheck = new ScopedCallback( function () {
6067 $this->mInParse = false;
6068 } );
6069
6070 return $recursiveCheck;
6071 }
6072
6073 /**
6074 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6075 *
6076 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6077 * or if there is more than one <p/> tag in the input HTML.
6078 *
6079 * @param string $html
6080 * @return string
6081 * @since 1.24
6082 */
6083 public static function stripOuterParagraph( $html ) {
6084 $m = [];
6085 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6086 if ( strpos( $m[1], '</p>' ) === false ) {
6087 $html = $m[1];
6088 }
6089 }
6090
6091 return $html;
6092 }
6093
6094 /**
6095 * Return this parser if it is not doing anything, otherwise
6096 * get a fresh parser. You can use this method by doing
6097 * $myParser = $wgParser->getFreshParser(), or more simply
6098 * $wgParser->getFreshParser()->parse( ... );
6099 * if you're unsure if $wgParser is safe to use.
6100 *
6101 * @since 1.24
6102 * @return Parser A parser object that is not parsing anything
6103 */
6104 public function getFreshParser() {
6105 global $wgParserConf;
6106 if ( $this->mInParse ) {
6107 return new $wgParserConf['class']( $wgParserConf );
6108 } else {
6109 return $this;
6110 }
6111 }
6112
6113 /**
6114 * Set's up the PHP implementation of OOUI for use in this request
6115 * and instructs OutputPage to enable OOUI for itself.
6116 *
6117 * @since 1.26
6118 */
6119 public function enableOOUI() {
6120 OutputPage::setupOOUI();
6121 $this->mOutput->setEnableOOUI( true );
6122 }
6123 }