Merge "OOUI-ificiation of TablePager nav"
[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 = Parser::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 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 Hooks::run( 'ParserLimitReport', [ $this, &$limitReport ] );
554
555 // Sanitize for comment. Note '‐' in the replacement is U+2010,
556 // which looks much like the problematic '-'.
557 $limitReport = str_replace( [ '-', '&' ], [ '‐', '&amp;' ], $limitReport );
558 $text .= "\n<!-- \n$limitReport-->\n";
559
560 // Add on template profiling data in human/machine readable way
561 $dataByFunc = $this->mProfiler->getFunctionStats();
562 uasort( $dataByFunc, function ( $a, $b ) {
563 return $a['real'] < $b['real']; // descending order
564 } );
565 $profileReport = [];
566 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
567 $profileReport[] = sprintf( "%6.2f%% %8.3f %6d %s",
568 $item['%real'], $item['real'], $item['calls'],
569 htmlspecialchars( $item['name'] ) );
570 }
571 $text .= "<!--\nTransclusion expansion time report (%,ms,calls,template)\n";
572 $text .= implode( "\n", $profileReport ) . "\n-->\n";
573
574 $this->mOutput->setLimitReportData( 'limitreport-timingprofile', $profileReport );
575
576 // Add other cache related metadata
577 if ( $wgShowHostnames ) {
578 $this->mOutput->setLimitReportData( 'cachereport-origin', wfHostname() );
579 }
580 $this->mOutput->setLimitReportData( 'cachereport-timestamp',
581 $this->mOutput->getCacheTime() );
582 $this->mOutput->setLimitReportData( 'cachereport-ttl',
583 $this->mOutput->getCacheExpiry() );
584 $this->mOutput->setLimitReportData( 'cachereport-transientcontent',
585 $this->mOutput->hasDynamicContent() );
586
587 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
588 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
589 $this->mTitle->getPrefixedDBkey() );
590 }
591 }
592
593 # Wrap non-interface parser output in a <div> so it can be targeted
594 # with CSS (T37247)
595 $class = $this->mOptions->getWrapOutputClass();
596 if ( $class !== false && !$this->mOptions->getInterfaceMessage() ) {
597 $text = Html::rawElement( 'div', [ 'class' => $class ], $text );
598 }
599
600 $this->mOutput->setText( $text );
601
602 $this->mRevisionId = $oldRevisionId;
603 $this->mRevisionObject = $oldRevisionObject;
604 $this->mRevisionTimestamp = $oldRevisionTimestamp;
605 $this->mRevisionUser = $oldRevisionUser;
606 $this->mRevisionSize = $oldRevisionSize;
607 $this->mInputSize = false;
608 $this->currentRevisionCache = null;
609
610 return $this->mOutput;
611 }
612
613 /**
614 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
615 * can be called from an extension tag hook.
616 *
617 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
618 * instead, which means that lists and links have not been fully parsed yet,
619 * and strip markers are still present.
620 *
621 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
622 *
623 * Use this function if you're a parser tag hook and you want to parse
624 * wikitext before or after applying additional transformations, and you
625 * intend to *return the result as hook output*, which will cause it to go
626 * through the rest of parsing process automatically.
627 *
628 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
629 * $text are not expanded
630 *
631 * @param string $text Text extension wants to have parsed
632 * @param bool|PPFrame $frame The frame to use for expanding any template variables
633 * @return string UNSAFE half-parsed HTML
634 */
635 public function recursiveTagParse( $text, $frame = false ) {
636 // Avoid PHP 7.1 warning from passing $this by reference
637 $parser = $this;
638 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
639 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
640 $text = $this->internalParse( $text, false, $frame );
641 return $text;
642 }
643
644 /**
645 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
646 * point can be called from an extension tag hook.
647 *
648 * The output of this function is fully-parsed HTML that is safe for output.
649 * If you're a parser tag hook, you might want to use recursiveTagParse()
650 * instead.
651 *
652 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
653 * $text are not expanded
654 *
655 * @since 1.25
656 *
657 * @param string $text Text extension wants to have parsed
658 * @param bool|PPFrame $frame The frame to use for expanding any template variables
659 * @return string Fully parsed HTML
660 */
661 public function recursiveTagParseFully( $text, $frame = false ) {
662 $text = $this->recursiveTagParse( $text, $frame );
663 $text = $this->internalParseHalfParsed( $text, false );
664 return $text;
665 }
666
667 /**
668 * Expand templates and variables in the text, producing valid, static wikitext.
669 * Also removes comments.
670 * Do not call this function recursively.
671 * @param string $text
672 * @param Title $title
673 * @param ParserOptions $options
674 * @param int|null $revid
675 * @param bool|PPFrame $frame
676 * @return mixed|string
677 */
678 public function preprocess( $text, Title $title = null,
679 ParserOptions $options, $revid = null, $frame = false
680 ) {
681 $magicScopeVariable = $this->lock();
682 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
683 if ( $revid !== null ) {
684 $this->mRevisionId = $revid;
685 }
686 // Avoid PHP 7.1 warning from passing $this by reference
687 $parser = $this;
688 Hooks::run( 'ParserBeforeStrip', [ &$parser, &$text, &$this->mStripState ] );
689 Hooks::run( 'ParserAfterStrip', [ &$parser, &$text, &$this->mStripState ] );
690 $text = $this->replaceVariables( $text, $frame );
691 $text = $this->mStripState->unstripBoth( $text );
692 return $text;
693 }
694
695 /**
696 * Recursive parser entry point that can be called from an extension tag
697 * hook.
698 *
699 * @param string $text Text to be expanded
700 * @param bool|PPFrame $frame The frame to use for expanding any template variables
701 * @return string
702 * @since 1.19
703 */
704 public function recursivePreprocess( $text, $frame = false ) {
705 $text = $this->replaceVariables( $text, $frame );
706 $text = $this->mStripState->unstripBoth( $text );
707 return $text;
708 }
709
710 /**
711 * Process the wikitext for the "?preload=" feature. (T7210)
712 *
713 * "<noinclude>", "<includeonly>" etc. are parsed as for template
714 * transclusion, comments, templates, arguments, tags hooks and parser
715 * functions are untouched.
716 *
717 * @param string $text
718 * @param Title $title
719 * @param ParserOptions $options
720 * @param array $params
721 * @return string
722 */
723 public function getPreloadText( $text, Title $title, ParserOptions $options, $params = [] ) {
724 $msg = new RawMessage( $text );
725 $text = $msg->params( $params )->plain();
726
727 # Parser (re)initialisation
728 $magicScopeVariable = $this->lock();
729 $this->startParse( $title, $options, self::OT_PLAIN, true );
730
731 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
732 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
733 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
734 $text = $this->mStripState->unstripBoth( $text );
735 return $text;
736 }
737
738 /**
739 * Get a random string
740 *
741 * @return string
742 * @deprecated since 1.26; use wfRandomString() instead.
743 */
744 public static function getRandomString() {
745 wfDeprecated( __METHOD__, '1.26' );
746 return wfRandomString( 16 );
747 }
748
749 /**
750 * Set the current user.
751 * Should only be used when doing pre-save transform.
752 *
753 * @param User|null $user User object or null (to reset)
754 */
755 public function setUser( $user ) {
756 $this->mUser = $user;
757 }
758
759 /**
760 * Accessor for mUniqPrefix.
761 *
762 * @return string
763 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
764 */
765 public function uniqPrefix() {
766 wfDeprecated( __METHOD__, '1.26' );
767 return self::MARKER_PREFIX;
768 }
769
770 /**
771 * Set the context title
772 *
773 * @param Title $t
774 */
775 public function setTitle( $t ) {
776 if ( !$t ) {
777 $t = Title::newFromText( 'NO TITLE' );
778 }
779
780 if ( $t->hasFragment() ) {
781 # Strip the fragment to avoid various odd effects
782 $this->mTitle = $t->createFragmentTarget( '' );
783 } else {
784 $this->mTitle = $t;
785 }
786 }
787
788 /**
789 * Accessor for the Title object
790 *
791 * @return Title
792 */
793 public function getTitle() {
794 return $this->mTitle;
795 }
796
797 /**
798 * Accessor/mutator for the Title object
799 *
800 * @param Title $x Title object or null to just get the current one
801 * @return Title
802 */
803 public function Title( $x = null ) {
804 return wfSetVar( $this->mTitle, $x );
805 }
806
807 /**
808 * Set the output type
809 *
810 * @param int $ot New value
811 */
812 public function setOutputType( $ot ) {
813 $this->mOutputType = $ot;
814 # Shortcut alias
815 $this->ot = [
816 'html' => $ot == self::OT_HTML,
817 'wiki' => $ot == self::OT_WIKI,
818 'pre' => $ot == self::OT_PREPROCESS,
819 'plain' => $ot == self::OT_PLAIN,
820 ];
821 }
822
823 /**
824 * Accessor/mutator for the output type
825 *
826 * @param int|null $x New value or null to just get the current one
827 * @return int
828 */
829 public function OutputType( $x = null ) {
830 return wfSetVar( $this->mOutputType, $x );
831 }
832
833 /**
834 * Get the ParserOutput object
835 *
836 * @return ParserOutput
837 */
838 public function getOutput() {
839 return $this->mOutput;
840 }
841
842 /**
843 * Get the ParserOptions object
844 *
845 * @return ParserOptions
846 */
847 public function getOptions() {
848 return $this->mOptions;
849 }
850
851 /**
852 * Accessor/mutator for the ParserOptions object
853 *
854 * @param ParserOptions $x New value or null to just get the current one
855 * @return ParserOptions Current ParserOptions object
856 */
857 public function Options( $x = null ) {
858 return wfSetVar( $this->mOptions, $x );
859 }
860
861 /**
862 * @return int
863 */
864 public function nextLinkID() {
865 return $this->mLinkID++;
866 }
867
868 /**
869 * @param int $id
870 */
871 public function setLinkID( $id ) {
872 $this->mLinkID = $id;
873 }
874
875 /**
876 * Get a language object for use in parser functions such as {{FORMATNUM:}}
877 * @return Language
878 */
879 public function getFunctionLang() {
880 return $this->getTargetLanguage();
881 }
882
883 /**
884 * Get the target language for the content being parsed. This is usually the
885 * language that the content is in.
886 *
887 * @since 1.19
888 *
889 * @throws MWException
890 * @return Language
891 */
892 public function getTargetLanguage() {
893 $target = $this->mOptions->getTargetLanguage();
894
895 if ( $target !== null ) {
896 return $target;
897 } elseif ( $this->mOptions->getInterfaceMessage() ) {
898 return $this->mOptions->getUserLangObj();
899 } elseif ( is_null( $this->mTitle ) ) {
900 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
901 }
902
903 return $this->mTitle->getPageLanguage();
904 }
905
906 /**
907 * Get the language object for language conversion
908 * @return Language|null
909 */
910 public function getConverterLanguage() {
911 return $this->getTargetLanguage();
912 }
913
914 /**
915 * Get a User object either from $this->mUser, if set, or from the
916 * ParserOptions object otherwise
917 *
918 * @return User
919 */
920 public function getUser() {
921 if ( !is_null( $this->mUser ) ) {
922 return $this->mUser;
923 }
924 return $this->mOptions->getUser();
925 }
926
927 /**
928 * Get a preprocessor object
929 *
930 * @return Preprocessor
931 */
932 public function getPreprocessor() {
933 if ( !isset( $this->mPreprocessor ) ) {
934 $class = $this->mPreprocessorClass;
935 $this->mPreprocessor = new $class( $this );
936 }
937 return $this->mPreprocessor;
938 }
939
940 /**
941 * Get a LinkRenderer instance to make links with
942 *
943 * @since 1.28
944 * @return LinkRenderer
945 */
946 public function getLinkRenderer() {
947 if ( !$this->mLinkRenderer ) {
948 $this->mLinkRenderer = MediaWikiServices::getInstance()
949 ->getLinkRendererFactory()->create();
950 $this->mLinkRenderer->setStubThreshold(
951 $this->getOptions()->getStubThreshold()
952 );
953 }
954
955 return $this->mLinkRenderer;
956 }
957
958 /**
959 * Replaces all occurrences of HTML-style comments and the given tags
960 * in the text with a random marker and returns the next text. The output
961 * parameter $matches will be an associative array filled with data in
962 * the form:
963 *
964 * @code
965 * 'UNIQ-xxxxx' => [
966 * 'element',
967 * 'tag content',
968 * [ 'param' => 'x' ],
969 * '<element param="x">tag content</element>' ]
970 * @endcode
971 *
972 * @param array $elements List of element names. Comments are always extracted.
973 * @param string $text Source text string.
974 * @param array $matches Out parameter, Array: extracted tags
975 * @param string|null $uniq_prefix
976 * @return string Stripped text
977 * @since 1.26 The uniq_prefix argument is deprecated.
978 */
979 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
980 if ( $uniq_prefix !== null ) {
981 wfDeprecated( __METHOD__ . ' called with $prefix argument', '1.26' );
982 }
983 static $n = 1;
984 $stripped = '';
985 $matches = [];
986
987 $taglist = implode( '|', $elements );
988 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
989
990 while ( $text != '' ) {
991 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
992 $stripped .= $p[0];
993 if ( count( $p ) < 5 ) {
994 break;
995 }
996 if ( count( $p ) > 5 ) {
997 # comment
998 $element = $p[4];
999 $attributes = '';
1000 $close = '';
1001 $inside = $p[5];
1002 } else {
1003 # tag
1004 $element = $p[1];
1005 $attributes = $p[2];
1006 $close = $p[3];
1007 $inside = $p[4];
1008 }
1009
1010 $marker = self::MARKER_PREFIX . "-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
1011 $stripped .= $marker;
1012
1013 if ( $close === '/>' ) {
1014 # Empty element tag, <tag />
1015 $content = null;
1016 $text = $inside;
1017 $tail = null;
1018 } else {
1019 if ( $element === '!--' ) {
1020 $end = '/(-->)/';
1021 } else {
1022 $end = "/(<\\/$element\\s*>)/i";
1023 }
1024 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
1025 $content = $q[0];
1026 if ( count( $q ) < 3 ) {
1027 # No end tag -- let it run out to the end of the text.
1028 $tail = '';
1029 $text = '';
1030 } else {
1031 $tail = $q[1];
1032 $text = $q[2];
1033 }
1034 }
1035
1036 $matches[$marker] = [ $element,
1037 $content,
1038 Sanitizer::decodeTagAttributes( $attributes ),
1039 "<$element$attributes$close$content$tail" ];
1040 }
1041 return $stripped;
1042 }
1043
1044 /**
1045 * Get a list of strippable XML-like elements
1046 *
1047 * @return array
1048 */
1049 public function getStripList() {
1050 return $this->mStripList;
1051 }
1052
1053 /**
1054 * Add an item to the strip state
1055 * Returns the unique tag which must be inserted into the stripped text
1056 * The tag will be replaced with the original text in unstrip()
1057 *
1058 * @param string $text
1059 *
1060 * @return string
1061 */
1062 public function insertStripItem( $text ) {
1063 $marker = self::MARKER_PREFIX . "-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
1064 $this->mMarkerIndex++;
1065 $this->mStripState->addGeneral( $marker, $text );
1066 return $marker;
1067 }
1068
1069 /**
1070 * parse the wiki syntax used to render tables
1071 *
1072 * @private
1073 * @param string $text
1074 * @return string
1075 */
1076 public function doTableStuff( $text ) {
1077
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
1282 $origText = $text;
1283
1284 // Avoid PHP 7.1 warning from passing $this by reference
1285 $parser = $this;
1286
1287 # Hook to suspend the parser in this state
1288 if ( !Hooks::run( 'ParserBeforeInternalParse', [ &$parser, &$text, &$this->mStripState ] ) ) {
1289 return $text;
1290 }
1291
1292 # if $frame is provided, then use $frame for replacing any variables
1293 if ( $frame ) {
1294 # use frame depth to infer how include/noinclude tags should be handled
1295 # depth=0 means this is the top-level document; otherwise it's an included document
1296 if ( !$frame->depth ) {
1297 $flag = 0;
1298 } else {
1299 $flag = Parser::PTD_FOR_INCLUSION;
1300 }
1301 $dom = $this->preprocessToDom( $text, $flag );
1302 $text = $frame->expand( $dom );
1303 } else {
1304 # if $frame is not provided, then use old-style replaceVariables
1305 $text = $this->replaceVariables( $text );
1306 }
1307
1308 Hooks::run( 'InternalParseBeforeSanitize', [ &$parser, &$text, &$this->mStripState ] );
1309 $text = Sanitizer::removeHTMLtags(
1310 $text,
1311 [ $this, 'attributeStripCallback' ],
1312 false,
1313 array_keys( $this->mTransparentTagHooks ),
1314 [],
1315 [ $this, 'addTrackingCategory' ]
1316 );
1317 Hooks::run( 'InternalParseBeforeLinks', [ &$parser, &$text, &$this->mStripState ] );
1318
1319 # Tables need to come after variable replacement for things to work
1320 # properly; putting them before other transformations should keep
1321 # exciting things like link expansions from showing up in surprising
1322 # places.
1323 $text = $this->doTableStuff( $text );
1324
1325 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1326
1327 $text = $this->doDoubleUnderscore( $text );
1328
1329 $text = $this->doHeadings( $text );
1330 $text = $this->replaceInternalLinks( $text );
1331 $text = $this->doAllQuotes( $text );
1332 $text = $this->replaceExternalLinks( $text );
1333
1334 # replaceInternalLinks may sometimes leave behind
1335 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1336 $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text );
1337
1338 $text = $this->doMagicLinks( $text );
1339 $text = $this->formatHeadings( $text, $origText, $isMain );
1340
1341 return $text;
1342 }
1343
1344 /**
1345 * Helper function for parse() that transforms half-parsed HTML into fully
1346 * parsed HTML.
1347 *
1348 * @param string $text
1349 * @param bool $isMain
1350 * @param bool $linestart
1351 * @return string
1352 */
1353 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1354 $text = $this->mStripState->unstripGeneral( $text );
1355
1356 // Avoid PHP 7.1 warning from passing $this by reference
1357 $parser = $this;
1358
1359 if ( $isMain ) {
1360 Hooks::run( 'ParserAfterUnstrip', [ &$parser, &$text ] );
1361 }
1362
1363 # Clean up special characters, only run once, next-to-last before doBlockLevels
1364 $fixtags = [
1365 # French spaces, last one Guillemet-left
1366 # only if there is something before the space
1367 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
1368 # french spaces, Guillemet-right
1369 '/(\\302\\253) /' => '\\1&#160;',
1370 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, T13874.
1371 ];
1372 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1373
1374 $text = $this->doBlockLevels( $text, $linestart );
1375
1376 $this->replaceLinkHolders( $text );
1377
1378 /**
1379 * The input doesn't get language converted if
1380 * a) It's disabled
1381 * b) Content isn't converted
1382 * c) It's a conversion table
1383 * d) it is an interface message (which is in the user language)
1384 */
1385 if ( !( $this->mOptions->getDisableContentConversion()
1386 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
1387 ) {
1388 if ( !$this->mOptions->getInterfaceMessage() ) {
1389 # The position of the convert() call should not be changed. it
1390 # assumes that the links are all replaced and the only thing left
1391 # is the <nowiki> mark.
1392 $text = $this->getConverterLanguage()->convert( $text );
1393 }
1394 }
1395
1396 $text = $this->mStripState->unstripNoWiki( $text );
1397
1398 if ( $isMain ) {
1399 Hooks::run( 'ParserBeforeTidy', [ &$parser, &$text ] );
1400 }
1401
1402 $text = $this->replaceTransparentTags( $text );
1403 $text = $this->mStripState->unstripGeneral( $text );
1404
1405 $text = Sanitizer::normalizeCharReferences( $text );
1406
1407 if ( MWTidy::isEnabled() ) {
1408 if ( $this->mOptions->getTidy() ) {
1409 $text = MWTidy::tidy( $text );
1410 }
1411 } else {
1412 # attempt to sanitize at least some nesting problems
1413 # (T4702 and quite a few others)
1414 $tidyregs = [
1415 # ''Something [http://www.cool.com cool''] -->
1416 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1417 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1418 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1419 # fix up an anchor inside another anchor, only
1420 # at least for a single single nested link (T5695)
1421 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1422 '\\1\\2</a>\\3</a>\\1\\4</a>',
1423 # fix div inside inline elements- doBlockLevels won't wrap a line which
1424 # contains a div, so fix it up here; replace
1425 # div with escaped text
1426 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1427 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
1428 # remove empty italic or bold tag pairs, some
1429 # introduced by rules above
1430 '/<([bi])><\/\\1>/' => '',
1431 ];
1432
1433 $text = preg_replace(
1434 array_keys( $tidyregs ),
1435 array_values( $tidyregs ),
1436 $text );
1437 }
1438
1439 if ( $isMain ) {
1440 Hooks::run( 'ParserAfterTidy', [ &$parser, &$text ] );
1441 }
1442
1443 return $text;
1444 }
1445
1446 /**
1447 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1448 * magic external links.
1449 *
1450 * DML
1451 * @private
1452 *
1453 * @param string $text
1454 *
1455 * @return string
1456 */
1457 public function doMagicLinks( $text ) {
1458 $prots = wfUrlProtocolsWithoutProtRel();
1459 $urlChar = self::EXT_LINK_URL_CLASS;
1460 $addr = self::EXT_LINK_ADDR;
1461 $space = self::SPACE_NOT_NL; # non-newline space
1462 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1463 $spaces = "$space++"; # possessive match of 1 or more spaces
1464 $text = preg_replace_callback(
1465 '!(?: # Start cases
1466 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1467 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1468 (\b # m[3]: Free external links
1469 (?i:$prots)
1470 ($addr$urlChar*) # m[4]: Post-protocol path
1471 ) |
1472 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1473 ([0-9]+)\b |
1474 \bISBN $spaces ( # m[6]: ISBN, capture number
1475 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1476 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1477 [0-9Xx] # check digit
1478 )\b
1479 )!xu", [ $this, 'magicLinkCallback' ], $text );
1480 return $text;
1481 }
1482
1483 /**
1484 * @throws MWException
1485 * @param array $m
1486 * @return HTML|string
1487 */
1488 public function magicLinkCallback( $m ) {
1489 if ( isset( $m[1] ) && $m[1] !== '' ) {
1490 # Skip anchor
1491 return $m[0];
1492 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1493 # Skip HTML element
1494 return $m[0];
1495 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1496 # Free external link
1497 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1498 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1499 # RFC or PMID
1500 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1501 if ( !$this->mOptions->getMagicRFCLinks() ) {
1502 return $m[0];
1503 }
1504 $keyword = 'RFC';
1505 $urlmsg = 'rfcurl';
1506 $cssClass = 'mw-magiclink-rfc';
1507 $trackingCat = 'magiclink-tracking-rfc';
1508 $id = $m[5];
1509 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1510 if ( !$this->mOptions->getMagicPMIDLinks() ) {
1511 return $m[0];
1512 }
1513 $keyword = 'PMID';
1514 $urlmsg = 'pubmedurl';
1515 $cssClass = 'mw-magiclink-pmid';
1516 $trackingCat = 'magiclink-tracking-pmid';
1517 $id = $m[5];
1518 } else {
1519 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1520 substr( $m[0], 0, 20 ) . '"' );
1521 }
1522 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1523 $this->addTrackingCategory( $trackingCat );
1524 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass, [], $this->mTitle );
1525 } elseif ( isset( $m[6] ) && $m[6] !== ''
1526 && $this->mOptions->getMagicISBNLinks()
1527 ) {
1528 # ISBN
1529 $isbn = $m[6];
1530 $space = self::SPACE_NOT_NL; # non-newline space
1531 $isbn = preg_replace( "/$space/", ' ', $isbn );
1532 $num = strtr( $isbn, [
1533 '-' => '',
1534 ' ' => '',
1535 'x' => 'X',
1536 ] );
1537 $this->addTrackingCategory( 'magiclink-tracking-isbn' );
1538 return $this->getLinkRenderer()->makeKnownLink(
1539 SpecialPage::getTitleFor( 'Booksources', $num ),
1540 "ISBN $isbn",
1541 [
1542 'class' => 'internal mw-magiclink-isbn',
1543 'title' => false // suppress title attribute
1544 ]
1545 );
1546 } else {
1547 return $m[0];
1548 }
1549 }
1550
1551 /**
1552 * Make a free external link, given a user-supplied URL
1553 *
1554 * @param string $url
1555 * @param int $numPostProto
1556 * The number of characters after the protocol.
1557 * @return string HTML
1558 * @private
1559 */
1560 public function makeFreeExternalLink( $url, $numPostProto ) {
1561 $trail = '';
1562
1563 # The characters '<' and '>' (which were escaped by
1564 # removeHTMLtags()) should not be included in
1565 # URLs, per RFC 2396.
1566 # Make &nbsp; terminate a URL as well (bug T84937)
1567 $m2 = [];
1568 if ( preg_match(
1569 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1570 $url,
1571 $m2,
1572 PREG_OFFSET_CAPTURE
1573 ) ) {
1574 $trail = substr( $url, $m2[0][1] ) . $trail;
1575 $url = substr( $url, 0, $m2[0][1] );
1576 }
1577
1578 # Move trailing punctuation to $trail
1579 $sep = ',;\.:!?';
1580 # If there is no left bracket, then consider right brackets fair game too
1581 if ( strpos( $url, '(' ) === false ) {
1582 $sep .= ')';
1583 }
1584
1585 $urlRev = strrev( $url );
1586 $numSepChars = strspn( $urlRev, $sep );
1587 # Don't break a trailing HTML entity by moving the ; into $trail
1588 # This is in hot code, so use substr_compare to avoid having to
1589 # create a new string object for the comparison
1590 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1591 # more optimization: instead of running preg_match with a $
1592 # anchor, which can be slow, do the match on the reversed
1593 # string starting at the desired offset.
1594 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1595 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1596 $numSepChars--;
1597 }
1598 }
1599 if ( $numSepChars ) {
1600 $trail = substr( $url, -$numSepChars ) . $trail;
1601 $url = substr( $url, 0, -$numSepChars );
1602 }
1603
1604 # Verify that we still have a real URL after trail removal, and
1605 # not just lone protocol
1606 if ( strlen( $trail ) >= $numPostProto ) {
1607 return $url . $trail;
1608 }
1609
1610 $url = Sanitizer::cleanUrl( $url );
1611
1612 # Is this an external image?
1613 $text = $this->maybeMakeExternalImage( $url );
1614 if ( $text === false ) {
1615 # Not an image, make a link
1616 $text = Linker::makeExternalLink( $url,
1617 $this->getConverterLanguage()->markNoConversion( $url, true ),
1618 true, 'free',
1619 $this->getExternalLinkAttribs( $url ), $this->mTitle );
1620 # Register it in the output object...
1621 $this->mOutput->addExternalLink( $url );
1622 }
1623 return $text . $trail;
1624 }
1625
1626 /**
1627 * Parse headers and return html
1628 *
1629 * @private
1630 *
1631 * @param string $text
1632 *
1633 * @return string
1634 */
1635 public function doHeadings( $text ) {
1636 for ( $i = 6; $i >= 1; --$i ) {
1637 $h = str_repeat( '=', $i );
1638 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1639 }
1640 return $text;
1641 }
1642
1643 /**
1644 * Replace single quotes with HTML markup
1645 * @private
1646 *
1647 * @param string $text
1648 *
1649 * @return string The altered text
1650 */
1651 public function doAllQuotes( $text ) {
1652 $outtext = '';
1653 $lines = StringUtils::explode( "\n", $text );
1654 foreach ( $lines as $line ) {
1655 $outtext .= $this->doQuotes( $line ) . "\n";
1656 }
1657 $outtext = substr( $outtext, 0, -1 );
1658 return $outtext;
1659 }
1660
1661 /**
1662 * Helper function for doAllQuotes()
1663 *
1664 * @param string $text
1665 *
1666 * @return string
1667 */
1668 public function doQuotes( $text ) {
1669 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1670 $countarr = count( $arr );
1671 if ( $countarr == 1 ) {
1672 return $text;
1673 }
1674
1675 // First, do some preliminary work. This may shift some apostrophes from
1676 // being mark-up to being text. It also counts the number of occurrences
1677 // of bold and italics mark-ups.
1678 $numbold = 0;
1679 $numitalics = 0;
1680 for ( $i = 1; $i < $countarr; $i += 2 ) {
1681 $thislen = strlen( $arr[$i] );
1682 // If there are ever four apostrophes, assume the first is supposed to
1683 // be text, and the remaining three constitute mark-up for bold text.
1684 // (T15227: ''''foo'''' turns into ' ''' foo ' ''')
1685 if ( $thislen == 4 ) {
1686 $arr[$i - 1] .= "'";
1687 $arr[$i] = "'''";
1688 $thislen = 3;
1689 } elseif ( $thislen > 5 ) {
1690 // If there are more than 5 apostrophes in a row, assume they're all
1691 // text except for the last 5.
1692 // (T15227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1693 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1694 $arr[$i] = "'''''";
1695 $thislen = 5;
1696 }
1697 // Count the number of occurrences of bold and italics mark-ups.
1698 if ( $thislen == 2 ) {
1699 $numitalics++;
1700 } elseif ( $thislen == 3 ) {
1701 $numbold++;
1702 } elseif ( $thislen == 5 ) {
1703 $numitalics++;
1704 $numbold++;
1705 }
1706 }
1707
1708 // If there is an odd number of both bold and italics, it is likely
1709 // that one of the bold ones was meant to be an apostrophe followed
1710 // by italics. Which one we cannot know for certain, but it is more
1711 // likely to be one that has a single-letter word before it.
1712 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1713 $firstsingleletterword = -1;
1714 $firstmultiletterword = -1;
1715 $firstspace = -1;
1716 for ( $i = 1; $i < $countarr; $i += 2 ) {
1717 if ( strlen( $arr[$i] ) == 3 ) {
1718 $x1 = substr( $arr[$i - 1], -1 );
1719 $x2 = substr( $arr[$i - 1], -2, 1 );
1720 if ( $x1 === ' ' ) {
1721 if ( $firstspace == -1 ) {
1722 $firstspace = $i;
1723 }
1724 } elseif ( $x2 === ' ' ) {
1725 $firstsingleletterword = $i;
1726 // if $firstsingleletterword is set, we don't
1727 // look at the other options, so we can bail early.
1728 break;
1729 } else {
1730 if ( $firstmultiletterword == -1 ) {
1731 $firstmultiletterword = $i;
1732 }
1733 }
1734 }
1735 }
1736
1737 // If there is a single-letter word, use it!
1738 if ( $firstsingleletterword > -1 ) {
1739 $arr[$firstsingleletterword] = "''";
1740 $arr[$firstsingleletterword - 1] .= "'";
1741 } elseif ( $firstmultiletterword > -1 ) {
1742 // If not, but there's a multi-letter word, use that one.
1743 $arr[$firstmultiletterword] = "''";
1744 $arr[$firstmultiletterword - 1] .= "'";
1745 } elseif ( $firstspace > -1 ) {
1746 // ... otherwise use the first one that has neither.
1747 // (notice that it is possible for all three to be -1 if, for example,
1748 // there is only one pentuple-apostrophe in the line)
1749 $arr[$firstspace] = "''";
1750 $arr[$firstspace - 1] .= "'";
1751 }
1752 }
1753
1754 // Now let's actually convert our apostrophic mush to HTML!
1755 $output = '';
1756 $buffer = '';
1757 $state = '';
1758 $i = 0;
1759 foreach ( $arr as $r ) {
1760 if ( ( $i % 2 ) == 0 ) {
1761 if ( $state === 'both' ) {
1762 $buffer .= $r;
1763 } else {
1764 $output .= $r;
1765 }
1766 } else {
1767 $thislen = strlen( $r );
1768 if ( $thislen == 2 ) {
1769 if ( $state === 'i' ) {
1770 $output .= '</i>';
1771 $state = '';
1772 } elseif ( $state === 'bi' ) {
1773 $output .= '</i>';
1774 $state = 'b';
1775 } elseif ( $state === 'ib' ) {
1776 $output .= '</b></i><b>';
1777 $state = 'b';
1778 } elseif ( $state === 'both' ) {
1779 $output .= '<b><i>' . $buffer . '</i>';
1780 $state = 'b';
1781 } else { // $state can be 'b' or ''
1782 $output .= '<i>';
1783 $state .= 'i';
1784 }
1785 } elseif ( $thislen == 3 ) {
1786 if ( $state === 'b' ) {
1787 $output .= '</b>';
1788 $state = '';
1789 } elseif ( $state === 'bi' ) {
1790 $output .= '</i></b><i>';
1791 $state = 'i';
1792 } elseif ( $state === 'ib' ) {
1793 $output .= '</b>';
1794 $state = 'i';
1795 } elseif ( $state === 'both' ) {
1796 $output .= '<i><b>' . $buffer . '</b>';
1797 $state = 'i';
1798 } else { // $state can be 'i' or ''
1799 $output .= '<b>';
1800 $state .= 'b';
1801 }
1802 } elseif ( $thislen == 5 ) {
1803 if ( $state === 'b' ) {
1804 $output .= '</b><i>';
1805 $state = 'i';
1806 } elseif ( $state === 'i' ) {
1807 $output .= '</i><b>';
1808 $state = 'b';
1809 } elseif ( $state === 'bi' ) {
1810 $output .= '</i></b>';
1811 $state = '';
1812 } elseif ( $state === 'ib' ) {
1813 $output .= '</b></i>';
1814 $state = '';
1815 } elseif ( $state === 'both' ) {
1816 $output .= '<i><b>' . $buffer . '</b></i>';
1817 $state = '';
1818 } else { // ($state == '')
1819 $buffer = '';
1820 $state = 'both';
1821 }
1822 }
1823 }
1824 $i++;
1825 }
1826 // Now close all remaining tags. Notice that the order is important.
1827 if ( $state === 'b' || $state === 'ib' ) {
1828 $output .= '</b>';
1829 }
1830 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1831 $output .= '</i>';
1832 }
1833 if ( $state === 'bi' ) {
1834 $output .= '</b>';
1835 }
1836 // There might be lonely ''''', so make sure we have a buffer
1837 if ( $state === 'both' && $buffer ) {
1838 $output .= '<b><i>' . $buffer . '</i></b>';
1839 }
1840 return $output;
1841 }
1842
1843 /**
1844 * Replace external links (REL)
1845 *
1846 * Note: this is all very hackish and the order of execution matters a lot.
1847 * Make sure to run tests/parser/parserTests.php if you change this code.
1848 *
1849 * @private
1850 *
1851 * @param string $text
1852 *
1853 * @throws MWException
1854 * @return string
1855 */
1856 public function replaceExternalLinks( $text ) {
1857
1858 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1859 if ( $bits === false ) {
1860 throw new MWException( "PCRE needs to be compiled with "
1861 . "--enable-unicode-properties in order for MediaWiki to function" );
1862 }
1863 $s = array_shift( $bits );
1864
1865 $i = 0;
1866 while ( $i < count( $bits ) ) {
1867 $url = $bits[$i++];
1868 $i++; // protocol
1869 $text = $bits[$i++];
1870 $trail = $bits[$i++];
1871
1872 # The characters '<' and '>' (which were escaped by
1873 # removeHTMLtags()) should not be included in
1874 # URLs, per RFC 2396.
1875 $m2 = [];
1876 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1877 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1878 $url = substr( $url, 0, $m2[0][1] );
1879 }
1880
1881 # If the link text is an image URL, replace it with an <img> tag
1882 # This happened by accident in the original parser, but some people used it extensively
1883 $img = $this->maybeMakeExternalImage( $text );
1884 if ( $img !== false ) {
1885 $text = $img;
1886 }
1887
1888 $dtrail = '';
1889
1890 # Set linktype for CSS - if URL==text, link is essentially free
1891 $linktype = ( $text === $url ) ? 'free' : 'text';
1892
1893 # No link text, e.g. [http://domain.tld/some.link]
1894 if ( $text == '' ) {
1895 # Autonumber
1896 $langObj = $this->getTargetLanguage();
1897 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1898 $linktype = 'autonumber';
1899 } else {
1900 # Have link text, e.g. [http://domain.tld/some.link text]s
1901 # Check for trail
1902 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1903 }
1904
1905 $text = $this->getConverterLanguage()->markNoConversion( $text );
1906
1907 $url = Sanitizer::cleanUrl( $url );
1908
1909 # Use the encoded URL
1910 # This means that users can paste URLs directly into the text
1911 # Funny characters like ö aren't valid in URLs anyway
1912 # This was changed in August 2004
1913 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1914 $this->getExternalLinkAttribs( $url ), $this->mTitle ) . $dtrail . $trail;
1915
1916 # Register link in the output object.
1917 $this->mOutput->addExternalLink( $url );
1918 }
1919
1920 return $s;
1921 }
1922
1923 /**
1924 * Get the rel attribute for a particular external link.
1925 *
1926 * @since 1.21
1927 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1928 * nofollow if appropriate
1929 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1930 * @return string|null Rel attribute for $url
1931 */
1932 public static function getExternalLinkRel( $url = false, $title = null ) {
1933 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1934 $ns = $title ? $title->getNamespace() : false;
1935 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1936 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1937 ) {
1938 return 'nofollow';
1939 }
1940 return null;
1941 }
1942
1943 /**
1944 * Get an associative array of additional HTML attributes appropriate for a
1945 * particular external link. This currently may include rel => nofollow
1946 * (depending on configuration, namespace, and the URL's domain) and/or a
1947 * target attribute (depending on configuration).
1948 *
1949 * @param string $url URL to extract the domain from for rel =>
1950 * nofollow if appropriate
1951 * @return array Associative array of HTML attributes
1952 */
1953 public function getExternalLinkAttribs( $url ) {
1954 $attribs = [];
1955 $rel = self::getExternalLinkRel( $url, $this->mTitle );
1956
1957 $target = $this->mOptions->getExternalLinkTarget();
1958 if ( $target ) {
1959 $attribs['target'] = $target;
1960 if ( !in_array( $target, [ '_self', '_parent', '_top' ] ) ) {
1961 // T133507. New windows can navigate parent cross-origin.
1962 // Including noreferrer due to lacking browser
1963 // support of noopener. Eventually noreferrer should be removed.
1964 if ( $rel !== '' ) {
1965 $rel .= ' ';
1966 }
1967 $rel .= 'noreferrer noopener';
1968 }
1969 }
1970 $attribs['rel'] = $rel;
1971 return $attribs;
1972 }
1973
1974 /**
1975 * Replace unusual escape codes in a URL with their equivalent characters
1976 *
1977 * This generally follows the syntax defined in RFC 3986, with special
1978 * consideration for HTTP query strings.
1979 *
1980 * @param string $url
1981 * @return string
1982 */
1983 public static function normalizeLinkUrl( $url ) {
1984 # First, make sure unsafe characters are encoded
1985 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1986 function ( $m ) {
1987 return rawurlencode( $m[0] );
1988 },
1989 $url
1990 );
1991
1992 $ret = '';
1993 $end = strlen( $url );
1994
1995 # Fragment part - 'fragment'
1996 $start = strpos( $url, '#' );
1997 if ( $start !== false && $start < $end ) {
1998 $ret = self::normalizeUrlComponent(
1999 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
2000 $end = $start;
2001 }
2002
2003 # Query part - 'query' minus &=+;
2004 $start = strpos( $url, '?' );
2005 if ( $start !== false && $start < $end ) {
2006 $ret = self::normalizeUrlComponent(
2007 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
2008 $end = $start;
2009 }
2010
2011 # Scheme and path part - 'pchar'
2012 # (we assume no userinfo or encoded colons in the host)
2013 $ret = self::normalizeUrlComponent(
2014 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
2015
2016 return $ret;
2017 }
2018
2019 private static function normalizeUrlComponent( $component, $unsafe ) {
2020 $callback = function ( $matches ) use ( $unsafe ) {
2021 $char = urldecode( $matches[0] );
2022 $ord = ord( $char );
2023 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
2024 # Unescape it
2025 return $char;
2026 } else {
2027 # Leave it escaped, but use uppercase for a-f
2028 return strtoupper( $matches[0] );
2029 }
2030 };
2031 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
2032 }
2033
2034 /**
2035 * make an image if it's allowed, either through the global
2036 * option, through the exception, or through the on-wiki whitelist
2037 *
2038 * @param string $url
2039 *
2040 * @return string
2041 */
2042 private function maybeMakeExternalImage( $url ) {
2043 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
2044 $imagesexception = !empty( $imagesfrom );
2045 $text = false;
2046 # $imagesfrom could be either a single string or an array of strings, parse out the latter
2047 if ( $imagesexception && is_array( $imagesfrom ) ) {
2048 $imagematch = false;
2049 foreach ( $imagesfrom as $match ) {
2050 if ( strpos( $url, $match ) === 0 ) {
2051 $imagematch = true;
2052 break;
2053 }
2054 }
2055 } elseif ( $imagesexception ) {
2056 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
2057 } else {
2058 $imagematch = false;
2059 }
2060
2061 if ( $this->mOptions->getAllowExternalImages()
2062 || ( $imagesexception && $imagematch )
2063 ) {
2064 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
2065 # Image found
2066 $text = Linker::makeExternalImage( $url );
2067 }
2068 }
2069 if ( !$text && $this->mOptions->getEnableImageWhitelist()
2070 && preg_match( self::EXT_IMAGE_REGEX, $url )
2071 ) {
2072 $whitelist = explode(
2073 "\n",
2074 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
2075 );
2076
2077 foreach ( $whitelist as $entry ) {
2078 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2079 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
2080 continue;
2081 }
2082 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2083 # Image matches a whitelist entry
2084 $text = Linker::makeExternalImage( $url );
2085 break;
2086 }
2087 }
2088 }
2089 return $text;
2090 }
2091
2092 /**
2093 * Process [[ ]] wikilinks
2094 *
2095 * @param string $s
2096 *
2097 * @return string Processed text
2098 *
2099 * @private
2100 */
2101 public function replaceInternalLinks( $s ) {
2102 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
2103 return $s;
2104 }
2105
2106 /**
2107 * Process [[ ]] wikilinks (RIL)
2108 * @param string $s
2109 * @throws MWException
2110 * @return LinkHolderArray
2111 *
2112 * @private
2113 */
2114 public function replaceInternalLinks2( &$s ) {
2115 global $wgExtraInterlanguageLinkPrefixes;
2116
2117 static $tc = false, $e1, $e1_img;
2118 # the % is needed to support urlencoded titles as well
2119 if ( !$tc ) {
2120 $tc = Title::legalChars() . '#%';
2121 # Match a link having the form [[namespace:link|alternate]]trail
2122 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2123 # Match cases where there is no "]]", which might still be images
2124 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2125 }
2126
2127 $holders = new LinkHolderArray( $this );
2128
2129 # split the entire text string on occurrences of [[
2130 $a = StringUtils::explode( '[[', ' ' . $s );
2131 # get the first element (all text up to first [[), and remove the space we added
2132 $s = $a->current();
2133 $a->next();
2134 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2135 $s = substr( $s, 1 );
2136
2137 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2138 $e2 = null;
2139 if ( $useLinkPrefixExtension ) {
2140 # Match the end of a line for a word that's not followed by whitespace,
2141 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2142 global $wgContLang;
2143 $charset = $wgContLang->linkPrefixCharset();
2144 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2145 }
2146
2147 if ( is_null( $this->mTitle ) ) {
2148 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
2149 }
2150 $nottalk = !$this->mTitle->isTalkPage();
2151
2152 if ( $useLinkPrefixExtension ) {
2153 $m = [];
2154 if ( preg_match( $e2, $s, $m ) ) {
2155 $first_prefix = $m[2];
2156 } else {
2157 $first_prefix = false;
2158 }
2159 } else {
2160 $prefix = '';
2161 }
2162
2163 $useSubpages = $this->areSubpagesAllowed();
2164
2165 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2166 # Loop for each link
2167 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2168 // @codingStandardsIgnoreEnd
2169
2170 # Check for excessive memory usage
2171 if ( $holders->isBig() ) {
2172 # Too big
2173 # Do the existence check, replace the link holders and clear the array
2174 $holders->replace( $s );
2175 $holders->clear();
2176 }
2177
2178 if ( $useLinkPrefixExtension ) {
2179 if ( preg_match( $e2, $s, $m ) ) {
2180 $prefix = $m[2];
2181 $s = $m[1];
2182 } else {
2183 $prefix = '';
2184 }
2185 # first link
2186 if ( $first_prefix ) {
2187 $prefix = $first_prefix;
2188 $first_prefix = false;
2189 }
2190 }
2191
2192 $might_be_img = false;
2193
2194 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2195 $text = $m[2];
2196 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2197 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2198 # the real problem is with the $e1 regex
2199 # See T1500.
2200 # Still some problems for cases where the ] is meant to be outside punctuation,
2201 # and no image is in sight. See T4095.
2202 if ( $text !== ''
2203 && substr( $m[3], 0, 1 ) === ']'
2204 && strpos( $text, '[' ) !== false
2205 ) {
2206 $text .= ']'; # so that replaceExternalLinks($text) works later
2207 $m[3] = substr( $m[3], 1 );
2208 }
2209 # fix up urlencoded title texts
2210 if ( strpos( $m[1], '%' ) !== false ) {
2211 # Should anchors '#' also be rejected?
2212 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2213 }
2214 $trail = $m[3];
2215 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2216 # Invalid, but might be an image with a link in its caption
2217 $might_be_img = true;
2218 $text = $m[2];
2219 if ( strpos( $m[1], '%' ) !== false ) {
2220 $m[1] = str_replace( [ '<', '>' ], [ '&lt;', '&gt;' ], rawurldecode( $m[1] ) );
2221 }
2222 $trail = "";
2223 } else { # Invalid form; output directly
2224 $s .= $prefix . '[[' . $line;
2225 continue;
2226 }
2227
2228 $origLink = ltrim( $m[1], ' ' );
2229
2230 # Don't allow internal links to pages containing
2231 # PROTO: where PROTO is a valid URL protocol; these
2232 # should be external links.
2233 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $origLink ) ) {
2234 $s .= $prefix . '[[' . $line;
2235 continue;
2236 }
2237
2238 # Make subpage if necessary
2239 if ( $useSubpages ) {
2240 $link = $this->maybeDoSubpageLink( $origLink, $text );
2241 } else {
2242 $link = $origLink;
2243 }
2244
2245 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2246 if ( !$noforce ) {
2247 # Strip off leading ':'
2248 $link = substr( $link, 1 );
2249 }
2250
2251 $unstrip = $this->mStripState->unstripNoWiki( $link );
2252 $nt = is_string( $unstrip ) ? Title::newFromText( $unstrip ) : null;
2253 if ( $nt === null ) {
2254 $s .= $prefix . '[[' . $line;
2255 continue;
2256 }
2257
2258 $ns = $nt->getNamespace();
2259 $iw = $nt->getInterwiki();
2260
2261 if ( $might_be_img ) { # if this is actually an invalid link
2262 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2263 $found = false;
2264 while ( true ) {
2265 # look at the next 'line' to see if we can close it there
2266 $a->next();
2267 $next_line = $a->current();
2268 if ( $next_line === false || $next_line === null ) {
2269 break;
2270 }
2271 $m = explode( ']]', $next_line, 3 );
2272 if ( count( $m ) == 3 ) {
2273 # the first ]] closes the inner link, the second the image
2274 $found = true;
2275 $text .= "[[{$m[0]}]]{$m[1]}";
2276 $trail = $m[2];
2277 break;
2278 } elseif ( count( $m ) == 2 ) {
2279 # if there's exactly one ]] that's fine, we'll keep looking
2280 $text .= "[[{$m[0]}]]{$m[1]}";
2281 } else {
2282 # if $next_line is invalid too, we need look no further
2283 $text .= '[[' . $next_line;
2284 break;
2285 }
2286 }
2287 if ( !$found ) {
2288 # we couldn't find the end of this imageLink, so output it raw
2289 # but don't ignore what might be perfectly normal links in the text we've examined
2290 $holders->merge( $this->replaceInternalLinks2( $text ) );
2291 $s .= "{$prefix}[[$link|$text";
2292 # note: no $trail, because without an end, there *is* no trail
2293 continue;
2294 }
2295 } else { # it's not an image, so output it raw
2296 $s .= "{$prefix}[[$link|$text";
2297 # note: no $trail, because without an end, there *is* no trail
2298 continue;
2299 }
2300 }
2301
2302 $wasblank = ( $text == '' );
2303 if ( $wasblank ) {
2304 $text = $link;
2305 } else {
2306 # T6598 madness. Handle the quotes only if they come from the alternate part
2307 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2308 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2309 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2310 $text = $this->doQuotes( $text );
2311 }
2312
2313 # Link not escaped by : , create the various objects
2314 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2315 # Interwikis
2316 if (
2317 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2318 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2319 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2320 )
2321 ) {
2322 # T26502: filter duplicates
2323 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2324 $this->mLangLinkLanguages[$iw] = true;
2325 $this->mOutput->addLanguageLink( $nt->getFullText() );
2326 }
2327
2328 $s = rtrim( $s . $prefix );
2329 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2330 continue;
2331 }
2332
2333 if ( $ns == NS_FILE ) {
2334 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2335 if ( $wasblank ) {
2336 # if no parameters were passed, $text
2337 # becomes something like "File:Foo.png",
2338 # which we don't want to pass on to the
2339 # image generator
2340 $text = '';
2341 } else {
2342 # recursively parse links inside the image caption
2343 # actually, this will parse them in any other parameters, too,
2344 # but it might be hard to fix that, and it doesn't matter ATM
2345 $text = $this->replaceExternalLinks( $text );
2346 $holders->merge( $this->replaceInternalLinks2( $text ) );
2347 }
2348 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2349 $s .= $prefix . $this->armorLinks(
2350 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2351 continue;
2352 }
2353 } elseif ( $ns == NS_CATEGORY ) {
2354 $s = rtrim( $s . "\n" ); # T2087
2355
2356 if ( $wasblank ) {
2357 $sortkey = $this->getDefaultSort();
2358 } else {
2359 $sortkey = $text;
2360 }
2361 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2362 $sortkey = str_replace( "\n", '', $sortkey );
2363 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2364 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2365
2366 /**
2367 * Strip the whitespace Category links produce, see T2087
2368 */
2369 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
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
3034 // Flags
3035
3036 // $text has been filled
3037 $found = false;
3038 // wiki markup in $text should be escaped
3039 $nowiki = false;
3040 // $text is HTML, armour it against wikitext transformation
3041 $isHTML = false;
3042 // Force interwiki transclusion to be done in raw mode not rendered
3043 $forceRawInterwiki = false;
3044 // $text is a DOM node needing expansion in a child frame
3045 $isChildObj = false;
3046 // $text is a DOM node needing expansion in the current frame
3047 $isLocalObj = false;
3048
3049 # Title object, where $text came from
3050 $title = false;
3051
3052 # $part1 is the bit before the first |, and must contain only title characters.
3053 # Various prefixes will be stripped from it later.
3054 $titleWithSpaces = $frame->expand( $piece['title'] );
3055 $part1 = trim( $titleWithSpaces );
3056 $titleText = false;
3057
3058 # Original title text preserved for various purposes
3059 $originalTitle = $part1;
3060
3061 # $args is a list of argument nodes, starting from index 0, not including $part1
3062 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3063 # below won't work b/c this $args isn't an object
3064 $args = ( null == $piece['parts'] ) ? [] : $piece['parts'];
3065
3066 $profileSection = null; // profile templates
3067
3068 # SUBST
3069 if ( !$found ) {
3070 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3071
3072 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3073 # Decide whether to expand template or keep wikitext as-is.
3074 if ( $this->ot['wiki'] ) {
3075 if ( $substMatch === false ) {
3076 $literal = true; # literal when in PST with no prefix
3077 } else {
3078 $literal = false; # expand when in PST with subst: or safesubst:
3079 }
3080 } else {
3081 if ( $substMatch == 'subst' ) {
3082 $literal = true; # literal when not in PST with plain subst:
3083 } else {
3084 $literal = false; # expand when not in PST with safesubst: or no prefix
3085 }
3086 }
3087 if ( $literal ) {
3088 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3089 $isLocalObj = true;
3090 $found = true;
3091 }
3092 }
3093
3094 # Variables
3095 if ( !$found && $args->getLength() == 0 ) {
3096 $id = $this->mVariables->matchStartToEnd( $part1 );
3097 if ( $id !== false ) {
3098 $text = $this->getVariableValue( $id, $frame );
3099 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3100 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3101 }
3102 $found = true;
3103 }
3104 }
3105
3106 # MSG, MSGNW and RAW
3107 if ( !$found ) {
3108 # Check for MSGNW:
3109 $mwMsgnw = MagicWord::get( 'msgnw' );
3110 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3111 $nowiki = true;
3112 } else {
3113 # Remove obsolete MSG:
3114 $mwMsg = MagicWord::get( 'msg' );
3115 $mwMsg->matchStartAndRemove( $part1 );
3116 }
3117
3118 # Check for RAW:
3119 $mwRaw = MagicWord::get( 'raw' );
3120 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3121 $forceRawInterwiki = true;
3122 }
3123 }
3124
3125 # Parser functions
3126 if ( !$found ) {
3127 $colonPos = strpos( $part1, ':' );
3128 if ( $colonPos !== false ) {
3129 $func = substr( $part1, 0, $colonPos );
3130 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3131 $argsLength = $args->getLength();
3132 for ( $i = 0; $i < $argsLength; $i++ ) {
3133 $funcArgs[] = $args->item( $i );
3134 }
3135 try {
3136 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3137 } catch ( Exception $ex ) {
3138 throw $ex;
3139 }
3140
3141 # The interface for parser functions allows for extracting
3142 # flags into the local scope. Extract any forwarded flags
3143 # here.
3144 extract( $result );
3145 }
3146 }
3147
3148 # Finish mangling title and then check for loops.
3149 # Set $title to a Title object and $titleText to the PDBK
3150 if ( !$found ) {
3151 $ns = NS_TEMPLATE;
3152 # Split the title into page and subpage
3153 $subpage = '';
3154 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3155 if ( $part1 !== $relative ) {
3156 $part1 = $relative;
3157 $ns = $this->mTitle->getNamespace();
3158 }
3159 $title = Title::newFromText( $part1, $ns );
3160 if ( $title ) {
3161 $titleText = $title->getPrefixedText();
3162 # Check for language variants if the template is not found
3163 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3164 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3165 }
3166 # Do recursion depth check
3167 $limit = $this->mOptions->getMaxTemplateDepth();
3168 if ( $frame->depth >= $limit ) {
3169 $found = true;
3170 $text = '<span class="error">'
3171 . wfMessage( 'parser-template-recursion-depth-warning' )
3172 ->numParams( $limit )->inContentLanguage()->text()
3173 . '</span>';
3174 }
3175 }
3176 }
3177
3178 # Load from database
3179 if ( !$found && $title ) {
3180 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3181 if ( !$title->isExternal() ) {
3182 if ( $title->isSpecialPage()
3183 && $this->mOptions->getAllowSpecialInclusion()
3184 && $this->ot['html']
3185 ) {
3186 $specialPage = SpecialPageFactory::getPage( $title->getDBkey() );
3187 // Pass the template arguments as URL parameters.
3188 // "uselang" will have no effect since the Language object
3189 // is forced to the one defined in ParserOptions.
3190 $pageArgs = [];
3191 $argsLength = $args->getLength();
3192 for ( $i = 0; $i < $argsLength; $i++ ) {
3193 $bits = $args->item( $i )->splitArg();
3194 if ( strval( $bits['index'] ) === '' ) {
3195 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3196 $value = trim( $frame->expand( $bits['value'] ) );
3197 $pageArgs[$name] = $value;
3198 }
3199 }
3200
3201 // Create a new context to execute the special page
3202 $context = new RequestContext;
3203 $context->setTitle( $title );
3204 $context->setRequest( new FauxRequest( $pageArgs ) );
3205 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3206 $context->setUser( $this->getUser() );
3207 } else {
3208 // If this page is cached, then we better not be per user.
3209 $context->setUser( User::newFromName( '127.0.0.1', false ) );
3210 }
3211 $context->setLanguage( $this->mOptions->getUserLangObj() );
3212 $ret = SpecialPageFactory::capturePath(
3213 $title, $context, $this->getLinkRenderer() );
3214 if ( $ret ) {
3215 $text = $context->getOutput()->getHTML();
3216 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3217 $found = true;
3218 $isHTML = true;
3219 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3220 $this->mOutput->updateRuntimeAdaptiveExpiry(
3221 $specialPage->maxIncludeCacheTime()
3222 );
3223 }
3224 }
3225 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3226 $found = false; # access denied
3227 wfDebug( __METHOD__ . ": template inclusion denied for " .
3228 $title->getPrefixedDBkey() . "\n" );
3229 } else {
3230 list( $text, $title ) = $this->getTemplateDom( $title );
3231 if ( $text !== false ) {
3232 $found = true;
3233 $isChildObj = true;
3234 }
3235 }
3236
3237 # If the title is valid but undisplayable, make a link to it
3238 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3239 $text = "[[:$titleText]]";
3240 $found = true;
3241 }
3242 } elseif ( $title->isTrans() ) {
3243 # Interwiki transclusion
3244 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3245 $text = $this->interwikiTransclude( $title, 'render' );
3246 $isHTML = true;
3247 } else {
3248 $text = $this->interwikiTransclude( $title, 'raw' );
3249 # Preprocess it like a template
3250 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3251 $isChildObj = true;
3252 }
3253 $found = true;
3254 }
3255
3256 # Do infinite loop check
3257 # This has to be done after redirect resolution to avoid infinite loops via redirects
3258 if ( !$frame->loopCheck( $title ) ) {
3259 $found = true;
3260 $text = '<span class="error">'
3261 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3262 . '</span>';
3263 $this->addTrackingCategory( 'template-loop-category' );
3264 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3265 }
3266 }
3267
3268 # If we haven't found text to substitute by now, we're done
3269 # Recover the source wikitext and return it
3270 if ( !$found ) {
3271 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3272 if ( $profileSection ) {
3273 $this->mProfiler->scopedProfileOut( $profileSection );
3274 }
3275 return [ 'object' => $text ];
3276 }
3277
3278 # Expand DOM-style return values in a child frame
3279 if ( $isChildObj ) {
3280 # Clean up argument array
3281 $newFrame = $frame->newChild( $args, $title );
3282
3283 if ( $nowiki ) {
3284 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3285 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3286 # Expansion is eligible for the empty-frame cache
3287 $text = $newFrame->cachedExpand( $titleText, $text );
3288 } else {
3289 # Uncached expansion
3290 $text = $newFrame->expand( $text );
3291 }
3292 }
3293 if ( $isLocalObj && $nowiki ) {
3294 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3295 $isLocalObj = false;
3296 }
3297
3298 if ( $profileSection ) {
3299 $this->mProfiler->scopedProfileOut( $profileSection );
3300 }
3301
3302 # Replace raw HTML by a placeholder
3303 if ( $isHTML ) {
3304 $text = $this->insertStripItem( $text );
3305 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3306 # Escape nowiki-style return values
3307 $text = wfEscapeWikiText( $text );
3308 } elseif ( is_string( $text )
3309 && !$piece['lineStart']
3310 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3311 ) {
3312 # T2529: if the template begins with a table or block-level
3313 # element, it should be treated as beginning a new line.
3314 # This behavior is somewhat controversial.
3315 $text = "\n" . $text;
3316 }
3317
3318 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3319 # Error, oversize inclusion
3320 if ( $titleText !== false ) {
3321 # Make a working, properly escaped link if possible (T25588)
3322 $text = "[[:$titleText]]";
3323 } else {
3324 # This will probably not be a working link, but at least it may
3325 # provide some hint of where the problem is
3326 preg_replace( '/^:/', '', $originalTitle );
3327 $text = "[[:$originalTitle]]";
3328 }
3329 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3330 . 'post-expand include size too large -->' );
3331 $this->limitationWarn( 'post-expand-template-inclusion' );
3332 }
3333
3334 if ( $isLocalObj ) {
3335 $ret = [ 'object' => $text ];
3336 } else {
3337 $ret = [ 'text' => $text ];
3338 }
3339
3340 return $ret;
3341 }
3342
3343 /**
3344 * Call a parser function and return an array with text and flags.
3345 *
3346 * The returned array will always contain a boolean 'found', indicating
3347 * whether the parser function was found or not. It may also contain the
3348 * following:
3349 * text: string|object, resulting wikitext or PP DOM object
3350 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3351 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3352 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3353 * nowiki: bool, wiki markup in $text should be escaped
3354 *
3355 * @since 1.21
3356 * @param PPFrame $frame The current frame, contains template arguments
3357 * @param string $function Function name
3358 * @param array $args Arguments to the function
3359 * @throws MWException
3360 * @return array
3361 */
3362 public function callParserFunction( $frame, $function, array $args = [] ) {
3363 global $wgContLang;
3364
3365 # Case sensitive functions
3366 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3367 $function = $this->mFunctionSynonyms[1][$function];
3368 } else {
3369 # Case insensitive functions
3370 $function = $wgContLang->lc( $function );
3371 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3372 $function = $this->mFunctionSynonyms[0][$function];
3373 } else {
3374 return [ 'found' => false ];
3375 }
3376 }
3377
3378 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3379
3380 # Workaround for PHP bug 35229 and similar
3381 if ( !is_callable( $callback ) ) {
3382 throw new MWException( "Tag hook for $function is not callable\n" );
3383 }
3384
3385 // Avoid PHP 7.1 warning from passing $this by reference
3386 $parser = $this;
3387
3388 $allArgs = [ &$parser ];
3389 if ( $flags & self::SFH_OBJECT_ARGS ) {
3390 # Convert arguments to PPNodes and collect for appending to $allArgs
3391 $funcArgs = [];
3392 foreach ( $args as $k => $v ) {
3393 if ( $v instanceof PPNode || $k === 0 ) {
3394 $funcArgs[] = $v;
3395 } else {
3396 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3397 }
3398 }
3399
3400 # Add a frame parameter, and pass the arguments as an array
3401 $allArgs[] = $frame;
3402 $allArgs[] = $funcArgs;
3403 } else {
3404 # Convert arguments to plain text and append to $allArgs
3405 foreach ( $args as $k => $v ) {
3406 if ( $v instanceof PPNode ) {
3407 $allArgs[] = trim( $frame->expand( $v ) );
3408 } elseif ( is_int( $k ) && $k >= 0 ) {
3409 $allArgs[] = trim( $v );
3410 } else {
3411 $allArgs[] = trim( "$k=$v" );
3412 }
3413 }
3414 }
3415
3416 $result = call_user_func_array( $callback, $allArgs );
3417
3418 # The interface for function hooks allows them to return a wikitext
3419 # string or an array containing the string and any flags. This mungs
3420 # things around to match what this method should return.
3421 if ( !is_array( $result ) ) {
3422 $result =[
3423 'found' => true,
3424 'text' => $result,
3425 ];
3426 } else {
3427 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3428 $result['text'] = $result[0];
3429 }
3430 unset( $result[0] );
3431 $result += [
3432 'found' => true,
3433 ];
3434 }
3435
3436 $noparse = true;
3437 $preprocessFlags = 0;
3438 if ( isset( $result['noparse'] ) ) {
3439 $noparse = $result['noparse'];
3440 }
3441 if ( isset( $result['preprocessFlags'] ) ) {
3442 $preprocessFlags = $result['preprocessFlags'];
3443 }
3444
3445 if ( !$noparse ) {
3446 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3447 $result['isChildObj'] = true;
3448 }
3449
3450 return $result;
3451 }
3452
3453 /**
3454 * Get the semi-parsed DOM representation of a template with a given title,
3455 * and its redirect destination title. Cached.
3456 *
3457 * @param Title $title
3458 *
3459 * @return array
3460 */
3461 public function getTemplateDom( $title ) {
3462 $cacheTitle = $title;
3463 $titleText = $title->getPrefixedDBkey();
3464
3465 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3466 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3467 $title = Title::makeTitle( $ns, $dbk );
3468 $titleText = $title->getPrefixedDBkey();
3469 }
3470 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3471 return [ $this->mTplDomCache[$titleText], $title ];
3472 }
3473
3474 # Cache miss, go to the database
3475 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3476
3477 if ( $text === false ) {
3478 $this->mTplDomCache[$titleText] = false;
3479 return [ false, $title ];
3480 }
3481
3482 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3483 $this->mTplDomCache[$titleText] = $dom;
3484
3485 if ( !$title->equals( $cacheTitle ) ) {
3486 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3487 [ $title->getNamespace(), $title->getDBkey() ];
3488 }
3489
3490 return [ $dom, $title ];
3491 }
3492
3493 /**
3494 * Fetch the current revision of a given title. Note that the revision
3495 * (and even the title) may not exist in the database, so everything
3496 * contributing to the output of the parser should use this method
3497 * where possible, rather than getting the revisions themselves. This
3498 * method also caches its results, so using it benefits performance.
3499 *
3500 * @since 1.24
3501 * @param Title $title
3502 * @return Revision
3503 */
3504 public function fetchCurrentRevisionOfTitle( $title ) {
3505 $cacheKey = $title->getPrefixedDBkey();
3506 if ( !$this->currentRevisionCache ) {
3507 $this->currentRevisionCache = new MapCacheLRU( 100 );
3508 }
3509 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3510 $this->currentRevisionCache->set( $cacheKey,
3511 // Defaults to Parser::statelessFetchRevision()
3512 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3513 );
3514 }
3515 return $this->currentRevisionCache->get( $cacheKey );
3516 }
3517
3518 /**
3519 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3520 * without passing them on to it.
3521 *
3522 * @since 1.24
3523 * @param Title $title
3524 * @param Parser|bool $parser
3525 * @return Revision|bool False if missing
3526 */
3527 public static function statelessFetchRevision( Title $title, $parser = false ) {
3528 $pageId = $title->getArticleID();
3529 $revId = $title->getLatestRevID();
3530
3531 $rev = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $pageId, $revId );
3532 if ( $rev ) {
3533 $rev->setTitle( $title );
3534 }
3535
3536 return $rev;
3537 }
3538
3539 /**
3540 * Fetch the unparsed text of a template and register a reference to it.
3541 * @param Title $title
3542 * @return array ( string or false, Title )
3543 */
3544 public function fetchTemplateAndTitle( $title ) {
3545 // Defaults to Parser::statelessFetchTemplate()
3546 $templateCb = $this->mOptions->getTemplateCallback();
3547 $stuff = call_user_func( $templateCb, $title, $this );
3548 // We use U+007F DELETE to distinguish strip markers from regular text.
3549 $text = $stuff['text'];
3550 if ( is_string( $stuff['text'] ) ) {
3551 $text = strtr( $text, "\x7f", "?" );
3552 }
3553 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3554 if ( isset( $stuff['deps'] ) ) {
3555 foreach ( $stuff['deps'] as $dep ) {
3556 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3557 if ( $dep['title']->equals( $this->getTitle() ) ) {
3558 // If we transclude ourselves, the final result
3559 // will change based on the new version of the page
3560 $this->mOutput->setFlag( 'vary-revision' );
3561 }
3562 }
3563 }
3564 return [ $text, $finalTitle ];
3565 }
3566
3567 /**
3568 * Fetch the unparsed text of a template and register a reference to it.
3569 * @param Title $title
3570 * @return string|bool
3571 */
3572 public function fetchTemplate( $title ) {
3573 return $this->fetchTemplateAndTitle( $title )[0];
3574 }
3575
3576 /**
3577 * Static function to get a template
3578 * Can be overridden via ParserOptions::setTemplateCallback().
3579 *
3580 * @param Title $title
3581 * @param bool|Parser $parser
3582 *
3583 * @return array
3584 */
3585 public static function statelessFetchTemplate( $title, $parser = false ) {
3586 $text = $skip = false;
3587 $finalTitle = $title;
3588 $deps = [];
3589
3590 # Loop to fetch the article, with up to 1 redirect
3591 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3592 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3593 // @codingStandardsIgnoreEnd
3594 # Give extensions a chance to select the revision instead
3595 $id = false; # Assume current
3596 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3597 [ $parser, $title, &$skip, &$id ] );
3598
3599 if ( $skip ) {
3600 $text = false;
3601 $deps[] = [
3602 'title' => $title,
3603 'page_id' => $title->getArticleID(),
3604 'rev_id' => null
3605 ];
3606 break;
3607 }
3608 # Get the revision
3609 if ( $id ) {
3610 $rev = Revision::newFromId( $id );
3611 } elseif ( $parser ) {
3612 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3613 } else {
3614 $rev = Revision::newFromTitle( $title );
3615 }
3616 $rev_id = $rev ? $rev->getId() : 0;
3617 # If there is no current revision, there is no page
3618 if ( $id === false && !$rev ) {
3619 $linkCache = LinkCache::singleton();
3620 $linkCache->addBadLinkObj( $title );
3621 }
3622
3623 $deps[] = [
3624 'title' => $title,
3625 'page_id' => $title->getArticleID(),
3626 'rev_id' => $rev_id ];
3627 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3628 # We fetched a rev from a different title; register it too...
3629 $deps[] = [
3630 'title' => $rev->getTitle(),
3631 'page_id' => $rev->getPage(),
3632 'rev_id' => $rev_id ];
3633 }
3634
3635 if ( $rev ) {
3636 $content = $rev->getContent();
3637 $text = $content ? $content->getWikitextForTransclusion() : null;
3638
3639 Hooks::run( 'ParserFetchTemplate',
3640 [ $parser, $title, $rev, &$text, &$deps ] );
3641
3642 if ( $text === false || $text === null ) {
3643 $text = false;
3644 break;
3645 }
3646 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3647 global $wgContLang;
3648 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3649 if ( !$message->exists() ) {
3650 $text = false;
3651 break;
3652 }
3653 $content = $message->content();
3654 $text = $message->plain();
3655 } else {
3656 break;
3657 }
3658 if ( !$content ) {
3659 break;
3660 }
3661 # Redirect?
3662 $finalTitle = $title;
3663 $title = $content->getRedirectTarget();
3664 }
3665 return [
3666 'text' => $text,
3667 'finalTitle' => $finalTitle,
3668 'deps' => $deps ];
3669 }
3670
3671 /**
3672 * Fetch a file and its title and register a reference to it.
3673 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3674 * @param Title $title
3675 * @param array $options Array of options to RepoGroup::findFile
3676 * @return File|bool
3677 */
3678 public function fetchFile( $title, $options = [] ) {
3679 return $this->fetchFileAndTitle( $title, $options )[0];
3680 }
3681
3682 /**
3683 * Fetch a file and its title and register a reference to it.
3684 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3685 * @param Title $title
3686 * @param array $options Array of options to RepoGroup::findFile
3687 * @return array ( File or false, Title of file )
3688 */
3689 public function fetchFileAndTitle( $title, $options = [] ) {
3690 $file = $this->fetchFileNoRegister( $title, $options );
3691
3692 $time = $file ? $file->getTimestamp() : false;
3693 $sha1 = $file ? $file->getSha1() : false;
3694 # Register the file as a dependency...
3695 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3696 if ( $file && !$title->equals( $file->getTitle() ) ) {
3697 # Update fetched file title
3698 $title = $file->getTitle();
3699 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3700 }
3701 return [ $file, $title ];
3702 }
3703
3704 /**
3705 * Helper function for fetchFileAndTitle.
3706 *
3707 * Also useful if you need to fetch a file but not use it yet,
3708 * for example to get the file's handler.
3709 *
3710 * @param Title $title
3711 * @param array $options Array of options to RepoGroup::findFile
3712 * @return File|bool
3713 */
3714 protected function fetchFileNoRegister( $title, $options = [] ) {
3715 if ( isset( $options['broken'] ) ) {
3716 $file = false; // broken thumbnail forced by hook
3717 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3718 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3719 } else { // get by (name,timestamp)
3720 $file = wfFindFile( $title, $options );
3721 }
3722 return $file;
3723 }
3724
3725 /**
3726 * Transclude an interwiki link.
3727 *
3728 * @param Title $title
3729 * @param string $action
3730 *
3731 * @return string
3732 */
3733 public function interwikiTransclude( $title, $action ) {
3734 global $wgEnableScaryTranscluding;
3735
3736 if ( !$wgEnableScaryTranscluding ) {
3737 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3738 }
3739
3740 $url = $title->getFullURL( [ 'action' => $action ] );
3741
3742 if ( strlen( $url ) > 255 ) {
3743 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3744 }
3745 return $this->fetchScaryTemplateMaybeFromCache( $url );
3746 }
3747
3748 /**
3749 * @param string $url
3750 * @return mixed|string
3751 */
3752 public function fetchScaryTemplateMaybeFromCache( $url ) {
3753 global $wgTranscludeCacheExpiry;
3754 $dbr = wfGetDB( DB_REPLICA );
3755 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3756 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3757 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3758 if ( $obj ) {
3759 return $obj->tc_contents;
3760 }
3761
3762 $req = MWHttpRequest::factory( $url, [], __METHOD__ );
3763 $status = $req->execute(); // Status object
3764 if ( $status->isOK() ) {
3765 $text = $req->getContent();
3766 } elseif ( $req->getStatus() != 200 ) {
3767 // Though we failed to fetch the content, this status is useless.
3768 return wfMessage( 'scarytranscludefailed-httpstatus' )
3769 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3770 } else {
3771 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3772 }
3773
3774 $dbw = wfGetDB( DB_MASTER );
3775 $dbw->replace( 'transcache', [ 'tc_url' ], [
3776 'tc_url' => $url,
3777 'tc_time' => $dbw->timestamp( time() ),
3778 'tc_contents' => $text
3779 ] );
3780 return $text;
3781 }
3782
3783 /**
3784 * Triple brace replacement -- used for template arguments
3785 * @private
3786 *
3787 * @param array $piece
3788 * @param PPFrame $frame
3789 *
3790 * @return array
3791 */
3792 public function argSubstitution( $piece, $frame ) {
3793
3794 $error = false;
3795 $parts = $piece['parts'];
3796 $nameWithSpaces = $frame->expand( $piece['title'] );
3797 $argName = trim( $nameWithSpaces );
3798 $object = false;
3799 $text = $frame->getArgument( $argName );
3800 if ( $text === false && $parts->getLength() > 0
3801 && ( $this->ot['html']
3802 || $this->ot['pre']
3803 || ( $this->ot['wiki'] && $frame->isTemplate() )
3804 )
3805 ) {
3806 # No match in frame, use the supplied default
3807 $object = $parts->item( 0 )->getChildren();
3808 }
3809 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3810 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3811 $this->limitationWarn( 'post-expand-template-argument' );
3812 }
3813
3814 if ( $text === false && $object === false ) {
3815 # No match anywhere
3816 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3817 }
3818 if ( $error !== false ) {
3819 $text .= $error;
3820 }
3821 if ( $object !== false ) {
3822 $ret = [ 'object' => $object ];
3823 } else {
3824 $ret = [ 'text' => $text ];
3825 }
3826
3827 return $ret;
3828 }
3829
3830 /**
3831 * Return the text to be used for a given extension tag.
3832 * This is the ghost of strip().
3833 *
3834 * @param array $params Associative array of parameters:
3835 * name PPNode for the tag name
3836 * attr PPNode for unparsed text where tag attributes are thought to be
3837 * attributes Optional associative array of parsed attributes
3838 * inner Contents of extension element
3839 * noClose Original text did not have a close tag
3840 * @param PPFrame $frame
3841 *
3842 * @throws MWException
3843 * @return string
3844 */
3845 public function extensionSubstitution( $params, $frame ) {
3846 static $errorStr = '<span class="error">';
3847 static $errorLen = 20;
3848
3849 $name = $frame->expand( $params['name'] );
3850 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3851 // Probably expansion depth or node count exceeded. Just punt the
3852 // error up.
3853 return $name;
3854 }
3855
3856 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3857 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3858 // See above
3859 return $attrText;
3860 }
3861
3862 // We can't safely check if the expansion for $content resulted in an
3863 // error, because the content could happen to be the error string
3864 // (T149622).
3865 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3866
3867 $marker = self::MARKER_PREFIX . "-$name-"
3868 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3869
3870 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3871 ( $this->ot['html'] || $this->ot['pre'] );
3872 if ( $isFunctionTag ) {
3873 $markerType = 'none';
3874 } else {
3875 $markerType = 'general';
3876 }
3877 if ( $this->ot['html'] || $isFunctionTag ) {
3878 $name = strtolower( $name );
3879 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3880 if ( isset( $params['attributes'] ) ) {
3881 $attributes = $attributes + $params['attributes'];
3882 }
3883
3884 if ( isset( $this->mTagHooks[$name] ) ) {
3885 # Workaround for PHP bug 35229 and similar
3886 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3887 throw new MWException( "Tag hook for $name is not callable\n" );
3888 }
3889 $output = call_user_func_array( $this->mTagHooks[$name],
3890 [ $content, $attributes, $this, $frame ] );
3891 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3892 list( $callback, ) = $this->mFunctionTagHooks[$name];
3893 if ( !is_callable( $callback ) ) {
3894 throw new MWException( "Tag hook for $name is not callable\n" );
3895 }
3896
3897 // Avoid PHP 7.1 warning from passing $this by reference
3898 $parser = $this;
3899 $output = call_user_func_array( $callback, [ &$parser, $frame, $content, $attributes ] );
3900 } else {
3901 $output = '<span class="error">Invalid tag extension name: ' .
3902 htmlspecialchars( $name ) . '</span>';
3903 }
3904
3905 if ( is_array( $output ) ) {
3906 # Extract flags to local scope (to override $markerType)
3907 $flags = $output;
3908 $output = $flags[0];
3909 unset( $flags[0] );
3910 extract( $flags );
3911 }
3912 } else {
3913 if ( is_null( $attrText ) ) {
3914 $attrText = '';
3915 }
3916 if ( isset( $params['attributes'] ) ) {
3917 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3918 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3919 htmlspecialchars( $attrValue ) . '"';
3920 }
3921 }
3922 if ( $content === null ) {
3923 $output = "<$name$attrText/>";
3924 } else {
3925 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3926 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3927 // See above
3928 return $close;
3929 }
3930 $output = "<$name$attrText>$content$close";
3931 }
3932 }
3933
3934 if ( $markerType === 'none' ) {
3935 return $output;
3936 } elseif ( $markerType === 'nowiki' ) {
3937 $this->mStripState->addNoWiki( $marker, $output );
3938 } elseif ( $markerType === 'general' ) {
3939 $this->mStripState->addGeneral( $marker, $output );
3940 } else {
3941 throw new MWException( __METHOD__ . ': invalid marker type' );
3942 }
3943 return $marker;
3944 }
3945
3946 /**
3947 * Increment an include size counter
3948 *
3949 * @param string $type The type of expansion
3950 * @param int $size The size of the text
3951 * @return bool False if this inclusion would take it over the maximum, true otherwise
3952 */
3953 public function incrementIncludeSize( $type, $size ) {
3954 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3955 return false;
3956 } else {
3957 $this->mIncludeSizes[$type] += $size;
3958 return true;
3959 }
3960 }
3961
3962 /**
3963 * Increment the expensive function count
3964 *
3965 * @return bool False if the limit has been exceeded
3966 */
3967 public function incrementExpensiveFunctionCount() {
3968 $this->mExpensiveFunctionCount++;
3969 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
3970 }
3971
3972 /**
3973 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3974 * Fills $this->mDoubleUnderscores, returns the modified text
3975 *
3976 * @param string $text
3977 *
3978 * @return string
3979 */
3980 public function doDoubleUnderscore( $text ) {
3981
3982 # The position of __TOC__ needs to be recorded
3983 $mw = MagicWord::get( 'toc' );
3984 if ( $mw->match( $text ) ) {
3985 $this->mShowToc = true;
3986 $this->mForceTocPosition = true;
3987
3988 # Set a placeholder. At the end we'll fill it in with the TOC.
3989 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3990
3991 # Only keep the first one.
3992 $text = $mw->replace( '', $text );
3993 }
3994
3995 # Now match and remove the rest of them
3996 $mwa = MagicWord::getDoubleUnderscoreArray();
3997 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3998
3999 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4000 $this->mOutput->mNoGallery = true;
4001 }
4002 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4003 $this->mShowToc = false;
4004 }
4005 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4006 && $this->mTitle->getNamespace() == NS_CATEGORY
4007 ) {
4008 $this->addTrackingCategory( 'hidden-category-category' );
4009 }
4010 # (T10068) Allow control over whether robots index a page.
4011 # __INDEX__ always overrides __NOINDEX__, see T16899
4012 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4013 $this->mOutput->setIndexPolicy( 'noindex' );
4014 $this->addTrackingCategory( 'noindex-category' );
4015 }
4016 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4017 $this->mOutput->setIndexPolicy( 'index' );
4018 $this->addTrackingCategory( 'index-category' );
4019 }
4020
4021 # Cache all double underscores in the database
4022 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4023 $this->mOutput->setProperty( $key, '' );
4024 }
4025
4026 return $text;
4027 }
4028
4029 /**
4030 * @see ParserOutput::addTrackingCategory()
4031 * @param string $msg Message key
4032 * @return bool Whether the addition was successful
4033 */
4034 public function addTrackingCategory( $msg ) {
4035 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4036 }
4037
4038 /**
4039 * This function accomplishes several tasks:
4040 * 1) Auto-number headings if that option is enabled
4041 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4042 * 3) Add a Table of contents on the top for users who have enabled the option
4043 * 4) Auto-anchor headings
4044 *
4045 * It loops through all headlines, collects the necessary data, then splits up the
4046 * string and re-inserts the newly formatted headlines.
4047 *
4048 * @param string $text
4049 * @param string $origText Original, untouched wikitext
4050 * @param bool $isMain
4051 * @return mixed|string
4052 * @private
4053 */
4054 public function formatHeadings( $text, $origText, $isMain = true ) {
4055 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4056
4057 # Inhibit editsection links if requested in the page
4058 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4059 $maybeShowEditLink = $showEditLink = false;
4060 } else {
4061 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4062 $showEditLink = $this->mOptions->getEditSection();
4063 }
4064 if ( $showEditLink ) {
4065 $this->mOutput->setEditSectionTokens( true );
4066 }
4067
4068 # Get all headlines for numbering them and adding funky stuff like [edit]
4069 # links - this is for later, but we need the number of headlines right now
4070 $matches = [];
4071 $numMatches = preg_match_all(
4072 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4073 $text,
4074 $matches
4075 );
4076
4077 # if there are fewer than 4 headlines in the article, do not show TOC
4078 # unless it's been explicitly enabled.
4079 $enoughToc = $this->mShowToc &&
4080 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4081
4082 # Allow user to stipulate that a page should have a "new section"
4083 # link added via __NEWSECTIONLINK__
4084 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4085 $this->mOutput->setNewSection( true );
4086 }
4087
4088 # Allow user to remove the "new section"
4089 # link via __NONEWSECTIONLINK__
4090 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4091 $this->mOutput->hideNewSection( true );
4092 }
4093
4094 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4095 # override above conditions and always show TOC above first header
4096 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4097 $this->mShowToc = true;
4098 $enoughToc = true;
4099 }
4100
4101 # headline counter
4102 $headlineCount = 0;
4103 $numVisible = 0;
4104
4105 # Ugh .. the TOC should have neat indentation levels which can be
4106 # passed to the skin functions. These are determined here
4107 $toc = '';
4108 $full = '';
4109 $head = [];
4110 $sublevelCount = [];
4111 $levelCount = [];
4112 $level = 0;
4113 $prevlevel = 0;
4114 $toclevel = 0;
4115 $prevtoclevel = 0;
4116 $markerRegex = self::MARKER_PREFIX . "-h-(\d+)-" . self::MARKER_SUFFIX;
4117 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4118 $oldType = $this->mOutputType;
4119 $this->setOutputType( self::OT_WIKI );
4120 $frame = $this->getPreprocessor()->newFrame();
4121 $root = $this->preprocessToDom( $origText );
4122 $node = $root->getFirstChild();
4123 $byteOffset = 0;
4124 $tocraw = [];
4125 $refers = [];
4126
4127 $headlines = $numMatches !== false ? $matches[3] : [];
4128
4129 foreach ( $headlines as $headline ) {
4130 $isTemplate = false;
4131 $titleText = false;
4132 $sectionIndex = false;
4133 $numbering = '';
4134 $markerMatches = [];
4135 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4136 $serial = $markerMatches[1];
4137 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4138 $isTemplate = ( $titleText != $baseTitleText );
4139 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4140 }
4141
4142 if ( $toclevel ) {
4143 $prevlevel = $level;
4144 }
4145 $level = $matches[1][$headlineCount];
4146
4147 if ( $level > $prevlevel ) {
4148 # Increase TOC level
4149 $toclevel++;
4150 $sublevelCount[$toclevel] = 0;
4151 if ( $toclevel < $wgMaxTocLevel ) {
4152 $prevtoclevel = $toclevel;
4153 $toc .= Linker::tocIndent();
4154 $numVisible++;
4155 }
4156 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4157 # Decrease TOC level, find level to jump to
4158
4159 for ( $i = $toclevel; $i > 0; $i-- ) {
4160 if ( $levelCount[$i] == $level ) {
4161 # Found last matching level
4162 $toclevel = $i;
4163 break;
4164 } elseif ( $levelCount[$i] < $level ) {
4165 # Found first matching level below current level
4166 $toclevel = $i + 1;
4167 break;
4168 }
4169 }
4170 if ( $i == 0 ) {
4171 $toclevel = 1;
4172 }
4173 if ( $toclevel < $wgMaxTocLevel ) {
4174 if ( $prevtoclevel < $wgMaxTocLevel ) {
4175 # Unindent only if the previous toc level was shown :p
4176 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4177 $prevtoclevel = $toclevel;
4178 } else {
4179 $toc .= Linker::tocLineEnd();
4180 }
4181 }
4182 } else {
4183 # No change in level, end TOC line
4184 if ( $toclevel < $wgMaxTocLevel ) {
4185 $toc .= Linker::tocLineEnd();
4186 }
4187 }
4188
4189 $levelCount[$toclevel] = $level;
4190
4191 # count number of headlines for each level
4192 $sublevelCount[$toclevel]++;
4193 $dot = 0;
4194 for ( $i = 1; $i <= $toclevel; $i++ ) {
4195 if ( !empty( $sublevelCount[$i] ) ) {
4196 if ( $dot ) {
4197 $numbering .= '.';
4198 }
4199 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4200 $dot = 1;
4201 }
4202 }
4203
4204 # The safe header is a version of the header text safe to use for links
4205
4206 # Remove link placeholders by the link text.
4207 # <!--LINK number-->
4208 # turns into
4209 # link text with suffix
4210 # Do this before unstrip since link text can contain strip markers
4211 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4212
4213 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4214 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4215
4216 # Strip out HTML (first regex removes any tag not allowed)
4217 # Allowed tags are:
4218 # * <sup> and <sub> (T10393)
4219 # * <i> (T28375)
4220 # * <b> (r105284)
4221 # * <bdi> (T74884)
4222 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4223 # * <s> and <strike> (T35715)
4224 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4225 # to allow setting directionality in toc items.
4226 $tocline = preg_replace(
4227 [
4228 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4229 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4230 ],
4231 [ '', '<$1>' ],
4232 $safeHeadline
4233 );
4234
4235 # Strip '<span></span>', which is the result from the above if
4236 # <span id="foo"></span> is used to produce an additional anchor
4237 # for a section.
4238 $tocline = str_replace( '<span></span>', '', $tocline );
4239
4240 $tocline = trim( $tocline );
4241
4242 # For the anchor, strip out HTML-y stuff period
4243 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4244 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4245
4246 # Save headline for section edit hint before it's escaped
4247 $headlineHint = $safeHeadline;
4248
4249 if ( $wgExperimentalHtmlIds ) {
4250 # For reverse compatibility, provide an id that's
4251 # HTML4-compatible, like we used to.
4252 # It may be worth noting, academically, that it's possible for
4253 # the legacy anchor to conflict with a non-legacy headline
4254 # anchor on the page. In this case likely the "correct" thing
4255 # would be to either drop the legacy anchors or make sure
4256 # they're numbered first. However, this would require people
4257 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4258 # manually, so let's not bother worrying about it.
4259 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4260 [ 'noninitial', 'legacy' ] );
4261 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4262
4263 if ( $legacyHeadline == $safeHeadline ) {
4264 # No reason to have both (in fact, we can't)
4265 $legacyHeadline = false;
4266 }
4267 } else {
4268 $legacyHeadline = false;
4269 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4270 'noninitial' );
4271 }
4272
4273 # HTML names must be case-insensitively unique (T12721).
4274 # This does not apply to Unicode characters per
4275 # https://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4276 # @todo FIXME: We may be changing them depending on the current locale.
4277 $arrayKey = strtolower( $safeHeadline );
4278 if ( $legacyHeadline === false ) {
4279 $legacyArrayKey = false;
4280 } else {
4281 $legacyArrayKey = strtolower( $legacyHeadline );
4282 }
4283
4284 # Create the anchor for linking from the TOC to the section
4285 $anchor = $safeHeadline;
4286 $legacyAnchor = $legacyHeadline;
4287 if ( isset( $refers[$arrayKey] ) ) {
4288 // @codingStandardsIgnoreStart
4289 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4290 // @codingStandardsIgnoreEnd
4291 $anchor .= "_$i";
4292 $refers["${arrayKey}_$i"] = true;
4293 } else {
4294 $refers[$arrayKey] = true;
4295 }
4296 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4297 // @codingStandardsIgnoreStart
4298 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++$i );
4299 // @codingStandardsIgnoreEnd
4300 $legacyAnchor .= "_$i";
4301 $refers["${legacyArrayKey}_$i"] = true;
4302 } else {
4303 $refers[$legacyArrayKey] = true;
4304 }
4305
4306 # Don't number the heading if it is the only one (looks silly)
4307 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4308 # the two are different if the line contains a link
4309 $headline = Html::element(
4310 'span',
4311 [ 'class' => 'mw-headline-number' ],
4312 $numbering
4313 ) . ' ' . $headline;
4314 }
4315
4316 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4317 $toc .= Linker::tocLine( $anchor, $tocline,
4318 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4319 }
4320
4321 # Add the section to the section tree
4322 # Find the DOM node for this header
4323 $noOffset = ( $isTemplate || $sectionIndex === false );
4324 while ( $node && !$noOffset ) {
4325 if ( $node->getName() === 'h' ) {
4326 $bits = $node->splitHeading();
4327 if ( $bits['i'] == $sectionIndex ) {
4328 break;
4329 }
4330 }
4331 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4332 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4333 $node = $node->getNextSibling();
4334 }
4335 $tocraw[] = [
4336 'toclevel' => $toclevel,
4337 'level' => $level,
4338 'line' => $tocline,
4339 'number' => $numbering,
4340 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4341 'fromtitle' => $titleText,
4342 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4343 'anchor' => $anchor,
4344 ];
4345
4346 # give headline the correct <h#> tag
4347 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4348 // Output edit section links as markers with styles that can be customized by skins
4349 if ( $isTemplate ) {
4350 # Put a T flag in the section identifier, to indicate to extractSections()
4351 # that sections inside <includeonly> should be counted.
4352 $editsectionPage = $titleText;
4353 $editsectionSection = "T-$sectionIndex";
4354 $editsectionContent = null;
4355 } else {
4356 $editsectionPage = $this->mTitle->getPrefixedText();
4357 $editsectionSection = $sectionIndex;
4358 $editsectionContent = $headlineHint;
4359 }
4360 // We use a bit of pesudo-xml for editsection markers. The
4361 // language converter is run later on. Using a UNIQ style marker
4362 // leads to the converter screwing up the tokens when it
4363 // converts stuff. And trying to insert strip tags fails too. At
4364 // this point all real inputted tags have already been escaped,
4365 // so we don't have to worry about a user trying to input one of
4366 // these markers directly. We use a page and section attribute
4367 // to stop the language converter from converting these
4368 // important bits of data, but put the headline hint inside a
4369 // content block because the language converter is supposed to
4370 // be able to convert that piece of data.
4371 // Gets replaced with html in ParserOutput::getText
4372 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4373 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4374 if ( $editsectionContent !== null ) {
4375 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4376 } else {
4377 $editlink .= '/>';
4378 }
4379 } else {
4380 $editlink = '';
4381 }
4382 $head[$headlineCount] = Linker::makeHeadline( $level,
4383 $matches['attrib'][$headlineCount], $anchor, $headline,
4384 $editlink, $legacyAnchor );
4385
4386 $headlineCount++;
4387 }
4388
4389 $this->setOutputType( $oldType );
4390
4391 # Never ever show TOC if no headers
4392 if ( $numVisible < 1 ) {
4393 $enoughToc = false;
4394 }
4395
4396 if ( $enoughToc ) {
4397 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4398 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4399 }
4400 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4401 $this->mOutput->setTOCHTML( $toc );
4402 $toc = self::TOC_START . $toc . self::TOC_END;
4403 $this->mOutput->addModules( 'mediawiki.toc' );
4404 }
4405
4406 if ( $isMain ) {
4407 $this->mOutput->setSections( $tocraw );
4408 }
4409
4410 # split up and insert constructed headlines
4411 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4412 $i = 0;
4413
4414 // build an array of document sections
4415 $sections = [];
4416 foreach ( $blocks as $block ) {
4417 // $head is zero-based, sections aren't.
4418 if ( empty( $head[$i - 1] ) ) {
4419 $sections[$i] = $block;
4420 } else {
4421 $sections[$i] = $head[$i - 1] . $block;
4422 }
4423
4424 /**
4425 * Send a hook, one per section.
4426 * The idea here is to be able to make section-level DIVs, but to do so in a
4427 * lower-impact, more correct way than r50769
4428 *
4429 * $this : caller
4430 * $section : the section number
4431 * &$sectionContent : ref to the content of the section
4432 * $showEditLinks : boolean describing whether this section has an edit link
4433 */
4434 Hooks::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $showEditLink ] );
4435
4436 $i++;
4437 }
4438
4439 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4440 // append the TOC at the beginning
4441 // Top anchor now in skin
4442 $sections[0] = $sections[0] . $toc . "\n";
4443 }
4444
4445 $full .= implode( '', $sections );
4446
4447 if ( $this->mForceTocPosition ) {
4448 return str_replace( '<!--MWTOC-->', $toc, $full );
4449 } else {
4450 return $full;
4451 }
4452 }
4453
4454 /**
4455 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4456 * conversion, substituting signatures, {{subst:}} templates, etc.
4457 *
4458 * @param string $text The text to transform
4459 * @param Title $title The Title object for the current article
4460 * @param User $user The User object describing the current user
4461 * @param ParserOptions $options Parsing options
4462 * @param bool $clearState Whether to clear the parser state first
4463 * @return string The altered wiki markup
4464 */
4465 public function preSaveTransform( $text, Title $title, User $user,
4466 ParserOptions $options, $clearState = true
4467 ) {
4468 if ( $clearState ) {
4469 $magicScopeVariable = $this->lock();
4470 }
4471 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4472 $this->setUser( $user );
4473
4474 // Strip U+0000 NULL (T159174)
4475 $text = str_replace( "\000", '', $text );
4476
4477 // We still normalize line endings for backwards-compatibility
4478 // with other code that just calls PST, but this should already
4479 // be handled in TextContent subclasses
4480 $text = TextContent::normalizeLineEndings( $text );
4481
4482 if ( $options->getPreSaveTransform() ) {
4483 $text = $this->pstPass2( $text, $user );
4484 }
4485 $text = $this->mStripState->unstripBoth( $text );
4486
4487 $this->setUser( null ); # Reset
4488
4489 return $text;
4490 }
4491
4492 /**
4493 * Pre-save transform helper function
4494 *
4495 * @param string $text
4496 * @param User $user
4497 *
4498 * @return string
4499 */
4500 private function pstPass2( $text, $user ) {
4501 global $wgContLang;
4502
4503 # Note: This is the timestamp saved as hardcoded wikitext to
4504 # the database, we use $wgContLang here in order to give
4505 # everyone the same signature and use the default one rather
4506 # than the one selected in each user's preferences.
4507 # (see also T14815)
4508 $ts = $this->mOptions->getTimestamp();
4509 $timestamp = MWTimestamp::getLocalInstance( $ts );
4510 $ts = $timestamp->format( 'YmdHis' );
4511 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4512
4513 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4514
4515 # Variable replacement
4516 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4517 $text = $this->replaceVariables( $text );
4518
4519 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4520 # which may corrupt this parser instance via its wfMessage()->text() call-
4521
4522 # Signatures
4523 $sigText = $this->getUserSig( $user );
4524 $text = strtr( $text, [
4525 '~~~~~' => $d,
4526 '~~~~' => "$sigText $d",
4527 '~~~' => $sigText
4528 ] );
4529
4530 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4531 $tc = '[' . Title::legalChars() . ']';
4532 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4533
4534 // [[ns:page (context)|]]
4535 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4536 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4537 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4538 // [[ns:page (context), context|]] (using either single or double-width comma)
4539 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4540 // [[|page]] (reverse pipe trick: add context from page title)
4541 $p2 = "/\[\[\\|($tc+)]]/";
4542
4543 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4544 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4545 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4546 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4547
4548 $t = $this->mTitle->getText();
4549 $m = [];
4550 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4551 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4552 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4553 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4554 } else {
4555 # if there's no context, don't bother duplicating the title
4556 $text = preg_replace( $p2, '[[\\1]]', $text );
4557 }
4558
4559 return $text;
4560 }
4561
4562 /**
4563 * Fetch the user's signature text, if any, and normalize to
4564 * validated, ready-to-insert wikitext.
4565 * If you have pre-fetched the nickname or the fancySig option, you can
4566 * specify them here to save a database query.
4567 * Do not reuse this parser instance after calling getUserSig(),
4568 * as it may have changed if it's the $wgParser.
4569 *
4570 * @param User $user
4571 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4572 * @param bool|null $fancySig whether the nicknname is the complete signature
4573 * or null to use default value
4574 * @return string
4575 */
4576 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4577 global $wgMaxSigChars;
4578
4579 $username = $user->getName();
4580
4581 # If not given, retrieve from the user object.
4582 if ( $nickname === false ) {
4583 $nickname = $user->getOption( 'nickname' );
4584 }
4585
4586 if ( is_null( $fancySig ) ) {
4587 $fancySig = $user->getBoolOption( 'fancysig' );
4588 }
4589
4590 $nickname = $nickname == null ? $username : $nickname;
4591
4592 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4593 $nickname = $username;
4594 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4595 } elseif ( $fancySig !== false ) {
4596 # Sig. might contain markup; validate this
4597 if ( $this->validateSig( $nickname ) !== false ) {
4598 # Validated; clean up (if needed) and return it
4599 return $this->cleanSig( $nickname, true );
4600 } else {
4601 # Failed to validate; fall back to the default
4602 $nickname = $username;
4603 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4604 }
4605 }
4606
4607 # Make sure nickname doesnt get a sig in a sig
4608 $nickname = self::cleanSigInSig( $nickname );
4609
4610 # If we're still here, make it a link to the user page
4611 $userText = wfEscapeWikiText( $username );
4612 $nickText = wfEscapeWikiText( $nickname );
4613 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4614
4615 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4616 ->title( $this->getTitle() )->text();
4617 }
4618
4619 /**
4620 * Check that the user's signature contains no bad XML
4621 *
4622 * @param string $text
4623 * @return string|bool An expanded string, or false if invalid.
4624 */
4625 public function validateSig( $text ) {
4626 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4627 }
4628
4629 /**
4630 * Clean up signature text
4631 *
4632 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4633 * 2) Substitute all transclusions
4634 *
4635 * @param string $text
4636 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4637 * @return string Signature text
4638 */
4639 public function cleanSig( $text, $parsing = false ) {
4640 if ( !$parsing ) {
4641 global $wgTitle;
4642 $magicScopeVariable = $this->lock();
4643 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4644 }
4645
4646 # Option to disable this feature
4647 if ( !$this->mOptions->getCleanSignatures() ) {
4648 return $text;
4649 }
4650
4651 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4652 # => Move this logic to braceSubstitution()
4653 $substWord = MagicWord::get( 'subst' );
4654 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4655 $substText = '{{' . $substWord->getSynonym( 0 );
4656
4657 $text = preg_replace( $substRegex, $substText, $text );
4658 $text = self::cleanSigInSig( $text );
4659 $dom = $this->preprocessToDom( $text );
4660 $frame = $this->getPreprocessor()->newFrame();
4661 $text = $frame->expand( $dom );
4662
4663 if ( !$parsing ) {
4664 $text = $this->mStripState->unstripBoth( $text );
4665 }
4666
4667 return $text;
4668 }
4669
4670 /**
4671 * Strip 3, 4 or 5 tildes out of signatures.
4672 *
4673 * @param string $text
4674 * @return string Signature text with /~{3,5}/ removed
4675 */
4676 public static function cleanSigInSig( $text ) {
4677 $text = preg_replace( '/~{3,5}/', '', $text );
4678 return $text;
4679 }
4680
4681 /**
4682 * Set up some variables which are usually set up in parse()
4683 * so that an external function can call some class members with confidence
4684 *
4685 * @param Title|null $title
4686 * @param ParserOptions $options
4687 * @param int $outputType
4688 * @param bool $clearState
4689 */
4690 public function startExternalParse( Title $title = null, ParserOptions $options,
4691 $outputType, $clearState = true
4692 ) {
4693 $this->startParse( $title, $options, $outputType, $clearState );
4694 }
4695
4696 /**
4697 * @param Title|null $title
4698 * @param ParserOptions $options
4699 * @param int $outputType
4700 * @param bool $clearState
4701 */
4702 private function startParse( Title $title = null, ParserOptions $options,
4703 $outputType, $clearState = true
4704 ) {
4705 $this->setTitle( $title );
4706 $this->mOptions = $options;
4707 $this->setOutputType( $outputType );
4708 if ( $clearState ) {
4709 $this->clearState();
4710 }
4711 }
4712
4713 /**
4714 * Wrapper for preprocess()
4715 *
4716 * @param string $text The text to preprocess
4717 * @param ParserOptions $options Options
4718 * @param Title|null $title Title object or null to use $wgTitle
4719 * @return string
4720 */
4721 public function transformMsg( $text, $options, $title = null ) {
4722 static $executing = false;
4723
4724 # Guard against infinite recursion
4725 if ( $executing ) {
4726 return $text;
4727 }
4728 $executing = true;
4729
4730 if ( !$title ) {
4731 global $wgTitle;
4732 $title = $wgTitle;
4733 }
4734
4735 $text = $this->preprocess( $text, $title, $options );
4736
4737 $executing = false;
4738 return $text;
4739 }
4740
4741 /**
4742 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4743 * The callback should have the following form:
4744 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4745 *
4746 * Transform and return $text. Use $parser for any required context, e.g. use
4747 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4748 *
4749 * Hooks may return extended information by returning an array, of which the
4750 * first numbered element (index 0) must be the return string, and all other
4751 * entries are extracted into local variables within an internal function
4752 * in the Parser class.
4753 *
4754 * This interface (introduced r61913) appears to be undocumented, but
4755 * 'markerType' is used by some core tag hooks to override which strip
4756 * array their results are placed in. **Use great caution if attempting
4757 * this interface, as it is not documented and injudicious use could smash
4758 * private variables.**
4759 *
4760 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4761 * @param callable $callback The callback function (and object) to use for the tag
4762 * @throws MWException
4763 * @return callable|null The old value of the mTagHooks array associated with the hook
4764 */
4765 public function setHook( $tag, $callback ) {
4766 $tag = strtolower( $tag );
4767 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4768 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4769 }
4770 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4771 $this->mTagHooks[$tag] = $callback;
4772 if ( !in_array( $tag, $this->mStripList ) ) {
4773 $this->mStripList[] = $tag;
4774 }
4775
4776 return $oldVal;
4777 }
4778
4779 /**
4780 * As setHook(), but letting the contents be parsed.
4781 *
4782 * Transparent tag hooks are like regular XML-style tag hooks, except they
4783 * operate late in the transformation sequence, on HTML instead of wikitext.
4784 *
4785 * This is probably obsoleted by things dealing with parser frames?
4786 * The only extension currently using it is geoserver.
4787 *
4788 * @since 1.10
4789 * @todo better document or deprecate this
4790 *
4791 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4792 * @param callable $callback The callback function (and object) to use for the tag
4793 * @throws MWException
4794 * @return callable|null The old value of the mTagHooks array associated with the hook
4795 */
4796 public function setTransparentTagHook( $tag, $callback ) {
4797 $tag = strtolower( $tag );
4798 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4799 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4800 }
4801 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4802 $this->mTransparentTagHooks[$tag] = $callback;
4803
4804 return $oldVal;
4805 }
4806
4807 /**
4808 * Remove all tag hooks
4809 */
4810 public function clearTagHooks() {
4811 $this->mTagHooks = [];
4812 $this->mFunctionTagHooks = [];
4813 $this->mStripList = $this->mDefaultStripList;
4814 }
4815
4816 /**
4817 * Create a function, e.g. {{sum:1|2|3}}
4818 * The callback function should have the form:
4819 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4820 *
4821 * Or with Parser::SFH_OBJECT_ARGS:
4822 * function myParserFunction( $parser, $frame, $args ) { ... }
4823 *
4824 * The callback may either return the text result of the function, or an array with the text
4825 * in element 0, and a number of flags in the other elements. The names of the flags are
4826 * specified in the keys. Valid flags are:
4827 * found The text returned is valid, stop processing the template. This
4828 * is on by default.
4829 * nowiki Wiki markup in the return value should be escaped
4830 * isHTML The returned text is HTML, armour it against wikitext transformation
4831 *
4832 * @param string $id The magic word ID
4833 * @param callable $callback The callback function (and object) to use
4834 * @param int $flags A combination of the following flags:
4835 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4836 *
4837 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4838 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4839 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4840 * the arguments, and to control the way they are expanded.
4841 *
4842 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4843 * arguments, for instance:
4844 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4845 *
4846 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4847 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4848 * working if/when this is changed.
4849 *
4850 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4851 * expansion.
4852 *
4853 * Please read the documentation in includes/parser/Preprocessor.php for more information
4854 * about the methods available in PPFrame and PPNode.
4855 *
4856 * @throws MWException
4857 * @return string|callable The old callback function for this name, if any
4858 */
4859 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4860 global $wgContLang;
4861
4862 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4863 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4864
4865 # Add to function cache
4866 $mw = MagicWord::get( $id );
4867 if ( !$mw ) {
4868 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4869 }
4870
4871 $synonyms = $mw->getSynonyms();
4872 $sensitive = intval( $mw->isCaseSensitive() );
4873
4874 foreach ( $synonyms as $syn ) {
4875 # Case
4876 if ( !$sensitive ) {
4877 $syn = $wgContLang->lc( $syn );
4878 }
4879 # Add leading hash
4880 if ( !( $flags & self::SFH_NO_HASH ) ) {
4881 $syn = '#' . $syn;
4882 }
4883 # Remove trailing colon
4884 if ( substr( $syn, -1, 1 ) === ':' ) {
4885 $syn = substr( $syn, 0, -1 );
4886 }
4887 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4888 }
4889 return $oldVal;
4890 }
4891
4892 /**
4893 * Get all registered function hook identifiers
4894 *
4895 * @return array
4896 */
4897 public function getFunctionHooks() {
4898 return array_keys( $this->mFunctionHooks );
4899 }
4900
4901 /**
4902 * Create a tag function, e.g. "<test>some stuff</test>".
4903 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4904 * Unlike parser functions, their content is not preprocessed.
4905 * @param string $tag
4906 * @param callable $callback
4907 * @param int $flags
4908 * @throws MWException
4909 * @return null
4910 */
4911 public function setFunctionTagHook( $tag, $callback, $flags ) {
4912 $tag = strtolower( $tag );
4913 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4914 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4915 }
4916 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4917 $this->mFunctionTagHooks[$tag] : null;
4918 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
4919
4920 if ( !in_array( $tag, $this->mStripList ) ) {
4921 $this->mStripList[] = $tag;
4922 }
4923
4924 return $old;
4925 }
4926
4927 /**
4928 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4929 * Placeholders created in Linker::link()
4930 *
4931 * @param string $text
4932 * @param int $options
4933 */
4934 public function replaceLinkHolders( &$text, $options = 0 ) {
4935 $this->mLinkHolders->replace( $text );
4936 }
4937
4938 /**
4939 * Replace "<!--LINK-->" link placeholders with plain text of links
4940 * (not HTML-formatted).
4941 *
4942 * @param string $text
4943 * @return string
4944 */
4945 public function replaceLinkHoldersText( $text ) {
4946 return $this->mLinkHolders->replaceText( $text );
4947 }
4948
4949 /**
4950 * Renders an image gallery from a text with one line per image.
4951 * text labels may be given by using |-style alternative text. E.g.
4952 * Image:one.jpg|The number "1"
4953 * Image:tree.jpg|A tree
4954 * given as text will return the HTML of a gallery with two images,
4955 * labeled 'The number "1"' and
4956 * 'A tree'.
4957 *
4958 * @param string $text
4959 * @param array $params
4960 * @return string HTML
4961 */
4962 public function renderImageGallery( $text, $params ) {
4963
4964 $mode = false;
4965 if ( isset( $params['mode'] ) ) {
4966 $mode = $params['mode'];
4967 }
4968
4969 try {
4970 $ig = ImageGalleryBase::factory( $mode );
4971 } catch ( Exception $e ) {
4972 // If invalid type set, fallback to default.
4973 $ig = ImageGalleryBase::factory( false );
4974 }
4975
4976 $ig->setContextTitle( $this->mTitle );
4977 $ig->setShowBytes( false );
4978 $ig->setShowFilename( false );
4979 $ig->setParser( $this );
4980 $ig->setHideBadImages();
4981 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'ul' ) );
4982
4983 if ( isset( $params['showfilename'] ) ) {
4984 $ig->setShowFilename( true );
4985 } else {
4986 $ig->setShowFilename( false );
4987 }
4988 if ( isset( $params['caption'] ) ) {
4989 $caption = $params['caption'];
4990 $caption = htmlspecialchars( $caption );
4991 $caption = $this->replaceInternalLinks( $caption );
4992 $ig->setCaptionHtml( $caption );
4993 }
4994 if ( isset( $params['perrow'] ) ) {
4995 $ig->setPerRow( $params['perrow'] );
4996 }
4997 if ( isset( $params['widths'] ) ) {
4998 $ig->setWidths( $params['widths'] );
4999 }
5000 if ( isset( $params['heights'] ) ) {
5001 $ig->setHeights( $params['heights'] );
5002 }
5003 $ig->setAdditionalOptions( $params );
5004
5005 // Avoid PHP 7.1 warning from passing $this by reference
5006 $parser = $this;
5007 Hooks::run( 'BeforeParserrenderImageGallery', [ &$parser, &$ig ] );
5008
5009 $lines = StringUtils::explode( "\n", $text );
5010 foreach ( $lines as $line ) {
5011 # match lines like these:
5012 # Image:someimage.jpg|This is some image
5013 $matches = [];
5014 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5015 # Skip empty lines
5016 if ( count( $matches ) == 0 ) {
5017 continue;
5018 }
5019
5020 if ( strpos( $matches[0], '%' ) !== false ) {
5021 $matches[1] = rawurldecode( $matches[1] );
5022 }
5023 $title = Title::newFromText( $matches[1], NS_FILE );
5024 if ( is_null( $title ) ) {
5025 # Bogus title. Ignore these so we don't bomb out later.
5026 continue;
5027 }
5028
5029 # We need to get what handler the file uses, to figure out parameters.
5030 # Note, a hook can overide the file name, and chose an entirely different
5031 # file (which potentially could be of a different type and have different handler).
5032 $options = [];
5033 $descQuery = false;
5034 Hooks::run( 'BeforeParserFetchFileAndTitle',
5035 [ $this, $title, &$options, &$descQuery ] );
5036 # Don't register it now, as TraditionalImageGallery does that later.
5037 $file = $this->fetchFileNoRegister( $title, $options );
5038 $handler = $file ? $file->getHandler() : false;
5039
5040 $paramMap = [
5041 'img_alt' => 'gallery-internal-alt',
5042 'img_link' => 'gallery-internal-link',
5043 ];
5044 if ( $handler ) {
5045 $paramMap = $paramMap + $handler->getParamMap();
5046 // We don't want people to specify per-image widths.
5047 // Additionally the width parameter would need special casing anyhow.
5048 unset( $paramMap['img_width'] );
5049 }
5050
5051 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5052
5053 $label = '';
5054 $alt = '';
5055 $link = '';
5056 $handlerOptions = [];
5057 if ( isset( $matches[3] ) ) {
5058 // look for an |alt= definition while trying not to break existing
5059 // captions with multiple pipes (|) in it, until a more sensible grammar
5060 // is defined for images in galleries
5061
5062 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5063 // splitting on '|' is a bit odd, and different from makeImage.
5064 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5065 // Protect LanguageConverter markup
5066 $parameterMatches = StringUtils::delimiterExplode(
5067 '-{', '}-', '|', $matches[3], true /* nested */
5068 );
5069
5070 foreach ( $parameterMatches as $parameterMatch ) {
5071 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5072 if ( $magicName ) {
5073 $paramName = $paramMap[$magicName];
5074
5075 switch ( $paramName ) {
5076 case 'gallery-internal-alt':
5077 $alt = $this->stripAltText( $match, false );
5078 break;
5079 case 'gallery-internal-link':
5080 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5081 $chars = self::EXT_LINK_URL_CLASS;
5082 $addr = self::EXT_LINK_ADDR;
5083 $prots = $this->mUrlProtocols;
5084 // check to see if link matches an absolute url, if not then it must be a wiki link.
5085 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5086 // Result of LanguageConverter::markNoConversion
5087 // invoked on an external link.
5088 $linkValue = substr( $linkValue, 4, -2 );
5089 }
5090 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5091 $link = $linkValue;
5092 $this->mOutput->addExternalLink( $link );
5093 } else {
5094 $localLinkTitle = Title::newFromText( $linkValue );
5095 if ( $localLinkTitle !== null ) {
5096 $this->mOutput->addLink( $localLinkTitle );
5097 $link = $localLinkTitle->getLinkURL();
5098 }
5099 }
5100 break;
5101 default:
5102 // Must be a handler specific parameter.
5103 if ( $handler->validateParam( $paramName, $match ) ) {
5104 $handlerOptions[$paramName] = $match;
5105 } else {
5106 // Guess not, consider it as caption.
5107 wfDebug( "$parameterMatch failed parameter validation\n" );
5108 $label = '|' . $parameterMatch;
5109 }
5110 }
5111
5112 } else {
5113 // Last pipe wins.
5114 $label = '|' . $parameterMatch;
5115 }
5116 }
5117 // Remove the pipe.
5118 $label = substr( $label, 1 );
5119 }
5120
5121 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5122 }
5123 $html = $ig->toHTML();
5124 Hooks::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5125 return $html;
5126 }
5127
5128 /**
5129 * @param MediaHandler $handler
5130 * @return array
5131 */
5132 public function getImageParams( $handler ) {
5133 if ( $handler ) {
5134 $handlerClass = get_class( $handler );
5135 } else {
5136 $handlerClass = '';
5137 }
5138 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5139 # Initialise static lists
5140 static $internalParamNames = [
5141 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5142 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5143 'bottom', 'text-bottom' ],
5144 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5145 'upright', 'border', 'link', 'alt', 'class' ],
5146 ];
5147 static $internalParamMap;
5148 if ( !$internalParamMap ) {
5149 $internalParamMap = [];
5150 foreach ( $internalParamNames as $type => $names ) {
5151 foreach ( $names as $name ) {
5152 // For grep: img_left, img_right, img_center, img_none,
5153 // img_baseline, img_sub, img_super, img_top, img_text_top, img_middle,
5154 // img_bottom, img_text_bottom,
5155 // img_thumbnail, img_manualthumb, img_framed, img_frameless, img_upright,
5156 // img_border, img_link, img_alt, img_class
5157 $magicName = str_replace( '-', '_', "img_$name" );
5158 $internalParamMap[$magicName] = [ $type, $name ];
5159 }
5160 }
5161 }
5162
5163 # Add handler params
5164 $paramMap = $internalParamMap;
5165 if ( $handler ) {
5166 $handlerParamMap = $handler->getParamMap();
5167 foreach ( $handlerParamMap as $magic => $paramName ) {
5168 $paramMap[$magic] = [ 'handler', $paramName ];
5169 }
5170 }
5171 $this->mImageParams[$handlerClass] = $paramMap;
5172 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5173 }
5174 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5175 }
5176
5177 /**
5178 * Parse image options text and use it to make an image
5179 *
5180 * @param Title $title
5181 * @param string $options
5182 * @param LinkHolderArray|bool $holders
5183 * @return string HTML
5184 */
5185 public function makeImage( $title, $options, $holders = false ) {
5186 # Check if the options text is of the form "options|alt text"
5187 # Options are:
5188 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5189 # * left no resizing, just left align. label is used for alt= only
5190 # * right same, but right aligned
5191 # * none same, but not aligned
5192 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5193 # * center center the image
5194 # * frame Keep original image size, no magnify-button.
5195 # * framed Same as "frame"
5196 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5197 # * upright reduce width for upright images, rounded to full __0 px
5198 # * border draw a 1px border around the image
5199 # * alt Text for HTML alt attribute (defaults to empty)
5200 # * class Set a class for img node
5201 # * link Set the target of the image link. Can be external, interwiki, or local
5202 # vertical-align values (no % or length right now):
5203 # * baseline
5204 # * sub
5205 # * super
5206 # * top
5207 # * text-top
5208 # * middle
5209 # * bottom
5210 # * text-bottom
5211
5212 # Protect LanguageConverter markup when splitting into parts
5213 $parts = StringUtils::delimiterExplode(
5214 '-{', '}-', '|', $options, true /* allow nesting */
5215 );
5216
5217 # Give extensions a chance to select the file revision for us
5218 $options = [];
5219 $descQuery = false;
5220 Hooks::run( 'BeforeParserFetchFileAndTitle',
5221 [ $this, $title, &$options, &$descQuery ] );
5222 # Fetch and register the file (file title may be different via hooks)
5223 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5224
5225 # Get parameter map
5226 $handler = $file ? $file->getHandler() : false;
5227
5228 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5229
5230 if ( !$file ) {
5231 $this->addTrackingCategory( 'broken-file-category' );
5232 }
5233
5234 # Process the input parameters
5235 $caption = '';
5236 $params = [ 'frame' => [], 'handler' => [],
5237 'horizAlign' => [], 'vertAlign' => [] ];
5238 $seenformat = false;
5239 foreach ( $parts as $part ) {
5240 $part = trim( $part );
5241 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5242 $validated = false;
5243 if ( isset( $paramMap[$magicName] ) ) {
5244 list( $type, $paramName ) = $paramMap[$magicName];
5245
5246 # Special case; width and height come in one variable together
5247 if ( $type === 'handler' && $paramName === 'width' ) {
5248 $parsedWidthParam = $this->parseWidthParam( $value );
5249 if ( isset( $parsedWidthParam['width'] ) ) {
5250 $width = $parsedWidthParam['width'];
5251 if ( $handler->validateParam( 'width', $width ) ) {
5252 $params[$type]['width'] = $width;
5253 $validated = true;
5254 }
5255 }
5256 if ( isset( $parsedWidthParam['height'] ) ) {
5257 $height = $parsedWidthParam['height'];
5258 if ( $handler->validateParam( 'height', $height ) ) {
5259 $params[$type]['height'] = $height;
5260 $validated = true;
5261 }
5262 }
5263 # else no validation -- T15436
5264 } else {
5265 if ( $type === 'handler' ) {
5266 # Validate handler parameter
5267 $validated = $handler->validateParam( $paramName, $value );
5268 } else {
5269 # Validate internal parameters
5270 switch ( $paramName ) {
5271 case 'manualthumb':
5272 case 'alt':
5273 case 'class':
5274 # @todo FIXME: Possibly check validity here for
5275 # manualthumb? downstream behavior seems odd with
5276 # missing manual thumbs.
5277 $validated = true;
5278 $value = $this->stripAltText( $value, $holders );
5279 break;
5280 case 'link':
5281 $chars = self::EXT_LINK_URL_CLASS;
5282 $addr = self::EXT_LINK_ADDR;
5283 $prots = $this->mUrlProtocols;
5284 if ( $value === '' ) {
5285 $paramName = 'no-link';
5286 $value = true;
5287 $validated = true;
5288 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5289 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5290 $paramName = 'link-url';
5291 $this->mOutput->addExternalLink( $value );
5292 if ( $this->mOptions->getExternalLinkTarget() ) {
5293 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5294 }
5295 $validated = true;
5296 }
5297 } else {
5298 $linkTitle = Title::newFromText( $value );
5299 if ( $linkTitle ) {
5300 $paramName = 'link-title';
5301 $value = $linkTitle;
5302 $this->mOutput->addLink( $linkTitle );
5303 $validated = true;
5304 }
5305 }
5306 break;
5307 case 'frameless':
5308 case 'framed':
5309 case 'thumbnail':
5310 // use first appearing option, discard others.
5311 $validated = !$seenformat;
5312 $seenformat = true;
5313 break;
5314 default:
5315 # Most other things appear to be empty or numeric...
5316 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5317 }
5318 }
5319
5320 if ( $validated ) {
5321 $params[$type][$paramName] = $value;
5322 }
5323 }
5324 }
5325 if ( !$validated ) {
5326 $caption = $part;
5327 }
5328 }
5329
5330 # Process alignment parameters
5331 if ( $params['horizAlign'] ) {
5332 $params['frame']['align'] = key( $params['horizAlign'] );
5333 }
5334 if ( $params['vertAlign'] ) {
5335 $params['frame']['valign'] = key( $params['vertAlign'] );
5336 }
5337
5338 $params['frame']['caption'] = $caption;
5339
5340 # Will the image be presented in a frame, with the caption below?
5341 $imageIsFramed = isset( $params['frame']['frame'] )
5342 || isset( $params['frame']['framed'] )
5343 || isset( $params['frame']['thumbnail'] )
5344 || isset( $params['frame']['manualthumb'] );
5345
5346 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5347 # came to also set the caption, ordinary text after the image -- which
5348 # makes no sense, because that just repeats the text multiple times in
5349 # screen readers. It *also* came to set the title attribute.
5350 # Now that we have an alt attribute, we should not set the alt text to
5351 # equal the caption: that's worse than useless, it just repeats the
5352 # text. This is the framed/thumbnail case. If there's no caption, we
5353 # use the unnamed parameter for alt text as well, just for the time be-
5354 # ing, if the unnamed param is set and the alt param is not.
5355 # For the future, we need to figure out if we want to tweak this more,
5356 # e.g., introducing a title= parameter for the title; ignoring the un-
5357 # named parameter entirely for images without a caption; adding an ex-
5358 # plicit caption= parameter and preserving the old magic unnamed para-
5359 # meter for BC; ...
5360 if ( $imageIsFramed ) { # Framed image
5361 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5362 # No caption or alt text, add the filename as the alt text so
5363 # that screen readers at least get some description of the image
5364 $params['frame']['alt'] = $title->getText();
5365 }
5366 # Do not set $params['frame']['title'] because tooltips don't make sense
5367 # for framed images
5368 } else { # Inline image
5369 if ( !isset( $params['frame']['alt'] ) ) {
5370 # No alt text, use the "caption" for the alt text
5371 if ( $caption !== '' ) {
5372 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5373 } else {
5374 # No caption, fall back to using the filename for the
5375 # alt text
5376 $params['frame']['alt'] = $title->getText();
5377 }
5378 }
5379 # Use the "caption" for the tooltip text
5380 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5381 }
5382
5383 Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5384
5385 # Linker does the rest
5386 $time = isset( $options['time'] ) ? $options['time'] : false;
5387 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5388 $time, $descQuery, $this->mOptions->getThumbSize() );
5389
5390 # Give the handler a chance to modify the parser object
5391 if ( $handler ) {
5392 $handler->parserTransformHook( $this, $file );
5393 }
5394
5395 return $ret;
5396 }
5397
5398 /**
5399 * @param string $caption
5400 * @param LinkHolderArray|bool $holders
5401 * @return mixed|string
5402 */
5403 protected function stripAltText( $caption, $holders ) {
5404 # Strip bad stuff out of the title (tooltip). We can't just use
5405 # replaceLinkHoldersText() here, because if this function is called
5406 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5407 if ( $holders ) {
5408 $tooltip = $holders->replaceText( $caption );
5409 } else {
5410 $tooltip = $this->replaceLinkHoldersText( $caption );
5411 }
5412
5413 # make sure there are no placeholders in thumbnail attributes
5414 # that are later expanded to html- so expand them now and
5415 # remove the tags
5416 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5417 $tooltip = Sanitizer::stripAllTags( $tooltip );
5418
5419 return $tooltip;
5420 }
5421
5422 /**
5423 * Set a flag in the output object indicating that the content is dynamic and
5424 * shouldn't be cached.
5425 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5426 */
5427 public function disableCache() {
5428 wfDebug( "Parser output marked as uncacheable.\n" );
5429 if ( !$this->mOutput ) {
5430 throw new MWException( __METHOD__ .
5431 " can only be called when actually parsing something" );
5432 }
5433 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5434 }
5435
5436 /**
5437 * Callback from the Sanitizer for expanding items found in HTML attribute
5438 * values, so they can be safely tested and escaped.
5439 *
5440 * @param string $text
5441 * @param bool|PPFrame $frame
5442 * @return string
5443 */
5444 public function attributeStripCallback( &$text, $frame = false ) {
5445 $text = $this->replaceVariables( $text, $frame );
5446 $text = $this->mStripState->unstripBoth( $text );
5447 return $text;
5448 }
5449
5450 /**
5451 * Accessor
5452 *
5453 * @return array
5454 */
5455 public function getTags() {
5456 return array_merge(
5457 array_keys( $this->mTransparentTagHooks ),
5458 array_keys( $this->mTagHooks ),
5459 array_keys( $this->mFunctionTagHooks )
5460 );
5461 }
5462
5463 /**
5464 * Replace transparent tags in $text with the values given by the callbacks.
5465 *
5466 * Transparent tag hooks are like regular XML-style tag hooks, except they
5467 * operate late in the transformation sequence, on HTML instead of wikitext.
5468 *
5469 * @param string $text
5470 *
5471 * @return string
5472 */
5473 public function replaceTransparentTags( $text ) {
5474 $matches = [];
5475 $elements = array_keys( $this->mTransparentTagHooks );
5476 $text = self::extractTagsAndParams( $elements, $text, $matches );
5477 $replacements = [];
5478
5479 foreach ( $matches as $marker => $data ) {
5480 list( $element, $content, $params, $tag ) = $data;
5481 $tagName = strtolower( $element );
5482 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5483 $output = call_user_func_array(
5484 $this->mTransparentTagHooks[$tagName],
5485 [ $content, $params, $this ]
5486 );
5487 } else {
5488 $output = $tag;
5489 }
5490 $replacements[$marker] = $output;
5491 }
5492 return strtr( $text, $replacements );
5493 }
5494
5495 /**
5496 * Break wikitext input into sections, and either pull or replace
5497 * some particular section's text.
5498 *
5499 * External callers should use the getSection and replaceSection methods.
5500 *
5501 * @param string $text Page wikitext
5502 * @param string|int $sectionId A section identifier string of the form:
5503 * "<flag1> - <flag2> - ... - <section number>"
5504 *
5505 * Currently the only recognised flag is "T", which means the target section number
5506 * was derived during a template inclusion parse, in other words this is a template
5507 * section edit link. If no flags are given, it was an ordinary section edit link.
5508 * This flag is required to avoid a section numbering mismatch when a section is
5509 * enclosed by "<includeonly>" (T8563).
5510 *
5511 * The section number 0 pulls the text before the first heading; other numbers will
5512 * pull the given section along with its lower-level subsections. If the section is
5513 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5514 *
5515 * Section 0 is always considered to exist, even if it only contains the empty
5516 * string. If $text is the empty string and section 0 is replaced, $newText is
5517 * returned.
5518 *
5519 * @param string $mode One of "get" or "replace"
5520 * @param string $newText Replacement text for section data.
5521 * @return string For "get", the extracted section text.
5522 * for "replace", the whole page with the section replaced.
5523 */
5524 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5525 global $wgTitle; # not generally used but removes an ugly failure mode
5526
5527 $magicScopeVariable = $this->lock();
5528 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5529 $outText = '';
5530 $frame = $this->getPreprocessor()->newFrame();
5531
5532 # Process section extraction flags
5533 $flags = 0;
5534 $sectionParts = explode( '-', $sectionId );
5535 $sectionIndex = array_pop( $sectionParts );
5536 foreach ( $sectionParts as $part ) {
5537 if ( $part === 'T' ) {
5538 $flags |= self::PTD_FOR_INCLUSION;
5539 }
5540 }
5541
5542 # Check for empty input
5543 if ( strval( $text ) === '' ) {
5544 # Only sections 0 and T-0 exist in an empty document
5545 if ( $sectionIndex == 0 ) {
5546 if ( $mode === 'get' ) {
5547 return '';
5548 } else {
5549 return $newText;
5550 }
5551 } else {
5552 if ( $mode === 'get' ) {
5553 return $newText;
5554 } else {
5555 return $text;
5556 }
5557 }
5558 }
5559
5560 # Preprocess the text
5561 $root = $this->preprocessToDom( $text, $flags );
5562
5563 # <h> nodes indicate section breaks
5564 # They can only occur at the top level, so we can find them by iterating the root's children
5565 $node = $root->getFirstChild();
5566
5567 # Find the target section
5568 if ( $sectionIndex == 0 ) {
5569 # Section zero doesn't nest, level=big
5570 $targetLevel = 1000;
5571 } else {
5572 while ( $node ) {
5573 if ( $node->getName() === 'h' ) {
5574 $bits = $node->splitHeading();
5575 if ( $bits['i'] == $sectionIndex ) {
5576 $targetLevel = $bits['level'];
5577 break;
5578 }
5579 }
5580 if ( $mode === 'replace' ) {
5581 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5582 }
5583 $node = $node->getNextSibling();
5584 }
5585 }
5586
5587 if ( !$node ) {
5588 # Not found
5589 if ( $mode === 'get' ) {
5590 return $newText;
5591 } else {
5592 return $text;
5593 }
5594 }
5595
5596 # Find the end of the section, including nested sections
5597 do {
5598 if ( $node->getName() === 'h' ) {
5599 $bits = $node->splitHeading();
5600 $curLevel = $bits['level'];
5601 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5602 break;
5603 }
5604 }
5605 if ( $mode === 'get' ) {
5606 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5607 }
5608 $node = $node->getNextSibling();
5609 } while ( $node );
5610
5611 # Write out the remainder (in replace mode only)
5612 if ( $mode === 'replace' ) {
5613 # Output the replacement text
5614 # Add two newlines on -- trailing whitespace in $newText is conventionally
5615 # stripped by the editor, so we need both newlines to restore the paragraph gap
5616 # Only add trailing whitespace if there is newText
5617 if ( $newText != "" ) {
5618 $outText .= $newText . "\n\n";
5619 }
5620
5621 while ( $node ) {
5622 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5623 $node = $node->getNextSibling();
5624 }
5625 }
5626
5627 if ( is_string( $outText ) ) {
5628 # Re-insert stripped tags
5629 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5630 }
5631
5632 return $outText;
5633 }
5634
5635 /**
5636 * This function returns the text of a section, specified by a number ($section).
5637 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5638 * the first section before any such heading (section 0).
5639 *
5640 * If a section contains subsections, these are also returned.
5641 *
5642 * @param string $text Text to look in
5643 * @param string|int $sectionId Section identifier as a number or string
5644 * (e.g. 0, 1 or 'T-1').
5645 * @param string $defaultText Default to return if section is not found
5646 *
5647 * @return string Text of the requested section
5648 */
5649 public function getSection( $text, $sectionId, $defaultText = '' ) {
5650 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5651 }
5652
5653 /**
5654 * This function returns $oldtext after the content of the section
5655 * specified by $section has been replaced with $text. If the target
5656 * section does not exist, $oldtext is returned unchanged.
5657 *
5658 * @param string $oldText Former text of the article
5659 * @param string|int $sectionId Section identifier as a number or string
5660 * (e.g. 0, 1 or 'T-1').
5661 * @param string $newText Replacing text
5662 *
5663 * @return string Modified text
5664 */
5665 public function replaceSection( $oldText, $sectionId, $newText ) {
5666 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5667 }
5668
5669 /**
5670 * Get the ID of the revision we are parsing
5671 *
5672 * @return int|null
5673 */
5674 public function getRevisionId() {
5675 return $this->mRevisionId;
5676 }
5677
5678 /**
5679 * Get the revision object for $this->mRevisionId
5680 *
5681 * @return Revision|null Either a Revision object or null
5682 * @since 1.23 (public since 1.23)
5683 */
5684 public function getRevisionObject() {
5685 if ( !is_null( $this->mRevisionObject ) ) {
5686 return $this->mRevisionObject;
5687 }
5688 if ( is_null( $this->mRevisionId ) ) {
5689 return null;
5690 }
5691
5692 $rev = call_user_func(
5693 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5694 );
5695
5696 # If the parse is for a new revision, then the callback should have
5697 # already been set to force the object and should match mRevisionId.
5698 # If not, try to fetch by mRevisionId for sanity.
5699 if ( $rev && $rev->getId() != $this->mRevisionId ) {
5700 $rev = Revision::newFromId( $this->mRevisionId );
5701 }
5702
5703 $this->mRevisionObject = $rev;
5704
5705 return $this->mRevisionObject;
5706 }
5707
5708 /**
5709 * Get the timestamp associated with the current revision, adjusted for
5710 * the default server-local timestamp
5711 * @return string
5712 */
5713 public function getRevisionTimestamp() {
5714 if ( is_null( $this->mRevisionTimestamp ) ) {
5715 global $wgContLang;
5716
5717 $revObject = $this->getRevisionObject();
5718 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5719
5720 # The cryptic '' timezone parameter tells to use the site-default
5721 # timezone offset instead of the user settings.
5722 # Since this value will be saved into the parser cache, served
5723 # to other users, and potentially even used inside links and such,
5724 # it needs to be consistent for all visitors.
5725 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5726
5727 }
5728 return $this->mRevisionTimestamp;
5729 }
5730
5731 /**
5732 * Get the name of the user that edited the last revision
5733 *
5734 * @return string User name
5735 */
5736 public function getRevisionUser() {
5737 if ( is_null( $this->mRevisionUser ) ) {
5738 $revObject = $this->getRevisionObject();
5739
5740 # if this template is subst: the revision id will be blank,
5741 # so just use the current user's name
5742 if ( $revObject ) {
5743 $this->mRevisionUser = $revObject->getUserText();
5744 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5745 $this->mRevisionUser = $this->getUser()->getName();
5746 }
5747 }
5748 return $this->mRevisionUser;
5749 }
5750
5751 /**
5752 * Get the size of the revision
5753 *
5754 * @return int|null Revision size
5755 */
5756 public function getRevisionSize() {
5757 if ( is_null( $this->mRevisionSize ) ) {
5758 $revObject = $this->getRevisionObject();
5759
5760 # if this variable is subst: the revision id will be blank,
5761 # so just use the parser input size, because the own substituation
5762 # will change the size.
5763 if ( $revObject ) {
5764 $this->mRevisionSize = $revObject->getSize();
5765 } else {
5766 $this->mRevisionSize = $this->mInputSize;
5767 }
5768 }
5769 return $this->mRevisionSize;
5770 }
5771
5772 /**
5773 * Mutator for $mDefaultSort
5774 *
5775 * @param string $sort New value
5776 */
5777 public function setDefaultSort( $sort ) {
5778 $this->mDefaultSort = $sort;
5779 $this->mOutput->setProperty( 'defaultsort', $sort );
5780 }
5781
5782 /**
5783 * Accessor for $mDefaultSort
5784 * Will use the empty string if none is set.
5785 *
5786 * This value is treated as a prefix, so the
5787 * empty string is equivalent to sorting by
5788 * page name.
5789 *
5790 * @return string
5791 */
5792 public function getDefaultSort() {
5793 if ( $this->mDefaultSort !== false ) {
5794 return $this->mDefaultSort;
5795 } else {
5796 return '';
5797 }
5798 }
5799
5800 /**
5801 * Accessor for $mDefaultSort
5802 * Unlike getDefaultSort(), will return false if none is set
5803 *
5804 * @return string|bool
5805 */
5806 public function getCustomDefaultSort() {
5807 return $this->mDefaultSort;
5808 }
5809
5810 /**
5811 * Try to guess the section anchor name based on a wikitext fragment
5812 * presumably extracted from a heading, for example "Header" from
5813 * "== Header ==".
5814 *
5815 * @param string $text
5816 *
5817 * @return string
5818 */
5819 public function guessSectionNameFromWikiText( $text ) {
5820 # Strip out wikitext links(they break the anchor)
5821 $text = $this->stripSectionName( $text );
5822 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5823 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5824 }
5825
5826 /**
5827 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5828 * instead. For use in redirects, since IE6 interprets Redirect: headers
5829 * as something other than UTF-8 (apparently?), resulting in breakage.
5830 *
5831 * @param string $text The section name
5832 * @return string An anchor
5833 */
5834 public function guessLegacySectionNameFromWikiText( $text ) {
5835 # Strip out wikitext links(they break the anchor)
5836 $text = $this->stripSectionName( $text );
5837 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5838 return '#' . Sanitizer::escapeId( $text, [ 'noninitial', 'legacy' ] );
5839 }
5840
5841 /**
5842 * Strips a text string of wikitext for use in a section anchor
5843 *
5844 * Accepts a text string and then removes all wikitext from the
5845 * string and leaves only the resultant text (i.e. the result of
5846 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5847 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5848 * to create valid section anchors by mimicing the output of the
5849 * parser when headings are parsed.
5850 *
5851 * @param string $text Text string to be stripped of wikitext
5852 * for use in a Section anchor
5853 * @return string Filtered text string
5854 */
5855 public function stripSectionName( $text ) {
5856 # Strip internal link markup
5857 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5858 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5859
5860 # Strip external link markup
5861 # @todo FIXME: Not tolerant to blank link text
5862 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5863 # on how many empty links there are on the page - need to figure that out.
5864 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5865
5866 # Parse wikitext quotes (italics & bold)
5867 $text = $this->doQuotes( $text );
5868
5869 # Strip HTML tags
5870 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5871 return $text;
5872 }
5873
5874 /**
5875 * strip/replaceVariables/unstrip for preprocessor regression testing
5876 *
5877 * @param string $text
5878 * @param Title $title
5879 * @param ParserOptions $options
5880 * @param int $outputType
5881 *
5882 * @return string
5883 */
5884 public function testSrvus( $text, Title $title, ParserOptions $options,
5885 $outputType = self::OT_HTML
5886 ) {
5887 $magicScopeVariable = $this->lock();
5888 $this->startParse( $title, $options, $outputType, true );
5889
5890 $text = $this->replaceVariables( $text );
5891 $text = $this->mStripState->unstripBoth( $text );
5892 $text = Sanitizer::removeHTMLtags( $text );
5893 return $text;
5894 }
5895
5896 /**
5897 * @param string $text
5898 * @param Title $title
5899 * @param ParserOptions $options
5900 * @return string
5901 */
5902 public function testPst( $text, Title $title, ParserOptions $options ) {
5903 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5904 }
5905
5906 /**
5907 * @param string $text
5908 * @param Title $title
5909 * @param ParserOptions $options
5910 * @return string
5911 */
5912 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
5913 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5914 }
5915
5916 /**
5917 * Call a callback function on all regions of the given text that are not
5918 * inside strip markers, and replace those regions with the return value
5919 * of the callback. For example, with input:
5920 *
5921 * aaa<MARKER>bbb
5922 *
5923 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5924 * two strings will be replaced with the value returned by the callback in
5925 * each case.
5926 *
5927 * @param string $s
5928 * @param callable $callback
5929 *
5930 * @return string
5931 */
5932 public function markerSkipCallback( $s, $callback ) {
5933 $i = 0;
5934 $out = '';
5935 while ( $i < strlen( $s ) ) {
5936 $markerStart = strpos( $s, self::MARKER_PREFIX, $i );
5937 if ( $markerStart === false ) {
5938 $out .= call_user_func( $callback, substr( $s, $i ) );
5939 break;
5940 } else {
5941 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5942 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5943 if ( $markerEnd === false ) {
5944 $out .= substr( $s, $markerStart );
5945 break;
5946 } else {
5947 $markerEnd += strlen( self::MARKER_SUFFIX );
5948 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5949 $i = $markerEnd;
5950 }
5951 }
5952 }
5953 return $out;
5954 }
5955
5956 /**
5957 * Remove any strip markers found in the given text.
5958 *
5959 * @param string $text Input string
5960 * @return string
5961 */
5962 public function killMarkers( $text ) {
5963 return $this->mStripState->killMarkers( $text );
5964 }
5965
5966 /**
5967 * Save the parser state required to convert the given half-parsed text to
5968 * HTML. "Half-parsed" in this context means the output of
5969 * recursiveTagParse() or internalParse(). This output has strip markers
5970 * from replaceVariables (extensionSubstitution() etc.), and link
5971 * placeholders from replaceLinkHolders().
5972 *
5973 * Returns an array which can be serialized and stored persistently. This
5974 * array can later be loaded into another parser instance with
5975 * unserializeHalfParsedText(). The text can then be safely incorporated into
5976 * the return value of a parser hook.
5977 *
5978 * @param string $text
5979 *
5980 * @return array
5981 */
5982 public function serializeHalfParsedText( $text ) {
5983 $data = [
5984 'text' => $text,
5985 'version' => self::HALF_PARSED_VERSION,
5986 'stripState' => $this->mStripState->getSubState( $text ),
5987 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5988 ];
5989 return $data;
5990 }
5991
5992 /**
5993 * Load the parser state given in the $data array, which is assumed to
5994 * have been generated by serializeHalfParsedText(). The text contents is
5995 * extracted from the array, and its markers are transformed into markers
5996 * appropriate for the current Parser instance. This transformed text is
5997 * returned, and can be safely included in the return value of a parser
5998 * hook.
5999 *
6000 * If the $data array has been stored persistently, the caller should first
6001 * check whether it is still valid, by calling isValidHalfParsedText().
6002 *
6003 * @param array $data Serialized data
6004 * @throws MWException
6005 * @return string
6006 */
6007 public function unserializeHalfParsedText( $data ) {
6008 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6009 throw new MWException( __METHOD__ . ': invalid version' );
6010 }
6011
6012 # First, extract the strip state.
6013 $texts = [ $data['text'] ];
6014 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6015
6016 # Now renumber links
6017 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6018
6019 # Should be good to go.
6020 return $texts[0];
6021 }
6022
6023 /**
6024 * Returns true if the given array, presumed to be generated by
6025 * serializeHalfParsedText(), is compatible with the current version of the
6026 * parser.
6027 *
6028 * @param array $data
6029 *
6030 * @return bool
6031 */
6032 public function isValidHalfParsedText( $data ) {
6033 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6034 }
6035
6036 /**
6037 * Parsed a width param of imagelink like 300px or 200x300px
6038 *
6039 * @param string $value
6040 *
6041 * @return array
6042 * @since 1.20
6043 */
6044 public function parseWidthParam( $value ) {
6045 $parsedWidthParam = [];
6046 if ( $value === '' ) {
6047 return $parsedWidthParam;
6048 }
6049 $m = [];
6050 # (T15500) In both cases (width/height and width only),
6051 # permit trailing "px" for backward compatibility.
6052 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6053 $width = intval( $m[1] );
6054 $height = intval( $m[2] );
6055 $parsedWidthParam['width'] = $width;
6056 $parsedWidthParam['height'] = $height;
6057 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6058 $width = intval( $value );
6059 $parsedWidthParam['width'] = $width;
6060 }
6061 return $parsedWidthParam;
6062 }
6063
6064 /**
6065 * Lock the current instance of the parser.
6066 *
6067 * This is meant to stop someone from calling the parser
6068 * recursively and messing up all the strip state.
6069 *
6070 * @throws MWException If parser is in a parse
6071 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6072 */
6073 protected function lock() {
6074 if ( $this->mInParse ) {
6075 throw new MWException( "Parser state cleared while parsing. "
6076 . "Did you call Parser::parse recursively?" );
6077 }
6078 $this->mInParse = true;
6079
6080 $recursiveCheck = new ScopedCallback( function() {
6081 $this->mInParse = false;
6082 } );
6083
6084 return $recursiveCheck;
6085 }
6086
6087 /**
6088 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6089 *
6090 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6091 * or if there is more than one <p/> tag in the input HTML.
6092 *
6093 * @param string $html
6094 * @return string
6095 * @since 1.24
6096 */
6097 public static function stripOuterParagraph( $html ) {
6098 $m = [];
6099 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6100 if ( strpos( $m[1], '</p>' ) === false ) {
6101 $html = $m[1];
6102 }
6103 }
6104
6105 return $html;
6106 }
6107
6108 /**
6109 * Return this parser if it is not doing anything, otherwise
6110 * get a fresh parser. You can use this method by doing
6111 * $myParser = $wgParser->getFreshParser(), or more simply
6112 * $wgParser->getFreshParser()->parse( ... );
6113 * if you're unsure if $wgParser is safe to use.
6114 *
6115 * @since 1.24
6116 * @return Parser A parser object that is not parsing anything
6117 */
6118 public function getFreshParser() {
6119 global $wgParserConf;
6120 if ( $this->mInParse ) {
6121 return new $wgParserConf['class']( $wgParserConf );
6122 } else {
6123 return $this;
6124 }
6125 }
6126
6127 /**
6128 * Set's up the PHP implementation of OOUI for use in this request
6129 * and instructs OutputPage to enable OOUI for itself.
6130 *
6131 * @since 1.26
6132 */
6133 public function enableOOUI() {
6134 OutputPage::setupOOUI();
6135 $this->mOutput->setEnableOOUI( true );
6136 }
6137 }