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