Merge "phpunit: Use assertEquals(, $delta) in UserTest instead of greater/lessThan"
[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 'cascadingsources':
2816 $value = CoreParserFunctions::cascadingsources( $this );
2817 break;
2818 default:
2819 $ret = null;
2820 Hooks::run(
2821 'ParserGetVariableValueSwitch',
2822 [ &$this, &$this->mVarCache, &$index, &$ret, &$frame ]
2823 );
2824
2825 return $ret;
2826 }
2827
2828 if ( $index ) {
2829 $this->mVarCache[$index] = $value;
2830 }
2831
2832 return $value;
2833 }
2834
2835 /**
2836 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2837 *
2838 * @private
2839 */
2840 public function initialiseVariables() {
2841 $variableIDs = MagicWord::getVariableIDs();
2842 $substIDs = MagicWord::getSubstIDs();
2843
2844 $this->mVariables = new MagicWordArray( $variableIDs );
2845 $this->mSubstWords = new MagicWordArray( $substIDs );
2846 }
2847
2848 /**
2849 * Preprocess some wikitext and return the document tree.
2850 * This is the ghost of replace_variables().
2851 *
2852 * @param string $text The text to parse
2853 * @param int $flags Bitwise combination of:
2854 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
2855 * included. Default is to assume a direct page view.
2856 *
2857 * The generated DOM tree must depend only on the input text and the flags.
2858 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of T6899.
2859 *
2860 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2861 * change in the DOM tree for a given text, must be passed through the section identifier
2862 * in the section edit link and thus back to extractSections().
2863 *
2864 * The output of this function is currently only cached in process memory, but a persistent
2865 * cache may be implemented at a later date which takes further advantage of these strict
2866 * dependency requirements.
2867 *
2868 * @return PPNode
2869 */
2870 public function preprocessToDom( $text, $flags = 0 ) {
2871 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2872 return $dom;
2873 }
2874
2875 /**
2876 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2877 *
2878 * @param string $s
2879 *
2880 * @return array
2881 */
2882 public static function splitWhitespace( $s ) {
2883 $ltrimmed = ltrim( $s );
2884 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2885 $trimmed = rtrim( $ltrimmed );
2886 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2887 if ( $diff > 0 ) {
2888 $w2 = substr( $ltrimmed, -$diff );
2889 } else {
2890 $w2 = '';
2891 }
2892 return [ $w1, $trimmed, $w2 ];
2893 }
2894
2895 /**
2896 * Replace magic variables, templates, and template arguments
2897 * with the appropriate text. Templates are substituted recursively,
2898 * taking care to avoid infinite loops.
2899 *
2900 * Note that the substitution depends on value of $mOutputType:
2901 * self::OT_WIKI: only {{subst:}} templates
2902 * self::OT_PREPROCESS: templates but not extension tags
2903 * self::OT_HTML: all templates and extension tags
2904 *
2905 * @param string $text The text to transform
2906 * @param bool|PPFrame $frame Object describing the arguments passed to the
2907 * template. Arguments may also be provided as an associative array, as
2908 * was the usual case before MW1.12. Providing arguments this way may be
2909 * useful for extensions wishing to perform variable replacement
2910 * explicitly.
2911 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
2912 * double-brace expansion.
2913 * @return string
2914 */
2915 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2916 # Is there any text? Also, Prevent too big inclusions!
2917 $textSize = strlen( $text );
2918 if ( $textSize < 1 || $textSize > $this->mOptions->getMaxIncludeSize() ) {
2919 return $text;
2920 }
2921
2922 if ( $frame === false ) {
2923 $frame = $this->getPreprocessor()->newFrame();
2924 } elseif ( !( $frame instanceof PPFrame ) ) {
2925 wfDebug( __METHOD__ . " called using plain parameters instead of "
2926 . "a PPFrame instance. Creating custom frame.\n" );
2927 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2928 }
2929
2930 $dom = $this->preprocessToDom( $text );
2931 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2932 $text = $frame->expand( $dom, $flags );
2933
2934 return $text;
2935 }
2936
2937 /**
2938 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2939 *
2940 * @param array $args
2941 *
2942 * @return array
2943 */
2944 public static function createAssocArgs( $args ) {
2945 $assocArgs = [];
2946 $index = 1;
2947 foreach ( $args as $arg ) {
2948 $eqpos = strpos( $arg, '=' );
2949 if ( $eqpos === false ) {
2950 $assocArgs[$index++] = $arg;
2951 } else {
2952 $name = trim( substr( $arg, 0, $eqpos ) );
2953 $value = trim( substr( $arg, $eqpos + 1 ) );
2954 if ( $value === false ) {
2955 $value = '';
2956 }
2957 if ( $name !== false ) {
2958 $assocArgs[$name] = $value;
2959 }
2960 }
2961 }
2962
2963 return $assocArgs;
2964 }
2965
2966 /**
2967 * Warn the user when a parser limitation is reached
2968 * Will warn at most once the user per limitation type
2969 *
2970 * The results are shown during preview and run through the Parser (See EditPage.php)
2971 *
2972 * @param string $limitationType Should be one of:
2973 * 'expensive-parserfunction' (corresponding messages:
2974 * 'expensive-parserfunction-warning',
2975 * 'expensive-parserfunction-category')
2976 * 'post-expand-template-argument' (corresponding messages:
2977 * 'post-expand-template-argument-warning',
2978 * 'post-expand-template-argument-category')
2979 * 'post-expand-template-inclusion' (corresponding messages:
2980 * 'post-expand-template-inclusion-warning',
2981 * 'post-expand-template-inclusion-category')
2982 * 'node-count-exceeded' (corresponding messages:
2983 * 'node-count-exceeded-warning',
2984 * 'node-count-exceeded-category')
2985 * 'expansion-depth-exceeded' (corresponding messages:
2986 * 'expansion-depth-exceeded-warning',
2987 * 'expansion-depth-exceeded-category')
2988 * @param string|int|null $current Current value
2989 * @param string|int|null $max Maximum allowed, when an explicit limit has been
2990 * exceeded, provide the values (optional)
2991 */
2992 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
2993 # does no harm if $current and $max are present but are unnecessary for the message
2994 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
2995 # only during preview, and that would split the parser cache unnecessarily.
2996 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
2997 ->text();
2998 $this->mOutput->addWarning( $warning );
2999 $this->addTrackingCategory( "$limitationType-category" );
3000 }
3001
3002 /**
3003 * Return the text of a template, after recursively
3004 * replacing any variables or templates within the template.
3005 *
3006 * @param array $piece The parts of the template
3007 * $piece['title']: the title, i.e. the part before the |
3008 * $piece['parts']: the parameter array
3009 * $piece['lineStart']: whether the brace was at the start of a line
3010 * @param PPFrame $frame The current frame, contains template arguments
3011 * @throws Exception
3012 * @return string The text of the template
3013 */
3014 public function braceSubstitution( $piece, $frame ) {
3015
3016 // Flags
3017
3018 // $text has been filled
3019 $found = false;
3020 // wiki markup in $text should be escaped
3021 $nowiki = false;
3022 // $text is HTML, armour it against wikitext transformation
3023 $isHTML = false;
3024 // Force interwiki transclusion to be done in raw mode not rendered
3025 $forceRawInterwiki = false;
3026 // $text is a DOM node needing expansion in a child frame
3027 $isChildObj = false;
3028 // $text is a DOM node needing expansion in the current frame
3029 $isLocalObj = false;
3030
3031 # Title object, where $text came from
3032 $title = false;
3033
3034 # $part1 is the bit before the first |, and must contain only title characters.
3035 # Various prefixes will be stripped from it later.
3036 $titleWithSpaces = $frame->expand( $piece['title'] );
3037 $part1 = trim( $titleWithSpaces );
3038 $titleText = false;
3039
3040 # Original title text preserved for various purposes
3041 $originalTitle = $part1;
3042
3043 # $args is a list of argument nodes, starting from index 0, not including $part1
3044 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3045 # below won't work b/c this $args isn't an object
3046 $args = ( null == $piece['parts'] ) ? [] : $piece['parts'];
3047
3048 $profileSection = null; // profile templates
3049
3050 # SUBST
3051 if ( !$found ) {
3052 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3053
3054 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3055 # Decide whether to expand template or keep wikitext as-is.
3056 if ( $this->ot['wiki'] ) {
3057 if ( $substMatch === false ) {
3058 $literal = true; # literal when in PST with no prefix
3059 } else {
3060 $literal = false; # expand when in PST with subst: or safesubst:
3061 }
3062 } else {
3063 if ( $substMatch == 'subst' ) {
3064 $literal = true; # literal when not in PST with plain subst:
3065 } else {
3066 $literal = false; # expand when not in PST with safesubst: or no prefix
3067 }
3068 }
3069 if ( $literal ) {
3070 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3071 $isLocalObj = true;
3072 $found = true;
3073 }
3074 }
3075
3076 # Variables
3077 if ( !$found && $args->getLength() == 0 ) {
3078 $id = $this->mVariables->matchStartToEnd( $part1 );
3079 if ( $id !== false ) {
3080 $text = $this->getVariableValue( $id, $frame );
3081 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3082 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3083 }
3084 $found = true;
3085 }
3086 }
3087
3088 # MSG, MSGNW and RAW
3089 if ( !$found ) {
3090 # Check for MSGNW:
3091 $mwMsgnw = MagicWord::get( 'msgnw' );
3092 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3093 $nowiki = true;
3094 } else {
3095 # Remove obsolete MSG:
3096 $mwMsg = MagicWord::get( 'msg' );
3097 $mwMsg->matchStartAndRemove( $part1 );
3098 }
3099
3100 # Check for RAW:
3101 $mwRaw = MagicWord::get( 'raw' );
3102 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3103 $forceRawInterwiki = true;
3104 }
3105 }
3106
3107 # Parser functions
3108 if ( !$found ) {
3109 $colonPos = strpos( $part1, ':' );
3110 if ( $colonPos !== false ) {
3111 $func = substr( $part1, 0, $colonPos );
3112 $funcArgs = [ trim( substr( $part1, $colonPos + 1 ) ) ];
3113 $argsLength = $args->getLength();
3114 for ( $i = 0; $i < $argsLength; $i++ ) {
3115 $funcArgs[] = $args->item( $i );
3116 }
3117 try {
3118 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3119 } catch ( Exception $ex ) {
3120 throw $ex;
3121 }
3122
3123 # The interface for parser functions allows for extracting
3124 # flags into the local scope. Extract any forwarded flags
3125 # here.
3126 extract( $result );
3127 }
3128 }
3129
3130 # Finish mangling title and then check for loops.
3131 # Set $title to a Title object and $titleText to the PDBK
3132 if ( !$found ) {
3133 $ns = NS_TEMPLATE;
3134 # Split the title into page and subpage
3135 $subpage = '';
3136 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3137 if ( $part1 !== $relative ) {
3138 $part1 = $relative;
3139 $ns = $this->mTitle->getNamespace();
3140 }
3141 $title = Title::newFromText( $part1, $ns );
3142 if ( $title ) {
3143 $titleText = $title->getPrefixedText();
3144 # Check for language variants if the template is not found
3145 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3146 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3147 }
3148 # Do recursion depth check
3149 $limit = $this->mOptions->getMaxTemplateDepth();
3150 if ( $frame->depth >= $limit ) {
3151 $found = true;
3152 $text = '<span class="error">'
3153 . wfMessage( 'parser-template-recursion-depth-warning' )
3154 ->numParams( $limit )->inContentLanguage()->text()
3155 . '</span>';
3156 }
3157 }
3158 }
3159
3160 # Load from database
3161 if ( !$found && $title ) {
3162 $profileSection = $this->mProfiler->scopedProfileIn( $title->getPrefixedDBkey() );
3163 if ( !$title->isExternal() ) {
3164 if ( $title->isSpecialPage()
3165 && $this->mOptions->getAllowSpecialInclusion()
3166 && $this->ot['html']
3167 ) {
3168 $specialPage = SpecialPageFactory::getPage( $title->getDBkey() );
3169 // Pass the template arguments as URL parameters.
3170 // "uselang" will have no effect since the Language object
3171 // is forced to the one defined in ParserOptions.
3172 $pageArgs = [];
3173 $argsLength = $args->getLength();
3174 for ( $i = 0; $i < $argsLength; $i++ ) {
3175 $bits = $args->item( $i )->splitArg();
3176 if ( strval( $bits['index'] ) === '' ) {
3177 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3178 $value = trim( $frame->expand( $bits['value'] ) );
3179 $pageArgs[$name] = $value;
3180 }
3181 }
3182
3183 // Create a new context to execute the special page
3184 $context = new RequestContext;
3185 $context->setTitle( $title );
3186 $context->setRequest( new FauxRequest( $pageArgs ) );
3187 if ( $specialPage && $specialPage->maxIncludeCacheTime() === 0 ) {
3188 $context->setUser( $this->getUser() );
3189 } else {
3190 // If this page is cached, then we better not be per user.
3191 $context->setUser( User::newFromName( '127.0.0.1', false ) );
3192 }
3193 $context->setLanguage( $this->mOptions->getUserLangObj() );
3194 $ret = SpecialPageFactory::capturePath(
3195 $title, $context, $this->getLinkRenderer() );
3196 if ( $ret ) {
3197 $text = $context->getOutput()->getHTML();
3198 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3199 $found = true;
3200 $isHTML = true;
3201 if ( $specialPage && $specialPage->maxIncludeCacheTime() !== false ) {
3202 $this->mOutput->updateRuntimeAdaptiveExpiry(
3203 $specialPage->maxIncludeCacheTime()
3204 );
3205 }
3206 }
3207 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3208 $found = false; # access denied
3209 wfDebug( __METHOD__ . ": template inclusion denied for " .
3210 $title->getPrefixedDBkey() . "\n" );
3211 } else {
3212 list( $text, $title ) = $this->getTemplateDom( $title );
3213 if ( $text !== false ) {
3214 $found = true;
3215 $isChildObj = true;
3216 }
3217 }
3218
3219 # If the title is valid but undisplayable, make a link to it
3220 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3221 $text = "[[:$titleText]]";
3222 $found = true;
3223 }
3224 } elseif ( $title->isTrans() ) {
3225 # Interwiki transclusion
3226 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3227 $text = $this->interwikiTransclude( $title, 'render' );
3228 $isHTML = true;
3229 } else {
3230 $text = $this->interwikiTransclude( $title, 'raw' );
3231 # Preprocess it like a template
3232 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3233 $isChildObj = true;
3234 }
3235 $found = true;
3236 }
3237
3238 # Do infinite loop check
3239 # This has to be done after redirect resolution to avoid infinite loops via redirects
3240 if ( !$frame->loopCheck( $title ) ) {
3241 $found = true;
3242 $text = '<span class="error">'
3243 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3244 . '</span>';
3245 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3246 }
3247 }
3248
3249 # If we haven't found text to substitute by now, we're done
3250 # Recover the source wikitext and return it
3251 if ( !$found ) {
3252 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3253 if ( $profileSection ) {
3254 $this->mProfiler->scopedProfileOut( $profileSection );
3255 }
3256 return [ 'object' => $text ];
3257 }
3258
3259 # Expand DOM-style return values in a child frame
3260 if ( $isChildObj ) {
3261 # Clean up argument array
3262 $newFrame = $frame->newChild( $args, $title );
3263
3264 if ( $nowiki ) {
3265 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3266 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3267 # Expansion is eligible for the empty-frame cache
3268 $text = $newFrame->cachedExpand( $titleText, $text );
3269 } else {
3270 # Uncached expansion
3271 $text = $newFrame->expand( $text );
3272 }
3273 }
3274 if ( $isLocalObj && $nowiki ) {
3275 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3276 $isLocalObj = false;
3277 }
3278
3279 if ( $profileSection ) {
3280 $this->mProfiler->scopedProfileOut( $profileSection );
3281 }
3282
3283 # Replace raw HTML by a placeholder
3284 if ( $isHTML ) {
3285 $text = $this->insertStripItem( $text );
3286 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3287 # Escape nowiki-style return values
3288 $text = wfEscapeWikiText( $text );
3289 } elseif ( is_string( $text )
3290 && !$piece['lineStart']
3291 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3292 ) {
3293 # T2529: if the template begins with a table or block-level
3294 # element, it should be treated as beginning a new line.
3295 # This behavior is somewhat controversial.
3296 $text = "\n" . $text;
3297 }
3298
3299 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3300 # Error, oversize inclusion
3301 if ( $titleText !== false ) {
3302 # Make a working, properly escaped link if possible (T25588)
3303 $text = "[[:$titleText]]";
3304 } else {
3305 # This will probably not be a working link, but at least it may
3306 # provide some hint of where the problem is
3307 preg_replace( '/^:/', '', $originalTitle );
3308 $text = "[[:$originalTitle]]";
3309 }
3310 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3311 . 'post-expand include size too large -->' );
3312 $this->limitationWarn( 'post-expand-template-inclusion' );
3313 }
3314
3315 if ( $isLocalObj ) {
3316 $ret = [ 'object' => $text ];
3317 } else {
3318 $ret = [ 'text' => $text ];
3319 }
3320
3321 return $ret;
3322 }
3323
3324 /**
3325 * Call a parser function and return an array with text and flags.
3326 *
3327 * The returned array will always contain a boolean 'found', indicating
3328 * whether the parser function was found or not. It may also contain the
3329 * following:
3330 * text: string|object, resulting wikitext or PP DOM object
3331 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3332 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3333 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3334 * nowiki: bool, wiki markup in $text should be escaped
3335 *
3336 * @since 1.21
3337 * @param PPFrame $frame The current frame, contains template arguments
3338 * @param string $function Function name
3339 * @param array $args Arguments to the function
3340 * @throws MWException
3341 * @return array
3342 */
3343 public function callParserFunction( $frame, $function, array $args = [] ) {
3344 global $wgContLang;
3345
3346 # Case sensitive functions
3347 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3348 $function = $this->mFunctionSynonyms[1][$function];
3349 } else {
3350 # Case insensitive functions
3351 $function = $wgContLang->lc( $function );
3352 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3353 $function = $this->mFunctionSynonyms[0][$function];
3354 } else {
3355 return [ 'found' => false ];
3356 }
3357 }
3358
3359 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3360
3361 # Workaround for PHP bug 35229 and similar
3362 if ( !is_callable( $callback ) ) {
3363 throw new MWException( "Tag hook for $function is not callable\n" );
3364 }
3365
3366 $allArgs = [ &$this ];
3367 if ( $flags & self::SFH_OBJECT_ARGS ) {
3368 # Convert arguments to PPNodes and collect for appending to $allArgs
3369 $funcArgs = [];
3370 foreach ( $args as $k => $v ) {
3371 if ( $v instanceof PPNode || $k === 0 ) {
3372 $funcArgs[] = $v;
3373 } else {
3374 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( [ $k => $v ] )->item( 0 );
3375 }
3376 }
3377
3378 # Add a frame parameter, and pass the arguments as an array
3379 $allArgs[] = $frame;
3380 $allArgs[] = $funcArgs;
3381 } else {
3382 # Convert arguments to plain text and append to $allArgs
3383 foreach ( $args as $k => $v ) {
3384 if ( $v instanceof PPNode ) {
3385 $allArgs[] = trim( $frame->expand( $v ) );
3386 } elseif ( is_int( $k ) && $k >= 0 ) {
3387 $allArgs[] = trim( $v );
3388 } else {
3389 $allArgs[] = trim( "$k=$v" );
3390 }
3391 }
3392 }
3393
3394 $result = call_user_func_array( $callback, $allArgs );
3395
3396 # The interface for function hooks allows them to return a wikitext
3397 # string or an array containing the string and any flags. This mungs
3398 # things around to match what this method should return.
3399 if ( !is_array( $result ) ) {
3400 $result =[
3401 'found' => true,
3402 'text' => $result,
3403 ];
3404 } else {
3405 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3406 $result['text'] = $result[0];
3407 }
3408 unset( $result[0] );
3409 $result += [
3410 'found' => true,
3411 ];
3412 }
3413
3414 $noparse = true;
3415 $preprocessFlags = 0;
3416 if ( isset( $result['noparse'] ) ) {
3417 $noparse = $result['noparse'];
3418 }
3419 if ( isset( $result['preprocessFlags'] ) ) {
3420 $preprocessFlags = $result['preprocessFlags'];
3421 }
3422
3423 if ( !$noparse ) {
3424 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3425 $result['isChildObj'] = true;
3426 }
3427
3428 return $result;
3429 }
3430
3431 /**
3432 * Get the semi-parsed DOM representation of a template with a given title,
3433 * and its redirect destination title. Cached.
3434 *
3435 * @param Title $title
3436 *
3437 * @return array
3438 */
3439 public function getTemplateDom( $title ) {
3440 $cacheTitle = $title;
3441 $titleText = $title->getPrefixedDBkey();
3442
3443 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3444 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3445 $title = Title::makeTitle( $ns, $dbk );
3446 $titleText = $title->getPrefixedDBkey();
3447 }
3448 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3449 return [ $this->mTplDomCache[$titleText], $title ];
3450 }
3451
3452 # Cache miss, go to the database
3453 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3454
3455 if ( $text === false ) {
3456 $this->mTplDomCache[$titleText] = false;
3457 return [ false, $title ];
3458 }
3459
3460 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3461 $this->mTplDomCache[$titleText] = $dom;
3462
3463 if ( !$title->equals( $cacheTitle ) ) {
3464 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3465 [ $title->getNamespace(), $cdb = $title->getDBkey() ];
3466 }
3467
3468 return [ $dom, $title ];
3469 }
3470
3471 /**
3472 * Fetch the current revision of a given title. Note that the revision
3473 * (and even the title) may not exist in the database, so everything
3474 * contributing to the output of the parser should use this method
3475 * where possible, rather than getting the revisions themselves. This
3476 * method also caches its results, so using it benefits performance.
3477 *
3478 * @since 1.24
3479 * @param Title $title
3480 * @return Revision
3481 */
3482 public function fetchCurrentRevisionOfTitle( $title ) {
3483 $cacheKey = $title->getPrefixedDBkey();
3484 if ( !$this->currentRevisionCache ) {
3485 $this->currentRevisionCache = new MapCacheLRU( 100 );
3486 }
3487 if ( !$this->currentRevisionCache->has( $cacheKey ) ) {
3488 $this->currentRevisionCache->set( $cacheKey,
3489 // Defaults to Parser::statelessFetchRevision()
3490 call_user_func( $this->mOptions->getCurrentRevisionCallback(), $title, $this )
3491 );
3492 }
3493 return $this->currentRevisionCache->get( $cacheKey );
3494 }
3495
3496 /**
3497 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3498 * without passing them on to it.
3499 *
3500 * @since 1.24
3501 * @param Title $title
3502 * @param Parser|bool $parser
3503 * @return Revision|bool False if missing
3504 */
3505 public static function statelessFetchRevision( Title $title, $parser = false ) {
3506 $pageId = $title->getArticleID();
3507 $revId = $title->getLatestRevID();
3508
3509 $rev = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $pageId, $revId );
3510 if ( $rev ) {
3511 $rev->setTitle( $title );
3512 }
3513
3514 return $rev;
3515 }
3516
3517 /**
3518 * Fetch the unparsed text of a template and register a reference to it.
3519 * @param Title $title
3520 * @return array ( string or false, Title )
3521 */
3522 public function fetchTemplateAndTitle( $title ) {
3523 // Defaults to Parser::statelessFetchTemplate()
3524 $templateCb = $this->mOptions->getTemplateCallback();
3525 $stuff = call_user_func( $templateCb, $title, $this );
3526 // We use U+007F DELETE to distinguish strip markers from regular text.
3527 $text = $stuff['text'];
3528 if ( is_string( $stuff['text'] ) ) {
3529 $text = strtr( $text, "\x7f", "?" );
3530 }
3531 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3532 if ( isset( $stuff['deps'] ) ) {
3533 foreach ( $stuff['deps'] as $dep ) {
3534 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3535 if ( $dep['title']->equals( $this->getTitle() ) ) {
3536 // If we transclude ourselves, the final result
3537 // will change based on the new version of the page
3538 $this->mOutput->setFlag( 'vary-revision' );
3539 }
3540 }
3541 }
3542 return [ $text, $finalTitle ];
3543 }
3544
3545 /**
3546 * Fetch the unparsed text of a template and register a reference to it.
3547 * @param Title $title
3548 * @return string|bool
3549 */
3550 public function fetchTemplate( $title ) {
3551 return $this->fetchTemplateAndTitle( $title )[0];
3552 }
3553
3554 /**
3555 * Static function to get a template
3556 * Can be overridden via ParserOptions::setTemplateCallback().
3557 *
3558 * @param Title $title
3559 * @param bool|Parser $parser
3560 *
3561 * @return array
3562 */
3563 public static function statelessFetchTemplate( $title, $parser = false ) {
3564 $text = $skip = false;
3565 $finalTitle = $title;
3566 $deps = [];
3567
3568 # Loop to fetch the article, with up to 1 redirect
3569 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3570 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3571 // @codingStandardsIgnoreEnd
3572 # Give extensions a chance to select the revision instead
3573 $id = false; # Assume current
3574 Hooks::run( 'BeforeParserFetchTemplateAndtitle',
3575 [ $parser, $title, &$skip, &$id ] );
3576
3577 if ( $skip ) {
3578 $text = false;
3579 $deps[] = [
3580 'title' => $title,
3581 'page_id' => $title->getArticleID(),
3582 'rev_id' => null
3583 ];
3584 break;
3585 }
3586 # Get the revision
3587 if ( $id ) {
3588 $rev = Revision::newFromId( $id );
3589 } elseif ( $parser ) {
3590 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3591 } else {
3592 $rev = Revision::newFromTitle( $title );
3593 }
3594 $rev_id = $rev ? $rev->getId() : 0;
3595 # If there is no current revision, there is no page
3596 if ( $id === false && !$rev ) {
3597 $linkCache = LinkCache::singleton();
3598 $linkCache->addBadLinkObj( $title );
3599 }
3600
3601 $deps[] = [
3602 'title' => $title,
3603 'page_id' => $title->getArticleID(),
3604 'rev_id' => $rev_id ];
3605 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3606 # We fetched a rev from a different title; register it too...
3607 $deps[] = [
3608 'title' => $rev->getTitle(),
3609 'page_id' => $rev->getPage(),
3610 'rev_id' => $rev_id ];
3611 }
3612
3613 if ( $rev ) {
3614 $content = $rev->getContent();
3615 $text = $content ? $content->getWikitextForTransclusion() : null;
3616
3617 Hooks::run( 'ParserFetchTemplate',
3618 [ $parser, $title, $rev, &$text, &$deps ] );
3619
3620 if ( $text === false || $text === null ) {
3621 $text = false;
3622 break;
3623 }
3624 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3625 global $wgContLang;
3626 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3627 if ( !$message->exists() ) {
3628 $text = false;
3629 break;
3630 }
3631 $content = $message->content();
3632 $text = $message->plain();
3633 } else {
3634 break;
3635 }
3636 if ( !$content ) {
3637 break;
3638 }
3639 # Redirect?
3640 $finalTitle = $title;
3641 $title = $content->getRedirectTarget();
3642 }
3643 return [
3644 'text' => $text,
3645 'finalTitle' => $finalTitle,
3646 'deps' => $deps ];
3647 }
3648
3649 /**
3650 * Fetch a file and its title and register a reference to it.
3651 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3652 * @param Title $title
3653 * @param array $options Array of options to RepoGroup::findFile
3654 * @return File|bool
3655 */
3656 public function fetchFile( $title, $options = [] ) {
3657 return $this->fetchFileAndTitle( $title, $options )[0];
3658 }
3659
3660 /**
3661 * Fetch a file and its title and register a reference to it.
3662 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3663 * @param Title $title
3664 * @param array $options Array of options to RepoGroup::findFile
3665 * @return array ( File or false, Title of file )
3666 */
3667 public function fetchFileAndTitle( $title, $options = [] ) {
3668 $file = $this->fetchFileNoRegister( $title, $options );
3669
3670 $time = $file ? $file->getTimestamp() : false;
3671 $sha1 = $file ? $file->getSha1() : false;
3672 # Register the file as a dependency...
3673 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3674 if ( $file && !$title->equals( $file->getTitle() ) ) {
3675 # Update fetched file title
3676 $title = $file->getTitle();
3677 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3678 }
3679 return [ $file, $title ];
3680 }
3681
3682 /**
3683 * Helper function for fetchFileAndTitle.
3684 *
3685 * Also useful if you need to fetch a file but not use it yet,
3686 * for example to get the file's handler.
3687 *
3688 * @param Title $title
3689 * @param array $options Array of options to RepoGroup::findFile
3690 * @return File|bool
3691 */
3692 protected function fetchFileNoRegister( $title, $options = [] ) {
3693 if ( isset( $options['broken'] ) ) {
3694 $file = false; // broken thumbnail forced by hook
3695 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3696 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3697 } else { // get by (name,timestamp)
3698 $file = wfFindFile( $title, $options );
3699 }
3700 return $file;
3701 }
3702
3703 /**
3704 * Transclude an interwiki link.
3705 *
3706 * @param Title $title
3707 * @param string $action
3708 *
3709 * @return string
3710 */
3711 public function interwikiTransclude( $title, $action ) {
3712 global $wgEnableScaryTranscluding;
3713
3714 if ( !$wgEnableScaryTranscluding ) {
3715 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3716 }
3717
3718 $url = $title->getFullURL( [ 'action' => $action ] );
3719
3720 if ( strlen( $url ) > 255 ) {
3721 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3722 }
3723 return $this->fetchScaryTemplateMaybeFromCache( $url );
3724 }
3725
3726 /**
3727 * @param string $url
3728 * @return mixed|string
3729 */
3730 public function fetchScaryTemplateMaybeFromCache( $url ) {
3731 global $wgTranscludeCacheExpiry;
3732 $dbr = wfGetDB( DB_REPLICA );
3733 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3734 $obj = $dbr->selectRow( 'transcache', [ 'tc_time', 'tc_contents' ],
3735 [ 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ] );
3736 if ( $obj ) {
3737 return $obj->tc_contents;
3738 }
3739
3740 $req = MWHttpRequest::factory( $url, [], __METHOD__ );
3741 $status = $req->execute(); // Status object
3742 if ( $status->isOK() ) {
3743 $text = $req->getContent();
3744 } elseif ( $req->getStatus() != 200 ) {
3745 // Though we failed to fetch the content, this status is useless.
3746 return wfMessage( 'scarytranscludefailed-httpstatus' )
3747 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3748 } else {
3749 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3750 }
3751
3752 $dbw = wfGetDB( DB_MASTER );
3753 $dbw->replace( 'transcache', [ 'tc_url' ], [
3754 'tc_url' => $url,
3755 'tc_time' => $dbw->timestamp( time() ),
3756 'tc_contents' => $text
3757 ] );
3758 return $text;
3759 }
3760
3761 /**
3762 * Triple brace replacement -- used for template arguments
3763 * @private
3764 *
3765 * @param array $piece
3766 * @param PPFrame $frame
3767 *
3768 * @return array
3769 */
3770 public function argSubstitution( $piece, $frame ) {
3771
3772 $error = false;
3773 $parts = $piece['parts'];
3774 $nameWithSpaces = $frame->expand( $piece['title'] );
3775 $argName = trim( $nameWithSpaces );
3776 $object = false;
3777 $text = $frame->getArgument( $argName );
3778 if ( $text === false && $parts->getLength() > 0
3779 && ( $this->ot['html']
3780 || $this->ot['pre']
3781 || ( $this->ot['wiki'] && $frame->isTemplate() )
3782 )
3783 ) {
3784 # No match in frame, use the supplied default
3785 $object = $parts->item( 0 )->getChildren();
3786 }
3787 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3788 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3789 $this->limitationWarn( 'post-expand-template-argument' );
3790 }
3791
3792 if ( $text === false && $object === false ) {
3793 # No match anywhere
3794 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3795 }
3796 if ( $error !== false ) {
3797 $text .= $error;
3798 }
3799 if ( $object !== false ) {
3800 $ret = [ 'object' => $object ];
3801 } else {
3802 $ret = [ 'text' => $text ];
3803 }
3804
3805 return $ret;
3806 }
3807
3808 /**
3809 * Return the text to be used for a given extension tag.
3810 * This is the ghost of strip().
3811 *
3812 * @param array $params Associative array of parameters:
3813 * name PPNode for the tag name
3814 * attr PPNode for unparsed text where tag attributes are thought to be
3815 * attributes Optional associative array of parsed attributes
3816 * inner Contents of extension element
3817 * noClose Original text did not have a close tag
3818 * @param PPFrame $frame
3819 *
3820 * @throws MWException
3821 * @return string
3822 */
3823 public function extensionSubstitution( $params, $frame ) {
3824 static $errorStr = '<span class="error">';
3825 static $errorLen = 20;
3826
3827 $name = $frame->expand( $params['name'] );
3828 if ( substr( $name, 0, $errorLen ) === $errorStr ) {
3829 // Probably expansion depth or node count exceeded. Just punt the
3830 // error up.
3831 return $name;
3832 }
3833
3834 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3835 if ( substr( $attrText, 0, $errorLen ) === $errorStr ) {
3836 // See above
3837 return $attrText;
3838 }
3839
3840 // We can't safely check if the expansion for $content resulted in an
3841 // error, because the content could happen to be the error string
3842 // (T149622).
3843 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3844
3845 $marker = self::MARKER_PREFIX . "-$name-"
3846 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3847
3848 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3849 ( $this->ot['html'] || $this->ot['pre'] );
3850 if ( $isFunctionTag ) {
3851 $markerType = 'none';
3852 } else {
3853 $markerType = 'general';
3854 }
3855 if ( $this->ot['html'] || $isFunctionTag ) {
3856 $name = strtolower( $name );
3857 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3858 if ( isset( $params['attributes'] ) ) {
3859 $attributes = $attributes + $params['attributes'];
3860 }
3861
3862 if ( isset( $this->mTagHooks[$name] ) ) {
3863 # Workaround for PHP bug 35229 and similar
3864 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3865 throw new MWException( "Tag hook for $name is not callable\n" );
3866 }
3867 $output = call_user_func_array( $this->mTagHooks[$name],
3868 [ $content, $attributes, $this, $frame ] );
3869 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3870 list( $callback, ) = $this->mFunctionTagHooks[$name];
3871 if ( !is_callable( $callback ) ) {
3872 throw new MWException( "Tag hook for $name is not callable\n" );
3873 }
3874
3875 $output = call_user_func_array( $callback, [ &$this, $frame, $content, $attributes ] );
3876 } else {
3877 $output = '<span class="error">Invalid tag extension name: ' .
3878 htmlspecialchars( $name ) . '</span>';
3879 }
3880
3881 if ( is_array( $output ) ) {
3882 # Extract flags to local scope (to override $markerType)
3883 $flags = $output;
3884 $output = $flags[0];
3885 unset( $flags[0] );
3886 extract( $flags );
3887 }
3888 } else {
3889 if ( is_null( $attrText ) ) {
3890 $attrText = '';
3891 }
3892 if ( isset( $params['attributes'] ) ) {
3893 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3894 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3895 htmlspecialchars( $attrValue ) . '"';
3896 }
3897 }
3898 if ( $content === null ) {
3899 $output = "<$name$attrText/>";
3900 } else {
3901 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3902 if ( substr( $close, 0, $errorLen ) === $errorStr ) {
3903 // See above
3904 return $close;
3905 }
3906 $output = "<$name$attrText>$content$close";
3907 }
3908 }
3909
3910 if ( $markerType === 'none' ) {
3911 return $output;
3912 } elseif ( $markerType === 'nowiki' ) {
3913 $this->mStripState->addNoWiki( $marker, $output );
3914 } elseif ( $markerType === 'general' ) {
3915 $this->mStripState->addGeneral( $marker, $output );
3916 } else {
3917 throw new MWException( __METHOD__ . ': invalid marker type' );
3918 }
3919 return $marker;
3920 }
3921
3922 /**
3923 * Increment an include size counter
3924 *
3925 * @param string $type The type of expansion
3926 * @param int $size The size of the text
3927 * @return bool False if this inclusion would take it over the maximum, true otherwise
3928 */
3929 public function incrementIncludeSize( $type, $size ) {
3930 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3931 return false;
3932 } else {
3933 $this->mIncludeSizes[$type] += $size;
3934 return true;
3935 }
3936 }
3937
3938 /**
3939 * Increment the expensive function count
3940 *
3941 * @return bool False if the limit has been exceeded
3942 */
3943 public function incrementExpensiveFunctionCount() {
3944 $this->mExpensiveFunctionCount++;
3945 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
3946 }
3947
3948 /**
3949 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3950 * Fills $this->mDoubleUnderscores, returns the modified text
3951 *
3952 * @param string $text
3953 *
3954 * @return string
3955 */
3956 public function doDoubleUnderscore( $text ) {
3957
3958 # The position of __TOC__ needs to be recorded
3959 $mw = MagicWord::get( 'toc' );
3960 if ( $mw->match( $text ) ) {
3961 $this->mShowToc = true;
3962 $this->mForceTocPosition = true;
3963
3964 # Set a placeholder. At the end we'll fill it in with the TOC.
3965 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3966
3967 # Only keep the first one.
3968 $text = $mw->replace( '', $text );
3969 }
3970
3971 # Now match and remove the rest of them
3972 $mwa = MagicWord::getDoubleUnderscoreArray();
3973 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3974
3975 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3976 $this->mOutput->mNoGallery = true;
3977 }
3978 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3979 $this->mShowToc = false;
3980 }
3981 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
3982 && $this->mTitle->getNamespace() == NS_CATEGORY
3983 ) {
3984 $this->addTrackingCategory( 'hidden-category-category' );
3985 }
3986 # (T10068) Allow control over whether robots index a page.
3987 # __INDEX__ always overrides __NOINDEX__, see T16899
3988 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3989 $this->mOutput->setIndexPolicy( 'noindex' );
3990 $this->addTrackingCategory( 'noindex-category' );
3991 }
3992 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
3993 $this->mOutput->setIndexPolicy( 'index' );
3994 $this->addTrackingCategory( 'index-category' );
3995 }
3996
3997 # Cache all double underscores in the database
3998 foreach ( $this->mDoubleUnderscores as $key => $val ) {
3999 $this->mOutput->setProperty( $key, '' );
4000 }
4001
4002 return $text;
4003 }
4004
4005 /**
4006 * @see ParserOutput::addTrackingCategory()
4007 * @param string $msg Message key
4008 * @return bool Whether the addition was successful
4009 */
4010 public function addTrackingCategory( $msg ) {
4011 return $this->mOutput->addTrackingCategory( $msg, $this->mTitle );
4012 }
4013
4014 /**
4015 * This function accomplishes several tasks:
4016 * 1) Auto-number headings if that option is enabled
4017 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4018 * 3) Add a Table of contents on the top for users who have enabled the option
4019 * 4) Auto-anchor headings
4020 *
4021 * It loops through all headlines, collects the necessary data, then splits up the
4022 * string and re-inserts the newly formatted headlines.
4023 *
4024 * @param string $text
4025 * @param string $origText Original, untouched wikitext
4026 * @param bool $isMain
4027 * @return mixed|string
4028 * @private
4029 */
4030 public function formatHeadings( $text, $origText, $isMain = true ) {
4031 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4032
4033 # Inhibit editsection links if requested in the page
4034 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4035 $maybeShowEditLink = $showEditLink = false;
4036 } else {
4037 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4038 $showEditLink = $this->mOptions->getEditSection();
4039 }
4040 if ( $showEditLink ) {
4041 $this->mOutput->setEditSectionTokens( true );
4042 }
4043
4044 # Get all headlines for numbering them and adding funky stuff like [edit]
4045 # links - this is for later, but we need the number of headlines right now
4046 $matches = [];
4047 $numMatches = preg_match_all(
4048 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4049 $text,
4050 $matches
4051 );
4052
4053 # if there are fewer than 4 headlines in the article, do not show TOC
4054 # unless it's been explicitly enabled.
4055 $enoughToc = $this->mShowToc &&
4056 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4057
4058 # Allow user to stipulate that a page should have a "new section"
4059 # link added via __NEWSECTIONLINK__
4060 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4061 $this->mOutput->setNewSection( true );
4062 }
4063
4064 # Allow user to remove the "new section"
4065 # link via __NONEWSECTIONLINK__
4066 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4067 $this->mOutput->hideNewSection( true );
4068 }
4069
4070 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4071 # override above conditions and always show TOC above first header
4072 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4073 $this->mShowToc = true;
4074 $enoughToc = true;
4075 }
4076
4077 # headline counter
4078 $headlineCount = 0;
4079 $numVisible = 0;
4080
4081 # Ugh .. the TOC should have neat indentation levels which can be
4082 # passed to the skin functions. These are determined here
4083 $toc = '';
4084 $full = '';
4085 $head = [];
4086 $sublevelCount = [];
4087 $levelCount = [];
4088 $level = 0;
4089 $prevlevel = 0;
4090 $toclevel = 0;
4091 $prevtoclevel = 0;
4092 $markerRegex = self::MARKER_PREFIX . "-h-(\d+)-" . self::MARKER_SUFFIX;
4093 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4094 $oldType = $this->mOutputType;
4095 $this->setOutputType( self::OT_WIKI );
4096 $frame = $this->getPreprocessor()->newFrame();
4097 $root = $this->preprocessToDom( $origText );
4098 $node = $root->getFirstChild();
4099 $byteOffset = 0;
4100 $tocraw = [];
4101 $refers = [];
4102
4103 $headlines = $numMatches !== false ? $matches[3] : [];
4104
4105 foreach ( $headlines as $headline ) {
4106 $isTemplate = false;
4107 $titleText = false;
4108 $sectionIndex = false;
4109 $numbering = '';
4110 $markerMatches = [];
4111 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4112 $serial = $markerMatches[1];
4113 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4114 $isTemplate = ( $titleText != $baseTitleText );
4115 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4116 }
4117
4118 if ( $toclevel ) {
4119 $prevlevel = $level;
4120 }
4121 $level = $matches[1][$headlineCount];
4122
4123 if ( $level > $prevlevel ) {
4124 # Increase TOC level
4125 $toclevel++;
4126 $sublevelCount[$toclevel] = 0;
4127 if ( $toclevel < $wgMaxTocLevel ) {
4128 $prevtoclevel = $toclevel;
4129 $toc .= Linker::tocIndent();
4130 $numVisible++;
4131 }
4132 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4133 # Decrease TOC level, find level to jump to
4134
4135 for ( $i = $toclevel; $i > 0; $i-- ) {
4136 if ( $levelCount[$i] == $level ) {
4137 # Found last matching level
4138 $toclevel = $i;
4139 break;
4140 } elseif ( $levelCount[$i] < $level ) {
4141 # Found first matching level below current level
4142 $toclevel = $i + 1;
4143 break;
4144 }
4145 }
4146 if ( $i == 0 ) {
4147 $toclevel = 1;
4148 }
4149 if ( $toclevel < $wgMaxTocLevel ) {
4150 if ( $prevtoclevel < $wgMaxTocLevel ) {
4151 # Unindent only if the previous toc level was shown :p
4152 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4153 $prevtoclevel = $toclevel;
4154 } else {
4155 $toc .= Linker::tocLineEnd();
4156 }
4157 }
4158 } else {
4159 # No change in level, end TOC line
4160 if ( $toclevel < $wgMaxTocLevel ) {
4161 $toc .= Linker::tocLineEnd();
4162 }
4163 }
4164
4165 $levelCount[$toclevel] = $level;
4166
4167 # count number of headlines for each level
4168 $sublevelCount[$toclevel]++;
4169 $dot = 0;
4170 for ( $i = 1; $i <= $toclevel; $i++ ) {
4171 if ( !empty( $sublevelCount[$i] ) ) {
4172 if ( $dot ) {
4173 $numbering .= '.';
4174 }
4175 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4176 $dot = 1;
4177 }
4178 }
4179
4180 # The safe header is a version of the header text safe to use for links
4181
4182 # Remove link placeholders by the link text.
4183 # <!--LINK number-->
4184 # turns into
4185 # link text with suffix
4186 # Do this before unstrip since link text can contain strip markers
4187 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4188
4189 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4190 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4191
4192 # Strip out HTML (first regex removes any tag not allowed)
4193 # Allowed tags are:
4194 # * <sup> and <sub> (T10393)
4195 # * <i> (T28375)
4196 # * <b> (r105284)
4197 # * <bdi> (T74884)
4198 # * <span dir="rtl"> and <span dir="ltr"> (T37167)
4199 # * <s> and <strike> (T35715)
4200 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4201 # to allow setting directionality in toc items.
4202 $tocline = preg_replace(
4203 [
4204 '#<(?!/?(span|sup|sub|bdi|i|b|s|strike)(?: [^>]*)?>).*?>#',
4205 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b|s|strike))(?: .*?)?>#'
4206 ],
4207 [ '', '<$1>' ],
4208 $safeHeadline
4209 );
4210
4211 # Strip '<span></span>', which is the result from the above if
4212 # <span id="foo"></span> is used to produce an additional anchor
4213 # for a section.
4214 $tocline = str_replace( '<span></span>', '', $tocline );
4215
4216 $tocline = trim( $tocline );
4217
4218 # For the anchor, strip out HTML-y stuff period
4219 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4220 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4221
4222 # Save headline for section edit hint before it's escaped
4223 $headlineHint = $safeHeadline;
4224
4225 if ( $wgExperimentalHtmlIds ) {
4226 # For reverse compatibility, provide an id that's
4227 # HTML4-compatible, like we used to.
4228 # It may be worth noting, academically, that it's possible for
4229 # the legacy anchor to conflict with a non-legacy headline
4230 # anchor on the page. In this case likely the "correct" thing
4231 # would be to either drop the legacy anchors or make sure
4232 # they're numbered first. However, this would require people
4233 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4234 # manually, so let's not bother worrying about it.
4235 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4236 [ 'noninitial', 'legacy' ] );
4237 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4238
4239 if ( $legacyHeadline == $safeHeadline ) {
4240 # No reason to have both (in fact, we can't)
4241 $legacyHeadline = false;
4242 }
4243 } else {
4244 $legacyHeadline = false;
4245 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4246 'noninitial' );
4247 }
4248
4249 # HTML names must be case-insensitively unique (T12721).
4250 # This does not apply to Unicode characters per
4251 # https://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4252 # @todo FIXME: We may be changing them depending on the current locale.
4253 $arrayKey = strtolower( $safeHeadline );
4254 if ( $legacyHeadline === false ) {
4255 $legacyArrayKey = false;
4256 } else {
4257 $legacyArrayKey = strtolower( $legacyHeadline );
4258 }
4259
4260 # Create the anchor for linking from the TOC to the section
4261 $anchor = $safeHeadline;
4262 $legacyAnchor = $legacyHeadline;
4263 if ( isset( $refers[$arrayKey] ) ) {
4264 // @codingStandardsIgnoreStart
4265 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++$i );
4266 // @codingStandardsIgnoreEnd
4267 $anchor .= "_$i";
4268 $refers["${arrayKey}_$i"] = true;
4269 } else {
4270 $refers[$arrayKey] = true;
4271 }
4272 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4273 // @codingStandardsIgnoreStart
4274 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++$i );
4275 // @codingStandardsIgnoreEnd
4276 $legacyAnchor .= "_$i";
4277 $refers["${legacyArrayKey}_$i"] = true;
4278 } else {
4279 $refers[$legacyArrayKey] = true;
4280 }
4281
4282 # Don't number the heading if it is the only one (looks silly)
4283 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4284 # the two are different if the line contains a link
4285 $headline = Html::element(
4286 'span',
4287 [ 'class' => 'mw-headline-number' ],
4288 $numbering
4289 ) . ' ' . $headline;
4290 }
4291
4292 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4293 $toc .= Linker::tocLine( $anchor, $tocline,
4294 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4295 }
4296
4297 # Add the section to the section tree
4298 # Find the DOM node for this header
4299 $noOffset = ( $isTemplate || $sectionIndex === false );
4300 while ( $node && !$noOffset ) {
4301 if ( $node->getName() === 'h' ) {
4302 $bits = $node->splitHeading();
4303 if ( $bits['i'] == $sectionIndex ) {
4304 break;
4305 }
4306 }
4307 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4308 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4309 $node = $node->getNextSibling();
4310 }
4311 $tocraw[] = [
4312 'toclevel' => $toclevel,
4313 'level' => $level,
4314 'line' => $tocline,
4315 'number' => $numbering,
4316 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4317 'fromtitle' => $titleText,
4318 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4319 'anchor' => $anchor,
4320 ];
4321
4322 # give headline the correct <h#> tag
4323 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4324 // Output edit section links as markers with styles that can be customized by skins
4325 if ( $isTemplate ) {
4326 # Put a T flag in the section identifier, to indicate to extractSections()
4327 # that sections inside <includeonly> should be counted.
4328 $editsectionPage = $titleText;
4329 $editsectionSection = "T-$sectionIndex";
4330 $editsectionContent = null;
4331 } else {
4332 $editsectionPage = $this->mTitle->getPrefixedText();
4333 $editsectionSection = $sectionIndex;
4334 $editsectionContent = $headlineHint;
4335 }
4336 // We use a bit of pesudo-xml for editsection markers. The
4337 // language converter is run later on. Using a UNIQ style marker
4338 // leads to the converter screwing up the tokens when it
4339 // converts stuff. And trying to insert strip tags fails too. At
4340 // this point all real inputted tags have already been escaped,
4341 // so we don't have to worry about a user trying to input one of
4342 // these markers directly. We use a page and section attribute
4343 // to stop the language converter from converting these
4344 // important bits of data, but put the headline hint inside a
4345 // content block because the language converter is supposed to
4346 // be able to convert that piece of data.
4347 // Gets replaced with html in ParserOutput::getText
4348 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4349 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4350 if ( $editsectionContent !== null ) {
4351 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4352 } else {
4353 $editlink .= '/>';
4354 }
4355 } else {
4356 $editlink = '';
4357 }
4358 $head[$headlineCount] = Linker::makeHeadline( $level,
4359 $matches['attrib'][$headlineCount], $anchor, $headline,
4360 $editlink, $legacyAnchor );
4361
4362 $headlineCount++;
4363 }
4364
4365 $this->setOutputType( $oldType );
4366
4367 # Never ever show TOC if no headers
4368 if ( $numVisible < 1 ) {
4369 $enoughToc = false;
4370 }
4371
4372 if ( $enoughToc ) {
4373 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4374 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4375 }
4376 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4377 $this->mOutput->setTOCHTML( $toc );
4378 $toc = self::TOC_START . $toc . self::TOC_END;
4379 $this->mOutput->addModules( 'mediawiki.toc' );
4380 }
4381
4382 if ( $isMain ) {
4383 $this->mOutput->setSections( $tocraw );
4384 }
4385
4386 # split up and insert constructed headlines
4387 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4388 $i = 0;
4389
4390 // build an array of document sections
4391 $sections = [];
4392 foreach ( $blocks as $block ) {
4393 // $head is zero-based, sections aren't.
4394 if ( empty( $head[$i - 1] ) ) {
4395 $sections[$i] = $block;
4396 } else {
4397 $sections[$i] = $head[$i - 1] . $block;
4398 }
4399
4400 /**
4401 * Send a hook, one per section.
4402 * The idea here is to be able to make section-level DIVs, but to do so in a
4403 * lower-impact, more correct way than r50769
4404 *
4405 * $this : caller
4406 * $section : the section number
4407 * &$sectionContent : ref to the content of the section
4408 * $showEditLinks : boolean describing whether this section has an edit link
4409 */
4410 Hooks::run( 'ParserSectionCreate', [ $this, $i, &$sections[$i], $showEditLink ] );
4411
4412 $i++;
4413 }
4414
4415 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4416 // append the TOC at the beginning
4417 // Top anchor now in skin
4418 $sections[0] = $sections[0] . $toc . "\n";
4419 }
4420
4421 $full .= implode( '', $sections );
4422
4423 if ( $this->mForceTocPosition ) {
4424 return str_replace( '<!--MWTOC-->', $toc, $full );
4425 } else {
4426 return $full;
4427 }
4428 }
4429
4430 /**
4431 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4432 * conversion, substituting signatures, {{subst:}} templates, etc.
4433 *
4434 * @param string $text The text to transform
4435 * @param Title $title The Title object for the current article
4436 * @param User $user The User object describing the current user
4437 * @param ParserOptions $options Parsing options
4438 * @param bool $clearState Whether to clear the parser state first
4439 * @return string The altered wiki markup
4440 */
4441 public function preSaveTransform( $text, Title $title, User $user,
4442 ParserOptions $options, $clearState = true
4443 ) {
4444 if ( $clearState ) {
4445 $magicScopeVariable = $this->lock();
4446 }
4447 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4448 $this->setUser( $user );
4449
4450 // We still normalize line endings for backwards-compatibility
4451 // with other code that just calls PST, but this should already
4452 // be handled in TextContent subclasses
4453 $text = TextContent::normalizeLineEndings( $text );
4454
4455 if ( $options->getPreSaveTransform() ) {
4456 $text = $this->pstPass2( $text, $user );
4457 }
4458 $text = $this->mStripState->unstripBoth( $text );
4459
4460 $this->setUser( null ); # Reset
4461
4462 return $text;
4463 }
4464
4465 /**
4466 * Pre-save transform helper function
4467 *
4468 * @param string $text
4469 * @param User $user
4470 *
4471 * @return string
4472 */
4473 private function pstPass2( $text, $user ) {
4474 global $wgContLang;
4475
4476 # Note: This is the timestamp saved as hardcoded wikitext to
4477 # the database, we use $wgContLang here in order to give
4478 # everyone the same signature and use the default one rather
4479 # than the one selected in each user's preferences.
4480 # (see also T14815)
4481 $ts = $this->mOptions->getTimestamp();
4482 $timestamp = MWTimestamp::getLocalInstance( $ts );
4483 $ts = $timestamp->format( 'YmdHis' );
4484 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4485
4486 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4487
4488 # Variable replacement
4489 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4490 $text = $this->replaceVariables( $text );
4491
4492 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4493 # which may corrupt this parser instance via its wfMessage()->text() call-
4494
4495 # Signatures
4496 $sigText = $this->getUserSig( $user );
4497 $text = strtr( $text, [
4498 '~~~~~' => $d,
4499 '~~~~' => "$sigText $d",
4500 '~~~' => $sigText
4501 ] );
4502
4503 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4504 $tc = '[' . Title::legalChars() . ']';
4505 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4506
4507 // [[ns:page (context)|]]
4508 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4509 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4510 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4511 // [[ns:page (context), context|]] (using either single or double-width comma)
4512 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4513 // [[|page]] (reverse pipe trick: add context from page title)
4514 $p2 = "/\[\[\\|($tc+)]]/";
4515
4516 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4517 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4518 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4519 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4520
4521 $t = $this->mTitle->getText();
4522 $m = [];
4523 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4524 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4525 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4526 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4527 } else {
4528 # if there's no context, don't bother duplicating the title
4529 $text = preg_replace( $p2, '[[\\1]]', $text );
4530 }
4531
4532 return $text;
4533 }
4534
4535 /**
4536 * Fetch the user's signature text, if any, and normalize to
4537 * validated, ready-to-insert wikitext.
4538 * If you have pre-fetched the nickname or the fancySig option, you can
4539 * specify them here to save a database query.
4540 * Do not reuse this parser instance after calling getUserSig(),
4541 * as it may have changed if it's the $wgParser.
4542 *
4543 * @param User $user
4544 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4545 * @param bool|null $fancySig whether the nicknname is the complete signature
4546 * or null to use default value
4547 * @return string
4548 */
4549 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4550 global $wgMaxSigChars;
4551
4552 $username = $user->getName();
4553
4554 # If not given, retrieve from the user object.
4555 if ( $nickname === false ) {
4556 $nickname = $user->getOption( 'nickname' );
4557 }
4558
4559 if ( is_null( $fancySig ) ) {
4560 $fancySig = $user->getBoolOption( 'fancysig' );
4561 }
4562
4563 $nickname = $nickname == null ? $username : $nickname;
4564
4565 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4566 $nickname = $username;
4567 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4568 } elseif ( $fancySig !== false ) {
4569 # Sig. might contain markup; validate this
4570 if ( $this->validateSig( $nickname ) !== false ) {
4571 # Validated; clean up (if needed) and return it
4572 return $this->cleanSig( $nickname, true );
4573 } else {
4574 # Failed to validate; fall back to the default
4575 $nickname = $username;
4576 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4577 }
4578 }
4579
4580 # Make sure nickname doesnt get a sig in a sig
4581 $nickname = self::cleanSigInSig( $nickname );
4582
4583 # If we're still here, make it a link to the user page
4584 $userText = wfEscapeWikiText( $username );
4585 $nickText = wfEscapeWikiText( $nickname );
4586 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4587
4588 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4589 ->title( $this->getTitle() )->text();
4590 }
4591
4592 /**
4593 * Check that the user's signature contains no bad XML
4594 *
4595 * @param string $text
4596 * @return string|bool An expanded string, or false if invalid.
4597 */
4598 public function validateSig( $text ) {
4599 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4600 }
4601
4602 /**
4603 * Clean up signature text
4604 *
4605 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4606 * 2) Substitute all transclusions
4607 *
4608 * @param string $text
4609 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4610 * @return string Signature text
4611 */
4612 public function cleanSig( $text, $parsing = false ) {
4613 if ( !$parsing ) {
4614 global $wgTitle;
4615 $magicScopeVariable = $this->lock();
4616 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4617 }
4618
4619 # Option to disable this feature
4620 if ( !$this->mOptions->getCleanSignatures() ) {
4621 return $text;
4622 }
4623
4624 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4625 # => Move this logic to braceSubstitution()
4626 $substWord = MagicWord::get( 'subst' );
4627 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4628 $substText = '{{' . $substWord->getSynonym( 0 );
4629
4630 $text = preg_replace( $substRegex, $substText, $text );
4631 $text = self::cleanSigInSig( $text );
4632 $dom = $this->preprocessToDom( $text );
4633 $frame = $this->getPreprocessor()->newFrame();
4634 $text = $frame->expand( $dom );
4635
4636 if ( !$parsing ) {
4637 $text = $this->mStripState->unstripBoth( $text );
4638 }
4639
4640 return $text;
4641 }
4642
4643 /**
4644 * Strip 3, 4 or 5 tildes out of signatures.
4645 *
4646 * @param string $text
4647 * @return string Signature text with /~{3,5}/ removed
4648 */
4649 public static function cleanSigInSig( $text ) {
4650 $text = preg_replace( '/~{3,5}/', '', $text );
4651 return $text;
4652 }
4653
4654 /**
4655 * Set up some variables which are usually set up in parse()
4656 * so that an external function can call some class members with confidence
4657 *
4658 * @param Title|null $title
4659 * @param ParserOptions $options
4660 * @param int $outputType
4661 * @param bool $clearState
4662 */
4663 public function startExternalParse( Title $title = null, ParserOptions $options,
4664 $outputType, $clearState = true
4665 ) {
4666 $this->startParse( $title, $options, $outputType, $clearState );
4667 }
4668
4669 /**
4670 * @param Title|null $title
4671 * @param ParserOptions $options
4672 * @param int $outputType
4673 * @param bool $clearState
4674 */
4675 private function startParse( Title $title = null, ParserOptions $options,
4676 $outputType, $clearState = true
4677 ) {
4678 $this->setTitle( $title );
4679 $this->mOptions = $options;
4680 $this->setOutputType( $outputType );
4681 if ( $clearState ) {
4682 $this->clearState();
4683 }
4684 }
4685
4686 /**
4687 * Wrapper for preprocess()
4688 *
4689 * @param string $text The text to preprocess
4690 * @param ParserOptions $options Options
4691 * @param Title|null $title Title object or null to use $wgTitle
4692 * @return string
4693 */
4694 public function transformMsg( $text, $options, $title = null ) {
4695 static $executing = false;
4696
4697 # Guard against infinite recursion
4698 if ( $executing ) {
4699 return $text;
4700 }
4701 $executing = true;
4702
4703 if ( !$title ) {
4704 global $wgTitle;
4705 $title = $wgTitle;
4706 }
4707
4708 $text = $this->preprocess( $text, $title, $options );
4709
4710 $executing = false;
4711 return $text;
4712 }
4713
4714 /**
4715 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4716 * The callback should have the following form:
4717 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4718 *
4719 * Transform and return $text. Use $parser for any required context, e.g. use
4720 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4721 *
4722 * Hooks may return extended information by returning an array, of which the
4723 * first numbered element (index 0) must be the return string, and all other
4724 * entries are extracted into local variables within an internal function
4725 * in the Parser class.
4726 *
4727 * This interface (introduced r61913) appears to be undocumented, but
4728 * 'markerType' is used by some core tag hooks to override which strip
4729 * array their results are placed in. **Use great caution if attempting
4730 * this interface, as it is not documented and injudicious use could smash
4731 * private variables.**
4732 *
4733 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4734 * @param callable $callback The callback function (and object) to use for the tag
4735 * @throws MWException
4736 * @return callable|null The old value of the mTagHooks array associated with the hook
4737 */
4738 public function setHook( $tag, $callback ) {
4739 $tag = strtolower( $tag );
4740 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4741 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4742 }
4743 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4744 $this->mTagHooks[$tag] = $callback;
4745 if ( !in_array( $tag, $this->mStripList ) ) {
4746 $this->mStripList[] = $tag;
4747 }
4748
4749 return $oldVal;
4750 }
4751
4752 /**
4753 * As setHook(), but letting the contents be parsed.
4754 *
4755 * Transparent tag hooks are like regular XML-style tag hooks, except they
4756 * operate late in the transformation sequence, on HTML instead of wikitext.
4757 *
4758 * This is probably obsoleted by things dealing with parser frames?
4759 * The only extension currently using it is geoserver.
4760 *
4761 * @since 1.10
4762 * @todo better document or deprecate this
4763 *
4764 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4765 * @param callable $callback The callback function (and object) to use for the tag
4766 * @throws MWException
4767 * @return callable|null The old value of the mTagHooks array associated with the hook
4768 */
4769 public function setTransparentTagHook( $tag, $callback ) {
4770 $tag = strtolower( $tag );
4771 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4772 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4773 }
4774 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4775 $this->mTransparentTagHooks[$tag] = $callback;
4776
4777 return $oldVal;
4778 }
4779
4780 /**
4781 * Remove all tag hooks
4782 */
4783 public function clearTagHooks() {
4784 $this->mTagHooks = [];
4785 $this->mFunctionTagHooks = [];
4786 $this->mStripList = $this->mDefaultStripList;
4787 }
4788
4789 /**
4790 * Create a function, e.g. {{sum:1|2|3}}
4791 * The callback function should have the form:
4792 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4793 *
4794 * Or with Parser::SFH_OBJECT_ARGS:
4795 * function myParserFunction( $parser, $frame, $args ) { ... }
4796 *
4797 * The callback may either return the text result of the function, or an array with the text
4798 * in element 0, and a number of flags in the other elements. The names of the flags are
4799 * specified in the keys. Valid flags are:
4800 * found The text returned is valid, stop processing the template. This
4801 * is on by default.
4802 * nowiki Wiki markup in the return value should be escaped
4803 * isHTML The returned text is HTML, armour it against wikitext transformation
4804 *
4805 * @param string $id The magic word ID
4806 * @param callable $callback The callback function (and object) to use
4807 * @param int $flags A combination of the following flags:
4808 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4809 *
4810 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
4811 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
4812 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4813 * the arguments, and to control the way they are expanded.
4814 *
4815 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4816 * arguments, for instance:
4817 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4818 *
4819 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4820 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4821 * working if/when this is changed.
4822 *
4823 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4824 * expansion.
4825 *
4826 * Please read the documentation in includes/parser/Preprocessor.php for more information
4827 * about the methods available in PPFrame and PPNode.
4828 *
4829 * @throws MWException
4830 * @return string|callable The old callback function for this name, if any
4831 */
4832 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4833 global $wgContLang;
4834
4835 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4836 $this->mFunctionHooks[$id] = [ $callback, $flags ];
4837
4838 # Add to function cache
4839 $mw = MagicWord::get( $id );
4840 if ( !$mw ) {
4841 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4842 }
4843
4844 $synonyms = $mw->getSynonyms();
4845 $sensitive = intval( $mw->isCaseSensitive() );
4846
4847 foreach ( $synonyms as $syn ) {
4848 # Case
4849 if ( !$sensitive ) {
4850 $syn = $wgContLang->lc( $syn );
4851 }
4852 # Add leading hash
4853 if ( !( $flags & self::SFH_NO_HASH ) ) {
4854 $syn = '#' . $syn;
4855 }
4856 # Remove trailing colon
4857 if ( substr( $syn, -1, 1 ) === ':' ) {
4858 $syn = substr( $syn, 0, -1 );
4859 }
4860 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4861 }
4862 return $oldVal;
4863 }
4864
4865 /**
4866 * Get all registered function hook identifiers
4867 *
4868 * @return array
4869 */
4870 public function getFunctionHooks() {
4871 return array_keys( $this->mFunctionHooks );
4872 }
4873
4874 /**
4875 * Create a tag function, e.g. "<test>some stuff</test>".
4876 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4877 * Unlike parser functions, their content is not preprocessed.
4878 * @param string $tag
4879 * @param callable $callback
4880 * @param int $flags
4881 * @throws MWException
4882 * @return null
4883 */
4884 public function setFunctionTagHook( $tag, $callback, $flags ) {
4885 $tag = strtolower( $tag );
4886 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4887 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4888 }
4889 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4890 $this->mFunctionTagHooks[$tag] : null;
4891 $this->mFunctionTagHooks[$tag] = [ $callback, $flags ];
4892
4893 if ( !in_array( $tag, $this->mStripList ) ) {
4894 $this->mStripList[] = $tag;
4895 }
4896
4897 return $old;
4898 }
4899
4900 /**
4901 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4902 * Placeholders created in Linker::link()
4903 *
4904 * @param string $text
4905 * @param int $options
4906 */
4907 public function replaceLinkHolders( &$text, $options = 0 ) {
4908 $this->mLinkHolders->replace( $text );
4909 }
4910
4911 /**
4912 * Replace "<!--LINK-->" link placeholders with plain text of links
4913 * (not HTML-formatted).
4914 *
4915 * @param string $text
4916 * @return string
4917 */
4918 public function replaceLinkHoldersText( $text ) {
4919 return $this->mLinkHolders->replaceText( $text );
4920 }
4921
4922 /**
4923 * Renders an image gallery from a text with one line per image.
4924 * text labels may be given by using |-style alternative text. E.g.
4925 * Image:one.jpg|The number "1"
4926 * Image:tree.jpg|A tree
4927 * given as text will return the HTML of a gallery with two images,
4928 * labeled 'The number "1"' and
4929 * 'A tree'.
4930 *
4931 * @param string $text
4932 * @param array $params
4933 * @return string HTML
4934 */
4935 public function renderImageGallery( $text, $params ) {
4936
4937 $mode = false;
4938 if ( isset( $params['mode'] ) ) {
4939 $mode = $params['mode'];
4940 }
4941
4942 try {
4943 $ig = ImageGalleryBase::factory( $mode );
4944 } catch ( Exception $e ) {
4945 // If invalid type set, fallback to default.
4946 $ig = ImageGalleryBase::factory( false );
4947 }
4948
4949 $ig->setContextTitle( $this->mTitle );
4950 $ig->setShowBytes( false );
4951 $ig->setShowFilename( false );
4952 $ig->setParser( $this );
4953 $ig->setHideBadImages();
4954 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4955
4956 if ( isset( $params['showfilename'] ) ) {
4957 $ig->setShowFilename( true );
4958 } else {
4959 $ig->setShowFilename( false );
4960 }
4961 if ( isset( $params['caption'] ) ) {
4962 $caption = $params['caption'];
4963 $caption = htmlspecialchars( $caption );
4964 $caption = $this->replaceInternalLinks( $caption );
4965 $ig->setCaptionHtml( $caption );
4966 }
4967 if ( isset( $params['perrow'] ) ) {
4968 $ig->setPerRow( $params['perrow'] );
4969 }
4970 if ( isset( $params['widths'] ) ) {
4971 $ig->setWidths( $params['widths'] );
4972 }
4973 if ( isset( $params['heights'] ) ) {
4974 $ig->setHeights( $params['heights'] );
4975 }
4976 $ig->setAdditionalOptions( $params );
4977
4978 Hooks::run( 'BeforeParserrenderImageGallery', [ &$this, &$ig ] );
4979
4980 $lines = StringUtils::explode( "\n", $text );
4981 foreach ( $lines as $line ) {
4982 # match lines like these:
4983 # Image:someimage.jpg|This is some image
4984 $matches = [];
4985 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4986 # Skip empty lines
4987 if ( count( $matches ) == 0 ) {
4988 continue;
4989 }
4990
4991 if ( strpos( $matches[0], '%' ) !== false ) {
4992 $matches[1] = rawurldecode( $matches[1] );
4993 }
4994 $title = Title::newFromText( $matches[1], NS_FILE );
4995 if ( is_null( $title ) ) {
4996 # Bogus title. Ignore these so we don't bomb out later.
4997 continue;
4998 }
4999
5000 # We need to get what handler the file uses, to figure out parameters.
5001 # Note, a hook can overide the file name, and chose an entirely different
5002 # file (which potentially could be of a different type and have different handler).
5003 $options = [];
5004 $descQuery = false;
5005 Hooks::run( 'BeforeParserFetchFileAndTitle',
5006 [ $this, $title, &$options, &$descQuery ] );
5007 # Don't register it now, as TraditionalImageGallery does that later.
5008 $file = $this->fetchFileNoRegister( $title, $options );
5009 $handler = $file ? $file->getHandler() : false;
5010
5011 $paramMap = [
5012 'img_alt' => 'gallery-internal-alt',
5013 'img_link' => 'gallery-internal-link',
5014 ];
5015 if ( $handler ) {
5016 $paramMap = $paramMap + $handler->getParamMap();
5017 // We don't want people to specify per-image widths.
5018 // Additionally the width parameter would need special casing anyhow.
5019 unset( $paramMap['img_width'] );
5020 }
5021
5022 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5023
5024 $label = '';
5025 $alt = '';
5026 $link = '';
5027 $handlerOptions = [];
5028 if ( isset( $matches[3] ) ) {
5029 // look for an |alt= definition while trying not to break existing
5030 // captions with multiple pipes (|) in it, until a more sensible grammar
5031 // is defined for images in galleries
5032
5033 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5034 // splitting on '|' is a bit odd, and different from makeImage.
5035 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5036 // Protect LanguageConverter markup
5037 $parameterMatches = StringUtils::delimiterExplode(
5038 '-{', '}-', '|', $matches[3], true /* nested */
5039 );
5040
5041 foreach ( $parameterMatches as $parameterMatch ) {
5042 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5043 if ( $magicName ) {
5044 $paramName = $paramMap[$magicName];
5045
5046 switch ( $paramName ) {
5047 case 'gallery-internal-alt':
5048 $alt = $this->stripAltText( $match, false );
5049 break;
5050 case 'gallery-internal-link':
5051 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5052 $chars = self::EXT_LINK_URL_CLASS;
5053 $addr = self::EXT_LINK_ADDR;
5054 $prots = $this->mUrlProtocols;
5055 // check to see if link matches an absolute url, if not then it must be a wiki link.
5056 if ( preg_match( '/^-{R|(.*)}-$/', $linkValue ) ) {
5057 // Result of LanguageConverter::markNoConversion
5058 // invoked on an external link.
5059 $linkValue = substr( $linkValue, 4, -2 );
5060 }
5061 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5062 $link = $linkValue;
5063 } else {
5064 $localLinkTitle = Title::newFromText( $linkValue );
5065 if ( $localLinkTitle !== null ) {
5066 $link = $localLinkTitle->getLinkURL();
5067 }
5068 }
5069 break;
5070 default:
5071 // Must be a handler specific parameter.
5072 if ( $handler->validateParam( $paramName, $match ) ) {
5073 $handlerOptions[$paramName] = $match;
5074 } else {
5075 // Guess not, consider it as caption.
5076 wfDebug( "$parameterMatch failed parameter validation\n" );
5077 $label = '|' . $parameterMatch;
5078 }
5079 }
5080
5081 } else {
5082 // Last pipe wins.
5083 $label = '|' . $parameterMatch;
5084 }
5085 }
5086 // Remove the pipe.
5087 $label = substr( $label, 1 );
5088 }
5089
5090 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5091 }
5092 $html = $ig->toHTML();
5093 Hooks::run( 'AfterParserFetchFileAndTitle', [ $this, $ig, &$html ] );
5094 return $html;
5095 }
5096
5097 /**
5098 * @param MediaHandler $handler
5099 * @return array
5100 */
5101 public function getImageParams( $handler ) {
5102 if ( $handler ) {
5103 $handlerClass = get_class( $handler );
5104 } else {
5105 $handlerClass = '';
5106 }
5107 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5108 # Initialise static lists
5109 static $internalParamNames = [
5110 'horizAlign' => [ 'left', 'right', 'center', 'none' ],
5111 'vertAlign' => [ 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5112 'bottom', 'text-bottom' ],
5113 'frame' => [ 'thumbnail', 'manualthumb', 'framed', 'frameless',
5114 'upright', 'border', 'link', 'alt', 'class' ],
5115 ];
5116 static $internalParamMap;
5117 if ( !$internalParamMap ) {
5118 $internalParamMap = [];
5119 foreach ( $internalParamNames as $type => $names ) {
5120 foreach ( $names as $name ) {
5121 $magicName = str_replace( '-', '_', "img_$name" );
5122 $internalParamMap[$magicName] = [ $type, $name ];
5123 }
5124 }
5125 }
5126
5127 # Add handler params
5128 $paramMap = $internalParamMap;
5129 if ( $handler ) {
5130 $handlerParamMap = $handler->getParamMap();
5131 foreach ( $handlerParamMap as $magic => $paramName ) {
5132 $paramMap[$magic] = [ 'handler', $paramName ];
5133 }
5134 }
5135 $this->mImageParams[$handlerClass] = $paramMap;
5136 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5137 }
5138 return [ $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] ];
5139 }
5140
5141 /**
5142 * Parse image options text and use it to make an image
5143 *
5144 * @param Title $title
5145 * @param string $options
5146 * @param LinkHolderArray|bool $holders
5147 * @return string HTML
5148 */
5149 public function makeImage( $title, $options, $holders = false ) {
5150 # Check if the options text is of the form "options|alt text"
5151 # Options are:
5152 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5153 # * left no resizing, just left align. label is used for alt= only
5154 # * right same, but right aligned
5155 # * none same, but not aligned
5156 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5157 # * center center the image
5158 # * frame Keep original image size, no magnify-button.
5159 # * framed Same as "frame"
5160 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5161 # * upright reduce width for upright images, rounded to full __0 px
5162 # * border draw a 1px border around the image
5163 # * alt Text for HTML alt attribute (defaults to empty)
5164 # * class Set a class for img node
5165 # * link Set the target of the image link. Can be external, interwiki, or local
5166 # vertical-align values (no % or length right now):
5167 # * baseline
5168 # * sub
5169 # * super
5170 # * top
5171 # * text-top
5172 # * middle
5173 # * bottom
5174 # * text-bottom
5175
5176 # Protect LanguageConverter markup when splitting into parts
5177 $parts = StringUtils::delimiterExplode(
5178 '-{', '}-', '|', $options, true /* allow nesting */
5179 );
5180
5181 # Give extensions a chance to select the file revision for us
5182 $options = [];
5183 $descQuery = false;
5184 Hooks::run( 'BeforeParserFetchFileAndTitle',
5185 [ $this, $title, &$options, &$descQuery ] );
5186 # Fetch and register the file (file title may be different via hooks)
5187 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5188
5189 # Get parameter map
5190 $handler = $file ? $file->getHandler() : false;
5191
5192 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5193
5194 if ( !$file ) {
5195 $this->addTrackingCategory( 'broken-file-category' );
5196 }
5197
5198 # Process the input parameters
5199 $caption = '';
5200 $params = [ 'frame' => [], 'handler' => [],
5201 'horizAlign' => [], 'vertAlign' => [] ];
5202 $seenformat = false;
5203 foreach ( $parts as $part ) {
5204 $part = trim( $part );
5205 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5206 $validated = false;
5207 if ( isset( $paramMap[$magicName] ) ) {
5208 list( $type, $paramName ) = $paramMap[$magicName];
5209
5210 # Special case; width and height come in one variable together
5211 if ( $type === 'handler' && $paramName === 'width' ) {
5212 $parsedWidthParam = $this->parseWidthParam( $value );
5213 if ( isset( $parsedWidthParam['width'] ) ) {
5214 $width = $parsedWidthParam['width'];
5215 if ( $handler->validateParam( 'width', $width ) ) {
5216 $params[$type]['width'] = $width;
5217 $validated = true;
5218 }
5219 }
5220 if ( isset( $parsedWidthParam['height'] ) ) {
5221 $height = $parsedWidthParam['height'];
5222 if ( $handler->validateParam( 'height', $height ) ) {
5223 $params[$type]['height'] = $height;
5224 $validated = true;
5225 }
5226 }
5227 # else no validation -- T15436
5228 } else {
5229 if ( $type === 'handler' ) {
5230 # Validate handler parameter
5231 $validated = $handler->validateParam( $paramName, $value );
5232 } else {
5233 # Validate internal parameters
5234 switch ( $paramName ) {
5235 case 'manualthumb':
5236 case 'alt':
5237 case 'class':
5238 # @todo FIXME: Possibly check validity here for
5239 # manualthumb? downstream behavior seems odd with
5240 # missing manual thumbs.
5241 $validated = true;
5242 $value = $this->stripAltText( $value, $holders );
5243 break;
5244 case 'link':
5245 $chars = self::EXT_LINK_URL_CLASS;
5246 $addr = self::EXT_LINK_ADDR;
5247 $prots = $this->mUrlProtocols;
5248 if ( $value === '' ) {
5249 $paramName = 'no-link';
5250 $value = true;
5251 $validated = true;
5252 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5253 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5254 $paramName = 'link-url';
5255 $this->mOutput->addExternalLink( $value );
5256 if ( $this->mOptions->getExternalLinkTarget() ) {
5257 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5258 }
5259 $validated = true;
5260 }
5261 } else {
5262 $linkTitle = Title::newFromText( $value );
5263 if ( $linkTitle ) {
5264 $paramName = 'link-title';
5265 $value = $linkTitle;
5266 $this->mOutput->addLink( $linkTitle );
5267 $validated = true;
5268 }
5269 }
5270 break;
5271 case 'frameless':
5272 case 'framed':
5273 case 'thumbnail':
5274 // use first appearing option, discard others.
5275 $validated = !$seenformat;
5276 $seenformat = true;
5277 break;
5278 default:
5279 # Most other things appear to be empty or numeric...
5280 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5281 }
5282 }
5283
5284 if ( $validated ) {
5285 $params[$type][$paramName] = $value;
5286 }
5287 }
5288 }
5289 if ( !$validated ) {
5290 $caption = $part;
5291 }
5292 }
5293
5294 # Process alignment parameters
5295 if ( $params['horizAlign'] ) {
5296 $params['frame']['align'] = key( $params['horizAlign'] );
5297 }
5298 if ( $params['vertAlign'] ) {
5299 $params['frame']['valign'] = key( $params['vertAlign'] );
5300 }
5301
5302 $params['frame']['caption'] = $caption;
5303
5304 # Will the image be presented in a frame, with the caption below?
5305 $imageIsFramed = isset( $params['frame']['frame'] )
5306 || isset( $params['frame']['framed'] )
5307 || isset( $params['frame']['thumbnail'] )
5308 || isset( $params['frame']['manualthumb'] );
5309
5310 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5311 # came to also set the caption, ordinary text after the image -- which
5312 # makes no sense, because that just repeats the text multiple times in
5313 # screen readers. It *also* came to set the title attribute.
5314 # Now that we have an alt attribute, we should not set the alt text to
5315 # equal the caption: that's worse than useless, it just repeats the
5316 # text. This is the framed/thumbnail case. If there's no caption, we
5317 # use the unnamed parameter for alt text as well, just for the time be-
5318 # ing, if the unnamed param is set and the alt param is not.
5319 # For the future, we need to figure out if we want to tweak this more,
5320 # e.g., introducing a title= parameter for the title; ignoring the un-
5321 # named parameter entirely for images without a caption; adding an ex-
5322 # plicit caption= parameter and preserving the old magic unnamed para-
5323 # meter for BC; ...
5324 if ( $imageIsFramed ) { # Framed image
5325 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5326 # No caption or alt text, add the filename as the alt text so
5327 # that screen readers at least get some description of the image
5328 $params['frame']['alt'] = $title->getText();
5329 }
5330 # Do not set $params['frame']['title'] because tooltips don't make sense
5331 # for framed images
5332 } else { # Inline image
5333 if ( !isset( $params['frame']['alt'] ) ) {
5334 # No alt text, use the "caption" for the alt text
5335 if ( $caption !== '' ) {
5336 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5337 } else {
5338 # No caption, fall back to using the filename for the
5339 # alt text
5340 $params['frame']['alt'] = $title->getText();
5341 }
5342 }
5343 # Use the "caption" for the tooltip text
5344 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5345 }
5346
5347 Hooks::run( 'ParserMakeImageParams', [ $title, $file, &$params, $this ] );
5348
5349 # Linker does the rest
5350 $time = isset( $options['time'] ) ? $options['time'] : false;
5351 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5352 $time, $descQuery, $this->mOptions->getThumbSize() );
5353
5354 # Give the handler a chance to modify the parser object
5355 if ( $handler ) {
5356 $handler->parserTransformHook( $this, $file );
5357 }
5358
5359 return $ret;
5360 }
5361
5362 /**
5363 * @param string $caption
5364 * @param LinkHolderArray|bool $holders
5365 * @return mixed|string
5366 */
5367 protected function stripAltText( $caption, $holders ) {
5368 # Strip bad stuff out of the title (tooltip). We can't just use
5369 # replaceLinkHoldersText() here, because if this function is called
5370 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5371 if ( $holders ) {
5372 $tooltip = $holders->replaceText( $caption );
5373 } else {
5374 $tooltip = $this->replaceLinkHoldersText( $caption );
5375 }
5376
5377 # make sure there are no placeholders in thumbnail attributes
5378 # that are later expanded to html- so expand them now and
5379 # remove the tags
5380 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5381 $tooltip = Sanitizer::stripAllTags( $tooltip );
5382
5383 return $tooltip;
5384 }
5385
5386 /**
5387 * Set a flag in the output object indicating that the content is dynamic and
5388 * shouldn't be cached.
5389 * @deprecated since 1.28; use getOutput()->updateCacheExpiry()
5390 */
5391 public function disableCache() {
5392 wfDebug( "Parser output marked as uncacheable.\n" );
5393 if ( !$this->mOutput ) {
5394 throw new MWException( __METHOD__ .
5395 " can only be called when actually parsing something" );
5396 }
5397 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5398 }
5399
5400 /**
5401 * Callback from the Sanitizer for expanding items found in HTML attribute
5402 * values, so they can be safely tested and escaped.
5403 *
5404 * @param string $text
5405 * @param bool|PPFrame $frame
5406 * @return string
5407 */
5408 public function attributeStripCallback( &$text, $frame = false ) {
5409 $text = $this->replaceVariables( $text, $frame );
5410 $text = $this->mStripState->unstripBoth( $text );
5411 return $text;
5412 }
5413
5414 /**
5415 * Accessor
5416 *
5417 * @return array
5418 */
5419 public function getTags() {
5420 return array_merge(
5421 array_keys( $this->mTransparentTagHooks ),
5422 array_keys( $this->mTagHooks ),
5423 array_keys( $this->mFunctionTagHooks )
5424 );
5425 }
5426
5427 /**
5428 * Replace transparent tags in $text with the values given by the callbacks.
5429 *
5430 * Transparent tag hooks are like regular XML-style tag hooks, except they
5431 * operate late in the transformation sequence, on HTML instead of wikitext.
5432 *
5433 * @param string $text
5434 *
5435 * @return string
5436 */
5437 public function replaceTransparentTags( $text ) {
5438 $matches = [];
5439 $elements = array_keys( $this->mTransparentTagHooks );
5440 $text = self::extractTagsAndParams( $elements, $text, $matches );
5441 $replacements = [];
5442
5443 foreach ( $matches as $marker => $data ) {
5444 list( $element, $content, $params, $tag ) = $data;
5445 $tagName = strtolower( $element );
5446 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5447 $output = call_user_func_array(
5448 $this->mTransparentTagHooks[$tagName],
5449 [ $content, $params, $this ]
5450 );
5451 } else {
5452 $output = $tag;
5453 }
5454 $replacements[$marker] = $output;
5455 }
5456 return strtr( $text, $replacements );
5457 }
5458
5459 /**
5460 * Break wikitext input into sections, and either pull or replace
5461 * some particular section's text.
5462 *
5463 * External callers should use the getSection and replaceSection methods.
5464 *
5465 * @param string $text Page wikitext
5466 * @param string|int $sectionId A section identifier string of the form:
5467 * "<flag1> - <flag2> - ... - <section number>"
5468 *
5469 * Currently the only recognised flag is "T", which means the target section number
5470 * was derived during a template inclusion parse, in other words this is a template
5471 * section edit link. If no flags are given, it was an ordinary section edit link.
5472 * This flag is required to avoid a section numbering mismatch when a section is
5473 * enclosed by "<includeonly>" (T8563).
5474 *
5475 * The section number 0 pulls the text before the first heading; other numbers will
5476 * pull the given section along with its lower-level subsections. If the section is
5477 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5478 *
5479 * Section 0 is always considered to exist, even if it only contains the empty
5480 * string. If $text is the empty string and section 0 is replaced, $newText is
5481 * returned.
5482 *
5483 * @param string $mode One of "get" or "replace"
5484 * @param string $newText Replacement text for section data.
5485 * @return string For "get", the extracted section text.
5486 * for "replace", the whole page with the section replaced.
5487 */
5488 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5489 global $wgTitle; # not generally used but removes an ugly failure mode
5490
5491 $magicScopeVariable = $this->lock();
5492 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5493 $outText = '';
5494 $frame = $this->getPreprocessor()->newFrame();
5495
5496 # Process section extraction flags
5497 $flags = 0;
5498 $sectionParts = explode( '-', $sectionId );
5499 $sectionIndex = array_pop( $sectionParts );
5500 foreach ( $sectionParts as $part ) {
5501 if ( $part === 'T' ) {
5502 $flags |= self::PTD_FOR_INCLUSION;
5503 }
5504 }
5505
5506 # Check for empty input
5507 if ( strval( $text ) === '' ) {
5508 # Only sections 0 and T-0 exist in an empty document
5509 if ( $sectionIndex == 0 ) {
5510 if ( $mode === 'get' ) {
5511 return '';
5512 } else {
5513 return $newText;
5514 }
5515 } else {
5516 if ( $mode === 'get' ) {
5517 return $newText;
5518 } else {
5519 return $text;
5520 }
5521 }
5522 }
5523
5524 # Preprocess the text
5525 $root = $this->preprocessToDom( $text, $flags );
5526
5527 # <h> nodes indicate section breaks
5528 # They can only occur at the top level, so we can find them by iterating the root's children
5529 $node = $root->getFirstChild();
5530
5531 # Find the target section
5532 if ( $sectionIndex == 0 ) {
5533 # Section zero doesn't nest, level=big
5534 $targetLevel = 1000;
5535 } else {
5536 while ( $node ) {
5537 if ( $node->getName() === 'h' ) {
5538 $bits = $node->splitHeading();
5539 if ( $bits['i'] == $sectionIndex ) {
5540 $targetLevel = $bits['level'];
5541 break;
5542 }
5543 }
5544 if ( $mode === 'replace' ) {
5545 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5546 }
5547 $node = $node->getNextSibling();
5548 }
5549 }
5550
5551 if ( !$node ) {
5552 # Not found
5553 if ( $mode === 'get' ) {
5554 return $newText;
5555 } else {
5556 return $text;
5557 }
5558 }
5559
5560 # Find the end of the section, including nested sections
5561 do {
5562 if ( $node->getName() === 'h' ) {
5563 $bits = $node->splitHeading();
5564 $curLevel = $bits['level'];
5565 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5566 break;
5567 }
5568 }
5569 if ( $mode === 'get' ) {
5570 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5571 }
5572 $node = $node->getNextSibling();
5573 } while ( $node );
5574
5575 # Write out the remainder (in replace mode only)
5576 if ( $mode === 'replace' ) {
5577 # Output the replacement text
5578 # Add two newlines on -- trailing whitespace in $newText is conventionally
5579 # stripped by the editor, so we need both newlines to restore the paragraph gap
5580 # Only add trailing whitespace if there is newText
5581 if ( $newText != "" ) {
5582 $outText .= $newText . "\n\n";
5583 }
5584
5585 while ( $node ) {
5586 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5587 $node = $node->getNextSibling();
5588 }
5589 }
5590
5591 if ( is_string( $outText ) ) {
5592 # Re-insert stripped tags
5593 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5594 }
5595
5596 return $outText;
5597 }
5598
5599 /**
5600 * This function returns the text of a section, specified by a number ($section).
5601 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5602 * the first section before any such heading (section 0).
5603 *
5604 * If a section contains subsections, these are also returned.
5605 *
5606 * @param string $text Text to look in
5607 * @param string|int $sectionId Section identifier as a number or string
5608 * (e.g. 0, 1 or 'T-1').
5609 * @param string $defaultText Default to return if section is not found
5610 *
5611 * @return string Text of the requested section
5612 */
5613 public function getSection( $text, $sectionId, $defaultText = '' ) {
5614 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5615 }
5616
5617 /**
5618 * This function returns $oldtext after the content of the section
5619 * specified by $section has been replaced with $text. If the target
5620 * section does not exist, $oldtext is returned unchanged.
5621 *
5622 * @param string $oldText Former text of the article
5623 * @param string|int $sectionId Section identifier as a number or string
5624 * (e.g. 0, 1 or 'T-1').
5625 * @param string $newText Replacing text
5626 *
5627 * @return string Modified text
5628 */
5629 public function replaceSection( $oldText, $sectionId, $newText ) {
5630 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5631 }
5632
5633 /**
5634 * Get the ID of the revision we are parsing
5635 *
5636 * @return int|null
5637 */
5638 public function getRevisionId() {
5639 return $this->mRevisionId;
5640 }
5641
5642 /**
5643 * Get the revision object for $this->mRevisionId
5644 *
5645 * @return Revision|null Either a Revision object or null
5646 * @since 1.23 (public since 1.23)
5647 */
5648 public function getRevisionObject() {
5649 if ( !is_null( $this->mRevisionObject ) ) {
5650 return $this->mRevisionObject;
5651 }
5652 if ( is_null( $this->mRevisionId ) ) {
5653 return null;
5654 }
5655
5656 $rev = call_user_func(
5657 $this->mOptions->getCurrentRevisionCallback(), $this->getTitle(), $this
5658 );
5659
5660 # If the parse is for a new revision, then the callback should have
5661 # already been set to force the object and should match mRevisionId.
5662 # If not, try to fetch by mRevisionId for sanity.
5663 if ( $rev && $rev->getId() != $this->mRevisionId ) {
5664 $rev = Revision::newFromId( $this->mRevisionId );
5665 }
5666
5667 $this->mRevisionObject = $rev;
5668
5669 return $this->mRevisionObject;
5670 }
5671
5672 /**
5673 * Get the timestamp associated with the current revision, adjusted for
5674 * the default server-local timestamp
5675 * @return string
5676 */
5677 public function getRevisionTimestamp() {
5678 if ( is_null( $this->mRevisionTimestamp ) ) {
5679 global $wgContLang;
5680
5681 $revObject = $this->getRevisionObject();
5682 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5683
5684 # The cryptic '' timezone parameter tells to use the site-default
5685 # timezone offset instead of the user settings.
5686 # Since this value will be saved into the parser cache, served
5687 # to other users, and potentially even used inside links and such,
5688 # it needs to be consistent for all visitors.
5689 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5690
5691 }
5692 return $this->mRevisionTimestamp;
5693 }
5694
5695 /**
5696 * Get the name of the user that edited the last revision
5697 *
5698 * @return string User name
5699 */
5700 public function getRevisionUser() {
5701 if ( is_null( $this->mRevisionUser ) ) {
5702 $revObject = $this->getRevisionObject();
5703
5704 # if this template is subst: the revision id will be blank,
5705 # so just use the current user's name
5706 if ( $revObject ) {
5707 $this->mRevisionUser = $revObject->getUserText();
5708 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5709 $this->mRevisionUser = $this->getUser()->getName();
5710 }
5711 }
5712 return $this->mRevisionUser;
5713 }
5714
5715 /**
5716 * Get the size of the revision
5717 *
5718 * @return int|null Revision size
5719 */
5720 public function getRevisionSize() {
5721 if ( is_null( $this->mRevisionSize ) ) {
5722 $revObject = $this->getRevisionObject();
5723
5724 # if this variable is subst: the revision id will be blank,
5725 # so just use the parser input size, because the own substituation
5726 # will change the size.
5727 if ( $revObject ) {
5728 $this->mRevisionSize = $revObject->getSize();
5729 } else {
5730 $this->mRevisionSize = $this->mInputSize;
5731 }
5732 }
5733 return $this->mRevisionSize;
5734 }
5735
5736 /**
5737 * Mutator for $mDefaultSort
5738 *
5739 * @param string $sort New value
5740 */
5741 public function setDefaultSort( $sort ) {
5742 $this->mDefaultSort = $sort;
5743 $this->mOutput->setProperty( 'defaultsort', $sort );
5744 }
5745
5746 /**
5747 * Accessor for $mDefaultSort
5748 * Will use the empty string if none is set.
5749 *
5750 * This value is treated as a prefix, so the
5751 * empty string is equivalent to sorting by
5752 * page name.
5753 *
5754 * @return string
5755 */
5756 public function getDefaultSort() {
5757 if ( $this->mDefaultSort !== false ) {
5758 return $this->mDefaultSort;
5759 } else {
5760 return '';
5761 }
5762 }
5763
5764 /**
5765 * Accessor for $mDefaultSort
5766 * Unlike getDefaultSort(), will return false if none is set
5767 *
5768 * @return string|bool
5769 */
5770 public function getCustomDefaultSort() {
5771 return $this->mDefaultSort;
5772 }
5773
5774 /**
5775 * Try to guess the section anchor name based on a wikitext fragment
5776 * presumably extracted from a heading, for example "Header" from
5777 * "== Header ==".
5778 *
5779 * @param string $text
5780 *
5781 * @return string
5782 */
5783 public function guessSectionNameFromWikiText( $text ) {
5784 # Strip out wikitext links(they break the anchor)
5785 $text = $this->stripSectionName( $text );
5786 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5787 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5788 }
5789
5790 /**
5791 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5792 * instead. For use in redirects, since IE6 interprets Redirect: headers
5793 * as something other than UTF-8 (apparently?), resulting in breakage.
5794 *
5795 * @param string $text The section name
5796 * @return string An anchor
5797 */
5798 public function guessLegacySectionNameFromWikiText( $text ) {
5799 # Strip out wikitext links(they break the anchor)
5800 $text = $this->stripSectionName( $text );
5801 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5802 return '#' . Sanitizer::escapeId( $text, [ 'noninitial', 'legacy' ] );
5803 }
5804
5805 /**
5806 * Strips a text string of wikitext for use in a section anchor
5807 *
5808 * Accepts a text string and then removes all wikitext from the
5809 * string and leaves only the resultant text (i.e. the result of
5810 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5811 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5812 * to create valid section anchors by mimicing the output of the
5813 * parser when headings are parsed.
5814 *
5815 * @param string $text Text string to be stripped of wikitext
5816 * for use in a Section anchor
5817 * @return string Filtered text string
5818 */
5819 public function stripSectionName( $text ) {
5820 # Strip internal link markup
5821 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5822 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5823
5824 # Strip external link markup
5825 # @todo FIXME: Not tolerant to blank link text
5826 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5827 # on how many empty links there are on the page - need to figure that out.
5828 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5829
5830 # Parse wikitext quotes (italics & bold)
5831 $text = $this->doQuotes( $text );
5832
5833 # Strip HTML tags
5834 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5835 return $text;
5836 }
5837
5838 /**
5839 * strip/replaceVariables/unstrip for preprocessor regression testing
5840 *
5841 * @param string $text
5842 * @param Title $title
5843 * @param ParserOptions $options
5844 * @param int $outputType
5845 *
5846 * @return string
5847 */
5848 public function testSrvus( $text, Title $title, ParserOptions $options,
5849 $outputType = self::OT_HTML
5850 ) {
5851 $magicScopeVariable = $this->lock();
5852 $this->startParse( $title, $options, $outputType, true );
5853
5854 $text = $this->replaceVariables( $text );
5855 $text = $this->mStripState->unstripBoth( $text );
5856 $text = Sanitizer::removeHTMLtags( $text );
5857 return $text;
5858 }
5859
5860 /**
5861 * @param string $text
5862 * @param Title $title
5863 * @param ParserOptions $options
5864 * @return string
5865 */
5866 public function testPst( $text, Title $title, ParserOptions $options ) {
5867 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5868 }
5869
5870 /**
5871 * @param string $text
5872 * @param Title $title
5873 * @param ParserOptions $options
5874 * @return string
5875 */
5876 public function testPreprocess( $text, Title $title, ParserOptions $options ) {
5877 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5878 }
5879
5880 /**
5881 * Call a callback function on all regions of the given text that are not
5882 * inside strip markers, and replace those regions with the return value
5883 * of the callback. For example, with input:
5884 *
5885 * aaa<MARKER>bbb
5886 *
5887 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5888 * two strings will be replaced with the value returned by the callback in
5889 * each case.
5890 *
5891 * @param string $s
5892 * @param callable $callback
5893 *
5894 * @return string
5895 */
5896 public function markerSkipCallback( $s, $callback ) {
5897 $i = 0;
5898 $out = '';
5899 while ( $i < strlen( $s ) ) {
5900 $markerStart = strpos( $s, self::MARKER_PREFIX, $i );
5901 if ( $markerStart === false ) {
5902 $out .= call_user_func( $callback, substr( $s, $i ) );
5903 break;
5904 } else {
5905 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5906 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5907 if ( $markerEnd === false ) {
5908 $out .= substr( $s, $markerStart );
5909 break;
5910 } else {
5911 $markerEnd += strlen( self::MARKER_SUFFIX );
5912 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5913 $i = $markerEnd;
5914 }
5915 }
5916 }
5917 return $out;
5918 }
5919
5920 /**
5921 * Remove any strip markers found in the given text.
5922 *
5923 * @param string $text Input string
5924 * @return string
5925 */
5926 public function killMarkers( $text ) {
5927 return $this->mStripState->killMarkers( $text );
5928 }
5929
5930 /**
5931 * Save the parser state required to convert the given half-parsed text to
5932 * HTML. "Half-parsed" in this context means the output of
5933 * recursiveTagParse() or internalParse(). This output has strip markers
5934 * from replaceVariables (extensionSubstitution() etc.), and link
5935 * placeholders from replaceLinkHolders().
5936 *
5937 * Returns an array which can be serialized and stored persistently. This
5938 * array can later be loaded into another parser instance with
5939 * unserializeHalfParsedText(). The text can then be safely incorporated into
5940 * the return value of a parser hook.
5941 *
5942 * @param string $text
5943 *
5944 * @return array
5945 */
5946 public function serializeHalfParsedText( $text ) {
5947 $data = [
5948 'text' => $text,
5949 'version' => self::HALF_PARSED_VERSION,
5950 'stripState' => $this->mStripState->getSubState( $text ),
5951 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5952 ];
5953 return $data;
5954 }
5955
5956 /**
5957 * Load the parser state given in the $data array, which is assumed to
5958 * have been generated by serializeHalfParsedText(). The text contents is
5959 * extracted from the array, and its markers are transformed into markers
5960 * appropriate for the current Parser instance. This transformed text is
5961 * returned, and can be safely included in the return value of a parser
5962 * hook.
5963 *
5964 * If the $data array has been stored persistently, the caller should first
5965 * check whether it is still valid, by calling isValidHalfParsedText().
5966 *
5967 * @param array $data Serialized data
5968 * @throws MWException
5969 * @return string
5970 */
5971 public function unserializeHalfParsedText( $data ) {
5972 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5973 throw new MWException( __METHOD__ . ': invalid version' );
5974 }
5975
5976 # First, extract the strip state.
5977 $texts = [ $data['text'] ];
5978 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5979
5980 # Now renumber links
5981 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
5982
5983 # Should be good to go.
5984 return $texts[0];
5985 }
5986
5987 /**
5988 * Returns true if the given array, presumed to be generated by
5989 * serializeHalfParsedText(), is compatible with the current version of the
5990 * parser.
5991 *
5992 * @param array $data
5993 *
5994 * @return bool
5995 */
5996 public function isValidHalfParsedText( $data ) {
5997 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
5998 }
5999
6000 /**
6001 * Parsed a width param of imagelink like 300px or 200x300px
6002 *
6003 * @param string $value
6004 *
6005 * @return array
6006 * @since 1.20
6007 */
6008 public function parseWidthParam( $value ) {
6009 $parsedWidthParam = [];
6010 if ( $value === '' ) {
6011 return $parsedWidthParam;
6012 }
6013 $m = [];
6014 # (T15500) In both cases (width/height and width only),
6015 # permit trailing "px" for backward compatibility.
6016 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6017 $width = intval( $m[1] );
6018 $height = intval( $m[2] );
6019 $parsedWidthParam['width'] = $width;
6020 $parsedWidthParam['height'] = $height;
6021 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6022 $width = intval( $value );
6023 $parsedWidthParam['width'] = $width;
6024 }
6025 return $parsedWidthParam;
6026 }
6027
6028 /**
6029 * Lock the current instance of the parser.
6030 *
6031 * This is meant to stop someone from calling the parser
6032 * recursively and messing up all the strip state.
6033 *
6034 * @throws MWException If parser is in a parse
6035 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6036 */
6037 protected function lock() {
6038 if ( $this->mInParse ) {
6039 throw new MWException( "Parser state cleared while parsing. "
6040 . "Did you call Parser::parse recursively?" );
6041 }
6042 $this->mInParse = true;
6043
6044 $recursiveCheck = new ScopedCallback( function() {
6045 $this->mInParse = false;
6046 } );
6047
6048 return $recursiveCheck;
6049 }
6050
6051 /**
6052 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6053 *
6054 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6055 * or if there is more than one <p/> tag in the input HTML.
6056 *
6057 * @param string $html
6058 * @return string
6059 * @since 1.24
6060 */
6061 public static function stripOuterParagraph( $html ) {
6062 $m = [];
6063 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6064 if ( strpos( $m[1], '</p>' ) === false ) {
6065 $html = $m[1];
6066 }
6067 }
6068
6069 return $html;
6070 }
6071
6072 /**
6073 * Return this parser if it is not doing anything, otherwise
6074 * get a fresh parser. You can use this method by doing
6075 * $myParser = $wgParser->getFreshParser(), or more simply
6076 * $wgParser->getFreshParser()->parse( ... );
6077 * if you're unsure if $wgParser is safe to use.
6078 *
6079 * @since 1.24
6080 * @return Parser A parser object that is not parsing anything
6081 */
6082 public function getFreshParser() {
6083 global $wgParserConf;
6084 if ( $this->mInParse ) {
6085 return new $wgParserConf['class']( $wgParserConf );
6086 } else {
6087 return $this;
6088 }
6089 }
6090
6091 /**
6092 * Set's up the PHP implementation of OOUI for use in this request
6093 * and instructs OutputPage to enable OOUI for itself.
6094 *
6095 * @since 1.26
6096 */
6097 public function enableOOUI() {
6098 OutputPage::setupOOUI();
6099 $this->mOutput->setEnableOOUI( true );
6100 }
6101 }