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