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