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