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