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