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