Make line breaks in <blockquote> behave like <div> (bug 6200).
[mediawiki.git] / includes / parser / Parser.php
blob4a16f565302902100f367477588bc2d8fdf0cce6
1 <?php
2 /**
3 * PHP parser that converts wiki markup to HTML.
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.
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.
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
20 * @file
21 * @ingroup Parser
24 /**
25 * @defgroup Parser Parser
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).
34 * There are seven main entry points into the Parser class:
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.
51 * Globals used:
52 * object: $wgContLang
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
56 * @par Settings:
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
62 * $wgInterwikiMagic
63 * $wgMaxArticleSize
65 * @ingroup Parser
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.
73 const VERSION = '1.6.4';
75 /**
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION = 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH = 1;
84 const SFH_OBJECT_ARGS = 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT = 0;
96 const COLON_STATE_TAG = 1;
97 const COLON_STATE_TAGSTART = 2;
98 const COLON_STATE_CLOSETAG = 3;
99 const COLON_STATE_TAGSLASH = 4;
100 const COLON_STATE_COMMENT = 5;
101 const COLON_STATE_COMMENTDASH = 6;
102 const COLON_STATE_COMMENTDASHDASH = 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION = 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML = 1; # like parse()
110 const OT_WIKI = 2; # like preSaveTransform()
111 const OT_PREPROCESS = 3; # like preprocess()
112 const OT_MSG = 3;
113 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX = "-QINU\x7f";
118 # Persistent:
119 var $mTagHooks = array();
120 var $mTransparentTagHooks = array();
121 var $mFunctionHooks = array();
122 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
123 var $mFunctionTagHooks = array();
124 var $mStripList = array();
125 var $mDefaultStripList = array();
126 var $mVarCache = array();
127 var $mImageParams = array();
128 var $mImageParamsMagicArray = array();
129 var $mMarkerIndex = 0;
130 var $mFirstCall = true;
132 # Initialised by initialiseVariables()
135 * @var MagicWordArray
137 var $mVariables;
140 * @var MagicWordArray
142 var $mSubstWords;
143 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
145 # Cleared with clearState():
147 * @var ParserOutput
149 var $mOutput;
150 var $mAutonumber, $mDTopen;
153 * @var StripState
155 var $mStripState;
157 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
159 * @var LinkHolderArray
161 var $mLinkHolders;
163 var $mLinkID;
164 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
165 var $mDefaultSort;
166 var $mTplExpandCache; # empty-frame expansion cache
167 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
168 var $mExpensiveFunctionCount; # number of expensive parser function calls
169 var $mShowToc, $mForceTocPosition;
172 * @var User
174 var $mUser; # User object; only used when doing pre-save transform
176 # Temporary
177 # These are variables reset at least once per parse regardless of $clearState
180 * @var ParserOptions
182 var $mOptions;
185 * @var Title
187 var $mTitle; # Title context, used for self-link rendering and similar things
188 var $mOutputType; # Output type, one of the OT_xxx constants
189 var $ot; # Shortcut alias, see setOutputType()
190 var $mRevisionObject; # The revision object of the specified revision ID
191 var $mRevisionId; # ID to display in {{REVISIONID}} tags
192 var $mRevisionTimestamp; # The timestamp of the specified revision ID
193 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
194 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
195 var $mInputSize = false; # For {{PAGESIZE}} on current page.
198 * @var string
200 var $mUniqPrefix;
203 * @var Array with the language name of each language link (i.e. the
204 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
205 * duplicate language links to the ParserOutput.
207 var $mLangLinkLanguages;
210 * Constructor
212 * @param $conf array
214 public function __construct( $conf = array() ) {
215 $this->mConf = $conf;
216 $this->mUrlProtocols = wfUrlProtocols();
217 $this->mExtLinkBracketedRegex = '/\[(((?i)' . $this->mUrlProtocols . ')' .
218 self::EXT_LINK_URL_CLASS . '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
219 if ( isset( $conf['preprocessorClass'] ) ) {
220 $this->mPreprocessorClass = $conf['preprocessorClass'];
221 } elseif ( defined( 'HPHP_VERSION' ) ) {
222 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
223 $this->mPreprocessorClass = 'Preprocessor_Hash';
224 } elseif ( extension_loaded( 'domxml' ) ) {
225 # PECL extension that conflicts with the core DOM extension (bug 13770)
226 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
227 $this->mPreprocessorClass = 'Preprocessor_Hash';
228 } elseif ( extension_loaded( 'dom' ) ) {
229 $this->mPreprocessorClass = 'Preprocessor_DOM';
230 } else {
231 $this->mPreprocessorClass = 'Preprocessor_Hash';
233 wfDebug( __CLASS__ . ": using preprocessor: {$this->mPreprocessorClass}\n" );
237 * Reduce memory usage to reduce the impact of circular references
239 function __destruct() {
240 if ( isset( $this->mLinkHolders ) ) {
241 unset( $this->mLinkHolders );
243 foreach ( $this as $name => $value ) {
244 unset( $this->$name );
249 * Allow extensions to clean up when the parser is cloned
251 function __clone() {
252 wfRunHooks( 'ParserCloned', array( $this ) );
256 * Do various kinds of initialisation on the first call of the parser
258 function firstCallInit() {
259 if ( !$this->mFirstCall ) {
260 return;
262 $this->mFirstCall = false;
264 wfProfileIn( __METHOD__ );
266 CoreParserFunctions::register( $this );
267 CoreTagHooks::register( $this );
268 $this->initialiseVariables();
270 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
271 wfProfileOut( __METHOD__ );
275 * Clear Parser state
277 * @private
279 function clearState() {
280 wfProfileIn( __METHOD__ );
281 if ( $this->mFirstCall ) {
282 $this->firstCallInit();
284 $this->mOutput = new ParserOutput;
285 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
286 $this->mAutonumber = 0;
287 $this->mLastSection = '';
288 $this->mDTopen = false;
289 $this->mIncludeCount = array();
290 $this->mArgStack = false;
291 $this->mInPre = false;
292 $this->mLinkHolders = new LinkHolderArray( $this );
293 $this->mLinkID = 0;
294 $this->mRevisionObject = $this->mRevisionTimestamp =
295 $this->mRevisionId = $this->mRevisionUser = null;
296 $this->mVarCache = array();
297 $this->mUser = null;
298 $this->mLangLinkLanguages = array();
301 * Prefix for temporary replacement strings for the multipass parser.
302 * \x07 should never appear in input as it's disallowed in XML.
303 * Using it at the front also gives us a little extra robustness
304 * since it shouldn't match when butted up against identifier-like
305 * string constructs.
307 * Must not consist of all title characters, or else it will change
308 * the behavior of <nowiki> in a link.
310 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
311 $this->mStripState = new StripState( $this->mUniqPrefix );
313 # Clear these on every parse, bug 4549
314 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
316 $this->mShowToc = true;
317 $this->mForceTocPosition = false;
318 $this->mIncludeSizes = array(
319 'post-expand' => 0,
320 'arg' => 0,
322 $this->mPPNodeCount = 0;
323 $this->mGeneratedPPNodeCount = 0;
324 $this->mHighestExpansionDepth = 0;
325 $this->mDefaultSort = false;
326 $this->mHeadings = array();
327 $this->mDoubleUnderscores = array();
328 $this->mExpensiveFunctionCount = 0;
330 # Fix cloning
331 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
332 $this->mPreprocessor = null;
335 wfRunHooks( 'ParserClearState', array( &$this ) );
336 wfProfileOut( __METHOD__ );
340 * Convert wikitext to HTML
341 * Do not call this function recursively.
343 * @param string $text text we want to parse
344 * @param $title Title object
345 * @param $options ParserOptions
346 * @param $linestart boolean
347 * @param $clearState boolean
348 * @param int $revid number to pass in {{REVISIONID}}
349 * @return ParserOutput a ParserOutput
351 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
353 * First pass--just handle <nowiki> sections, pass the rest off
354 * to internalParse() which does all the real work.
357 global $wgUseTidy, $wgAlwaysUseTidy;
358 $fname = __METHOD__ . '-' . wfGetCaller();
359 wfProfileIn( __METHOD__ );
360 wfProfileIn( $fname );
362 $this->startParse( $title, $options, self::OT_HTML, $clearState );
364 $this->mInputSize = strlen( $text );
366 # Remove the strip marker tag prefix from the input, if present.
367 if ( $clearState ) {
368 $text = str_replace( $this->mUniqPrefix, '', $text );
371 $oldRevisionId = $this->mRevisionId;
372 $oldRevisionObject = $this->mRevisionObject;
373 $oldRevisionTimestamp = $this->mRevisionTimestamp;
374 $oldRevisionUser = $this->mRevisionUser;
375 if ( $revid !== null ) {
376 $this->mRevisionId = $revid;
377 $this->mRevisionObject = null;
378 $this->mRevisionTimestamp = null;
379 $this->mRevisionUser = null;
382 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
383 # No more strip!
384 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
385 $text = $this->internalParse( $text );
386 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState ) );
388 $text = $this->mStripState->unstripGeneral( $text );
390 # Clean up special characters, only run once, next-to-last before doBlockLevels
391 $fixtags = array(
392 # french spaces, last one Guillemet-left
393 # only if there is something before the space
394 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;',
395 # french spaces, Guillemet-right
396 '/(\\302\\253) /' => '\\1&#160;',
397 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
399 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
401 $text = $this->doBlockLevels( $text, $linestart );
403 $this->replaceLinkHolders( $text );
406 * The input doesn't get language converted if
407 * a) It's disabled
408 * b) Content isn't converted
409 * c) It's a conversion table
410 * d) it is an interface message (which is in the user language)
412 if ( !( $options->getDisableContentConversion()
413 || isset( $this->mDoubleUnderscores['nocontentconvert'] ) ) )
415 if ( !$this->mOptions->getInterfaceMessage() ) {
416 # The position of the convert() call should not be changed. it
417 # assumes that the links are all replaced and the only thing left
418 # is the <nowiki> mark.
419 $text = $this->getConverterLanguage()->convert( $text );
424 * A converted title will be provided in the output object if title and
425 * content conversion are enabled, the article text does not contain
426 * a conversion-suppressing double-underscore tag, and no
427 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
428 * automatic link conversion.
430 if ( !( $options->getDisableTitleConversion()
431 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
432 || isset( $this->mDoubleUnderscores['notitleconvert'] )
433 || $this->mOutput->getDisplayTitle() !== false ) )
435 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
436 if ( $convruletitle ) {
437 $this->mOutput->setTitleText( $convruletitle );
438 } else {
439 $titleText = $this->getConverterLanguage()->convertTitle( $title );
440 $this->mOutput->setTitleText( $titleText );
444 $text = $this->mStripState->unstripNoWiki( $text );
446 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
448 $text = $this->replaceTransparentTags( $text );
449 $text = $this->mStripState->unstripGeneral( $text );
451 $text = Sanitizer::normalizeCharReferences( $text );
453 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
454 $text = MWTidy::tidy( $text );
455 } else {
456 # attempt to sanitize at least some nesting problems
457 # (bug #2702 and quite a few others)
458 $tidyregs = array(
459 # ''Something [http://www.cool.com cool''] -->
460 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
461 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
462 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
463 # fix up an anchor inside another anchor, only
464 # at least for a single single nested link (bug 3695)
465 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
466 '\\1\\2</a>\\3</a>\\1\\4</a>',
467 # fix div inside inline elements- doBlockLevels won't wrap a line which
468 # contains a div, so fix it up here; replace
469 # div with escaped text
470 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
471 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
472 # remove empty italic or bold tag pairs, some
473 # introduced by rules above
474 '/<([bi])><\/\\1>/' => '',
477 $text = preg_replace(
478 array_keys( $tidyregs ),
479 array_values( $tidyregs ),
480 $text );
483 if ( $this->mExpensiveFunctionCount > $this->mOptions->getExpensiveParserFunctionLimit() ) {
484 $this->limitationWarn( 'expensive-parserfunction',
485 $this->mExpensiveFunctionCount,
486 $this->mOptions->getExpensiveParserFunctionLimit()
490 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
492 # Information on include size limits, for the benefit of users who try to skirt them
493 if ( $this->mOptions->getEnableLimitReport() ) {
494 $max = $this->mOptions->getMaxIncludeSize();
495 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
496 $limitReport =
497 "NewPP limit report\n" .
498 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
499 "Preprocessor generated node count: " .
500 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
501 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
502 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n" .
503 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n" .
504 $PFreport;
505 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
507 // Sanitize for comment. Note '‐' in the replacement is U+2010,
508 // which looks much like the problematic '-'.
509 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&amp;' ), $limitReport );
511 $text .= "\n<!-- \n$limitReport-->\n";
513 if ( $this->mGeneratedPPNodeCount > $this->mOptions->getMaxGeneratedPPNodeCount() / 10 ) {
514 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount . ' ' .
515 $this->mTitle->getPrefixedDBkey() );
518 $this->mOutput->setText( $text );
520 $this->mRevisionId = $oldRevisionId;
521 $this->mRevisionObject = $oldRevisionObject;
522 $this->mRevisionTimestamp = $oldRevisionTimestamp;
523 $this->mRevisionUser = $oldRevisionUser;
524 $this->mInputSize = false;
525 wfProfileOut( $fname );
526 wfProfileOut( __METHOD__ );
528 return $this->mOutput;
532 * Recursive parser entry point that can be called from an extension tag
533 * hook.
535 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
537 * @param string $text text extension wants to have parsed
538 * @param $frame PPFrame: The frame to use for expanding any template variables
540 * @return string
542 function recursiveTagParse( $text, $frame = false ) {
543 wfProfileIn( __METHOD__ );
544 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
545 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
546 $text = $this->internalParse( $text, false, $frame );
547 wfProfileOut( __METHOD__ );
548 return $text;
552 * Expand templates and variables in the text, producing valid, static wikitext.
553 * Also removes comments.
554 * @return mixed|string
556 function preprocess( $text, Title $title = null, ParserOptions $options, $revid = null ) {
557 wfProfileIn( __METHOD__ );
558 $this->startParse( $title, $options, self::OT_PREPROCESS, true );
559 if ( $revid !== null ) {
560 $this->mRevisionId = $revid;
562 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
563 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
564 $text = $this->replaceVariables( $text );
565 $text = $this->mStripState->unstripBoth( $text );
566 wfProfileOut( __METHOD__ );
567 return $text;
571 * Recursive parser entry point that can be called from an extension tag
572 * hook.
574 * @param string $text text to be expanded
575 * @param $frame PPFrame: The frame to use for expanding any template variables
576 * @return String
577 * @since 1.19
579 public function recursivePreprocess( $text, $frame = false ) {
580 wfProfileIn( __METHOD__ );
581 $text = $this->replaceVariables( $text, $frame );
582 $text = $this->mStripState->unstripBoth( $text );
583 wfProfileOut( __METHOD__ );
584 return $text;
588 * Process the wikitext for the "?preload=" feature. (bug 5210)
590 * "<noinclude>", "<includeonly>" etc. are parsed as for template
591 * transclusion, comments, templates, arguments, tags hooks and parser
592 * functions are untouched.
594 * @param $text String
595 * @param $title Title
596 * @param $options ParserOptions
597 * @return String
599 public function getPreloadText( $text, Title $title, ParserOptions $options ) {
600 # Parser (re)initialisation
601 $this->startParse( $title, $options, self::OT_PLAIN, true );
603 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
604 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
605 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
606 $text = $this->mStripState->unstripBoth( $text );
607 return $text;
611 * Get a random string
613 * @return string
615 public static function getRandomString() {
616 return wfRandomString( 16 );
620 * Set the current user.
621 * Should only be used when doing pre-save transform.
623 * @param $user Mixed: User object or null (to reset)
625 function setUser( $user ) {
626 $this->mUser = $user;
630 * Accessor for mUniqPrefix.
632 * @return String
634 public function uniqPrefix() {
635 if ( !isset( $this->mUniqPrefix ) ) {
636 # @todo FIXME: This is probably *horribly wrong*
637 # LanguageConverter seems to want $wgParser's uniqPrefix, however
638 # if this is called for a parser cache hit, the parser may not
639 # have ever been initialized in the first place.
640 # Not really sure what the heck is supposed to be going on here.
641 return '';
642 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
644 return $this->mUniqPrefix;
648 * Set the context title
650 * @param $t Title
652 function setTitle( $t ) {
653 if ( !$t || $t instanceof FakeTitle ) {
654 $t = Title::newFromText( 'NO TITLE' );
657 if ( strval( $t->getFragment() ) !== '' ) {
658 # Strip the fragment to avoid various odd effects
659 $this->mTitle = clone $t;
660 $this->mTitle->setFragment( '' );
661 } else {
662 $this->mTitle = $t;
667 * Accessor for the Title object
669 * @return Title object
671 function getTitle() {
672 return $this->mTitle;
676 * Accessor/mutator for the Title object
678 * @param $x Title object or null to just get the current one
679 * @return Title object
681 function Title( $x = null ) {
682 return wfSetVar( $this->mTitle, $x );
686 * Set the output type
688 * @param $ot Integer: new value
690 function setOutputType( $ot ) {
691 $this->mOutputType = $ot;
692 # Shortcut alias
693 $this->ot = array(
694 'html' => $ot == self::OT_HTML,
695 'wiki' => $ot == self::OT_WIKI,
696 'pre' => $ot == self::OT_PREPROCESS,
697 'plain' => $ot == self::OT_PLAIN,
702 * Accessor/mutator for the output type
704 * @param int|null $x New value or null to just get the current one
705 * @return Integer
707 function OutputType( $x = null ) {
708 return wfSetVar( $this->mOutputType, $x );
712 * Get the ParserOutput object
714 * @return ParserOutput object
716 function getOutput() {
717 return $this->mOutput;
721 * Get the ParserOptions object
723 * @return ParserOptions object
725 function getOptions() {
726 return $this->mOptions;
730 * Accessor/mutator for the ParserOptions object
732 * @param $x ParserOptions New value or null to just get the current one
733 * @return ParserOptions Current ParserOptions object
735 function Options( $x = null ) {
736 return wfSetVar( $this->mOptions, $x );
740 * @return int
742 function nextLinkID() {
743 return $this->mLinkID++;
747 * @param $id int
749 function setLinkID( $id ) {
750 $this->mLinkID = $id;
754 * Get a language object for use in parser functions such as {{FORMATNUM:}}
755 * @return Language
757 function getFunctionLang() {
758 return $this->getTargetLanguage();
762 * Get the target language for the content being parsed. This is usually the
763 * language that the content is in.
765 * @since 1.19
767 * @throws MWException
768 * @return Language|null
770 public function getTargetLanguage() {
771 $target = $this->mOptions->getTargetLanguage();
773 if ( $target !== null ) {
774 return $target;
775 } elseif ( $this->mOptions->getInterfaceMessage() ) {
776 return $this->mOptions->getUserLangObj();
777 } elseif ( is_null( $this->mTitle ) ) {
778 throw new MWException( __METHOD__ . ': $this->mTitle is null' );
781 return $this->mTitle->getPageLanguage();
785 * Get the language object for language conversion
787 function getConverterLanguage() {
788 return $this->getTargetLanguage();
792 * Get a User object either from $this->mUser, if set, or from the
793 * ParserOptions object otherwise
795 * @return User object
797 function getUser() {
798 if ( !is_null( $this->mUser ) ) {
799 return $this->mUser;
801 return $this->mOptions->getUser();
805 * Get a preprocessor object
807 * @return Preprocessor instance
809 function getPreprocessor() {
810 if ( !isset( $this->mPreprocessor ) ) {
811 $class = $this->mPreprocessorClass;
812 $this->mPreprocessor = new $class( $this );
814 return $this->mPreprocessor;
818 * Replaces all occurrences of HTML-style comments and the given tags
819 * in the text with a random marker and returns the next text. The output
820 * parameter $matches will be an associative array filled with data in
821 * the form:
823 * @code
824 * 'UNIQ-xxxxx' => array(
825 * 'element',
826 * 'tag content',
827 * array( 'param' => 'x' ),
828 * '<element param="x">tag content</element>' ) )
829 * @endcode
831 * @param array $elements list of element names. Comments are always extracted.
832 * @param string $text Source text string.
833 * @param array $matches Out parameter, Array: extracted tags
834 * @param $uniq_prefix string
835 * @return String: stripped text
837 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
838 static $n = 1;
839 $stripped = '';
840 $matches = array();
842 $taglist = implode( '|', $elements );
843 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
845 while ( $text != '' ) {
846 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
847 $stripped .= $p[0];
848 if ( count( $p ) < 5 ) {
849 break;
851 if ( count( $p ) > 5 ) {
852 # comment
853 $element = $p[4];
854 $attributes = '';
855 $close = '';
856 $inside = $p[5];
857 } else {
858 # tag
859 $element = $p[1];
860 $attributes = $p[2];
861 $close = $p[3];
862 $inside = $p[4];
865 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
866 $stripped .= $marker;
868 if ( $close === '/>' ) {
869 # Empty element tag, <tag />
870 $content = null;
871 $text = $inside;
872 $tail = null;
873 } else {
874 if ( $element === '!--' ) {
875 $end = '/(-->)/';
876 } else {
877 $end = "/(<\\/$element\\s*>)/i";
879 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
880 $content = $q[0];
881 if ( count( $q ) < 3 ) {
882 # No end tag -- let it run out to the end of the text.
883 $tail = '';
884 $text = '';
885 } else {
886 $tail = $q[1];
887 $text = $q[2];
891 $matches[$marker] = array( $element,
892 $content,
893 Sanitizer::decodeTagAttributes( $attributes ),
894 "<$element$attributes$close$content$tail" );
896 return $stripped;
900 * Get a list of strippable XML-like elements
902 * @return array
904 function getStripList() {
905 return $this->mStripList;
909 * Add an item to the strip state
910 * Returns the unique tag which must be inserted into the stripped text
911 * The tag will be replaced with the original text in unstrip()
913 * @param $text string
915 * @return string
917 function insertStripItem( $text ) {
918 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
919 $this->mMarkerIndex++;
920 $this->mStripState->addGeneral( $rnd, $text );
921 return $rnd;
925 * parse the wiki syntax used to render tables
927 * @private
928 * @return string
930 function doTableStuff( $text ) {
931 wfProfileIn( __METHOD__ );
933 $lines = StringUtils::explode( "\n", $text );
934 $out = '';
935 $td_history = array(); # Is currently a td tag open?
936 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
937 $tr_history = array(); # Is currently a tr tag open?
938 $tr_attributes = array(); # history of tr attributes
939 $has_opened_tr = array(); # Did this table open a <tr> element?
940 $indent_level = 0; # indent level of the table
942 foreach ( $lines as $outLine ) {
943 $line = trim( $outLine );
945 if ( $line === '' ) { # empty line, go to next line
946 $out .= $outLine . "\n";
947 continue;
950 $first_character = $line[0];
951 $matches = array();
953 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
954 # First check if we are starting a new table
955 $indent_level = strlen( $matches[1] );
957 $attributes = $this->mStripState->unstripBoth( $matches[2] );
958 $attributes = Sanitizer::fixTagAttributes( $attributes, 'table' );
960 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
961 array_push( $td_history, false );
962 array_push( $last_tag_history, '' );
963 array_push( $tr_history, false );
964 array_push( $tr_attributes, '' );
965 array_push( $has_opened_tr, false );
966 } elseif ( count( $td_history ) == 0 ) {
967 # Don't do any of the following
968 $out .= $outLine . "\n";
969 continue;
970 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
971 # We are ending a table
972 $line = '</table>' . substr( $line, 2 );
973 $last_tag = array_pop( $last_tag_history );
975 if ( !array_pop( $has_opened_tr ) ) {
976 $line = "<tr><td></td></tr>{$line}";
979 if ( array_pop( $tr_history ) ) {
980 $line = "</tr>{$line}";
983 if ( array_pop( $td_history ) ) {
984 $line = "</{$last_tag}>{$line}";
986 array_pop( $tr_attributes );
987 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
988 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
989 # Now we have a table row
990 $line = preg_replace( '#^\|-+#', '', $line );
992 # Whats after the tag is now only attributes
993 $attributes = $this->mStripState->unstripBoth( $line );
994 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
995 array_pop( $tr_attributes );
996 array_push( $tr_attributes, $attributes );
998 $line = '';
999 $last_tag = array_pop( $last_tag_history );
1000 array_pop( $has_opened_tr );
1001 array_push( $has_opened_tr, true );
1003 if ( array_pop( $tr_history ) ) {
1004 $line = '</tr>';
1007 if ( array_pop( $td_history ) ) {
1008 $line = "</{$last_tag}>{$line}";
1011 $outLine = $line;
1012 array_push( $tr_history, false );
1013 array_push( $td_history, false );
1014 array_push( $last_tag_history, '' );
1015 } elseif ( $first_character === '|' || $first_character === '!' || substr( $line, 0, 2 ) === '|+' ) {
1016 # This might be cell elements, td, th or captions
1017 if ( substr( $line, 0, 2 ) === '|+' ) {
1018 $first_character = '+';
1019 $line = substr( $line, 1 );
1022 $line = substr( $line, 1 );
1024 if ( $first_character === '!' ) {
1025 $line = str_replace( '!!', '||', $line );
1028 # Split up multiple cells on the same line.
1029 # FIXME : This can result in improper nesting of tags processed
1030 # by earlier parser steps, but should avoid splitting up eg
1031 # attribute values containing literal "||".
1032 $cells = StringUtils::explodeMarkup( '||', $line );
1034 $outLine = '';
1036 # Loop through each table cell
1037 foreach ( $cells as $cell ) {
1038 $previous = '';
1039 if ( $first_character !== '+' ) {
1040 $tr_after = array_pop( $tr_attributes );
1041 if ( !array_pop( $tr_history ) ) {
1042 $previous = "<tr{$tr_after}>\n";
1044 array_push( $tr_history, true );
1045 array_push( $tr_attributes, '' );
1046 array_pop( $has_opened_tr );
1047 array_push( $has_opened_tr, true );
1050 $last_tag = array_pop( $last_tag_history );
1052 if ( array_pop( $td_history ) ) {
1053 $previous = "</{$last_tag}>\n{$previous}";
1056 if ( $first_character === '|' ) {
1057 $last_tag = 'td';
1058 } elseif ( $first_character === '!' ) {
1059 $last_tag = 'th';
1060 } elseif ( $first_character === '+' ) {
1061 $last_tag = 'caption';
1062 } else {
1063 $last_tag = '';
1066 array_push( $last_tag_history, $last_tag );
1068 # A cell could contain both parameters and data
1069 $cell_data = explode( '|', $cell, 2 );
1071 # Bug 553: Note that a '|' inside an invalid link should not
1072 # be mistaken as delimiting cell parameters
1073 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1074 $cell = "{$previous}<{$last_tag}>{$cell}";
1075 } elseif ( count( $cell_data ) == 1 ) {
1076 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1077 } else {
1078 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
1079 $attributes = Sanitizer::fixTagAttributes( $attributes, $last_tag );
1080 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1083 $outLine .= $cell;
1084 array_push( $td_history, true );
1087 $out .= $outLine . "\n";
1090 # Closing open td, tr && table
1091 while ( count( $td_history ) > 0 ) {
1092 if ( array_pop( $td_history ) ) {
1093 $out .= "</td>\n";
1095 if ( array_pop( $tr_history ) ) {
1096 $out .= "</tr>\n";
1098 if ( !array_pop( $has_opened_tr ) ) {
1099 $out .= "<tr><td></td></tr>\n";
1102 $out .= "</table>\n";
1105 # Remove trailing line-ending (b/c)
1106 if ( substr( $out, -1 ) === "\n" ) {
1107 $out = substr( $out, 0, -1 );
1110 # special case: don't return empty table
1111 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1112 $out = '';
1115 wfProfileOut( __METHOD__ );
1117 return $out;
1121 * Helper function for parse() that transforms wiki markup into
1122 * HTML. Only called for $mOutputType == self::OT_HTML.
1124 * @private
1126 * @param $text string
1127 * @param $isMain bool
1128 * @param $frame bool
1130 * @return string
1132 function internalParse( $text, $isMain = true, $frame = false ) {
1133 wfProfileIn( __METHOD__ );
1135 $origText = $text;
1137 # Hook to suspend the parser in this state
1138 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
1139 wfProfileOut( __METHOD__ );
1140 return $text;
1143 # if $frame is provided, then use $frame for replacing any variables
1144 if ( $frame ) {
1145 # use frame depth to infer how include/noinclude tags should be handled
1146 # depth=0 means this is the top-level document; otherwise it's an included document
1147 if ( !$frame->depth ) {
1148 $flag = 0;
1149 } else {
1150 $flag = Parser::PTD_FOR_INCLUSION;
1152 $dom = $this->preprocessToDom( $text, $flag );
1153 $text = $frame->expand( $dom );
1154 } else {
1155 # if $frame is not provided, then use old-style replaceVariables
1156 $text = $this->replaceVariables( $text );
1159 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) );
1160 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
1161 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1163 # Tables need to come after variable replacement for things to work
1164 # properly; putting them before other transformations should keep
1165 # exciting things like link expansions from showing up in surprising
1166 # places.
1167 $text = $this->doTableStuff( $text );
1169 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1171 $text = $this->doDoubleUnderscore( $text );
1173 $text = $this->doHeadings( $text );
1174 $text = $this->replaceInternalLinks( $text );
1175 $text = $this->doAllQuotes( $text );
1176 $text = $this->replaceExternalLinks( $text );
1178 # replaceInternalLinks may sometimes leave behind
1179 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1180 $text = str_replace( $this->mUniqPrefix . 'NOPARSE', '', $text );
1182 $text = $this->doMagicLinks( $text );
1183 $text = $this->formatHeadings( $text, $origText, $isMain );
1185 wfProfileOut( __METHOD__ );
1186 return $text;
1190 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1191 * magic external links.
1193 * DML
1194 * @private
1196 * @param $text string
1198 * @return string
1200 function doMagicLinks( $text ) {
1201 wfProfileIn( __METHOD__ );
1202 $prots = wfUrlProtocolsWithoutProtRel();
1203 $urlChar = self::EXT_LINK_URL_CLASS;
1204 $text = preg_replace_callback(
1205 '!(?: # Start cases
1206 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1207 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1208 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1209 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1210 ISBN\s+(\b # m[5]: ISBN, capture number
1211 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1212 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1213 [0-9Xx] # check digit
1215 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1216 wfProfileOut( __METHOD__ );
1217 return $text;
1221 * @throws MWException
1222 * @param $m array
1223 * @return HTML|string
1225 function magicLinkCallback( $m ) {
1226 if ( isset( $m[1] ) && $m[1] !== '' ) {
1227 # Skip anchor
1228 return $m[0];
1229 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1230 # Skip HTML element
1231 return $m[0];
1232 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1233 # Free external link
1234 return $this->makeFreeExternalLink( $m[0] );
1235 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1236 # RFC or PMID
1237 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1238 $keyword = 'RFC';
1239 $urlmsg = 'rfcurl';
1240 $CssClass = 'mw-magiclink-rfc';
1241 $id = $m[4];
1242 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1243 $keyword = 'PMID';
1244 $urlmsg = 'pubmedurl';
1245 $CssClass = 'mw-magiclink-pmid';
1246 $id = $m[4];
1247 } else {
1248 throw new MWException( __METHOD__ . ': unrecognised match type "' .
1249 substr( $m[0], 0, 20 ) . '"' );
1251 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1252 return Linker::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1253 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1254 # ISBN
1255 $isbn = $m[5];
1256 $num = strtr( $isbn, array(
1257 '-' => '',
1258 ' ' => '',
1259 'x' => 'X',
1261 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1262 return '<a href="' .
1263 htmlspecialchars( $titleObj->getLocalURL() ) .
1264 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1265 } else {
1266 return $m[0];
1271 * Make a free external link, given a user-supplied URL
1273 * @param $url string
1275 * @return string HTML
1276 * @private
1278 function makeFreeExternalLink( $url ) {
1279 wfProfileIn( __METHOD__ );
1281 $trail = '';
1283 # The characters '<' and '>' (which were escaped by
1284 # removeHTMLtags()) should not be included in
1285 # URLs, per RFC 2396.
1286 $m2 = array();
1287 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1288 $trail = substr( $url, $m2[0][1] ) . $trail;
1289 $url = substr( $url, 0, $m2[0][1] );
1292 # Move trailing punctuation to $trail
1293 $sep = ',;\.:!?';
1294 # If there is no left bracket, then consider right brackets fair game too
1295 if ( strpos( $url, '(' ) === false ) {
1296 $sep .= ')';
1299 $numSepChars = strspn( strrev( $url ), $sep );
1300 if ( $numSepChars ) {
1301 $trail = substr( $url, -$numSepChars ) . $trail;
1302 $url = substr( $url, 0, -$numSepChars );
1305 $url = Sanitizer::cleanUrl( $url );
1307 # Is this an external image?
1308 $text = $this->maybeMakeExternalImage( $url );
1309 if ( $text === false ) {
1310 # Not an image, make a link
1311 $text = Linker::makeExternalLink( $url,
1312 $this->getConverterLanguage()->markNoConversion( $url, true ),
1313 true, 'free',
1314 $this->getExternalLinkAttribs( $url ) );
1315 # Register it in the output object...
1316 # Replace unnecessary URL escape codes with their equivalent characters
1317 $pasteurized = self::replaceUnusualEscapes( $url );
1318 $this->mOutput->addExternalLink( $pasteurized );
1320 wfProfileOut( __METHOD__ );
1321 return $text . $trail;
1325 * Parse headers and return html
1327 * @private
1329 * @param $text string
1331 * @return string
1333 function doHeadings( $text ) {
1334 wfProfileIn( __METHOD__ );
1335 for ( $i = 6; $i >= 1; --$i ) {
1336 $h = str_repeat( '=', $i );
1337 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1339 wfProfileOut( __METHOD__ );
1340 return $text;
1344 * Replace single quotes with HTML markup
1345 * @private
1347 * @param $text string
1349 * @return string the altered text
1351 function doAllQuotes( $text ) {
1352 wfProfileIn( __METHOD__ );
1353 $outtext = '';
1354 $lines = StringUtils::explode( "\n", $text );
1355 foreach ( $lines as $line ) {
1356 $outtext .= $this->doQuotes( $line ) . "\n";
1358 $outtext = substr( $outtext, 0, -1 );
1359 wfProfileOut( __METHOD__ );
1360 return $outtext;
1364 * Helper function for doAllQuotes()
1366 * @param $text string
1368 * @return string
1370 public function doQuotes( $text ) {
1371 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1372 if ( count( $arr ) == 1 ) {
1373 return $text;
1374 } else {
1375 # First, do some preliminary work. This may shift some apostrophes from
1376 # being mark-up to being text. It also counts the number of occurrences
1377 # of bold and italics mark-ups.
1378 $numbold = 0;
1379 $numitalics = 0;
1380 for ( $i = 0; $i < count( $arr ); $i++ ) {
1381 if ( ( $i % 2 ) == 1 ) {
1382 # If there are ever four apostrophes, assume the first is supposed to
1383 # be text, and the remaining three constitute mark-up for bold text.
1384 if ( strlen( $arr[$i] ) == 4 ) {
1385 $arr[$i - 1] .= "'";
1386 $arr[$i] = "'''";
1387 } elseif ( strlen( $arr[$i] ) > 5 ) {
1388 # If there are more than 5 apostrophes in a row, assume they're all
1389 # text except for the last 5.
1390 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1391 $arr[$i] = "'''''";
1393 # Count the number of occurrences of bold and italics mark-ups.
1394 # We are not counting sequences of five apostrophes.
1395 if ( strlen( $arr[$i] ) == 2 ) {
1396 $numitalics++;
1397 } elseif ( strlen( $arr[$i] ) == 3 ) {
1398 $numbold++;
1399 } elseif ( strlen( $arr[$i] ) == 5 ) {
1400 $numitalics++;
1401 $numbold++;
1406 # If there is an odd number of both bold and italics, it is likely
1407 # that one of the bold ones was meant to be an apostrophe followed
1408 # by italics. Which one we cannot know for certain, but it is more
1409 # likely to be one that has a single-letter word before it.
1410 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1411 $i = 0;
1412 $firstsingleletterword = -1;
1413 $firstmultiletterword = -1;
1414 $firstspace = -1;
1415 foreach ( $arr as $r ) {
1416 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1417 $x1 = substr( $arr[$i - 1], -1 );
1418 $x2 = substr( $arr[$i - 1], -2, 1 );
1419 if ( $x1 === ' ' ) {
1420 if ( $firstspace == -1 ) {
1421 $firstspace = $i;
1423 } elseif ( $x2 === ' ' ) {
1424 if ( $firstsingleletterword == -1 ) {
1425 $firstsingleletterword = $i;
1427 } else {
1428 if ( $firstmultiletterword == -1 ) {
1429 $firstmultiletterword = $i;
1433 $i++;
1436 # If there is a single-letter word, use it!
1437 if ( $firstsingleletterword > -1 ) {
1438 $arr[$firstsingleletterword] = "''";
1439 $arr[$firstsingleletterword - 1] .= "'";
1440 } elseif ( $firstmultiletterword > -1 ) {
1441 # If not, but there's a multi-letter word, use that one.
1442 $arr[$firstmultiletterword] = "''";
1443 $arr[$firstmultiletterword - 1] .= "'";
1444 } elseif ( $firstspace > -1 ) {
1445 # ... otherwise use the first one that has neither.
1446 # (notice that it is possible for all three to be -1 if, for example,
1447 # there is only one pentuple-apostrophe in the line)
1448 $arr[$firstspace] = "''";
1449 $arr[$firstspace - 1] .= "'";
1453 # Now let's actually convert our apostrophic mush to HTML!
1454 $output = '';
1455 $buffer = '';
1456 $state = '';
1457 $i = 0;
1458 foreach ( $arr as $r ) {
1459 if ( ( $i % 2 ) == 0 ) {
1460 if ( $state === 'both' ) {
1461 $buffer .= $r;
1462 } else {
1463 $output .= $r;
1465 } else {
1466 if ( strlen( $r ) == 2 ) {
1467 if ( $state === 'i' ) {
1468 $output .= '</i>';
1469 $state = '';
1470 } elseif ( $state === 'bi' ) {
1471 $output .= '</i>';
1472 $state = 'b';
1473 } elseif ( $state === 'ib' ) {
1474 $output .= '</b></i><b>';
1475 $state = 'b';
1476 } elseif ( $state === 'both' ) {
1477 $output .= '<b><i>' . $buffer . '</i>';
1478 $state = 'b';
1479 } else { # $state can be 'b' or ''
1480 $output .= '<i>';
1481 $state .= 'i';
1483 } elseif ( strlen( $r ) == 3 ) {
1484 if ( $state === 'b' ) {
1485 $output .= '</b>';
1486 $state = '';
1487 } elseif ( $state === 'bi' ) {
1488 $output .= '</i></b><i>';
1489 $state = 'i';
1490 } elseif ( $state === 'ib' ) {
1491 $output .= '</b>';
1492 $state = 'i';
1493 } elseif ( $state === 'both' ) {
1494 $output .= '<i><b>' . $buffer . '</b>';
1495 $state = 'i';
1496 } else { # $state can be 'i' or ''
1497 $output .= '<b>';
1498 $state .= 'b';
1500 } elseif ( strlen( $r ) == 5 ) {
1501 if ( $state === 'b' ) {
1502 $output .= '</b><i>';
1503 $state = 'i';
1504 } elseif ( $state === 'i' ) {
1505 $output .= '</i><b>';
1506 $state = 'b';
1507 } elseif ( $state === 'bi' ) {
1508 $output .= '</i></b>';
1509 $state = '';
1510 } elseif ( $state === 'ib' ) {
1511 $output .= '</b></i>';
1512 $state = '';
1513 } elseif ( $state === 'both' ) {
1514 $output .= '<i><b>' . $buffer . '</b></i>';
1515 $state = '';
1516 } else { # ($state == '')
1517 $buffer = '';
1518 $state = 'both';
1522 $i++;
1524 # Now close all remaining tags. Notice that the order is important.
1525 if ( $state === 'b' || $state === 'ib' ) {
1526 $output .= '</b>';
1528 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1529 $output .= '</i>';
1531 if ( $state === 'bi' ) {
1532 $output .= '</b>';
1534 # There might be lonely ''''', so make sure we have a buffer
1535 if ( $state === 'both' && $buffer ) {
1536 $output .= '<b><i>' . $buffer . '</i></b>';
1538 return $output;
1543 * Replace external links (REL)
1545 * Note: this is all very hackish and the order of execution matters a lot.
1546 * Make sure to run tests/parserTests.php if you change this code.
1548 * @private
1550 * @param $text string
1552 * @throws MWException
1553 * @return string
1555 function replaceExternalLinks( $text ) {
1556 wfProfileIn( __METHOD__ );
1558 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1559 if ( $bits === false ) {
1560 wfProfileOut( __METHOD__ );
1561 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1563 $s = array_shift( $bits );
1565 $i = 0;
1566 while ( $i < count( $bits ) ) {
1567 $url = $bits[$i++];
1568 $i++; // protocol
1569 $text = $bits[$i++];
1570 $trail = $bits[$i++];
1572 # The characters '<' and '>' (which were escaped by
1573 # removeHTMLtags()) should not be included in
1574 # URLs, per RFC 2396.
1575 $m2 = array();
1576 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1577 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1578 $url = substr( $url, 0, $m2[0][1] );
1581 # If the link text is an image URL, replace it with an <img> tag
1582 # This happened by accident in the original parser, but some people used it extensively
1583 $img = $this->maybeMakeExternalImage( $text );
1584 if ( $img !== false ) {
1585 $text = $img;
1588 $dtrail = '';
1590 # Set linktype for CSS - if URL==text, link is essentially free
1591 $linktype = ( $text === $url ) ? 'free' : 'text';
1593 # No link text, e.g. [http://domain.tld/some.link]
1594 if ( $text == '' ) {
1595 # Autonumber
1596 $langObj = $this->getTargetLanguage();
1597 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1598 $linktype = 'autonumber';
1599 } else {
1600 # Have link text, e.g. [http://domain.tld/some.link text]s
1601 # Check for trail
1602 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1605 $text = $this->getConverterLanguage()->markNoConversion( $text );
1607 $url = Sanitizer::cleanUrl( $url );
1609 # Use the encoded URL
1610 # This means that users can paste URLs directly into the text
1611 # Funny characters like ö aren't valid in URLs anyway
1612 # This was changed in August 2004
1613 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1614 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1616 # Register link in the output object.
1617 # Replace unnecessary URL escape codes with the referenced character
1618 # This prevents spammers from hiding links from the filters
1619 $pasteurized = self::replaceUnusualEscapes( $url );
1620 $this->mOutput->addExternalLink( $pasteurized );
1623 wfProfileOut( __METHOD__ );
1624 return $s;
1627 * Get the rel attribute for a particular external link.
1629 * @since 1.21
1630 * @param string|bool $url optional URL, to extract the domain from for rel =>
1631 * nofollow if appropriate
1632 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1633 * @return string|null rel attribute for $url
1635 public static function getExternalLinkRel( $url = false, $title = null ) {
1636 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1637 $ns = $title ? $title->getNamespace() : false;
1638 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1639 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1641 return 'nofollow';
1643 return null;
1646 * Get an associative array of additional HTML attributes appropriate for a
1647 * particular external link. This currently may include rel => nofollow
1648 * (depending on configuration, namespace, and the URL's domain) and/or a
1649 * target attribute (depending on configuration).
1651 * @param string|bool $url optional URL, to extract the domain from for rel =>
1652 * nofollow if appropriate
1653 * @return Array associative array of HTML attributes
1655 function getExternalLinkAttribs( $url = false ) {
1656 $attribs = array();
1657 $attribs['rel'] = self::getExternalLinkRel( $url, $this->mTitle );
1659 if ( $this->mOptions->getExternalLinkTarget() ) {
1660 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1662 return $attribs;
1666 * Replace unusual URL escape codes with their equivalent characters
1668 * @param $url String
1669 * @return String
1671 * @todo This can merge genuinely required bits in the path or query string,
1672 * breaking legit URLs. A proper fix would treat the various parts of
1673 * the URL differently; as a workaround, just use the output for
1674 * statistical records, not for actual linking/output.
1676 static function replaceUnusualEscapes( $url ) {
1677 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1678 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1682 * Callback function used in replaceUnusualEscapes().
1683 * Replaces unusual URL escape codes with their equivalent character
1685 * @param $matches array
1687 * @return string
1689 private static function replaceUnusualEscapesCallback( $matches ) {
1690 $char = urldecode( $matches[0] );
1691 $ord = ord( $char );
1692 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1693 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1694 # No, shouldn't be escaped
1695 return $char;
1696 } else {
1697 # Yes, leave it escaped
1698 return $matches[0];
1703 * make an image if it's allowed, either through the global
1704 * option, through the exception, or through the on-wiki whitelist
1705 * @private
1707 * $param $url string
1709 * @return string
1711 function maybeMakeExternalImage( $url ) {
1712 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1713 $imagesexception = !empty( $imagesfrom );
1714 $text = false;
1715 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1716 if ( $imagesexception && is_array( $imagesfrom ) ) {
1717 $imagematch = false;
1718 foreach ( $imagesfrom as $match ) {
1719 if ( strpos( $url, $match ) === 0 ) {
1720 $imagematch = true;
1721 break;
1724 } elseif ( $imagesexception ) {
1725 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1726 } else {
1727 $imagematch = false;
1729 if ( $this->mOptions->getAllowExternalImages()
1730 || ( $imagesexception && $imagematch ) ) {
1731 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1732 # Image found
1733 $text = Linker::makeExternalImage( $url );
1736 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1737 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1738 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1739 foreach ( $whitelist as $entry ) {
1740 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1741 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1742 continue;
1744 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1745 # Image matches a whitelist entry
1746 $text = Linker::makeExternalImage( $url );
1747 break;
1751 return $text;
1755 * Process [[ ]] wikilinks
1757 * @param $s string
1759 * @return String: processed text
1761 * @private
1763 function replaceInternalLinks( $s ) {
1764 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1765 return $s;
1769 * Process [[ ]] wikilinks (RIL)
1770 * @param $s
1771 * @throws MWException
1772 * @return LinkHolderArray
1774 * @private
1776 function replaceInternalLinks2( &$s ) {
1777 wfProfileIn( __METHOD__ );
1779 wfProfileIn( __METHOD__ . '-setup' );
1780 static $tc = false, $e1, $e1_img;
1781 # the % is needed to support urlencoded titles as well
1782 if ( !$tc ) {
1783 $tc = Title::legalChars() . '#%';
1784 # Match a link having the form [[namespace:link|alternate]]trail
1785 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1786 # Match cases where there is no "]]", which might still be images
1787 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1790 $holders = new LinkHolderArray( $this );
1792 # split the entire text string on occurrences of [[
1793 $a = StringUtils::explode( '[[', ' ' . $s );
1794 # get the first element (all text up to first [[), and remove the space we added
1795 $s = $a->current();
1796 $a->next();
1797 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1798 $s = substr( $s, 1 );
1800 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1801 $e2 = null;
1802 if ( $useLinkPrefixExtension ) {
1803 # Match the end of a line for a word that's not followed by whitespace,
1804 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1805 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1808 if ( is_null( $this->mTitle ) ) {
1809 wfProfileOut( __METHOD__ . '-setup' );
1810 wfProfileOut( __METHOD__ );
1811 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
1813 $nottalk = !$this->mTitle->isTalkPage();
1815 if ( $useLinkPrefixExtension ) {
1816 $m = array();
1817 if ( preg_match( $e2, $s, $m ) ) {
1818 $first_prefix = $m[2];
1819 } else {
1820 $first_prefix = false;
1822 } else {
1823 $prefix = '';
1826 $useSubpages = $this->areSubpagesAllowed();
1827 wfProfileOut( __METHOD__ . '-setup' );
1829 # Loop for each link
1830 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1831 # Check for excessive memory usage
1832 if ( $holders->isBig() ) {
1833 # Too big
1834 # Do the existence check, replace the link holders and clear the array
1835 $holders->replace( $s );
1836 $holders->clear();
1839 if ( $useLinkPrefixExtension ) {
1840 wfProfileIn( __METHOD__ . '-prefixhandling' );
1841 if ( preg_match( $e2, $s, $m ) ) {
1842 $prefix = $m[2];
1843 $s = $m[1];
1844 } else {
1845 $prefix = '';
1847 # first link
1848 if ( $first_prefix ) {
1849 $prefix = $first_prefix;
1850 $first_prefix = false;
1852 wfProfileOut( __METHOD__ . '-prefixhandling' );
1855 $might_be_img = false;
1857 wfProfileIn( __METHOD__ . "-e1" );
1858 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1859 $text = $m[2];
1860 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1861 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1862 # the real problem is with the $e1 regex
1863 # See bug 1300.
1865 # Still some problems for cases where the ] is meant to be outside punctuation,
1866 # and no image is in sight. See bug 2095.
1868 if ( $text !== '' &&
1869 substr( $m[3], 0, 1 ) === ']' &&
1870 strpos( $text, '[' ) !== false
1873 $text .= ']'; # so that replaceExternalLinks($text) works later
1874 $m[3] = substr( $m[3], 1 );
1876 # fix up urlencoded title texts
1877 if ( strpos( $m[1], '%' ) !== false ) {
1878 # Should anchors '#' also be rejected?
1879 $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
1881 $trail = $m[3];
1882 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1883 $might_be_img = true;
1884 $text = $m[2];
1885 if ( strpos( $m[1], '%' ) !== false ) {
1886 $m[1] = rawurldecode( $m[1] );
1888 $trail = "";
1889 } else { # Invalid form; output directly
1890 $s .= $prefix . '[[' . $line;
1891 wfProfileOut( __METHOD__ . "-e1" );
1892 continue;
1894 wfProfileOut( __METHOD__ . "-e1" );
1895 wfProfileIn( __METHOD__ . "-misc" );
1897 # Don't allow internal links to pages containing
1898 # PROTO: where PROTO is a valid URL protocol; these
1899 # should be external links.
1900 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
1901 $s .= $prefix . '[[' . $line;
1902 wfProfileOut( __METHOD__ . "-misc" );
1903 continue;
1906 # Make subpage if necessary
1907 if ( $useSubpages ) {
1908 $link = $this->maybeDoSubpageLink( $m[1], $text );
1909 } else {
1910 $link = $m[1];
1913 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1914 if ( !$noforce ) {
1915 # Strip off leading ':'
1916 $link = substr( $link, 1 );
1919 wfProfileOut( __METHOD__ . "-misc" );
1920 wfProfileIn( __METHOD__ . "-title" );
1921 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
1922 if ( $nt === null ) {
1923 $s .= $prefix . '[[' . $line;
1924 wfProfileOut( __METHOD__ . "-title" );
1925 continue;
1928 $ns = $nt->getNamespace();
1929 $iw = $nt->getInterWiki();
1930 wfProfileOut( __METHOD__ . "-title" );
1932 if ( $might_be_img ) { # if this is actually an invalid link
1933 wfProfileIn( __METHOD__ . "-might_be_img" );
1934 if ( $ns == NS_FILE && $noforce ) { # but might be an image
1935 $found = false;
1936 while ( true ) {
1937 # look at the next 'line' to see if we can close it there
1938 $a->next();
1939 $next_line = $a->current();
1940 if ( $next_line === false || $next_line === null ) {
1941 break;
1943 $m = explode( ']]', $next_line, 3 );
1944 if ( count( $m ) == 3 ) {
1945 # the first ]] closes the inner link, the second the image
1946 $found = true;
1947 $text .= "[[{$m[0]}]]{$m[1]}";
1948 $trail = $m[2];
1949 break;
1950 } elseif ( count( $m ) == 2 ) {
1951 # if there's exactly one ]] that's fine, we'll keep looking
1952 $text .= "[[{$m[0]}]]{$m[1]}";
1953 } else {
1954 # if $next_line is invalid too, we need look no further
1955 $text .= '[[' . $next_line;
1956 break;
1959 if ( !$found ) {
1960 # we couldn't find the end of this imageLink, so output it raw
1961 # but don't ignore what might be perfectly normal links in the text we've examined
1962 $holders->merge( $this->replaceInternalLinks2( $text ) );
1963 $s .= "{$prefix}[[$link|$text";
1964 # note: no $trail, because without an end, there *is* no trail
1965 wfProfileOut( __METHOD__ . "-might_be_img" );
1966 continue;
1968 } else { # it's not an image, so output it raw
1969 $s .= "{$prefix}[[$link|$text";
1970 # note: no $trail, because without an end, there *is* no trail
1971 wfProfileOut( __METHOD__ . "-might_be_img" );
1972 continue;
1974 wfProfileOut( __METHOD__ . "-might_be_img" );
1977 $wasblank = ( $text == '' );
1978 if ( $wasblank ) {
1979 $text = $link;
1980 } else {
1981 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1982 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1983 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1984 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1985 $text = $this->doQuotes( $text );
1988 # Link not escaped by : , create the various objects
1989 if ( $noforce ) {
1990 # Interwikis
1991 wfProfileIn( __METHOD__ . "-interwiki" );
1992 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) {
1993 // XXX: the above check prevents links to sites with identifiers that are not language codes
1995 # Bug 24502: filter duplicates
1996 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
1997 $this->mLangLinkLanguages[$iw] = true;
1998 $this->mOutput->addLanguageLink( $nt->getFullText() );
2001 $s = rtrim( $s . $prefix );
2002 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2003 wfProfileOut( __METHOD__ . "-interwiki" );
2004 continue;
2006 wfProfileOut( __METHOD__ . "-interwiki" );
2008 if ( $ns == NS_FILE ) {
2009 wfProfileIn( __METHOD__ . "-image" );
2010 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2011 if ( $wasblank ) {
2012 # if no parameters were passed, $text
2013 # becomes something like "File:Foo.png",
2014 # which we don't want to pass on to the
2015 # image generator
2016 $text = '';
2017 } else {
2018 # recursively parse links inside the image caption
2019 # actually, this will parse them in any other parameters, too,
2020 # but it might be hard to fix that, and it doesn't matter ATM
2021 $text = $this->replaceExternalLinks( $text );
2022 $holders->merge( $this->replaceInternalLinks2( $text ) );
2024 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2025 $s .= $prefix . $this->armorLinks(
2026 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2027 } else {
2028 $s .= $prefix . $trail;
2030 wfProfileOut( __METHOD__ . "-image" );
2031 continue;
2034 if ( $ns == NS_CATEGORY ) {
2035 wfProfileIn( __METHOD__ . "-category" );
2036 $s = rtrim( $s . "\n" ); # bug 87
2038 if ( $wasblank ) {
2039 $sortkey = $this->getDefaultSort();
2040 } else {
2041 $sortkey = $text;
2043 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2044 $sortkey = str_replace( "\n", '', $sortkey );
2045 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2046 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2049 * Strip the whitespace Category links produce, see bug 87
2050 * @todo We might want to use trim($tmp, "\n") here.
2052 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2054 wfProfileOut( __METHOD__ . "-category" );
2055 continue;
2059 # Self-link checking
2060 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
2061 if ( $nt->equals( $this->mTitle ) || ( !$nt->isKnown() && in_array(
2062 $this->mTitle->getPrefixedText(),
2063 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2064 true
2065 ) ) ) {
2066 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2067 continue;
2071 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2072 # @todo FIXME: Should do batch file existence checks, see comment below
2073 if ( $ns == NS_MEDIA ) {
2074 wfProfileIn( __METHOD__ . "-media" );
2075 # Give extensions a chance to select the file revision for us
2076 $options = array();
2077 $descQuery = false;
2078 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2079 array( $this, $nt, &$options, &$descQuery ) );
2080 # Fetch and register the file (file title may be different via hooks)
2081 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2082 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2083 $s .= $prefix . $this->armorLinks(
2084 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2085 wfProfileOut( __METHOD__ . "-media" );
2086 continue;
2089 wfProfileIn( __METHOD__ . "-always_known" );
2090 # Some titles, such as valid special pages or files in foreign repos, should
2091 # be shown as bluelinks even though they're not included in the page table
2093 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2094 # batch file existence checks for NS_FILE and NS_MEDIA
2095 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2096 $this->mOutput->addLink( $nt );
2097 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2098 } else {
2099 # Links will be added to the output link list after checking
2100 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2102 wfProfileOut( __METHOD__ . "-always_known" );
2104 wfProfileOut( __METHOD__ );
2105 return $holders;
2109 * Render a forced-blue link inline; protect against double expansion of
2110 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2111 * Since this little disaster has to split off the trail text to avoid
2112 * breaking URLs in the following text without breaking trails on the
2113 * wiki links, it's been made into a horrible function.
2115 * @param $nt Title
2116 * @param $text String
2117 * @param array $query or String
2118 * @param $trail String
2119 * @param $prefix String
2120 * @return String: HTML-wikitext mix oh yuck
2122 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2123 list( $inside, $trail ) = Linker::splitTrail( $trail );
2125 if ( is_string( $query ) ) {
2126 $query = wfCgiToArray( $query );
2128 if ( $text == '' ) {
2129 $text = htmlspecialchars( $nt->getPrefixedText() );
2132 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2134 return $this->armorLinks( $link ) . $trail;
2138 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2139 * going to go through further parsing steps before inline URL expansion.
2141 * Not needed quite as much as it used to be since free links are a bit
2142 * more sensible these days. But bracketed links are still an issue.
2144 * @param string $text more-or-less HTML
2145 * @return String: less-or-more HTML with NOPARSE bits
2147 function armorLinks( $text ) {
2148 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2149 "{$this->mUniqPrefix}NOPARSE$1", $text );
2153 * Return true if subpage links should be expanded on this page.
2154 * @return Boolean
2156 function areSubpagesAllowed() {
2157 # Some namespaces don't allow subpages
2158 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2162 * Handle link to subpage if necessary
2164 * @param string $target the source of the link
2165 * @param &$text String: the link text, modified as necessary
2166 * @return string the full name of the link
2167 * @private
2169 function maybeDoSubpageLink( $target, &$text ) {
2170 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2173 /**#@+
2174 * Used by doBlockLevels()
2175 * @private
2177 * @return string
2179 function closeParagraph() {
2180 $result = '';
2181 if ( $this->mLastSection != '' ) {
2182 $result = '</' . $this->mLastSection . ">\n";
2184 $this->mInPre = false;
2185 $this->mLastSection = '';
2186 return $result;
2190 * getCommon() returns the length of the longest common substring
2191 * of both arguments, starting at the beginning of both.
2192 * @private
2194 * @param $st1 string
2195 * @param $st2 string
2197 * @return int
2199 function getCommon( $st1, $st2 ) {
2200 $fl = strlen( $st1 );
2201 $shorter = strlen( $st2 );
2202 if ( $fl < $shorter ) {
2203 $shorter = $fl;
2206 for ( $i = 0; $i < $shorter; ++$i ) {
2207 if ( $st1[$i] != $st2[$i] ) {
2208 break;
2211 return $i;
2215 * These next three functions open, continue, and close the list
2216 * element appropriate to the prefix character passed into them.
2217 * @private
2219 * @param $char string
2221 * @return string
2223 function openList( $char ) {
2224 $result = $this->closeParagraph();
2226 if ( '*' === $char ) {
2227 $result .= '<ul><li>';
2228 } elseif ( '#' === $char ) {
2229 $result .= '<ol><li>';
2230 } elseif ( ':' === $char ) {
2231 $result .= '<dl><dd>';
2232 } elseif ( ';' === $char ) {
2233 $result .= '<dl><dt>';
2234 $this->mDTopen = true;
2235 } else {
2236 $result = '<!-- ERR 1 -->';
2239 return $result;
2243 * TODO: document
2244 * @param $char String
2245 * @private
2247 * @return string
2249 function nextItem( $char ) {
2250 if ( '*' === $char || '#' === $char ) {
2251 return '</li><li>';
2252 } elseif ( ':' === $char || ';' === $char ) {
2253 $close = '</dd>';
2254 if ( $this->mDTopen ) {
2255 $close = '</dt>';
2257 if ( ';' === $char ) {
2258 $this->mDTopen = true;
2259 return $close . '<dt>';
2260 } else {
2261 $this->mDTopen = false;
2262 return $close . '<dd>';
2265 return '<!-- ERR 2 -->';
2269 * TODO: document
2270 * @param $char String
2271 * @private
2273 * @return string
2275 function closeList( $char ) {
2276 if ( '*' === $char ) {
2277 $text = '</li></ul>';
2278 } elseif ( '#' === $char ) {
2279 $text = '</li></ol>';
2280 } elseif ( ':' === $char ) {
2281 if ( $this->mDTopen ) {
2282 $this->mDTopen = false;
2283 $text = '</dt></dl>';
2284 } else {
2285 $text = '</dd></dl>';
2287 } else {
2288 return '<!-- ERR 3 -->';
2290 return $text . "\n";
2292 /**#@-*/
2295 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2297 * @param $text String
2298 * @param $linestart Boolean: whether or not this is at the start of a line.
2299 * @private
2300 * @return string the lists rendered as HTML
2302 function doBlockLevels( $text, $linestart ) {
2303 wfProfileIn( __METHOD__ );
2305 # Parsing through the text line by line. The main thing
2306 # happening here is handling of block-level elements p, pre,
2307 # and making lists from lines starting with * # : etc.
2309 $textLines = StringUtils::explode( "\n", $text );
2311 $lastPrefix = $output = '';
2312 $this->mDTopen = $inBlockElem = false;
2313 $prefixLength = 0;
2314 $paragraphStack = false;
2316 foreach ( $textLines as $oLine ) {
2317 # Fix up $linestart
2318 if ( !$linestart ) {
2319 $output .= $oLine;
2320 $linestart = true;
2321 continue;
2323 # * = ul
2324 # # = ol
2325 # ; = dt
2326 # : = dd
2328 $lastPrefixLength = strlen( $lastPrefix );
2329 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2330 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2331 # If not in a <pre> element, scan for and figure out what prefixes are there.
2332 if ( !$this->mInPre ) {
2333 # Multiple prefixes may abut each other for nested lists.
2334 $prefixLength = strspn( $oLine, '*#:;' );
2335 $prefix = substr( $oLine, 0, $prefixLength );
2337 # eh?
2338 # ; and : are both from definition-lists, so they're equivalent
2339 # for the purposes of determining whether or not we need to open/close
2340 # elements.
2341 $prefix2 = str_replace( ';', ':', $prefix );
2342 $t = substr( $oLine, $prefixLength );
2343 $this->mInPre = (bool)$preOpenMatch;
2344 } else {
2345 # Don't interpret any other prefixes in preformatted text
2346 $prefixLength = 0;
2347 $prefix = $prefix2 = '';
2348 $t = $oLine;
2351 # List generation
2352 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2353 # Same as the last item, so no need to deal with nesting or opening stuff
2354 $output .= $this->nextItem( substr( $prefix, -1 ) );
2355 $paragraphStack = false;
2357 if ( substr( $prefix, -1 ) === ';' ) {
2358 # The one nasty exception: definition lists work like this:
2359 # ; title : definition text
2360 # So we check for : in the remainder text to split up the
2361 # title and definition, without b0rking links.
2362 $term = $t2 = '';
2363 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2364 $t = $t2;
2365 $output .= $term . $this->nextItem( ':' );
2368 } elseif ( $prefixLength || $lastPrefixLength ) {
2369 # We need to open or close prefixes, or both.
2371 # Either open or close a level...
2372 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2373 $paragraphStack = false;
2375 # Close all the prefixes which aren't shared.
2376 while ( $commonPrefixLength < $lastPrefixLength ) {
2377 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2378 --$lastPrefixLength;
2381 # Continue the current prefix if appropriate.
2382 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2383 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2386 # Open prefixes where appropriate.
2387 while ( $prefixLength > $commonPrefixLength ) {
2388 $char = substr( $prefix, $commonPrefixLength, 1 );
2389 $output .= $this->openList( $char );
2391 if ( ';' === $char ) {
2392 # @todo FIXME: This is dupe of code above
2393 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2394 $t = $t2;
2395 $output .= $term . $this->nextItem( ':' );
2398 ++$commonPrefixLength;
2400 $lastPrefix = $prefix2;
2403 # If we have no prefixes, go to paragraph mode.
2404 if ( 0 == $prefixLength ) {
2405 wfProfileIn( __METHOD__ . "-paragraph" );
2406 # No prefix (not in list)--go to paragraph mode
2407 # XXX: use a stack for nestable elements like span, table and div
2408 $openmatch = preg_match( '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2409 $closematch = preg_match(
2410 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2411 '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2412 if ( $openmatch or $closematch ) {
2413 $paragraphStack = false;
2414 # TODO bug 5718: paragraph closed
2415 $output .= $this->closeParagraph();
2416 if ( $preOpenMatch and !$preCloseMatch ) {
2417 $this->mInPre = true;
2419 $inBlockElem = !$closematch;
2420 } elseif ( !$inBlockElem && !$this->mInPre ) {
2421 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
2422 # pre
2423 if ( $this->mLastSection !== 'pre' ) {
2424 $paragraphStack = false;
2425 $output .= $this->closeParagraph() . '<pre>';
2426 $this->mLastSection = 'pre';
2428 $t = substr( $t, 1 );
2429 } else {
2430 # paragraph
2431 if ( trim( $t ) === '' ) {
2432 if ( $paragraphStack ) {
2433 $output .= $paragraphStack . '<br />';
2434 $paragraphStack = false;
2435 $this->mLastSection = 'p';
2436 } else {
2437 if ( $this->mLastSection !== 'p' ) {
2438 $output .= $this->closeParagraph();
2439 $this->mLastSection = '';
2440 $paragraphStack = '<p>';
2441 } else {
2442 $paragraphStack = '</p><p>';
2445 } else {
2446 if ( $paragraphStack ) {
2447 $output .= $paragraphStack;
2448 $paragraphStack = false;
2449 $this->mLastSection = 'p';
2450 } elseif ( $this->mLastSection !== 'p' ) {
2451 $output .= $this->closeParagraph() . '<p>';
2452 $this->mLastSection = 'p';
2457 wfProfileOut( __METHOD__ . "-paragraph" );
2459 # somewhere above we forget to get out of pre block (bug 785)
2460 if ( $preCloseMatch && $this->mInPre ) {
2461 $this->mInPre = false;
2463 if ( $paragraphStack === false ) {
2464 $output .= $t . "\n";
2467 while ( $prefixLength ) {
2468 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2469 --$prefixLength;
2471 if ( $this->mLastSection != '' ) {
2472 $output .= '</' . $this->mLastSection . '>';
2473 $this->mLastSection = '';
2476 wfProfileOut( __METHOD__ );
2477 return $output;
2481 * Split up a string on ':', ignoring any occurrences inside tags
2482 * to prevent illegal overlapping.
2484 * @param string $str the string to split
2485 * @param &$before String set to everything before the ':'
2486 * @param &$after String set to everything after the ':'
2487 * @throws MWException
2488 * @return String the position of the ':', or false if none found
2490 function findColonNoLinks( $str, &$before, &$after ) {
2491 wfProfileIn( __METHOD__ );
2493 $pos = strpos( $str, ':' );
2494 if ( $pos === false ) {
2495 # Nothing to find!
2496 wfProfileOut( __METHOD__ );
2497 return false;
2500 $lt = strpos( $str, '<' );
2501 if ( $lt === false || $lt > $pos ) {
2502 # Easy; no tag nesting to worry about
2503 $before = substr( $str, 0, $pos );
2504 $after = substr( $str, $pos + 1 );
2505 wfProfileOut( __METHOD__ );
2506 return $pos;
2509 # Ugly state machine to walk through avoiding tags.
2510 $state = self::COLON_STATE_TEXT;
2511 $stack = 0;
2512 $len = strlen( $str );
2513 for ( $i = 0; $i < $len; $i++ ) {
2514 $c = $str[$i];
2516 switch ( $state ) {
2517 # (Using the number is a performance hack for common cases)
2518 case 0: # self::COLON_STATE_TEXT:
2519 switch ( $c ) {
2520 case "<":
2521 # Could be either a <start> tag or an </end> tag
2522 $state = self::COLON_STATE_TAGSTART;
2523 break;
2524 case ":":
2525 if ( $stack == 0 ) {
2526 # We found it!
2527 $before = substr( $str, 0, $i );
2528 $after = substr( $str, $i + 1 );
2529 wfProfileOut( __METHOD__ );
2530 return $i;
2532 # Embedded in a tag; don't break it.
2533 break;
2534 default:
2535 # Skip ahead looking for something interesting
2536 $colon = strpos( $str, ':', $i );
2537 if ( $colon === false ) {
2538 # Nothing else interesting
2539 wfProfileOut( __METHOD__ );
2540 return false;
2542 $lt = strpos( $str, '<', $i );
2543 if ( $stack === 0 ) {
2544 if ( $lt === false || $colon < $lt ) {
2545 # We found it!
2546 $before = substr( $str, 0, $colon );
2547 $after = substr( $str, $colon + 1 );
2548 wfProfileOut( __METHOD__ );
2549 return $i;
2552 if ( $lt === false ) {
2553 # Nothing else interesting to find; abort!
2554 # We're nested, but there's no close tags left. Abort!
2555 break 2;
2557 # Skip ahead to next tag start
2558 $i = $lt;
2559 $state = self::COLON_STATE_TAGSTART;
2561 break;
2562 case 1: # self::COLON_STATE_TAG:
2563 # In a <tag>
2564 switch ( $c ) {
2565 case ">":
2566 $stack++;
2567 $state = self::COLON_STATE_TEXT;
2568 break;
2569 case "/":
2570 # Slash may be followed by >?
2571 $state = self::COLON_STATE_TAGSLASH;
2572 break;
2573 default:
2574 # ignore
2576 break;
2577 case 2: # self::COLON_STATE_TAGSTART:
2578 switch ( $c ) {
2579 case "/":
2580 $state = self::COLON_STATE_CLOSETAG;
2581 break;
2582 case "!":
2583 $state = self::COLON_STATE_COMMENT;
2584 break;
2585 case ">":
2586 # Illegal early close? This shouldn't happen D:
2587 $state = self::COLON_STATE_TEXT;
2588 break;
2589 default:
2590 $state = self::COLON_STATE_TAG;
2592 break;
2593 case 3: # self::COLON_STATE_CLOSETAG:
2594 # In a </tag>
2595 if ( $c === ">" ) {
2596 $stack--;
2597 if ( $stack < 0 ) {
2598 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
2599 wfProfileOut( __METHOD__ );
2600 return false;
2602 $state = self::COLON_STATE_TEXT;
2604 break;
2605 case self::COLON_STATE_TAGSLASH:
2606 if ( $c === ">" ) {
2607 # Yes, a self-closed tag <blah/>
2608 $state = self::COLON_STATE_TEXT;
2609 } else {
2610 # Probably we're jumping the gun, and this is an attribute
2611 $state = self::COLON_STATE_TAG;
2613 break;
2614 case 5: # self::COLON_STATE_COMMENT:
2615 if ( $c === "-" ) {
2616 $state = self::COLON_STATE_COMMENTDASH;
2618 break;
2619 case self::COLON_STATE_COMMENTDASH:
2620 if ( $c === "-" ) {
2621 $state = self::COLON_STATE_COMMENTDASHDASH;
2622 } else {
2623 $state = self::COLON_STATE_COMMENT;
2625 break;
2626 case self::COLON_STATE_COMMENTDASHDASH:
2627 if ( $c === ">" ) {
2628 $state = self::COLON_STATE_TEXT;
2629 } else {
2630 $state = self::COLON_STATE_COMMENT;
2632 break;
2633 default:
2634 wfProfileOut( __METHOD__ );
2635 throw new MWException( "State machine error in " . __METHOD__ );
2638 if ( $stack > 0 ) {
2639 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2640 wfProfileOut( __METHOD__ );
2641 return false;
2643 wfProfileOut( __METHOD__ );
2644 return false;
2648 * Return value of a magic variable (like PAGENAME)
2650 * @private
2652 * @param $index integer
2653 * @param bool|\PPFrame $frame
2655 * @throws MWException
2656 * @return string
2658 function getVariableValue( $index, $frame = false ) {
2659 global $wgContLang, $wgSitename, $wgServer;
2660 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2662 if ( is_null( $this->mTitle ) ) {
2663 // If no title set, bad things are going to happen
2664 // later. Title should always be set since this
2665 // should only be called in the middle of a parse
2666 // operation (but the unit-tests do funky stuff)
2667 throw new MWException( __METHOD__ . ' Should only be '
2668 . ' called while parsing (no title set)' );
2672 * Some of these require message or data lookups and can be
2673 * expensive to check many times.
2675 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2676 if ( isset( $this->mVarCache[$index] ) ) {
2677 return $this->mVarCache[$index];
2681 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2682 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2684 $pageLang = $this->getFunctionLang();
2686 switch ( $index ) {
2687 case 'currentmonth':
2688 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
2689 break;
2690 case 'currentmonth1':
2691 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2692 break;
2693 case 'currentmonthname':
2694 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2695 break;
2696 case 'currentmonthnamegen':
2697 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2698 break;
2699 case 'currentmonthabbrev':
2700 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2701 break;
2702 case 'currentday':
2703 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
2704 break;
2705 case 'currentday2':
2706 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
2707 break;
2708 case 'localmonth':
2709 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
2710 break;
2711 case 'localmonth1':
2712 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2713 break;
2714 case 'localmonthname':
2715 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2716 break;
2717 case 'localmonthnamegen':
2718 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2719 break;
2720 case 'localmonthabbrev':
2721 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2722 break;
2723 case 'localday':
2724 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
2725 break;
2726 case 'localday2':
2727 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
2728 break;
2729 case 'pagename':
2730 $value = wfEscapeWikiText( $this->mTitle->getText() );
2731 break;
2732 case 'pagenamee':
2733 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2734 break;
2735 case 'fullpagename':
2736 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2737 break;
2738 case 'fullpagenamee':
2739 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2740 break;
2741 case 'subpagename':
2742 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2743 break;
2744 case 'subpagenamee':
2745 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2746 break;
2747 case 'rootpagename':
2748 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2749 break;
2750 case 'rootpagenamee':
2751 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getRootText() ) ) );
2752 break;
2753 case 'basepagename':
2754 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2755 break;
2756 case 'basepagenamee':
2757 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) );
2758 break;
2759 case 'talkpagename':
2760 if ( $this->mTitle->canTalk() ) {
2761 $talkPage = $this->mTitle->getTalkPage();
2762 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2763 } else {
2764 $value = '';
2766 break;
2767 case 'talkpagenamee':
2768 if ( $this->mTitle->canTalk() ) {
2769 $talkPage = $this->mTitle->getTalkPage();
2770 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2771 } else {
2772 $value = '';
2774 break;
2775 case 'subjectpagename':
2776 $subjPage = $this->mTitle->getSubjectPage();
2777 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2778 break;
2779 case 'subjectpagenamee':
2780 $subjPage = $this->mTitle->getSubjectPage();
2781 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2782 break;
2783 case 'pageid': // requested in bug 23427
2784 $pageid = $this->getTitle()->getArticleID();
2785 if ( $pageid == 0 ) {
2786 # 0 means the page doesn't exist in the database,
2787 # which means the user is previewing a new page.
2788 # The vary-revision flag must be set, because the magic word
2789 # will have a different value once the page is saved.
2790 $this->mOutput->setFlag( 'vary-revision' );
2791 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2793 $value = $pageid ? $pageid : null;
2794 break;
2795 case 'revisionid':
2796 # Let the edit saving system know we should parse the page
2797 # *after* a revision ID has been assigned.
2798 $this->mOutput->setFlag( 'vary-revision' );
2799 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2800 $value = $this->mRevisionId;
2801 break;
2802 case 'revisionday':
2803 # Let the edit saving system know we should parse the page
2804 # *after* a revision ID has been assigned. This is for null edits.
2805 $this->mOutput->setFlag( 'vary-revision' );
2806 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2807 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2808 break;
2809 case 'revisionday2':
2810 # Let the edit saving system know we should parse the page
2811 # *after* a revision ID has been assigned. This is for null edits.
2812 $this->mOutput->setFlag( 'vary-revision' );
2813 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2814 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2815 break;
2816 case 'revisionmonth':
2817 # Let the edit saving system know we should parse the page
2818 # *after* a revision ID has been assigned. This is for null edits.
2819 $this->mOutput->setFlag( 'vary-revision' );
2820 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2821 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2822 break;
2823 case 'revisionmonth1':
2824 # Let the edit saving system know we should parse the page
2825 # *after* a revision ID has been assigned. This is for null edits.
2826 $this->mOutput->setFlag( 'vary-revision' );
2827 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2828 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2829 break;
2830 case 'revisionyear':
2831 # Let the edit saving system know we should parse the page
2832 # *after* a revision ID has been assigned. This is for null edits.
2833 $this->mOutput->setFlag( 'vary-revision' );
2834 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2835 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2836 break;
2837 case 'revisiontimestamp':
2838 # Let the edit saving system know we should parse the page
2839 # *after* a revision ID has been assigned. This is for null edits.
2840 $this->mOutput->setFlag( 'vary-revision' );
2841 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2842 $value = $this->getRevisionTimestamp();
2843 break;
2844 case 'revisionuser':
2845 # Let the edit saving system know we should parse the page
2846 # *after* a revision ID has been assigned. This is for null edits.
2847 $this->mOutput->setFlag( 'vary-revision' );
2848 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2849 $value = $this->getRevisionUser();
2850 break;
2851 case 'namespace':
2852 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2853 break;
2854 case 'namespacee':
2855 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2856 break;
2857 case 'namespacenumber':
2858 $value = $this->mTitle->getNamespace();
2859 break;
2860 case 'talkspace':
2861 $value = $this->mTitle->canTalk() ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() ) : '';
2862 break;
2863 case 'talkspacee':
2864 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2865 break;
2866 case 'subjectspace':
2867 $value = $this->mTitle->getSubjectNsText();
2868 break;
2869 case 'subjectspacee':
2870 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2871 break;
2872 case 'currentdayname':
2873 $value = $pageLang->getWeekdayName( MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
2874 break;
2875 case 'currentyear':
2876 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
2877 break;
2878 case 'currenttime':
2879 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2880 break;
2881 case 'currenthour':
2882 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
2883 break;
2884 case 'currentweek':
2885 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2886 # int to remove the padding
2887 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
2888 break;
2889 case 'currentdow':
2890 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
2891 break;
2892 case 'localdayname':
2893 $value = $pageLang->getWeekdayName( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1 );
2894 break;
2895 case 'localyear':
2896 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
2897 break;
2898 case 'localtime':
2899 $value = $pageLang->time( MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2900 break;
2901 case 'localhour':
2902 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
2903 break;
2904 case 'localweek':
2905 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2906 # int to remove the padding
2907 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
2908 break;
2909 case 'localdow':
2910 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
2911 break;
2912 case 'numberofarticles':
2913 $value = $pageLang->formatNum( SiteStats::articles() );
2914 break;
2915 case 'numberoffiles':
2916 $value = $pageLang->formatNum( SiteStats::images() );
2917 break;
2918 case 'numberofusers':
2919 $value = $pageLang->formatNum( SiteStats::users() );
2920 break;
2921 case 'numberofactiveusers':
2922 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2923 break;
2924 case 'numberofpages':
2925 $value = $pageLang->formatNum( SiteStats::pages() );
2926 break;
2927 case 'numberofadmins':
2928 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2929 break;
2930 case 'numberofedits':
2931 $value = $pageLang->formatNum( SiteStats::edits() );
2932 break;
2933 case 'numberofviews':
2934 global $wgDisableCounters;
2935 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
2936 break;
2937 case 'currenttimestamp':
2938 $value = wfTimestamp( TS_MW, $ts );
2939 break;
2940 case 'localtimestamp':
2941 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
2942 break;
2943 case 'currentversion':
2944 $value = SpecialVersion::getVersion();
2945 break;
2946 case 'articlepath':
2947 return $wgArticlePath;
2948 case 'sitename':
2949 return $wgSitename;
2950 case 'server':
2951 return $wgServer;
2952 case 'servername':
2953 $serverParts = wfParseUrl( $wgServer );
2954 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer;
2955 case 'scriptpath':
2956 return $wgScriptPath;
2957 case 'stylepath':
2958 return $wgStylePath;
2959 case 'directionmark':
2960 return $pageLang->getDirMark();
2961 case 'contentlanguage':
2962 global $wgLanguageCode;
2963 return $wgLanguageCode;
2964 default:
2965 $ret = null;
2966 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
2967 return $ret;
2968 } else {
2969 return null;
2973 if ( $index ) {
2974 $this->mVarCache[$index] = $value;
2977 return $value;
2981 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2983 * @private
2985 function initialiseVariables() {
2986 wfProfileIn( __METHOD__ );
2987 $variableIDs = MagicWord::getVariableIDs();
2988 $substIDs = MagicWord::getSubstIDs();
2990 $this->mVariables = new MagicWordArray( $variableIDs );
2991 $this->mSubstWords = new MagicWordArray( $substIDs );
2992 wfProfileOut( __METHOD__ );
2996 * Preprocess some wikitext and return the document tree.
2997 * This is the ghost of replace_variables().
2999 * @param string $text The text to parse
3000 * @param $flags Integer: bitwise combination of:
3001 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3002 * included. Default is to assume a direct page view.
3004 * The generated DOM tree must depend only on the input text and the flags.
3005 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3007 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3008 * change in the DOM tree for a given text, must be passed through the section identifier
3009 * in the section edit link and thus back to extractSections().
3011 * The output of this function is currently only cached in process memory, but a persistent
3012 * cache may be implemented at a later date which takes further advantage of these strict
3013 * dependency requirements.
3015 * @private
3017 * @return PPNode
3019 function preprocessToDom( $text, $flags = 0 ) {
3020 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3021 return $dom;
3025 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3027 * @param $s string
3029 * @return array
3031 public static function splitWhitespace( $s ) {
3032 $ltrimmed = ltrim( $s );
3033 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3034 $trimmed = rtrim( $ltrimmed );
3035 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3036 if ( $diff > 0 ) {
3037 $w2 = substr( $ltrimmed, -$diff );
3038 } else {
3039 $w2 = '';
3041 return array( $w1, $trimmed, $w2 );
3045 * Replace magic variables, templates, and template arguments
3046 * with the appropriate text. Templates are substituted recursively,
3047 * taking care to avoid infinite loops.
3049 * Note that the substitution depends on value of $mOutputType:
3050 * self::OT_WIKI: only {{subst:}} templates
3051 * self::OT_PREPROCESS: templates but not extension tags
3052 * self::OT_HTML: all templates and extension tags
3054 * @param string $text the text to transform
3055 * @param $frame PPFrame Object describing the arguments passed to the template.
3056 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3057 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3058 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3059 * @private
3061 * @return string
3063 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3064 # Is there any text? Also, Prevent too big inclusions!
3065 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3066 return $text;
3068 wfProfileIn( __METHOD__ );
3070 if ( $frame === false ) {
3071 $frame = $this->getPreprocessor()->newFrame();
3072 } elseif ( !( $frame instanceof PPFrame ) ) {
3073 wfDebug( __METHOD__ . " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3074 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3077 $dom = $this->preprocessToDom( $text );
3078 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3079 $text = $frame->expand( $dom, $flags );
3081 wfProfileOut( __METHOD__ );
3082 return $text;
3086 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3088 * @param $args array
3090 * @return array
3092 static function createAssocArgs( $args ) {
3093 $assocArgs = array();
3094 $index = 1;
3095 foreach ( $args as $arg ) {
3096 $eqpos = strpos( $arg, '=' );
3097 if ( $eqpos === false ) {
3098 $assocArgs[$index++] = $arg;
3099 } else {
3100 $name = trim( substr( $arg, 0, $eqpos ) );
3101 $value = trim( substr( $arg, $eqpos + 1 ) );
3102 if ( $value === false ) {
3103 $value = '';
3105 if ( $name !== false ) {
3106 $assocArgs[$name] = $value;
3111 return $assocArgs;
3115 * Warn the user when a parser limitation is reached
3116 * Will warn at most once the user per limitation type
3118 * @param string $limitationType should be one of:
3119 * 'expensive-parserfunction' (corresponding messages:
3120 * 'expensive-parserfunction-warning',
3121 * 'expensive-parserfunction-category')
3122 * 'post-expand-template-argument' (corresponding messages:
3123 * 'post-expand-template-argument-warning',
3124 * 'post-expand-template-argument-category')
3125 * 'post-expand-template-inclusion' (corresponding messages:
3126 * 'post-expand-template-inclusion-warning',
3127 * 'post-expand-template-inclusion-category')
3128 * @param int|null $current Current value
3129 * @param int|null $max Maximum allowed, when an explicit limit has been
3130 * exceeded, provide the values (optional)
3132 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3133 # does no harm if $current and $max are present but are unnecessary for the message
3134 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3135 ->inContentLanguage()->escaped();
3136 $this->mOutput->addWarning( $warning );
3137 $this->addTrackingCategory( "$limitationType-category" );
3141 * Return the text of a template, after recursively
3142 * replacing any variables or templates within the template.
3144 * @param array $piece the parts of the template
3145 * $piece['title']: the title, i.e. the part before the |
3146 * $piece['parts']: the parameter array
3147 * $piece['lineStart']: whether the brace was at the start of a line
3148 * @param $frame PPFrame The current frame, contains template arguments
3149 * @throws MWException
3150 * @return String: the text of the template
3151 * @private
3153 function braceSubstitution( $piece, $frame ) {
3154 wfProfileIn( __METHOD__ );
3155 wfProfileIn( __METHOD__ . '-setup' );
3157 # Flags
3158 $found = false; # $text has been filled
3159 $nowiki = false; # wiki markup in $text should be escaped
3160 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3161 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3162 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3163 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3165 # Title object, where $text came from
3166 $title = false;
3168 # $part1 is the bit before the first |, and must contain only title characters.
3169 # Various prefixes will be stripped from it later.
3170 $titleWithSpaces = $frame->expand( $piece['title'] );
3171 $part1 = trim( $titleWithSpaces );
3172 $titleText = false;
3174 # Original title text preserved for various purposes
3175 $originalTitle = $part1;
3177 # $args is a list of argument nodes, starting from index 0, not including $part1
3178 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3179 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3180 wfProfileOut( __METHOD__ . '-setup' );
3182 $titleProfileIn = null; // profile templates
3184 # SUBST
3185 wfProfileIn( __METHOD__ . '-modifiers' );
3186 if ( !$found ) {
3188 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3190 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3191 # Decide whether to expand template or keep wikitext as-is.
3192 if ( $this->ot['wiki'] ) {
3193 if ( $substMatch === false ) {
3194 $literal = true; # literal when in PST with no prefix
3195 } else {
3196 $literal = false; # expand when in PST with subst: or safesubst:
3198 } else {
3199 if ( $substMatch == 'subst' ) {
3200 $literal = true; # literal when not in PST with plain subst:
3201 } else {
3202 $literal = false; # expand when not in PST with safesubst: or no prefix
3205 if ( $literal ) {
3206 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3207 $isLocalObj = true;
3208 $found = true;
3212 # Variables
3213 if ( !$found && $args->getLength() == 0 ) {
3214 $id = $this->mVariables->matchStartToEnd( $part1 );
3215 if ( $id !== false ) {
3216 $text = $this->getVariableValue( $id, $frame );
3217 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3218 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3220 $found = true;
3224 # MSG, MSGNW and RAW
3225 if ( !$found ) {
3226 # Check for MSGNW:
3227 $mwMsgnw = MagicWord::get( 'msgnw' );
3228 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3229 $nowiki = true;
3230 } else {
3231 # Remove obsolete MSG:
3232 $mwMsg = MagicWord::get( 'msg' );
3233 $mwMsg->matchStartAndRemove( $part1 );
3236 # Check for RAW:
3237 $mwRaw = MagicWord::get( 'raw' );
3238 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3239 $forceRawInterwiki = true;
3242 wfProfileOut( __METHOD__ . '-modifiers' );
3244 # Parser functions
3245 if ( !$found ) {
3246 wfProfileIn( __METHOD__ . '-pfunc' );
3248 $colonPos = strpos( $part1, ':' );
3249 if ( $colonPos !== false ) {
3250 $func = substr( $part1, 0, $colonPos );
3251 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3252 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3253 $funcArgs[] = $args->item( $i );
3255 try {
3256 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3257 } catch ( Exception $ex ) {
3258 wfProfileOut( __METHOD__ . '-pfunc' );
3259 wfProfileOut( __METHOD__ );
3260 throw $ex;
3263 # The interface for parser functions allows for extracting
3264 # flags into the local scope. Extract any forwarded flags
3265 # here.
3266 extract( $result );
3268 wfProfileOut( __METHOD__ . '-pfunc' );
3271 # Finish mangling title and then check for loops.
3272 # Set $title to a Title object and $titleText to the PDBK
3273 if ( !$found ) {
3274 $ns = NS_TEMPLATE;
3275 # Split the title into page and subpage
3276 $subpage = '';
3277 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3278 if ( $part1 !== $relative ) {
3279 $part1 = $relative;
3280 $ns = $this->mTitle->getNamespace();
3282 $title = Title::newFromText( $part1, $ns );
3283 if ( $title ) {
3284 $titleText = $title->getPrefixedText();
3285 # Check for language variants if the template is not found
3286 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3287 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3289 # Do recursion depth check
3290 $limit = $this->mOptions->getMaxTemplateDepth();
3291 if ( $frame->depth >= $limit ) {
3292 $found = true;
3293 $text = '<span class="error">'
3294 . wfMessage( 'parser-template-recursion-depth-warning' )
3295 ->numParams( $limit )->inContentLanguage()->text()
3296 . '</span>';
3301 # Load from database
3302 if ( !$found && $title ) {
3303 if ( !Profiler::instance()->isPersistent() ) {
3304 # Too many unique items can kill profiling DBs/collectors
3305 $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey();
3306 wfProfileIn( $titleProfileIn ); // template in
3308 wfProfileIn( __METHOD__ . '-loadtpl' );
3309 if ( !$title->isExternal() ) {
3310 if ( $title->isSpecialPage()
3311 && $this->mOptions->getAllowSpecialInclusion()
3312 && $this->ot['html'] )
3314 // Pass the template arguments as URL parameters.
3315 // "uselang" will have no effect since the Language object
3316 // is forced to the one defined in ParserOptions.
3317 $pageArgs = array();
3318 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3319 $bits = $args->item( $i )->splitArg();
3320 if ( strval( $bits['index'] ) === '' ) {
3321 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3322 $value = trim( $frame->expand( $bits['value'] ) );
3323 $pageArgs[$name] = $value;
3327 // Create a new context to execute the special page
3328 $context = new RequestContext;
3329 $context->setTitle( $title );
3330 $context->setRequest( new FauxRequest( $pageArgs ) );
3331 $context->setUser( $this->getUser() );
3332 $context->setLanguage( $this->mOptions->getUserLangObj() );
3333 $ret = SpecialPageFactory::capturePath( $title, $context );
3334 if ( $ret ) {
3335 $text = $context->getOutput()->getHTML();
3336 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3337 $found = true;
3338 $isHTML = true;
3339 $this->disableCache();
3341 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3342 $found = false; # access denied
3343 wfDebug( __METHOD__ . ": template inclusion denied for " . $title->getPrefixedDBkey() );
3344 } else {
3345 list( $text, $title ) = $this->getTemplateDom( $title );
3346 if ( $text !== false ) {
3347 $found = true;
3348 $isChildObj = true;
3352 # If the title is valid but undisplayable, make a link to it
3353 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3354 $text = "[[:$titleText]]";
3355 $found = true;
3357 } elseif ( $title->isTrans() ) {
3358 # Interwiki transclusion
3359 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3360 $text = $this->interwikiTransclude( $title, 'render' );
3361 $isHTML = true;
3362 } else {
3363 $text = $this->interwikiTransclude( $title, 'raw' );
3364 # Preprocess it like a template
3365 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3366 $isChildObj = true;
3368 $found = true;
3371 # Do infinite loop check
3372 # This has to be done after redirect resolution to avoid infinite loops via redirects
3373 if ( !$frame->loopCheck( $title ) ) {
3374 $found = true;
3375 $text = '<span class="error">'
3376 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3377 . '</span>';
3378 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3380 wfProfileOut( __METHOD__ . '-loadtpl' );
3383 # If we haven't found text to substitute by now, we're done
3384 # Recover the source wikitext and return it
3385 if ( !$found ) {
3386 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3387 if ( $titleProfileIn ) {
3388 wfProfileOut( $titleProfileIn ); // template out
3390 wfProfileOut( __METHOD__ );
3391 return array( 'object' => $text );
3394 # Expand DOM-style return values in a child frame
3395 if ( $isChildObj ) {
3396 # Clean up argument array
3397 $newFrame = $frame->newChild( $args, $title );
3399 if ( $nowiki ) {
3400 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3401 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3402 # Expansion is eligible for the empty-frame cache
3403 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3404 $text = $this->mTplExpandCache[$titleText];
3405 } else {
3406 $text = $newFrame->expand( $text );
3407 $this->mTplExpandCache[$titleText] = $text;
3409 } else {
3410 # Uncached expansion
3411 $text = $newFrame->expand( $text );
3414 if ( $isLocalObj && $nowiki ) {
3415 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3416 $isLocalObj = false;
3419 if ( $titleProfileIn ) {
3420 wfProfileOut( $titleProfileIn ); // template out
3423 # Replace raw HTML by a placeholder
3424 if ( $isHTML ) {
3425 $text = $this->insertStripItem( $text );
3426 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3427 # Escape nowiki-style return values
3428 $text = wfEscapeWikiText( $text );
3429 } elseif ( is_string( $text )
3430 && !$piece['lineStart']
3431 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3433 # Bug 529: if the template begins with a table or block-level
3434 # element, it should be treated as beginning a new line.
3435 # This behavior is somewhat controversial.
3436 $text = "\n" . $text;
3439 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3440 # Error, oversize inclusion
3441 if ( $titleText !== false ) {
3442 # Make a working, properly escaped link if possible (bug 23588)
3443 $text = "[[:$titleText]]";
3444 } else {
3445 # This will probably not be a working link, but at least it may
3446 # provide some hint of where the problem is
3447 preg_replace( '/^:/', '', $originalTitle );
3448 $text = "[[:$originalTitle]]";
3450 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3451 $this->limitationWarn( 'post-expand-template-inclusion' );
3454 if ( $isLocalObj ) {
3455 $ret = array( 'object' => $text );
3456 } else {
3457 $ret = array( 'text' => $text );
3460 wfProfileOut( __METHOD__ );
3461 return $ret;
3465 * Call a parser function and return an array with text and flags.
3467 * The returned array will always contain a boolean 'found', indicating
3468 * whether the parser function was found or not. It may also contain the
3469 * following:
3470 * text: string|object, resulting wikitext or PP DOM object
3471 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3472 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3473 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3474 * nowiki: bool, wiki markup in $text should be escaped
3476 * @since 1.21
3477 * @param $frame PPFrame The current frame, contains template arguments
3478 * @param $function string Function name
3479 * @param $args array Arguments to the function
3480 * @return array
3482 public function callParserFunction( $frame, $function, array $args = array() ) {
3483 global $wgContLang;
3485 wfProfileIn( __METHOD__ );
3487 # Case sensitive functions
3488 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3489 $function = $this->mFunctionSynonyms[1][$function];
3490 } else {
3491 # Case insensitive functions
3492 $function = $wgContLang->lc( $function );
3493 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3494 $function = $this->mFunctionSynonyms[0][$function];
3495 } else {
3496 wfProfileOut( __METHOD__ );
3497 return array( 'found' => false );
3501 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3502 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3504 # Workaround for PHP bug 35229 and similar
3505 if ( !is_callable( $callback ) ) {
3506 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3507 wfProfileOut( __METHOD__ );
3508 throw new MWException( "Tag hook for $function is not callable\n" );
3511 $allArgs = array( &$this );
3512 if ( $flags & SFH_OBJECT_ARGS ) {
3513 # Convert arguments to PPNodes and collect for appending to $allArgs
3514 $funcArgs = array();
3515 foreach ( $args as $k => $v ) {
3516 if ( $v instanceof PPNode || $k === 0 ) {
3517 $funcArgs[] = $v;
3518 } else {
3519 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3523 # Add a frame parameter, and pass the arguments as an array
3524 $allArgs[] = $frame;
3525 $allArgs[] = $funcArgs;
3526 } else {
3527 # Convert arguments to plain text and append to $allArgs
3528 foreach ( $args as $k => $v ) {
3529 if ( $v instanceof PPNode ) {
3530 $allArgs[] = trim( $frame->expand( $v ) );
3531 } elseif ( is_int( $k ) && $k >= 0 ) {
3532 $allArgs[] = trim( $v );
3533 } else {
3534 $allArgs[] = trim( "$k=$v" );
3539 $result = call_user_func_array( $callback, $allArgs );
3541 # The interface for function hooks allows them to return a wikitext
3542 # string or an array containing the string and any flags. This mungs
3543 # things around to match what this method should return.
3544 if ( !is_array( $result ) ) {
3545 $result = array(
3546 'found' => true,
3547 'text' => $result,
3549 } else {
3550 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3551 $result['text'] = $result[0];
3553 unset( $result[0] );
3554 $result += array(
3555 'found' => true,
3559 $noparse = true;
3560 $preprocessFlags = 0;
3561 if ( isset( $result['noparse'] ) ) {
3562 $noparse = $result['noparse'];
3564 if ( isset( $result['preprocessFlags'] ) ) {
3565 $preprocessFlags = $result['preprocessFlags'];
3568 if ( !$noparse ) {
3569 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3570 $result['isChildObj'] = true;
3572 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3573 wfProfileOut( __METHOD__ );
3575 return $result;
3579 * Get the semi-parsed DOM representation of a template with a given title,
3580 * and its redirect destination title. Cached.
3582 * @param $title Title
3584 * @return array
3586 function getTemplateDom( $title ) {
3587 $cacheTitle = $title;
3588 $titleText = $title->getPrefixedDBkey();
3590 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3591 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3592 $title = Title::makeTitle( $ns, $dbk );
3593 $titleText = $title->getPrefixedDBkey();
3595 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3596 return array( $this->mTplDomCache[$titleText], $title );
3599 # Cache miss, go to the database
3600 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3602 if ( $text === false ) {
3603 $this->mTplDomCache[$titleText] = false;
3604 return array( false, $title );
3607 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3608 $this->mTplDomCache[$titleText] = $dom;
3610 if ( !$title->equals( $cacheTitle ) ) {
3611 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3612 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3615 return array( $dom, $title );
3619 * Fetch the unparsed text of a template and register a reference to it.
3620 * @param Title $title
3621 * @return Array ( string or false, Title )
3623 function fetchTemplateAndTitle( $title ) {
3624 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3625 $stuff = call_user_func( $templateCb, $title, $this );
3626 $text = $stuff['text'];
3627 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3628 if ( isset( $stuff['deps'] ) ) {
3629 foreach ( $stuff['deps'] as $dep ) {
3630 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3631 if ( $dep['title']->equals( $this->getTitle() ) ) {
3632 // If we transclude ourselves, the final result
3633 // will change based on the new version of the page
3634 $this->mOutput->setFlag( 'vary-revision' );
3638 return array( $text, $finalTitle );
3642 * Fetch the unparsed text of a template and register a reference to it.
3643 * @param Title $title
3644 * @return mixed string or false
3646 function fetchTemplate( $title ) {
3647 $rv = $this->fetchTemplateAndTitle( $title );
3648 return $rv[0];
3652 * Static function to get a template
3653 * Can be overridden via ParserOptions::setTemplateCallback().
3655 * @param $title Title
3656 * @param $parser Parser
3658 * @return array
3660 static function statelessFetchTemplate( $title, $parser = false ) {
3661 $text = $skip = false;
3662 $finalTitle = $title;
3663 $deps = array();
3665 # Loop to fetch the article, with up to 1 redirect
3666 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3667 # Give extensions a chance to select the revision instead
3668 $id = false; # Assume current
3669 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3670 array( $parser, $title, &$skip, &$id ) );
3672 if ( $skip ) {
3673 $text = false;
3674 $deps[] = array(
3675 'title' => $title,
3676 'page_id' => $title->getArticleID(),
3677 'rev_id' => null
3679 break;
3681 # Get the revision
3682 $rev = $id
3683 ? Revision::newFromId( $id )
3684 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
3685 $rev_id = $rev ? $rev->getId() : 0;
3686 # If there is no current revision, there is no page
3687 if ( $id === false && !$rev ) {
3688 $linkCache = LinkCache::singleton();
3689 $linkCache->addBadLinkObj( $title );
3692 $deps[] = array(
3693 'title' => $title,
3694 'page_id' => $title->getArticleID(),
3695 'rev_id' => $rev_id );
3696 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3697 # We fetched a rev from a different title; register it too...
3698 $deps[] = array(
3699 'title' => $rev->getTitle(),
3700 'page_id' => $rev->getPage(),
3701 'rev_id' => $rev_id );
3704 if ( $rev ) {
3705 $content = $rev->getContent();
3706 $text = $content ? $content->getWikitextForTransclusion() : null;
3708 if ( $text === false || $text === null ) {
3709 $text = false;
3710 break;
3712 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3713 global $wgContLang;
3714 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3715 if ( !$message->exists() ) {
3716 $text = false;
3717 break;
3719 $content = $message->content();
3720 $text = $message->plain();
3721 } else {
3722 break;
3724 if ( !$content ) {
3725 break;
3727 # Redirect?
3728 $finalTitle = $title;
3729 $title = $content->getRedirectTarget();
3731 return array(
3732 'text' => $text,
3733 'finalTitle' => $finalTitle,
3734 'deps' => $deps );
3738 * Fetch a file and its title and register a reference to it.
3739 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3740 * @param Title $title
3741 * @param array $options Array of options to RepoGroup::findFile
3742 * @return File|bool
3744 function fetchFile( $title, $options = array() ) {
3745 $res = $this->fetchFileAndTitle( $title, $options );
3746 return $res[0];
3750 * Fetch a file and its title and register a reference to it.
3751 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3752 * @param Title $title
3753 * @param array $options Array of options to RepoGroup::findFile
3754 * @return Array ( File or false, Title of file )
3756 function fetchFileAndTitle( $title, $options = array() ) {
3757 $file = $this->fetchFileNoRegister( $title, $options );
3759 $time = $file ? $file->getTimestamp() : false;
3760 $sha1 = $file ? $file->getSha1() : false;
3761 # Register the file as a dependency...
3762 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3763 if ( $file && !$title->equals( $file->getTitle() ) ) {
3764 # Update fetched file title
3765 $title = $file->getTitle();
3766 if ( is_null( $file->getRedirectedTitle() ) ) {
3767 # This file was not a redirect, but the title does not match.
3768 # Register under the new name because otherwise the link will
3769 # get lost.
3770 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3773 return array( $file, $title );
3777 * Helper function for fetchFileAndTitle.
3779 * Also useful if you need to fetch a file but not use it yet,
3780 * for example to get the file's handler.
3782 * @param Title $title
3783 * @param array $options Array of options to RepoGroup::findFile
3784 * @return File or false
3786 protected function fetchFileNoRegister( $title, $options = array() ) {
3787 if ( isset( $options['broken'] ) ) {
3788 $file = false; // broken thumbnail forced by hook
3789 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3790 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3791 } else { // get by (name,timestamp)
3792 $file = wfFindFile( $title, $options );
3794 return $file;
3798 * Transclude an interwiki link.
3800 * @param $title Title
3801 * @param $action
3803 * @return string
3805 function interwikiTransclude( $title, $action ) {
3806 global $wgEnableScaryTranscluding;
3808 if ( !$wgEnableScaryTranscluding ) {
3809 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3812 $url = $title->getFullURL( array( 'action' => $action ) );
3814 if ( strlen( $url ) > 255 ) {
3815 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3817 return $this->fetchScaryTemplateMaybeFromCache( $url );
3821 * @param $url string
3822 * @return Mixed|String
3824 function fetchScaryTemplateMaybeFromCache( $url ) {
3825 global $wgTranscludeCacheExpiry;
3826 $dbr = wfGetDB( DB_SLAVE );
3827 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3828 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3829 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3830 if ( $obj ) {
3831 return $obj->tc_contents;
3834 $req = MWHttpRequest::factory( $url );
3835 $status = $req->execute(); // Status object
3836 if ( $status->isOK() ) {
3837 $text = $req->getContent();
3838 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3839 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3840 } else {
3841 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3844 $dbw = wfGetDB( DB_MASTER );
3845 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3846 'tc_url' => $url,
3847 'tc_time' => $dbw->timestamp( time() ),
3848 'tc_contents' => $text
3849 ) );
3850 return $text;
3854 * Triple brace replacement -- used for template arguments
3855 * @private
3857 * @param $piece array
3858 * @param $frame PPFrame
3860 * @return array
3862 function argSubstitution( $piece, $frame ) {
3863 wfProfileIn( __METHOD__ );
3865 $error = false;
3866 $parts = $piece['parts'];
3867 $nameWithSpaces = $frame->expand( $piece['title'] );
3868 $argName = trim( $nameWithSpaces );
3869 $object = false;
3870 $text = $frame->getArgument( $argName );
3871 if ( $text === false && $parts->getLength() > 0
3872 && (
3873 $this->ot['html']
3874 || $this->ot['pre']
3875 || ( $this->ot['wiki'] && $frame->isTemplate() )
3878 # No match in frame, use the supplied default
3879 $object = $parts->item( 0 )->getChildren();
3881 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3882 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3883 $this->limitationWarn( 'post-expand-template-argument' );
3886 if ( $text === false && $object === false ) {
3887 # No match anywhere
3888 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3890 if ( $error !== false ) {
3891 $text .= $error;
3893 if ( $object !== false ) {
3894 $ret = array( 'object' => $object );
3895 } else {
3896 $ret = array( 'text' => $text );
3899 wfProfileOut( __METHOD__ );
3900 return $ret;
3904 * Return the text to be used for a given extension tag.
3905 * This is the ghost of strip().
3907 * @param array $params Associative array of parameters:
3908 * name PPNode for the tag name
3909 * attr PPNode for unparsed text where tag attributes are thought to be
3910 * attributes Optional associative array of parsed attributes
3911 * inner Contents of extension element
3912 * noClose Original text did not have a close tag
3913 * @param $frame PPFrame
3915 * @throws MWException
3916 * @return string
3918 function extensionSubstitution( $params, $frame ) {
3919 $name = $frame->expand( $params['name'] );
3920 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3921 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3922 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3924 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
3925 ( $this->ot['html'] || $this->ot['pre'] );
3926 if ( $isFunctionTag ) {
3927 $markerType = 'none';
3928 } else {
3929 $markerType = 'general';
3931 if ( $this->ot['html'] || $isFunctionTag ) {
3932 $name = strtolower( $name );
3933 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3934 if ( isset( $params['attributes'] ) ) {
3935 $attributes = $attributes + $params['attributes'];
3938 if ( isset( $this->mTagHooks[$name] ) ) {
3939 # Workaround for PHP bug 35229 and similar
3940 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3941 throw new MWException( "Tag hook for $name is not callable\n" );
3943 $output = call_user_func_array( $this->mTagHooks[$name],
3944 array( $content, $attributes, $this, $frame ) );
3945 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3946 list( $callback, ) = $this->mFunctionTagHooks[$name];
3947 if ( !is_callable( $callback ) ) {
3948 throw new MWException( "Tag hook for $name is not callable\n" );
3951 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3952 } else {
3953 $output = '<span class="error">Invalid tag extension name: ' .
3954 htmlspecialchars( $name ) . '</span>';
3957 if ( is_array( $output ) ) {
3958 # Extract flags to local scope (to override $markerType)
3959 $flags = $output;
3960 $output = $flags[0];
3961 unset( $flags[0] );
3962 extract( $flags );
3964 } else {
3965 if ( is_null( $attrText ) ) {
3966 $attrText = '';
3968 if ( isset( $params['attributes'] ) ) {
3969 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3970 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3971 htmlspecialchars( $attrValue ) . '"';
3974 if ( $content === null ) {
3975 $output = "<$name$attrText/>";
3976 } else {
3977 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3978 $output = "<$name$attrText>$content$close";
3982 if ( $markerType === 'none' ) {
3983 return $output;
3984 } elseif ( $markerType === 'nowiki' ) {
3985 $this->mStripState->addNoWiki( $marker, $output );
3986 } elseif ( $markerType === 'general' ) {
3987 $this->mStripState->addGeneral( $marker, $output );
3988 } else {
3989 throw new MWException( __METHOD__ . ': invalid marker type' );
3991 return $marker;
3995 * Increment an include size counter
3997 * @param string $type the type of expansion
3998 * @param $size Integer: the size of the text
3999 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4001 function incrementIncludeSize( $type, $size ) {
4002 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4003 return false;
4004 } else {
4005 $this->mIncludeSizes[$type] += $size;
4006 return true;
4011 * Increment the expensive function count
4013 * @return Boolean: false if the limit has been exceeded
4015 function incrementExpensiveFunctionCount() {
4016 $this->mExpensiveFunctionCount++;
4017 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4021 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4022 * Fills $this->mDoubleUnderscores, returns the modified text
4024 * @param $text string
4026 * @return string
4028 function doDoubleUnderscore( $text ) {
4029 wfProfileIn( __METHOD__ );
4031 # The position of __TOC__ needs to be recorded
4032 $mw = MagicWord::get( 'toc' );
4033 if ( $mw->match( $text ) ) {
4034 $this->mShowToc = true;
4035 $this->mForceTocPosition = true;
4037 # Set a placeholder. At the end we'll fill it in with the TOC.
4038 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4040 # Only keep the first one.
4041 $text = $mw->replace( '', $text );
4044 # Now match and remove the rest of them
4045 $mwa = MagicWord::getDoubleUnderscoreArray();
4046 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4048 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4049 $this->mOutput->mNoGallery = true;
4051 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4052 $this->mShowToc = false;
4054 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
4055 $this->addTrackingCategory( 'hidden-category-category' );
4057 # (bug 8068) Allow control over whether robots index a page.
4059 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4060 # is not desirable, the last one on the page should win.
4061 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4062 $this->mOutput->setIndexPolicy( 'noindex' );
4063 $this->addTrackingCategory( 'noindex-category' );
4065 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4066 $this->mOutput->setIndexPolicy( 'index' );
4067 $this->addTrackingCategory( 'index-category' );
4070 # Cache all double underscores in the database
4071 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4072 $this->mOutput->setProperty( $key, '' );
4075 wfProfileOut( __METHOD__ );
4076 return $text;
4080 * Add a tracking category, getting the title from a system message,
4081 * or print a debug message if the title is invalid.
4083 * @param string $msg message key
4084 * @return Boolean: whether the addition was successful
4086 public function addTrackingCategory( $msg ) {
4087 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
4088 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
4089 return false;
4091 // Important to parse with correct title (bug 31469)
4092 $cat = wfMessage( $msg )
4093 ->title( $this->getTitle() )
4094 ->inContentLanguage()
4095 ->text();
4097 # Allow tracking categories to be disabled by setting them to "-"
4098 if ( $cat === '-' ) {
4099 return false;
4102 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
4103 if ( $containerCategory ) {
4104 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4105 return true;
4106 } else {
4107 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
4108 return false;
4113 * This function accomplishes several tasks:
4114 * 1) Auto-number headings if that option is enabled
4115 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4116 * 3) Add a Table of contents on the top for users who have enabled the option
4117 * 4) Auto-anchor headings
4119 * It loops through all headlines, collects the necessary data, then splits up the
4120 * string and re-inserts the newly formatted headlines.
4122 * @param $text String
4123 * @param string $origText original, untouched wikitext
4124 * @param $isMain Boolean
4125 * @return mixed|string
4126 * @private
4128 function formatHeadings( $text, $origText, $isMain = true ) {
4129 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4131 # Inhibit editsection links if requested in the page
4132 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4133 $maybeShowEditLink = $showEditLink = false;
4134 } else {
4135 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4136 $showEditLink = $this->mOptions->getEditSection();
4138 if ( $showEditLink ) {
4139 $this->mOutput->setEditSectionTokens( true );
4142 # Get all headlines for numbering them and adding funky stuff like [edit]
4143 # links - this is for later, but we need the number of headlines right now
4144 $matches = array();
4145 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4147 # if there are fewer than 4 headlines in the article, do not show TOC
4148 # unless it's been explicitly enabled.
4149 $enoughToc = $this->mShowToc &&
4150 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4152 # Allow user to stipulate that a page should have a "new section"
4153 # link added via __NEWSECTIONLINK__
4154 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4155 $this->mOutput->setNewSection( true );
4158 # Allow user to remove the "new section"
4159 # link via __NONEWSECTIONLINK__
4160 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4161 $this->mOutput->hideNewSection( true );
4164 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4165 # override above conditions and always show TOC above first header
4166 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4167 $this->mShowToc = true;
4168 $enoughToc = true;
4171 # headline counter
4172 $headlineCount = 0;
4173 $numVisible = 0;
4175 # Ugh .. the TOC should have neat indentation levels which can be
4176 # passed to the skin functions. These are determined here
4177 $toc = '';
4178 $full = '';
4179 $head = array();
4180 $sublevelCount = array();
4181 $levelCount = array();
4182 $level = 0;
4183 $prevlevel = 0;
4184 $toclevel = 0;
4185 $prevtoclevel = 0;
4186 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4187 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4188 $oldType = $this->mOutputType;
4189 $this->setOutputType( self::OT_WIKI );
4190 $frame = $this->getPreprocessor()->newFrame();
4191 $root = $this->preprocessToDom( $origText );
4192 $node = $root->getFirstChild();
4193 $byteOffset = 0;
4194 $tocraw = array();
4195 $refers = array();
4197 foreach ( $matches[3] as $headline ) {
4198 $isTemplate = false;
4199 $titleText = false;
4200 $sectionIndex = false;
4201 $numbering = '';
4202 $markerMatches = array();
4203 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4204 $serial = $markerMatches[1];
4205 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4206 $isTemplate = ( $titleText != $baseTitleText );
4207 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4210 if ( $toclevel ) {
4211 $prevlevel = $level;
4213 $level = $matches[1][$headlineCount];
4215 if ( $level > $prevlevel ) {
4216 # Increase TOC level
4217 $toclevel++;
4218 $sublevelCount[$toclevel] = 0;
4219 if ( $toclevel < $wgMaxTocLevel ) {
4220 $prevtoclevel = $toclevel;
4221 $toc .= Linker::tocIndent();
4222 $numVisible++;
4224 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4225 # Decrease TOC level, find level to jump to
4227 for ( $i = $toclevel; $i > 0; $i-- ) {
4228 if ( $levelCount[$i] == $level ) {
4229 # Found last matching level
4230 $toclevel = $i;
4231 break;
4232 } elseif ( $levelCount[$i] < $level ) {
4233 # Found first matching level below current level
4234 $toclevel = $i + 1;
4235 break;
4238 if ( $i == 0 ) {
4239 $toclevel = 1;
4241 if ( $toclevel < $wgMaxTocLevel ) {
4242 if ( $prevtoclevel < $wgMaxTocLevel ) {
4243 # Unindent only if the previous toc level was shown :p
4244 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4245 $prevtoclevel = $toclevel;
4246 } else {
4247 $toc .= Linker::tocLineEnd();
4250 } else {
4251 # No change in level, end TOC line
4252 if ( $toclevel < $wgMaxTocLevel ) {
4253 $toc .= Linker::tocLineEnd();
4257 $levelCount[$toclevel] = $level;
4259 # count number of headlines for each level
4260 $sublevelCount[$toclevel]++;
4261 $dot = 0;
4262 for ( $i = 1; $i <= $toclevel; $i++ ) {
4263 if ( !empty( $sublevelCount[$i] ) ) {
4264 if ( $dot ) {
4265 $numbering .= '.';
4267 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4268 $dot = 1;
4272 # The safe header is a version of the header text safe to use for links
4274 # Remove link placeholders by the link text.
4275 # <!--LINK number-->
4276 # turns into
4277 # link text with suffix
4278 # Do this before unstrip since link text can contain strip markers
4279 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4281 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4282 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4284 # Strip out HTML (first regex removes any tag not allowed)
4285 # Allowed tags are:
4286 # * <sup> and <sub> (bug 8393)
4287 # * <i> (bug 26375)
4288 # * <b> (r105284)
4289 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4291 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4292 # to allow setting directionality in toc items.
4293 $tocline = preg_replace(
4294 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4295 array( '', '<$1>' ),
4296 $safeHeadline
4298 $tocline = trim( $tocline );
4300 # For the anchor, strip out HTML-y stuff period
4301 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4302 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4304 # Save headline for section edit hint before it's escaped
4305 $headlineHint = $safeHeadline;
4307 if ( $wgExperimentalHtmlIds ) {
4308 # For reverse compatibility, provide an id that's
4309 # HTML4-compatible, like we used to.
4311 # It may be worth noting, academically, that it's possible for
4312 # the legacy anchor to conflict with a non-legacy headline
4313 # anchor on the page. In this case likely the "correct" thing
4314 # would be to either drop the legacy anchors or make sure
4315 # they're numbered first. However, this would require people
4316 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4317 # manually, so let's not bother worrying about it.
4318 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4319 array( 'noninitial', 'legacy' ) );
4320 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4322 if ( $legacyHeadline == $safeHeadline ) {
4323 # No reason to have both (in fact, we can't)
4324 $legacyHeadline = false;
4326 } else {
4327 $legacyHeadline = false;
4328 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4329 'noninitial' );
4332 # HTML names must be case-insensitively unique (bug 10721).
4333 # This does not apply to Unicode characters per
4334 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4335 # @todo FIXME: We may be changing them depending on the current locale.
4336 $arrayKey = strtolower( $safeHeadline );
4337 if ( $legacyHeadline === false ) {
4338 $legacyArrayKey = false;
4339 } else {
4340 $legacyArrayKey = strtolower( $legacyHeadline );
4343 # count how many in assoc. array so we can track dupes in anchors
4344 if ( isset( $refers[$arrayKey] ) ) {
4345 $refers[$arrayKey]++;
4346 } else {
4347 $refers[$arrayKey] = 1;
4349 if ( isset( $refers[$legacyArrayKey] ) ) {
4350 $refers[$legacyArrayKey]++;
4351 } else {
4352 $refers[$legacyArrayKey] = 1;
4355 # Don't number the heading if it is the only one (looks silly)
4356 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4357 # the two are different if the line contains a link
4358 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4361 # Create the anchor for linking from the TOC to the section
4362 $anchor = $safeHeadline;
4363 $legacyAnchor = $legacyHeadline;
4364 if ( $refers[$arrayKey] > 1 ) {
4365 $anchor .= '_' . $refers[$arrayKey];
4367 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4368 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4370 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4371 $toc .= Linker::tocLine( $anchor, $tocline,
4372 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4375 # Add the section to the section tree
4376 # Find the DOM node for this header
4377 while ( $node && !$isTemplate ) {
4378 if ( $node->getName() === 'h' ) {
4379 $bits = $node->splitHeading();
4380 if ( $bits['i'] == $sectionIndex ) {
4381 break;
4384 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4385 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4386 $node = $node->getNextSibling();
4388 $tocraw[] = array(
4389 'toclevel' => $toclevel,
4390 'level' => $level,
4391 'line' => $tocline,
4392 'number' => $numbering,
4393 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4394 'fromtitle' => $titleText,
4395 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
4396 'anchor' => $anchor,
4399 # give headline the correct <h#> tag
4400 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4401 // Output edit section links as markers with styles that can be customized by skins
4402 if ( $isTemplate ) {
4403 # Put a T flag in the section identifier, to indicate to extractSections()
4404 # that sections inside <includeonly> should be counted.
4405 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4406 } else {
4407 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4409 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4410 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4411 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4412 // so we don't have to worry about a user trying to input one of these markers directly.
4413 // We use a page and section attribute to stop the language converter from converting these important bits
4414 // of data, but put the headline hint inside a content block because the language converter is supposed to
4415 // be able to convert that piece of data.
4416 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4417 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4418 if ( isset( $editlinkArgs[2] ) ) {
4419 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4420 } else {
4421 $editlink .= '/>';
4423 } else {
4424 $editlink = '';
4426 $head[$headlineCount] = Linker::makeHeadline( $level,
4427 $matches['attrib'][$headlineCount], $anchor, $headline,
4428 $editlink, $legacyAnchor );
4430 $headlineCount++;
4433 $this->setOutputType( $oldType );
4435 # Never ever show TOC if no headers
4436 if ( $numVisible < 1 ) {
4437 $enoughToc = false;
4440 if ( $enoughToc ) {
4441 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4442 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4444 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4445 $this->mOutput->setTOCHTML( $toc );
4448 if ( $isMain ) {
4449 $this->mOutput->setSections( $tocraw );
4452 # split up and insert constructed headlines
4453 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4454 $i = 0;
4456 // build an array of document sections
4457 $sections = array();
4458 foreach ( $blocks as $block ) {
4459 // $head is zero-based, sections aren't.
4460 if ( empty( $head[$i - 1] ) ) {
4461 $sections[$i] = $block;
4462 } else {
4463 $sections[$i] = $head[$i - 1] . $block;
4467 * Send a hook, one per section.
4468 * The idea here is to be able to make section-level DIVs, but to do so in a
4469 * lower-impact, more correct way than r50769
4471 * $this : caller
4472 * $section : the section number
4473 * &$sectionContent : ref to the content of the section
4474 * $showEditLinks : boolean describing whether this section has an edit link
4476 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4478 $i++;
4481 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4482 // append the TOC at the beginning
4483 // Top anchor now in skin
4484 $sections[0] = $sections[0] . $toc . "\n";
4487 $full .= join( '', $sections );
4489 if ( $this->mForceTocPosition ) {
4490 return str_replace( '<!--MWTOC-->', $toc, $full );
4491 } else {
4492 return $full;
4497 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4498 * conversion, substitting signatures, {{subst:}} templates, etc.
4500 * @param string $text the text to transform
4501 * @param $title Title: the Title object for the current article
4502 * @param $user User: the User object describing the current user
4503 * @param $options ParserOptions: parsing options
4504 * @param $clearState Boolean: whether to clear the parser state first
4505 * @return String: the altered wiki markup
4507 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
4508 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4509 $this->setUser( $user );
4511 $pairs = array(
4512 "\r\n" => "\n",
4514 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4515 if ( $options->getPreSaveTransform() ) {
4516 $text = $this->pstPass2( $text, $user );
4518 $text = $this->mStripState->unstripBoth( $text );
4520 $this->setUser( null ); #Reset
4522 return $text;
4526 * Pre-save transform helper function
4527 * @private
4529 * @param $text string
4530 * @param $user User
4532 * @return string
4534 function pstPass2( $text, $user ) {
4535 global $wgContLang;
4537 # Note: This is the timestamp saved as hardcoded wikitext to
4538 # the database, we use $wgContLang here in order to give
4539 # everyone the same signature and use the default one rather
4540 # than the one selected in each user's preferences.
4541 # (see also bug 12815)
4542 $ts = $this->mOptions->getTimestamp();
4543 $timestamp = MWTimestamp::getLocalInstance( $ts );
4544 $ts = $timestamp->format( 'YmdHis' );
4545 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4547 # Allow translation of timezones through wiki. format() can return
4548 # whatever crap the system uses, localised or not, so we cannot
4549 # ship premade translations.
4550 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4551 $msg = wfMessage( $key )->inContentLanguage();
4552 if ( $msg->exists() ) {
4553 $tzMsg = $msg->text();
4556 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4558 # Variable replacement
4559 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4560 $text = $this->replaceVariables( $text );
4562 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4563 # which may corrupt this parser instance via its wfMessage()->text() call-
4565 # Signatures
4566 $sigText = $this->getUserSig( $user );
4567 $text = strtr( $text, array(
4568 '~~~~~' => $d,
4569 '~~~~' => "$sigText $d",
4570 '~~~' => $sigText
4571 ) );
4573 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4574 $tc = '[' . Title::legalChars() . ']';
4575 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4577 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4578 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4579 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4580 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4582 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4583 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4584 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4585 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4587 $t = $this->mTitle->getText();
4588 $m = array();
4589 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4590 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4591 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4592 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4593 } else {
4594 # if there's no context, don't bother duplicating the title
4595 $text = preg_replace( $p2, '[[\\1]]', $text );
4598 # Trim trailing whitespace
4599 $text = rtrim( $text );
4601 return $text;
4605 * Fetch the user's signature text, if any, and normalize to
4606 * validated, ready-to-insert wikitext.
4607 * If you have pre-fetched the nickname or the fancySig option, you can
4608 * specify them here to save a database query.
4609 * Do not reuse this parser instance after calling getUserSig(),
4610 * as it may have changed if it's the $wgParser.
4612 * @param $user User
4613 * @param string|bool $nickname nickname to use or false to use user's default nickname
4614 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4615 * or null to use default value
4616 * @return string
4618 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4619 global $wgMaxSigChars;
4621 $username = $user->getName();
4623 # If not given, retrieve from the user object.
4624 if ( $nickname === false ) {
4625 $nickname = $user->getOption( 'nickname' );
4628 if ( is_null( $fancySig ) ) {
4629 $fancySig = $user->getBoolOption( 'fancysig' );
4632 $nickname = $nickname == null ? $username : $nickname;
4634 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4635 $nickname = $username;
4636 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4637 } elseif ( $fancySig !== false ) {
4638 # Sig. might contain markup; validate this
4639 if ( $this->validateSig( $nickname ) !== false ) {
4640 # Validated; clean up (if needed) and return it
4641 return $this->cleanSig( $nickname, true );
4642 } else {
4643 # Failed to validate; fall back to the default
4644 $nickname = $username;
4645 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4649 # Make sure nickname doesnt get a sig in a sig
4650 $nickname = self::cleanSigInSig( $nickname );
4652 # If we're still here, make it a link to the user page
4653 $userText = wfEscapeWikiText( $username );
4654 $nickText = wfEscapeWikiText( $nickname );
4655 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4657 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4661 * Check that the user's signature contains no bad XML
4663 * @param $text String
4664 * @return mixed An expanded string, or false if invalid.
4666 function validateSig( $text ) {
4667 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4671 * Clean up signature text
4673 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4674 * 2) Substitute all transclusions
4676 * @param $text String
4677 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4678 * @return String: signature text
4680 public function cleanSig( $text, $parsing = false ) {
4681 if ( !$parsing ) {
4682 global $wgTitle;
4683 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4686 # Option to disable this feature
4687 if ( !$this->mOptions->getCleanSignatures() ) {
4688 return $text;
4691 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4692 # => Move this logic to braceSubstitution()
4693 $substWord = MagicWord::get( 'subst' );
4694 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4695 $substText = '{{' . $substWord->getSynonym( 0 );
4697 $text = preg_replace( $substRegex, $substText, $text );
4698 $text = self::cleanSigInSig( $text );
4699 $dom = $this->preprocessToDom( $text );
4700 $frame = $this->getPreprocessor()->newFrame();
4701 $text = $frame->expand( $dom );
4703 if ( !$parsing ) {
4704 $text = $this->mStripState->unstripBoth( $text );
4707 return $text;
4711 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4713 * @param $text String
4714 * @return String: signature text with /~{3,5}/ removed
4716 public static function cleanSigInSig( $text ) {
4717 $text = preg_replace( '/~{3,5}/', '', $text );
4718 return $text;
4722 * Set up some variables which are usually set up in parse()
4723 * so that an external function can call some class members with confidence
4725 * @param $title Title|null
4726 * @param $options ParserOptions
4727 * @param $outputType
4728 * @param $clearState bool
4730 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4731 $this->startParse( $title, $options, $outputType, $clearState );
4735 * @param $title Title|null
4736 * @param $options ParserOptions
4737 * @param $outputType
4738 * @param $clearState bool
4740 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4741 $this->setTitle( $title );
4742 $this->mOptions = $options;
4743 $this->setOutputType( $outputType );
4744 if ( $clearState ) {
4745 $this->clearState();
4750 * Wrapper for preprocess()
4752 * @param string $text the text to preprocess
4753 * @param $options ParserOptions: options
4754 * @param $title Title object or null to use $wgTitle
4755 * @return String
4757 public function transformMsg( $text, $options, $title = null ) {
4758 static $executing = false;
4760 # Guard against infinite recursion
4761 if ( $executing ) {
4762 return $text;
4764 $executing = true;
4766 wfProfileIn( __METHOD__ );
4767 if ( !$title ) {
4768 global $wgTitle;
4769 $title = $wgTitle;
4772 $text = $this->preprocess( $text, $title, $options );
4774 $executing = false;
4775 wfProfileOut( __METHOD__ );
4776 return $text;
4780 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4781 * The callback should have the following form:
4782 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4784 * Transform and return $text. Use $parser for any required context, e.g. use
4785 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4787 * Hooks may return extended information by returning an array, of which the
4788 * first numbered element (index 0) must be the return string, and all other
4789 * entries are extracted into local variables within an internal function
4790 * in the Parser class.
4792 * This interface (introduced r61913) appears to be undocumented, but
4793 * 'markerName' is used by some core tag hooks to override which strip
4794 * array their results are placed in. **Use great caution if attempting
4795 * this interface, as it is not documented and injudicious use could smash
4796 * private variables.**
4798 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4799 * @param $callback Mixed: the callback function (and object) to use for the tag
4800 * @throws MWException
4801 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4803 public function setHook( $tag, $callback ) {
4804 $tag = strtolower( $tag );
4805 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4806 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4808 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4809 $this->mTagHooks[$tag] = $callback;
4810 if ( !in_array( $tag, $this->mStripList ) ) {
4811 $this->mStripList[] = $tag;
4814 return $oldVal;
4818 * As setHook(), but letting the contents be parsed.
4820 * Transparent tag hooks are like regular XML-style tag hooks, except they
4821 * operate late in the transformation sequence, on HTML instead of wikitext.
4823 * This is probably obsoleted by things dealing with parser frames?
4824 * The only extension currently using it is geoserver.
4826 * @since 1.10
4827 * @todo better document or deprecate this
4829 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4830 * @param $callback Mixed: the callback function (and object) to use for the tag
4831 * @throws MWException
4832 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4834 function setTransparentTagHook( $tag, $callback ) {
4835 $tag = strtolower( $tag );
4836 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4837 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4839 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4840 $this->mTransparentTagHooks[$tag] = $callback;
4842 return $oldVal;
4846 * Remove all tag hooks
4848 function clearTagHooks() {
4849 $this->mTagHooks = array();
4850 $this->mFunctionTagHooks = array();
4851 $this->mStripList = $this->mDefaultStripList;
4855 * Create a function, e.g. {{sum:1|2|3}}
4856 * The callback function should have the form:
4857 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4859 * Or with SFH_OBJECT_ARGS:
4860 * function myParserFunction( $parser, $frame, $args ) { ... }
4862 * The callback may either return the text result of the function, or an array with the text
4863 * in element 0, and a number of flags in the other elements. The names of the flags are
4864 * specified in the keys. Valid flags are:
4865 * found The text returned is valid, stop processing the template. This
4866 * is on by default.
4867 * nowiki Wiki markup in the return value should be escaped
4868 * isHTML The returned text is HTML, armour it against wikitext transformation
4870 * @param string $id The magic word ID
4871 * @param $callback Mixed: the callback function (and object) to use
4872 * @param $flags Integer: a combination of the following flags:
4873 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4875 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4876 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4877 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4878 * the arguments, and to control the way they are expanded.
4880 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4881 * arguments, for instance:
4882 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4884 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4885 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4886 * working if/when this is changed.
4888 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4889 * expansion.
4891 * Please read the documentation in includes/parser/Preprocessor.php for more information
4892 * about the methods available in PPFrame and PPNode.
4894 * @throws MWException
4895 * @return string|callback The old callback function for this name, if any
4897 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4898 global $wgContLang;
4900 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4901 $this->mFunctionHooks[$id] = array( $callback, $flags );
4903 # Add to function cache
4904 $mw = MagicWord::get( $id );
4905 if ( !$mw ) {
4906 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
4909 $synonyms = $mw->getSynonyms();
4910 $sensitive = intval( $mw->isCaseSensitive() );
4912 foreach ( $synonyms as $syn ) {
4913 # Case
4914 if ( !$sensitive ) {
4915 $syn = $wgContLang->lc( $syn );
4917 # Add leading hash
4918 if ( !( $flags & SFH_NO_HASH ) ) {
4919 $syn = '#' . $syn;
4921 # Remove trailing colon
4922 if ( substr( $syn, -1, 1 ) === ':' ) {
4923 $syn = substr( $syn, 0, -1 );
4925 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4927 return $oldVal;
4931 * Get all registered function hook identifiers
4933 * @return Array
4935 function getFunctionHooks() {
4936 return array_keys( $this->mFunctionHooks );
4940 * Create a tag function, e.g. "<test>some stuff</test>".
4941 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4942 * Unlike parser functions, their content is not preprocessed.
4943 * @param $tag
4944 * @param $callback
4945 * @param $flags
4946 * @throws MWException
4947 * @return null
4949 function setFunctionTagHook( $tag, $callback, $flags ) {
4950 $tag = strtolower( $tag );
4951 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4952 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4954 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4955 $this->mFunctionTagHooks[$tag] : null;
4956 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4958 if ( !in_array( $tag, $this->mStripList ) ) {
4959 $this->mStripList[] = $tag;
4962 return $old;
4966 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4967 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4968 * Placeholders created in Skin::makeLinkObj()
4970 * @param $text string
4971 * @param $options int
4973 * @return array of link CSS classes, indexed by PDBK.
4975 function replaceLinkHolders( &$text, $options = 0 ) {
4976 return $this->mLinkHolders->replace( $text );
4980 * Replace "<!--LINK-->" link placeholders with plain text of links
4981 * (not HTML-formatted).
4983 * @param $text String
4984 * @return String
4986 function replaceLinkHoldersText( $text ) {
4987 return $this->mLinkHolders->replaceText( $text );
4991 * Renders an image gallery from a text with one line per image.
4992 * text labels may be given by using |-style alternative text. E.g.
4993 * Image:one.jpg|The number "1"
4994 * Image:tree.jpg|A tree
4995 * given as text will return the HTML of a gallery with two images,
4996 * labeled 'The number "1"' and
4997 * 'A tree'.
4999 * @param string $text
5000 * @param array $params
5001 * @return string HTML
5003 function renderImageGallery( $text, $params ) {
5004 wfProfileIn( __METHOD__ );
5005 $ig = new ImageGallery();
5006 $ig->setContextTitle( $this->mTitle );
5007 $ig->setShowBytes( false );
5008 $ig->setShowFilename( false );
5009 $ig->setParser( $this );
5010 $ig->setHideBadImages();
5011 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5013 if ( isset( $params['showfilename'] ) ) {
5014 $ig->setShowFilename( true );
5015 } else {
5016 $ig->setShowFilename( false );
5018 if ( isset( $params['caption'] ) ) {
5019 $caption = $params['caption'];
5020 $caption = htmlspecialchars( $caption );
5021 $caption = $this->replaceInternalLinks( $caption );
5022 $ig->setCaptionHtml( $caption );
5024 if ( isset( $params['perrow'] ) ) {
5025 $ig->setPerRow( $params['perrow'] );
5027 if ( isset( $params['widths'] ) ) {
5028 $ig->setWidths( $params['widths'] );
5030 if ( isset( $params['heights'] ) ) {
5031 $ig->setHeights( $params['heights'] );
5034 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5036 $lines = StringUtils::explode( "\n", $text );
5037 foreach ( $lines as $line ) {
5038 # match lines like these:
5039 # Image:someimage.jpg|This is some image
5040 $matches = array();
5041 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5042 # Skip empty lines
5043 if ( count( $matches ) == 0 ) {
5044 continue;
5047 if ( strpos( $matches[0], '%' ) !== false ) {
5048 $matches[1] = rawurldecode( $matches[1] );
5050 $title = Title::newFromText( $matches[1], NS_FILE );
5051 if ( is_null( $title ) ) {
5052 # Bogus title. Ignore these so we don't bomb out later.
5053 continue;
5056 # We need to get what handler the file uses, to figure out parameters.
5057 # Note, a hook can overide the file name, and chose an entirely different
5058 # file (which potentially could be of a different type and have different handler).
5059 $options = array();
5060 $descQuery = false;
5061 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5062 array( $this, $title, &$options, &$descQuery ) );
5063 # Don't register it now, as ImageGallery does that later.
5064 $file = $this->fetchFileNoRegister( $title, $options );
5065 $handler = $file ? $file->getHandler() : false;
5067 wfProfileIn( __METHOD__ . '-getMagicWord' );
5068 $paramMap = array(
5069 'img_alt' => 'gallery-internal-alt',
5070 'img_link' => 'gallery-internal-link',
5072 if ( $handler ) {
5073 $paramMap = $paramMap + $handler->getParamMap();
5074 // We don't want people to specify per-image widths.
5075 // Additionally the width parameter would need special casing anyhow.
5076 unset( $paramMap['img_width'] );
5079 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5080 wfProfileOut( __METHOD__ . '-getMagicWord' );
5082 $label = '';
5083 $alt = '';
5084 $link = '';
5085 $handlerOptions = array();
5086 if ( isset( $matches[3] ) ) {
5087 // look for an |alt= definition while trying not to break existing
5088 // captions with multiple pipes (|) in it, until a more sensible grammar
5089 // is defined for images in galleries
5091 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5092 // splitting on '|' is a bit odd, and different from makeImage.
5093 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5094 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5096 foreach ( $parameterMatches as $parameterMatch ) {
5097 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5098 if ( $magicName ) {
5099 $paramName = $paramMap[$magicName];
5101 switch( $paramName ) {
5102 case 'gallery-internal-alt':
5103 $alt = $this->stripAltText( $match, false );
5104 break;
5105 case 'gallery-internal-link':
5106 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5107 $chars = self::EXT_LINK_URL_CLASS;
5108 $prots = $this->mUrlProtocols;
5109 //check to see if link matches an absolute url, if not then it must be a wiki link.
5110 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5111 $link = $linkValue;
5112 } else {
5113 $localLinkTitle = Title::newFromText( $linkValue );
5114 if ( $localLinkTitle !== null ) {
5115 $link = $localLinkTitle->getLocalURL();
5118 break;
5119 default:
5120 // Must be a handler specific parameter.
5121 if ( $handler->validateParam( $paramName, $match ) ) {
5122 $handlerOptions[$paramName] = $match;
5123 } else {
5124 // Guess not. Append it to the caption.
5125 wfDebug( "$parameterMatch failed parameter validation" );
5126 $label .= '|' . $parameterMatch;
5130 } else {
5131 // concatenate all other pipes
5132 $label .= '|' . $parameterMatch;
5135 // remove the first pipe
5136 $label = substr( $label, 1 );
5139 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5141 $html = $ig->toHTML();
5142 wfProfileOut( __METHOD__ );
5143 return $html;
5147 * @param $handler
5148 * @return array
5150 function getImageParams( $handler ) {
5151 if ( $handler ) {
5152 $handlerClass = get_class( $handler );
5153 } else {
5154 $handlerClass = '';
5156 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5157 # Initialise static lists
5158 static $internalParamNames = array(
5159 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5160 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5161 'bottom', 'text-bottom' ),
5162 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5163 'upright', 'border', 'link', 'alt', 'class' ),
5165 static $internalParamMap;
5166 if ( !$internalParamMap ) {
5167 $internalParamMap = array();
5168 foreach ( $internalParamNames as $type => $names ) {
5169 foreach ( $names as $name ) {
5170 $magicName = str_replace( '-', '_', "img_$name" );
5171 $internalParamMap[$magicName] = array( $type, $name );
5176 # Add handler params
5177 $paramMap = $internalParamMap;
5178 if ( $handler ) {
5179 $handlerParamMap = $handler->getParamMap();
5180 foreach ( $handlerParamMap as $magic => $paramName ) {
5181 $paramMap[$magic] = array( 'handler', $paramName );
5184 $this->mImageParams[$handlerClass] = $paramMap;
5185 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5187 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5191 * Parse image options text and use it to make an image
5193 * @param $title Title
5194 * @param $options String
5195 * @param $holders LinkHolderArray|bool
5196 * @return string HTML
5198 function makeImage( $title, $options, $holders = false ) {
5199 # Check if the options text is of the form "options|alt text"
5200 # Options are:
5201 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5202 # * left no resizing, just left align. label is used for alt= only
5203 # * right same, but right aligned
5204 # * none same, but not aligned
5205 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5206 # * center center the image
5207 # * frame Keep original image size, no magnify-button.
5208 # * framed Same as "frame"
5209 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5210 # * upright reduce width for upright images, rounded to full __0 px
5211 # * border draw a 1px border around the image
5212 # * alt Text for HTML alt attribute (defaults to empty)
5213 # * class Set a class for img node
5214 # * link Set the target of the image link. Can be external, interwiki, or local
5215 # vertical-align values (no % or length right now):
5216 # * baseline
5217 # * sub
5218 # * super
5219 # * top
5220 # * text-top
5221 # * middle
5222 # * bottom
5223 # * text-bottom
5225 $parts = StringUtils::explode( "|", $options );
5227 # Give extensions a chance to select the file revision for us
5228 $options = array();
5229 $descQuery = false;
5230 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5231 array( $this, $title, &$options, &$descQuery ) );
5232 # Fetch and register the file (file title may be different via hooks)
5233 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5235 # Get parameter map
5236 $handler = $file ? $file->getHandler() : false;
5238 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5240 if ( !$file ) {
5241 $this->addTrackingCategory( 'broken-file-category' );
5244 # Process the input parameters
5245 $caption = '';
5246 $params = array( 'frame' => array(), 'handler' => array(),
5247 'horizAlign' => array(), 'vertAlign' => array() );
5248 foreach ( $parts as $part ) {
5249 $part = trim( $part );
5250 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5251 $validated = false;
5252 if ( isset( $paramMap[$magicName] ) ) {
5253 list( $type, $paramName ) = $paramMap[$magicName];
5255 # Special case; width and height come in one variable together
5256 if ( $type === 'handler' && $paramName === 'width' ) {
5257 $parsedWidthParam = $this->parseWidthParam( $value );
5258 if ( isset( $parsedWidthParam['width'] ) ) {
5259 $width = $parsedWidthParam['width'];
5260 if ( $handler->validateParam( 'width', $width ) ) {
5261 $params[$type]['width'] = $width;
5262 $validated = true;
5265 if ( isset( $parsedWidthParam['height'] ) ) {
5266 $height = $parsedWidthParam['height'];
5267 if ( $handler->validateParam( 'height', $height ) ) {
5268 $params[$type]['height'] = $height;
5269 $validated = true;
5272 # else no validation -- bug 13436
5273 } else {
5274 if ( $type === 'handler' ) {
5275 # Validate handler parameter
5276 $validated = $handler->validateParam( $paramName, $value );
5277 } else {
5278 # Validate internal parameters
5279 switch ( $paramName ) {
5280 case 'manualthumb':
5281 case 'alt':
5282 case 'class':
5283 # @todo FIXME: Possibly check validity here for
5284 # manualthumb? downstream behavior seems odd with
5285 # missing manual thumbs.
5286 $validated = true;
5287 $value = $this->stripAltText( $value, $holders );
5288 break;
5289 case 'link':
5290 $chars = self::EXT_LINK_URL_CLASS;
5291 $prots = $this->mUrlProtocols;
5292 if ( $value === '' ) {
5293 $paramName = 'no-link';
5294 $value = true;
5295 $validated = true;
5296 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5297 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5298 $paramName = 'link-url';
5299 $this->mOutput->addExternalLink( $value );
5300 if ( $this->mOptions->getExternalLinkTarget() ) {
5301 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5303 $validated = true;
5305 } else {
5306 $linkTitle = Title::newFromText( $value );
5307 if ( $linkTitle ) {
5308 $paramName = 'link-title';
5309 $value = $linkTitle;
5310 $this->mOutput->addLink( $linkTitle );
5311 $validated = true;
5314 break;
5315 default:
5316 # Most other things appear to be empty or numeric...
5317 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5321 if ( $validated ) {
5322 $params[$type][$paramName] = $value;
5326 if ( !$validated ) {
5327 $caption = $part;
5331 # Process alignment parameters
5332 if ( $params['horizAlign'] ) {
5333 $params['frame']['align'] = key( $params['horizAlign'] );
5335 if ( $params['vertAlign'] ) {
5336 $params['frame']['valign'] = key( $params['vertAlign'] );
5339 $params['frame']['caption'] = $caption;
5341 # Will the image be presented in a frame, with the caption below?
5342 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5343 isset( $params['frame']['framed'] ) ||
5344 isset( $params['frame']['thumbnail'] ) ||
5345 isset( $params['frame']['manualthumb'] );
5347 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5348 # came to also set the caption, ordinary text after the image -- which
5349 # makes no sense, because that just repeats the text multiple times in
5350 # screen readers. It *also* came to set the title attribute.
5352 # Now that we have an alt attribute, we should not set the alt text to
5353 # equal the caption: that's worse than useless, it just repeats the
5354 # text. This is the framed/thumbnail case. If there's no caption, we
5355 # use the unnamed parameter for alt text as well, just for the time be-
5356 # ing, if the unnamed param is set and the alt param is not.
5358 # For the future, we need to figure out if we want to tweak this more,
5359 # e.g., introducing a title= parameter for the title; ignoring the un-
5360 # named parameter entirely for images without a caption; adding an ex-
5361 # plicit caption= parameter and preserving the old magic unnamed para-
5362 # meter for BC; ...
5363 if ( $imageIsFramed ) { # Framed image
5364 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5365 # No caption or alt text, add the filename as the alt text so
5366 # that screen readers at least get some description of the image
5367 $params['frame']['alt'] = $title->getText();
5369 # Do not set $params['frame']['title'] because tooltips don't make sense
5370 # for framed images
5371 } else { # Inline image
5372 if ( !isset( $params['frame']['alt'] ) ) {
5373 # No alt text, use the "caption" for the alt text
5374 if ( $caption !== '' ) {
5375 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5376 } else {
5377 # No caption, fall back to using the filename for the
5378 # alt text
5379 $params['frame']['alt'] = $title->getText();
5382 # Use the "caption" for the tooltip text
5383 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5386 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5388 # Linker does the rest
5389 $time = isset( $options['time'] ) ? $options['time'] : false;
5390 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5391 $time, $descQuery, $this->mOptions->getThumbSize() );
5393 # Give the handler a chance to modify the parser object
5394 if ( $handler ) {
5395 $handler->parserTransformHook( $this, $file );
5398 return $ret;
5402 * @param $caption
5403 * @param $holders LinkHolderArray
5404 * @return mixed|String
5406 protected function stripAltText( $caption, $holders ) {
5407 # Strip bad stuff out of the title (tooltip). We can't just use
5408 # replaceLinkHoldersText() here, because if this function is called
5409 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5410 if ( $holders ) {
5411 $tooltip = $holders->replaceText( $caption );
5412 } else {
5413 $tooltip = $this->replaceLinkHoldersText( $caption );
5416 # make sure there are no placeholders in thumbnail attributes
5417 # that are later expanded to html- so expand them now and
5418 # remove the tags
5419 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5420 $tooltip = Sanitizer::stripAllTags( $tooltip );
5422 return $tooltip;
5426 * Set a flag in the output object indicating that the content is dynamic and
5427 * shouldn't be cached.
5429 function disableCache() {
5430 wfDebug( "Parser output marked as uncacheable.\n" );
5431 if ( !$this->mOutput ) {
5432 throw new MWException( __METHOD__ .
5433 " can only be called when actually parsing something" );
5435 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5436 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5440 * Callback from the Sanitizer for expanding items found in HTML attribute
5441 * values, so they can be safely tested and escaped.
5443 * @param $text String
5444 * @param $frame PPFrame
5445 * @return String
5447 function attributeStripCallback( &$text, $frame = false ) {
5448 $text = $this->replaceVariables( $text, $frame );
5449 $text = $this->mStripState->unstripBoth( $text );
5450 return $text;
5454 * Accessor
5456 * @return array
5458 function getTags() {
5459 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
5463 * Replace transparent tags in $text with the values given by the callbacks.
5465 * Transparent tag hooks are like regular XML-style tag hooks, except they
5466 * operate late in the transformation sequence, on HTML instead of wikitext.
5468 * @param $text string
5470 * @return string
5472 function replaceTransparentTags( $text ) {
5473 $matches = array();
5474 $elements = array_keys( $this->mTransparentTagHooks );
5475 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5476 $replacements = array();
5478 foreach ( $matches as $marker => $data ) {
5479 list( $element, $content, $params, $tag ) = $data;
5480 $tagName = strtolower( $element );
5481 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5482 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
5483 } else {
5484 $output = $tag;
5486 $replacements[$marker] = $output;
5488 return strtr( $text, $replacements );
5492 * Break wikitext input into sections, and either pull or replace
5493 * some particular section's text.
5495 * External callers should use the getSection and replaceSection methods.
5497 * @param string $text Page wikitext
5498 * @param string $section a section identifier string of the form:
5499 * "<flag1> - <flag2> - ... - <section number>"
5501 * Currently the only recognised flag is "T", which means the target section number
5502 * was derived during a template inclusion parse, in other words this is a template
5503 * section edit link. If no flags are given, it was an ordinary section edit link.
5504 * This flag is required to avoid a section numbering mismatch when a section is
5505 * enclosed by "<includeonly>" (bug 6563).
5507 * The section number 0 pulls the text before the first heading; other numbers will
5508 * pull the given section along with its lower-level subsections. If the section is
5509 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5511 * Section 0 is always considered to exist, even if it only contains the empty
5512 * string. If $text is the empty string and section 0 is replaced, $newText is
5513 * returned.
5515 * @param string $mode one of "get" or "replace"
5516 * @param string $newText replacement text for section data.
5517 * @return String: for "get", the extracted section text.
5518 * for "replace", the whole page with the section replaced.
5520 private function extractSections( $text, $section, $mode, $newText = '' ) {
5521 global $wgTitle; # not generally used but removes an ugly failure mode
5522 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5523 $outText = '';
5524 $frame = $this->getPreprocessor()->newFrame();
5526 # Process section extraction flags
5527 $flags = 0;
5528 $sectionParts = explode( '-', $section );
5529 $sectionIndex = array_pop( $sectionParts );
5530 foreach ( $sectionParts as $part ) {
5531 if ( $part === 'T' ) {
5532 $flags |= self::PTD_FOR_INCLUSION;
5536 # Check for empty input
5537 if ( strval( $text ) === '' ) {
5538 # Only sections 0 and T-0 exist in an empty document
5539 if ( $sectionIndex == 0 ) {
5540 if ( $mode === 'get' ) {
5541 return '';
5542 } else {
5543 return $newText;
5545 } else {
5546 if ( $mode === 'get' ) {
5547 return $newText;
5548 } else {
5549 return $text;
5554 # Preprocess the text
5555 $root = $this->preprocessToDom( $text, $flags );
5557 # <h> nodes indicate section breaks
5558 # They can only occur at the top level, so we can find them by iterating the root's children
5559 $node = $root->getFirstChild();
5561 # Find the target section
5562 if ( $sectionIndex == 0 ) {
5563 # Section zero doesn't nest, level=big
5564 $targetLevel = 1000;
5565 } else {
5566 while ( $node ) {
5567 if ( $node->getName() === 'h' ) {
5568 $bits = $node->splitHeading();
5569 if ( $bits['i'] == $sectionIndex ) {
5570 $targetLevel = $bits['level'];
5571 break;
5574 if ( $mode === 'replace' ) {
5575 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5577 $node = $node->getNextSibling();
5581 if ( !$node ) {
5582 # Not found
5583 if ( $mode === 'get' ) {
5584 return $newText;
5585 } else {
5586 return $text;
5590 # Find the end of the section, including nested sections
5591 do {
5592 if ( $node->getName() === 'h' ) {
5593 $bits = $node->splitHeading();
5594 $curLevel = $bits['level'];
5595 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5596 break;
5599 if ( $mode === 'get' ) {
5600 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5602 $node = $node->getNextSibling();
5603 } while ( $node );
5605 # Write out the remainder (in replace mode only)
5606 if ( $mode === 'replace' ) {
5607 # Output the replacement text
5608 # Add two newlines on -- trailing whitespace in $newText is conventionally
5609 # stripped by the editor, so we need both newlines to restore the paragraph gap
5610 # Only add trailing whitespace if there is newText
5611 if ( $newText != "" ) {
5612 $outText .= $newText . "\n\n";
5615 while ( $node ) {
5616 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5617 $node = $node->getNextSibling();
5621 if ( is_string( $outText ) ) {
5622 # Re-insert stripped tags
5623 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5626 return $outText;
5630 * This function returns the text of a section, specified by a number ($section).
5631 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5632 * the first section before any such heading (section 0).
5634 * If a section contains subsections, these are also returned.
5636 * @param string $text text to look in
5637 * @param string $section section identifier
5638 * @param string $deftext default to return if section is not found
5639 * @return string text of the requested section
5641 public function getSection( $text, $section, $deftext = '' ) {
5642 return $this->extractSections( $text, $section, "get", $deftext );
5646 * This function returns $oldtext after the content of the section
5647 * specified by $section has been replaced with $text. If the target
5648 * section does not exist, $oldtext is returned unchanged.
5650 * @param string $oldtext former text of the article
5651 * @param int $section section identifier
5652 * @param string $text replacing text
5653 * @return String: modified text
5655 public function replaceSection( $oldtext, $section, $text ) {
5656 return $this->extractSections( $oldtext, $section, "replace", $text );
5660 * Get the ID of the revision we are parsing
5662 * @return Mixed: integer or null
5664 function getRevisionId() {
5665 return $this->mRevisionId;
5669 * Get the revision object for $this->mRevisionId
5671 * @return Revision|null either a Revision object or null
5673 protected function getRevisionObject() {
5674 if ( !is_null( $this->mRevisionObject ) ) {
5675 return $this->mRevisionObject;
5677 if ( is_null( $this->mRevisionId ) ) {
5678 return null;
5681 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5682 return $this->mRevisionObject;
5686 * Get the timestamp associated with the current revision, adjusted for
5687 * the default server-local timestamp
5689 function getRevisionTimestamp() {
5690 if ( is_null( $this->mRevisionTimestamp ) ) {
5691 wfProfileIn( __METHOD__ );
5693 global $wgContLang;
5695 $revObject = $this->getRevisionObject();
5696 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5698 # The cryptic '' timezone parameter tells to use the site-default
5699 # timezone offset instead of the user settings.
5701 # Since this value will be saved into the parser cache, served
5702 # to other users, and potentially even used inside links and such,
5703 # it needs to be consistent for all visitors.
5704 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5706 wfProfileOut( __METHOD__ );
5708 return $this->mRevisionTimestamp;
5712 * Get the name of the user that edited the last revision
5714 * @return String: user name
5716 function getRevisionUser() {
5717 if ( is_null( $this->mRevisionUser ) ) {
5718 $revObject = $this->getRevisionObject();
5720 # if this template is subst: the revision id will be blank,
5721 # so just use the current user's name
5722 if ( $revObject ) {
5723 $this->mRevisionUser = $revObject->getUserText();
5724 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5725 $this->mRevisionUser = $this->getUser()->getName();
5728 return $this->mRevisionUser;
5732 * Mutator for $mDefaultSort
5734 * @param string $sort New value
5736 public function setDefaultSort( $sort ) {
5737 $this->mDefaultSort = $sort;
5738 $this->mOutput->setProperty( 'defaultsort', $sort );
5742 * Accessor for $mDefaultSort
5743 * Will use the empty string if none is set.
5745 * This value is treated as a prefix, so the
5746 * empty string is equivalent to sorting by
5747 * page name.
5749 * @return string
5751 public function getDefaultSort() {
5752 if ( $this->mDefaultSort !== false ) {
5753 return $this->mDefaultSort;
5754 } else {
5755 return '';
5760 * Accessor for $mDefaultSort
5761 * Unlike getDefaultSort(), will return false if none is set
5763 * @return string or false
5765 public function getCustomDefaultSort() {
5766 return $this->mDefaultSort;
5770 * Try to guess the section anchor name based on a wikitext fragment
5771 * presumably extracted from a heading, for example "Header" from
5772 * "== Header ==".
5774 * @param $text string
5776 * @return string
5778 public function guessSectionNameFromWikiText( $text ) {
5779 # Strip out wikitext links(they break the anchor)
5780 $text = $this->stripSectionName( $text );
5781 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5782 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5786 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5787 * instead. For use in redirects, since IE6 interprets Redirect: headers
5788 * as something other than UTF-8 (apparently?), resulting in breakage.
5790 * @param string $text The section name
5791 * @return string An anchor
5793 public function guessLegacySectionNameFromWikiText( $text ) {
5794 # Strip out wikitext links(they break the anchor)
5795 $text = $this->stripSectionName( $text );
5796 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5797 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5801 * Strips a text string of wikitext for use in a section anchor
5803 * Accepts a text string and then removes all wikitext from the
5804 * string and leaves only the resultant text (i.e. the result of
5805 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5806 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5807 * to create valid section anchors by mimicing the output of the
5808 * parser when headings are parsed.
5810 * @param string $text text string to be stripped of wikitext
5811 * for use in a Section anchor
5812 * @return string Filtered text string
5814 public function stripSectionName( $text ) {
5815 # Strip internal link markup
5816 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5817 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5819 # Strip external link markup
5820 # @todo FIXME: Not tolerant to blank link text
5821 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5822 # on how many empty links there are on the page - need to figure that out.
5823 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5825 # Parse wikitext quotes (italics & bold)
5826 $text = $this->doQuotes( $text );
5828 # Strip HTML tags
5829 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5830 return $text;
5834 * strip/replaceVariables/unstrip for preprocessor regression testing
5836 * @param $text string
5837 * @param $title Title
5838 * @param $options ParserOptions
5839 * @param $outputType int
5841 * @return string
5843 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5844 $this->startParse( $title, $options, $outputType, true );
5846 $text = $this->replaceVariables( $text );
5847 $text = $this->mStripState->unstripBoth( $text );
5848 $text = Sanitizer::removeHTMLtags( $text );
5849 return $text;
5853 * @param $text string
5854 * @param $title Title
5855 * @param $options ParserOptions
5856 * @return string
5858 function testPst( $text, Title $title, ParserOptions $options ) {
5859 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5863 * @param $text
5864 * @param $title Title
5865 * @param $options ParserOptions
5866 * @return string
5868 function testPreprocess( $text, Title $title, ParserOptions $options ) {
5869 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5873 * Call a callback function on all regions of the given text that are not
5874 * inside strip markers, and replace those regions with the return value
5875 * of the callback. For example, with input:
5877 * aaa<MARKER>bbb
5879 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5880 * two strings will be replaced with the value returned by the callback in
5881 * each case.
5883 * @param $s string
5884 * @param $callback
5886 * @return string
5888 function markerSkipCallback( $s, $callback ) {
5889 $i = 0;
5890 $out = '';
5891 while ( $i < strlen( $s ) ) {
5892 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5893 if ( $markerStart === false ) {
5894 $out .= call_user_func( $callback, substr( $s, $i ) );
5895 break;
5896 } else {
5897 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5898 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5899 if ( $markerEnd === false ) {
5900 $out .= substr( $s, $markerStart );
5901 break;
5902 } else {
5903 $markerEnd += strlen( self::MARKER_SUFFIX );
5904 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5905 $i = $markerEnd;
5909 return $out;
5913 * Remove any strip markers found in the given text.
5915 * @param $text Input string
5916 * @return string
5918 function killMarkers( $text ) {
5919 return $this->mStripState->killMarkers( $text );
5923 * Save the parser state required to convert the given half-parsed text to
5924 * HTML. "Half-parsed" in this context means the output of
5925 * recursiveTagParse() or internalParse(). This output has strip markers
5926 * from replaceVariables (extensionSubstitution() etc.), and link
5927 * placeholders from replaceLinkHolders().
5929 * Returns an array which can be serialized and stored persistently. This
5930 * array can later be loaded into another parser instance with
5931 * unserializeHalfParsedText(). The text can then be safely incorporated into
5932 * the return value of a parser hook.
5934 * @param $text string
5936 * @return array
5938 function serializeHalfParsedText( $text ) {
5939 wfProfileIn( __METHOD__ );
5940 $data = array(
5941 'text' => $text,
5942 'version' => self::HALF_PARSED_VERSION,
5943 'stripState' => $this->mStripState->getSubState( $text ),
5944 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5946 wfProfileOut( __METHOD__ );
5947 return $data;
5951 * Load the parser state given in the $data array, which is assumed to
5952 * have been generated by serializeHalfParsedText(). The text contents is
5953 * extracted from the array, and its markers are transformed into markers
5954 * appropriate for the current Parser instance. This transformed text is
5955 * returned, and can be safely included in the return value of a parser
5956 * hook.
5958 * If the $data array has been stored persistently, the caller should first
5959 * check whether it is still valid, by calling isValidHalfParsedText().
5961 * @param array $data Serialized data
5962 * @throws MWException
5963 * @return String
5965 function unserializeHalfParsedText( $data ) {
5966 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5967 throw new MWException( __METHOD__ . ': invalid version' );
5970 # First, extract the strip state.
5971 $texts = array( $data['text'] );
5972 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5974 # Now renumber links
5975 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
5977 # Should be good to go.
5978 return $texts[0];
5982 * Returns true if the given array, presumed to be generated by
5983 * serializeHalfParsedText(), is compatible with the current version of the
5984 * parser.
5986 * @param $data Array
5988 * @return bool
5990 function isValidHalfParsedText( $data ) {
5991 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
5995 * Parsed a width param of imagelink like 300px or 200x300px
5997 * @param $value String
5999 * @return array
6000 * @since 1.20
6002 public function parseWidthParam( $value ) {
6003 $parsedWidthParam = array();
6004 if ( $value === '' ) {
6005 return $parsedWidthParam;
6007 $m = array();
6008 # (bug 13500) In both cases (width/height and width only),
6009 # permit trailing "px" for backward compatibility.
6010 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6011 $width = intval( $m[1] );
6012 $height = intval( $m[2] );
6013 $parsedWidthParam['width'] = $width;
6014 $parsedWidthParam['height'] = $height;
6015 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6016 $width = intval( $value );
6017 $parsedWidthParam['width'] = $width;
6019 return $parsedWidthParam;