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
25 * @defgroup Parser Parser
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:
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
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
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';
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()
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 # Markers used for wrapping the table of contents
119 const TOC_START
= '<mw:toc>';
120 const TOC_END
= '</mw:toc>';
123 public $mTagHooks = array();
124 public $mTransparentTagHooks = array();
125 public $mFunctionHooks = array();
126 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
127 public $mFunctionTagHooks = array();
128 public $mStripList = array();
129 public $mDefaultStripList = array();
130 public $mVarCache = array();
131 public $mImageParams = array();
132 public $mImageParamsMagicArray = array();
133 public $mMarkerIndex = 0;
134 public $mFirstCall = true;
136 # Initialised by initialiseVariables()
139 * @var MagicWordArray
144 * @var MagicWordArray
147 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
149 # Cleared with clearState():
154 public $mAutonumber, $mDTopen;
161 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
163 * @var LinkHolderArray
165 public $mLinkHolders;
168 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
169 public $mDefaultSort;
170 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
171 public $mExpensiveFunctionCount; # number of expensive parser function calls
172 public $mShowToc, $mForceTocPosition;
177 public $mUser; # User object; only used when doing pre-save transform
180 # These are variables reset at least once per parse regardless of $clearState
190 public $mTitle; # Title context, used for self-link rendering and similar things
191 public $mOutputType; # Output type, one of the OT_xxx constants
192 public $ot; # Shortcut alias, see setOutputType()
193 public $mRevisionObject; # The revision object of the specified revision ID
194 public $mRevisionId; # ID to display in {{REVISIONID}} tags
195 public $mRevisionTimestamp; # The timestamp of the specified revision ID
196 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
197 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
198 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
199 public $mInputSize = false; # For {{PAGESIZE}} on current page.
207 * @var array Array with the language name of each language link (i.e. the
208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
209 * duplicate language links to the ParserOutput.
211 public $mLangLinkLanguages;
214 * @var MapCacheLRU|null
217 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
219 public $currentRevisionCache;
222 * @var bool Recursive call protection.
223 * This variable should be treated as if it were private.
225 public $mInParse = false;
230 public function __construct( $conf = array() ) {
231 $this->mConf
= $conf;
232 $this->mUrlProtocols
= wfUrlProtocols();
233 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
234 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
235 if ( isset( $conf['preprocessorClass'] ) ) {
236 $this->mPreprocessorClass
= $conf['preprocessorClass'];
237 } elseif ( defined( 'HPHP_VERSION' ) ) {
238 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
239 $this->mPreprocessorClass
= 'Preprocessor_Hash';
240 } elseif ( extension_loaded( 'domxml' ) ) {
241 # PECL extension that conflicts with the core DOM extension (bug 13770)
242 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
243 $this->mPreprocessorClass
= 'Preprocessor_Hash';
244 } elseif ( extension_loaded( 'dom' ) ) {
245 $this->mPreprocessorClass
= 'Preprocessor_DOM';
247 $this->mPreprocessorClass
= 'Preprocessor_Hash';
249 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
253 * Reduce memory usage to reduce the impact of circular references
255 public function __destruct() {
256 if ( isset( $this->mLinkHolders
) ) {
257 unset( $this->mLinkHolders
);
259 foreach ( $this as $name => $value ) {
260 unset( $this->$name );
265 * Allow extensions to clean up when the parser is cloned
267 public function __clone() {
268 $this->mInParse
= false;
270 // Bug 56226: When you create a reference "to" an object field, that
271 // makes the object field itself be a reference too (until the other
272 // reference goes out of scope). When cloning, any field that's a
273 // reference is copied as a reference in the new object. Both of these
274 // are defined PHP5 behaviors, as inconvenient as it is for us when old
275 // hooks from PHP4 days are passing fields by reference.
276 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
277 // Make a non-reference copy of the field, then rebind the field to
278 // reference the new copy.
284 wfRunHooks( 'ParserCloned', array( $this ) );
288 * Do various kinds of initialisation on the first call of the parser
290 public function firstCallInit() {
291 if ( !$this->mFirstCall
) {
294 $this->mFirstCall
= false;
296 wfProfileIn( __METHOD__
);
298 CoreParserFunctions
::register( $this );
299 CoreTagHooks
::register( $this );
300 $this->initialiseVariables();
302 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
303 wfProfileOut( __METHOD__
);
311 public function clearState() {
312 wfProfileIn( __METHOD__
);
313 if ( $this->mFirstCall
) {
314 $this->firstCallInit();
316 $this->mOutput
= new ParserOutput
;
317 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
318 $this->mAutonumber
= 0;
319 $this->mLastSection
= '';
320 $this->mDTopen
= false;
321 $this->mIncludeCount
= array();
322 $this->mArgStack
= false;
323 $this->mInPre
= false;
324 $this->mLinkHolders
= new LinkHolderArray( $this );
326 $this->mRevisionObject
= $this->mRevisionTimestamp
=
327 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
328 $this->mVarCache
= array();
330 $this->mLangLinkLanguages
= array();
331 $this->currentRevisionCache
= null;
334 * Prefix for temporary replacement strings for the multipass parser.
335 * \x07 should never appear in input as it's disallowed in XML.
336 * Using it at the front also gives us a little extra robustness
337 * since it shouldn't match when butted up against identifier-like
340 * Must not consist of all title characters, or else it will change
341 * the behavior of <nowiki> in a link.
343 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
344 $this->mStripState
= new StripState( $this->mUniqPrefix
);
346 # Clear these on every parse, bug 4549
347 $this->mTplRedirCache
= $this->mTplDomCache
= array();
349 $this->mShowToc
= true;
350 $this->mForceTocPosition
= false;
351 $this->mIncludeSizes
= array(
355 $this->mPPNodeCount
= 0;
356 $this->mGeneratedPPNodeCount
= 0;
357 $this->mHighestExpansionDepth
= 0;
358 $this->mDefaultSort
= false;
359 $this->mHeadings
= array();
360 $this->mDoubleUnderscores
= array();
361 $this->mExpensiveFunctionCount
= 0;
364 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
365 $this->mPreprocessor
= null;
368 wfRunHooks( 'ParserClearState', array( &$this ) );
369 wfProfileOut( __METHOD__
);
373 * Convert wikitext to HTML
374 * Do not call this function recursively.
376 * @param string $text Text we want to parse
377 * @param Title $title
378 * @param ParserOptions $options
379 * @param bool $linestart
380 * @param bool $clearState
381 * @param int $revid Number to pass in {{REVISIONID}}
382 * @return ParserOutput A ParserOutput
384 public function parse( $text, Title
$title, ParserOptions
$options,
385 $linestart = true, $clearState = true, $revid = null
388 * First pass--just handle <nowiki> sections, pass the rest off
389 * to internalParse() which does all the real work.
392 global $wgShowHostnames;
393 $fname = __METHOD__
. '-' . wfGetCaller();
394 wfProfileIn( __METHOD__
);
395 wfProfileIn( $fname );
398 $magicScopeVariable = $this->lock();
401 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
403 $this->currentRevisionCache
= null;
404 $this->mInputSize
= strlen( $text );
405 if ( $this->mOptions
->getEnableLimitReport() ) {
406 $this->mOutput
->resetParseStartTime();
409 # Remove the strip marker tag prefix from the input, if present.
411 $text = str_replace( $this->mUniqPrefix
, '', $text );
414 $oldRevisionId = $this->mRevisionId
;
415 $oldRevisionObject = $this->mRevisionObject
;
416 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
417 $oldRevisionUser = $this->mRevisionUser
;
418 $oldRevisionSize = $this->mRevisionSize
;
419 if ( $revid !== null ) {
420 $this->mRevisionId
= $revid;
421 $this->mRevisionObject
= null;
422 $this->mRevisionTimestamp
= null;
423 $this->mRevisionUser
= null;
424 $this->mRevisionSize
= null;
427 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
429 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
430 $text = $this->internalParse( $text );
431 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
433 $text = $this->internalParseHalfParsed( $text, true, $linestart );
436 * A converted title will be provided in the output object if title and
437 * content conversion are enabled, the article text does not contain
438 * a conversion-suppressing double-underscore tag, and no
439 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
440 * automatic link conversion.
442 if ( !( $options->getDisableTitleConversion()
443 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
444 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
445 ||
$this->mOutput
->getDisplayTitle() !== false )
447 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
448 if ( $convruletitle ) {
449 $this->mOutput
->setTitleText( $convruletitle );
451 $titleText = $this->getConverterLanguage()->convertTitle( $title );
452 $this->mOutput
->setTitleText( $titleText );
456 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
457 $this->limitationWarn( 'expensive-parserfunction',
458 $this->mExpensiveFunctionCount
,
459 $this->mOptions
->getExpensiveParserFunctionLimit()
463 # Information on include size limits, for the benefit of users who try to skirt them
464 if ( $this->mOptions
->getEnableLimitReport() ) {
465 $max = $this->mOptions
->getMaxIncludeSize();
467 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
468 if ( $cpuTime !== null ) {
469 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
470 sprintf( "%.3f", $cpuTime )
474 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
475 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
476 sprintf( "%.3f", $wallTime )
479 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
480 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
482 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
483 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
485 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
486 array( $this->mIncludeSizes
['post-expand'], $max )
488 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
489 array( $this->mIncludeSizes
['arg'], $max )
491 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
492 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
494 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
495 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
497 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
499 $limitReport = "NewPP limit report\n";
500 if ( $wgShowHostnames ) {
501 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
503 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
504 if ( wfRunHooks( 'ParserLimitReportFormat',
505 array( $key, &$value, &$limitReport, false, false )
507 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
508 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
509 ->inLanguage( 'en' )->useDatabase( false );
510 if ( !$valueMsg->exists() ) {
511 $valueMsg = new RawMessage( '$1' );
513 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
514 $valueMsg->params( $value );
515 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
519 // Since we're not really outputting HTML, decode the entities and
520 // then re-encode the things that need hiding inside HTML comments.
521 $limitReport = htmlspecialchars_decode( $limitReport );
522 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
524 // Sanitize for comment. Note '‐' in the replacement is U+2010,
525 // which looks much like the problematic '-'.
526 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
527 $text .= "\n<!-- \n$limitReport-->\n";
529 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
530 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
531 $this->mTitle
->getPrefixedDBkey() );
534 $this->mOutput
->setText( $text );
536 $this->mRevisionId
= $oldRevisionId;
537 $this->mRevisionObject
= $oldRevisionObject;
538 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
539 $this->mRevisionUser
= $oldRevisionUser;
540 $this->mRevisionSize
= $oldRevisionSize;
541 $this->mInputSize
= false;
542 $this->currentRevisionCache
= null;
543 wfProfileOut( $fname );
544 wfProfileOut( __METHOD__
);
546 return $this->mOutput
;
550 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
551 * can be called from an extension tag hook.
553 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
554 * instead, which means that lists and links have not been fully parsed yet,
555 * and strip markers are still present.
557 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
559 * Use this function if you're a parser tag hook and you want to parse
560 * wikitext before or after applying additional transformations, and you
561 * intend to *return the result as hook output*, which will cause it to go
562 * through the rest of parsing process automatically.
564 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
565 * $text are not expanded
567 * @param string $text Text extension wants to have parsed
568 * @param bool|PPFrame $frame The frame to use for expanding any template variables
569 * @return string UNSAFE half-parsed HTML
571 public function recursiveTagParse( $text, $frame = false ) {
572 wfProfileIn( __METHOD__
);
573 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
574 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
575 $text = $this->internalParse( $text, false, $frame );
576 wfProfileOut( __METHOD__
);
581 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
582 * point can be called from an extension tag hook.
584 * The output of this function is fully-parsed HTML that is safe for output.
585 * If you're a parser tag hook, you might want to use recursiveTagParse()
588 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
589 * $text are not expanded
593 * @param string $text Text extension wants to have parsed
594 * @param bool|PPFrame $frame The frame to use for expanding any template variables
595 * @return string Fully parsed HTML
597 public function recursiveTagParseFully( $text, $frame = false ) {
598 wfProfileIn( __METHOD__
);
599 $text = $this->recursiveTagParse( $text, $frame );
600 $text = $this->internalParseHalfParsed( $text, false );
601 wfProfileOut( __METHOD__
);
606 * Expand templates and variables in the text, producing valid, static wikitext.
607 * Also removes comments.
608 * Do not call this function recursively.
609 * @param string $text
610 * @param Title $title
611 * @param ParserOptions $options
612 * @param int|null $revid
613 * @param bool|PPFrame $frame
614 * @return mixed|string
616 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
617 wfProfileIn( __METHOD__
);
618 $magicScopeVariable = $this->lock();
619 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
620 if ( $revid !== null ) {
621 $this->mRevisionId
= $revid;
623 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
624 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
625 $text = $this->replaceVariables( $text, $frame );
626 $text = $this->mStripState
->unstripBoth( $text );
627 wfProfileOut( __METHOD__
);
632 * Recursive parser entry point that can be called from an extension tag
635 * @param string $text Text to be expanded
636 * @param bool|PPFrame $frame The frame to use for expanding any template variables
640 public function recursivePreprocess( $text, $frame = false ) {
641 wfProfileIn( __METHOD__
);
642 $text = $this->replaceVariables( $text, $frame );
643 $text = $this->mStripState
->unstripBoth( $text );
644 wfProfileOut( __METHOD__
);
649 * Process the wikitext for the "?preload=" feature. (bug 5210)
651 * "<noinclude>", "<includeonly>" etc. are parsed as for template
652 * transclusion, comments, templates, arguments, tags hooks and parser
653 * functions are untouched.
655 * @param string $text
656 * @param Title $title
657 * @param ParserOptions $options
658 * @param array $params
661 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
662 $msg = new RawMessage( $text );
663 $text = $msg->params( $params )->plain();
665 # Parser (re)initialisation
666 $magicScopeVariable = $this->lock();
667 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
669 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
670 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
671 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
672 $text = $this->mStripState
->unstripBoth( $text );
677 * Get a random string
681 public static function getRandomString() {
682 return wfRandomString( 16 );
686 * Set the current user.
687 * Should only be used when doing pre-save transform.
689 * @param User|null $user User object or null (to reset)
691 public function setUser( $user ) {
692 $this->mUser
= $user;
696 * Accessor for mUniqPrefix.
700 public function uniqPrefix() {
701 if ( !isset( $this->mUniqPrefix
) ) {
702 # @todo FIXME: This is probably *horribly wrong*
703 # LanguageConverter seems to want $wgParser's uniqPrefix, however
704 # if this is called for a parser cache hit, the parser may not
705 # have ever been initialized in the first place.
706 # Not really sure what the heck is supposed to be going on here.
708 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
710 return $this->mUniqPrefix
;
714 * Set the context title
718 public function setTitle( $t ) {
720 $t = Title
::newFromText( 'NO TITLE' );
723 if ( $t->hasFragment() ) {
724 # Strip the fragment to avoid various odd effects
725 $this->mTitle
= clone $t;
726 $this->mTitle
->setFragment( '' );
733 * Accessor for the Title object
737 public function getTitle() {
738 return $this->mTitle
;
742 * Accessor/mutator for the Title object
744 * @param Title $x Title object or null to just get the current one
747 public function Title( $x = null ) {
748 return wfSetVar( $this->mTitle
, $x );
752 * Set the output type
754 * @param int $ot New value
756 public function setOutputType( $ot ) {
757 $this->mOutputType
= $ot;
760 'html' => $ot == self
::OT_HTML
,
761 'wiki' => $ot == self
::OT_WIKI
,
762 'pre' => $ot == self
::OT_PREPROCESS
,
763 'plain' => $ot == self
::OT_PLAIN
,
768 * Accessor/mutator for the output type
770 * @param int|null $x New value or null to just get the current one
773 public function OutputType( $x = null ) {
774 return wfSetVar( $this->mOutputType
, $x );
778 * Get the ParserOutput object
780 * @return ParserOutput
782 public function getOutput() {
783 return $this->mOutput
;
787 * Get the ParserOptions object
789 * @return ParserOptions
791 public function getOptions() {
792 return $this->mOptions
;
796 * Accessor/mutator for the ParserOptions object
798 * @param ParserOptions $x New value or null to just get the current one
799 * @return ParserOptions Current ParserOptions object
801 public function Options( $x = null ) {
802 return wfSetVar( $this->mOptions
, $x );
808 public function nextLinkID() {
809 return $this->mLinkID++
;
815 public function setLinkID( $id ) {
816 $this->mLinkID
= $id;
820 * Get a language object for use in parser functions such as {{FORMATNUM:}}
823 public function getFunctionLang() {
824 return $this->getTargetLanguage();
828 * Get the target language for the content being parsed. This is usually the
829 * language that the content is in.
833 * @throws MWException
836 public function getTargetLanguage() {
837 $target = $this->mOptions
->getTargetLanguage();
839 if ( $target !== null ) {
841 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
842 return $this->mOptions
->getUserLangObj();
843 } elseif ( is_null( $this->mTitle
) ) {
844 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
847 return $this->mTitle
->getPageLanguage();
851 * Get the language object for language conversion
852 * @return Language|null
854 public function getConverterLanguage() {
855 return $this->getTargetLanguage();
859 * Get a User object either from $this->mUser, if set, or from the
860 * ParserOptions object otherwise
864 public function getUser() {
865 if ( !is_null( $this->mUser
) ) {
868 return $this->mOptions
->getUser();
872 * Get a preprocessor object
874 * @return Preprocessor
876 public function getPreprocessor() {
877 if ( !isset( $this->mPreprocessor
) ) {
878 $class = $this->mPreprocessorClass
;
879 $this->mPreprocessor
= new $class( $this );
881 return $this->mPreprocessor
;
885 * Replaces all occurrences of HTML-style comments and the given tags
886 * in the text with a random marker and returns the next text. The output
887 * parameter $matches will be an associative array filled with data in
891 * 'UNIQ-xxxxx' => array(
894 * array( 'param' => 'x' ),
895 * '<element param="x">tag content</element>' ) )
898 * @param array $elements List of element names. Comments are always extracted.
899 * @param string $text Source text string.
900 * @param array $matches Out parameter, Array: extracted tags
901 * @param string $uniq_prefix
902 * @return string Stripped text
904 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
909 $taglist = implode( '|', $elements );
910 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
912 while ( $text != '' ) {
913 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
915 if ( count( $p ) < 5 ) {
918 if ( count( $p ) > 5 ) {
932 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
933 $stripped .= $marker;
935 if ( $close === '/>' ) {
936 # Empty element tag, <tag />
941 if ( $element === '!--' ) {
944 $end = "/(<\\/$element\\s*>)/i";
946 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
948 if ( count( $q ) < 3 ) {
949 # No end tag -- let it run out to the end of the text.
958 $matches[$marker] = array( $element,
960 Sanitizer
::decodeTagAttributes( $attributes ),
961 "<$element$attributes$close$content$tail" );
967 * Get a list of strippable XML-like elements
971 public function getStripList() {
972 return $this->mStripList
;
976 * Add an item to the strip state
977 * Returns the unique tag which must be inserted into the stripped text
978 * The tag will be replaced with the original text in unstrip()
980 * @param string $text
984 public function insertStripItem( $text ) {
985 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
986 $this->mMarkerIndex++
;
987 $this->mStripState
->addGeneral( $rnd, $text );
992 * parse the wiki syntax used to render tables
995 * @param string $text
998 public function doTableStuff( $text ) {
999 wfProfileIn( __METHOD__
);
1001 $lines = StringUtils
::explode( "\n", $text );
1003 $td_history = array(); # Is currently a td tag open?
1004 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1005 $tr_history = array(); # Is currently a tr tag open?
1006 $tr_attributes = array(); # history of tr attributes
1007 $has_opened_tr = array(); # Did this table open a <tr> element?
1008 $indent_level = 0; # indent level of the table
1010 foreach ( $lines as $outLine ) {
1011 $line = trim( $outLine );
1013 if ( $line === '' ) { # empty line, go to next line
1014 $out .= $outLine . "\n";
1018 $first_character = $line[0];
1021 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1022 # First check if we are starting a new table
1023 $indent_level = strlen( $matches[1] );
1025 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1026 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1028 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1029 array_push( $td_history, false );
1030 array_push( $last_tag_history, '' );
1031 array_push( $tr_history, false );
1032 array_push( $tr_attributes, '' );
1033 array_push( $has_opened_tr, false );
1034 } elseif ( count( $td_history ) == 0 ) {
1035 # Don't do any of the following
1036 $out .= $outLine . "\n";
1038 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1039 # We are ending a table
1040 $line = '</table>' . substr( $line, 2 );
1041 $last_tag = array_pop( $last_tag_history );
1043 if ( !array_pop( $has_opened_tr ) ) {
1044 $line = "<tr><td></td></tr>{$line}";
1047 if ( array_pop( $tr_history ) ) {
1048 $line = "</tr>{$line}";
1051 if ( array_pop( $td_history ) ) {
1052 $line = "</{$last_tag}>{$line}";
1054 array_pop( $tr_attributes );
1055 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1056 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1057 # Now we have a table row
1058 $line = preg_replace( '#^\|-+#', '', $line );
1060 # Whats after the tag is now only attributes
1061 $attributes = $this->mStripState
->unstripBoth( $line );
1062 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1063 array_pop( $tr_attributes );
1064 array_push( $tr_attributes, $attributes );
1067 $last_tag = array_pop( $last_tag_history );
1068 array_pop( $has_opened_tr );
1069 array_push( $has_opened_tr, true );
1071 if ( array_pop( $tr_history ) ) {
1075 if ( array_pop( $td_history ) ) {
1076 $line = "</{$last_tag}>{$line}";
1080 array_push( $tr_history, false );
1081 array_push( $td_history, false );
1082 array_push( $last_tag_history, '' );
1083 } elseif ( $first_character === '|'
1084 ||
$first_character === '!'
1085 ||
substr( $line, 0, 2 ) === '|+'
1087 # This might be cell elements, td, th or captions
1088 if ( substr( $line, 0, 2 ) === '|+' ) {
1089 $first_character = '+';
1090 $line = substr( $line, 1 );
1093 $line = substr( $line, 1 );
1095 if ( $first_character === '!' ) {
1096 $line = str_replace( '!!', '||', $line );
1099 # Split up multiple cells on the same line.
1100 # FIXME : This can result in improper nesting of tags processed
1101 # by earlier parser steps, but should avoid splitting up eg
1102 # attribute values containing literal "||".
1103 $cells = StringUtils
::explodeMarkup( '||', $line );
1107 # Loop through each table cell
1108 foreach ( $cells as $cell ) {
1110 if ( $first_character !== '+' ) {
1111 $tr_after = array_pop( $tr_attributes );
1112 if ( !array_pop( $tr_history ) ) {
1113 $previous = "<tr{$tr_after}>\n";
1115 array_push( $tr_history, true );
1116 array_push( $tr_attributes, '' );
1117 array_pop( $has_opened_tr );
1118 array_push( $has_opened_tr, true );
1121 $last_tag = array_pop( $last_tag_history );
1123 if ( array_pop( $td_history ) ) {
1124 $previous = "</{$last_tag}>\n{$previous}";
1127 if ( $first_character === '|' ) {
1129 } elseif ( $first_character === '!' ) {
1131 } elseif ( $first_character === '+' ) {
1132 $last_tag = 'caption';
1137 array_push( $last_tag_history, $last_tag );
1139 # A cell could contain both parameters and data
1140 $cell_data = explode( '|', $cell, 2 );
1142 # Bug 553: Note that a '|' inside an invalid link should not
1143 # be mistaken as delimiting cell parameters
1144 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1145 $cell = "{$previous}<{$last_tag}>{$cell}";
1146 } elseif ( count( $cell_data ) == 1 ) {
1147 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1149 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1150 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1151 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1155 array_push( $td_history, true );
1158 $out .= $outLine . "\n";
1161 # Closing open td, tr && table
1162 while ( count( $td_history ) > 0 ) {
1163 if ( array_pop( $td_history ) ) {
1166 if ( array_pop( $tr_history ) ) {
1169 if ( !array_pop( $has_opened_tr ) ) {
1170 $out .= "<tr><td></td></tr>\n";
1173 $out .= "</table>\n";
1176 # Remove trailing line-ending (b/c)
1177 if ( substr( $out, -1 ) === "\n" ) {
1178 $out = substr( $out, 0, -1 );
1181 # special case: don't return empty table
1182 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1186 wfProfileOut( __METHOD__
);
1192 * Helper function for parse() that transforms wiki markup into half-parsed
1193 * HTML. Only called for $mOutputType == self::OT_HTML.
1197 * @param string $text
1198 * @param bool $isMain
1199 * @param bool $frame
1203 public function internalParse( $text, $isMain = true, $frame = false ) {
1204 wfProfileIn( __METHOD__
);
1208 # Hook to suspend the parser in this state
1209 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1210 wfProfileOut( __METHOD__
);
1214 # if $frame is provided, then use $frame for replacing any variables
1216 # use frame depth to infer how include/noinclude tags should be handled
1217 # depth=0 means this is the top-level document; otherwise it's an included document
1218 if ( !$frame->depth
) {
1221 $flag = Parser
::PTD_FOR_INCLUSION
;
1223 $dom = $this->preprocessToDom( $text, $flag );
1224 $text = $frame->expand( $dom );
1226 # if $frame is not provided, then use old-style replaceVariables
1227 $text = $this->replaceVariables( $text );
1230 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1231 $text = Sanitizer
::removeHTMLtags(
1233 array( &$this, 'attributeStripCallback' ),
1235 array_keys( $this->mTransparentTagHooks
)
1237 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1239 # Tables need to come after variable replacement for things to work
1240 # properly; putting them before other transformations should keep
1241 # exciting things like link expansions from showing up in surprising
1243 $text = $this->doTableStuff( $text );
1245 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1247 $text = $this->doDoubleUnderscore( $text );
1249 $text = $this->doHeadings( $text );
1250 $text = $this->replaceInternalLinks( $text );
1251 $text = $this->doAllQuotes( $text );
1252 $text = $this->replaceExternalLinks( $text );
1254 # replaceInternalLinks may sometimes leave behind
1255 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1256 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1258 $text = $this->doMagicLinks( $text );
1259 $text = $this->formatHeadings( $text, $origText, $isMain );
1261 wfProfileOut( __METHOD__
);
1266 * Helper function for parse() that transforms half-parsed HTML into fully
1269 * @param string $text
1270 * @param bool $isMain
1271 * @param bool $linestart
1274 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1275 global $wgUseTidy, $wgAlwaysUseTidy;
1277 $text = $this->mStripState
->unstripGeneral( $text );
1279 # Clean up special characters, only run once, next-to-last before doBlockLevels
1281 # french spaces, last one Guillemet-left
1282 # only if there is something before the space
1283 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1284 # french spaces, Guillemet-right
1285 '/(\\302\\253) /' => '\\1 ',
1286 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1288 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1290 $text = $this->doBlockLevels( $text, $linestart );
1292 $this->replaceLinkHolders( $text );
1295 * The input doesn't get language converted if
1297 * b) Content isn't converted
1298 * c) It's a conversion table
1299 * d) it is an interface message (which is in the user language)
1301 if ( !( $this->mOptions
->getDisableContentConversion()
1302 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1304 if ( !$this->mOptions
->getInterfaceMessage() ) {
1305 # The position of the convert() call should not be changed. it
1306 # assumes that the links are all replaced and the only thing left
1307 # is the <nowiki> mark.
1308 $text = $this->getConverterLanguage()->convert( $text );
1312 $text = $this->mStripState
->unstripNoWiki( $text );
1315 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
1318 $text = $this->replaceTransparentTags( $text );
1319 $text = $this->mStripState
->unstripGeneral( $text );
1321 $text = Sanitizer
::normalizeCharReferences( $text );
1323 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1324 $text = MWTidy
::tidy( $text );
1326 # attempt to sanitize at least some nesting problems
1327 # (bug #2702 and quite a few others)
1329 # ''Something [http://www.cool.com cool''] -->
1330 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1331 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1332 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1333 # fix up an anchor inside another anchor, only
1334 # at least for a single single nested link (bug 3695)
1335 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1336 '\\1\\2</a>\\3</a>\\1\\4</a>',
1337 # fix div inside inline elements- doBlockLevels won't wrap a line which
1338 # contains a div, so fix it up here; replace
1339 # div with escaped text
1340 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1341 '\\1\\3<div\\5>\\6</div>\\8\\9',
1342 # remove empty italic or bold tag pairs, some
1343 # introduced by rules above
1344 '/<([bi])><\/\\1>/' => '',
1347 $text = preg_replace(
1348 array_keys( $tidyregs ),
1349 array_values( $tidyregs ),
1354 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
1361 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1362 * magic external links.
1367 * @param string $text
1371 public function doMagicLinks( $text ) {
1372 wfProfileIn( __METHOD__
);
1373 $prots = wfUrlProtocolsWithoutProtRel();
1374 $urlChar = self
::EXT_LINK_URL_CLASS
;
1375 $text = preg_replace_callback(
1377 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1378 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1379 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1380 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1381 ISBN\s+(\b # m[5]: ISBN, capture number
1382 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1383 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1384 [0-9Xx] # check digit
1386 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1387 wfProfileOut( __METHOD__
);
1392 * @throws MWException
1394 * @return HTML|string
1396 public function magicLinkCallback( $m ) {
1397 if ( isset( $m[1] ) && $m[1] !== '' ) {
1400 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1403 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1404 # Free external link
1405 return $this->makeFreeExternalLink( $m[0] );
1406 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1408 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1411 $cssClass = 'mw-magiclink-rfc';
1413 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1415 $urlmsg = 'pubmedurl';
1416 $cssClass = 'mw-magiclink-pmid';
1419 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1420 substr( $m[0], 0, 20 ) . '"' );
1422 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1423 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1424 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1427 $num = strtr( $isbn, array(
1432 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1433 return '<a href="' .
1434 htmlspecialchars( $titleObj->getLocalURL() ) .
1435 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1442 * Make a free external link, given a user-supplied URL
1444 * @param string $url
1446 * @return string HTML
1449 public function makeFreeExternalLink( $url ) {
1450 wfProfileIn( __METHOD__
);
1454 # The characters '<' and '>' (which were escaped by
1455 # removeHTMLtags()) should not be included in
1456 # URLs, per RFC 2396.
1458 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1459 $trail = substr( $url, $m2[0][1] ) . $trail;
1460 $url = substr( $url, 0, $m2[0][1] );
1463 # Move trailing punctuation to $trail
1465 # If there is no left bracket, then consider right brackets fair game too
1466 if ( strpos( $url, '(' ) === false ) {
1470 $numSepChars = strspn( strrev( $url ), $sep );
1471 if ( $numSepChars ) {
1472 $trail = substr( $url, -$numSepChars ) . $trail;
1473 $url = substr( $url, 0, -$numSepChars );
1476 $url = Sanitizer
::cleanUrl( $url );
1478 # Is this an external image?
1479 $text = $this->maybeMakeExternalImage( $url );
1480 if ( $text === false ) {
1481 # Not an image, make a link
1482 $text = Linker
::makeExternalLink( $url,
1483 $this->getConverterLanguage()->markNoConversion( $url, true ),
1485 $this->getExternalLinkAttribs( $url ) );
1486 # Register it in the output object...
1487 # Replace unnecessary URL escape codes with their equivalent characters
1488 $pasteurized = self
::normalizeLinkUrl( $url );
1489 $this->mOutput
->addExternalLink( $pasteurized );
1491 wfProfileOut( __METHOD__
);
1492 return $text . $trail;
1496 * Parse headers and return html
1500 * @param string $text
1504 public function doHeadings( $text ) {
1505 wfProfileIn( __METHOD__
);
1506 for ( $i = 6; $i >= 1; --$i ) {
1507 $h = str_repeat( '=', $i );
1508 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1510 wfProfileOut( __METHOD__
);
1515 * Replace single quotes with HTML markup
1518 * @param string $text
1520 * @return string The altered text
1522 public function doAllQuotes( $text ) {
1523 wfProfileIn( __METHOD__
);
1525 $lines = StringUtils
::explode( "\n", $text );
1526 foreach ( $lines as $line ) {
1527 $outtext .= $this->doQuotes( $line ) . "\n";
1529 $outtext = substr( $outtext, 0, -1 );
1530 wfProfileOut( __METHOD__
);
1535 * Helper function for doAllQuotes()
1537 * @param string $text
1541 public function doQuotes( $text ) {
1542 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1543 $countarr = count( $arr );
1544 if ( $countarr == 1 ) {
1548 // First, do some preliminary work. This may shift some apostrophes from
1549 // being mark-up to being text. It also counts the number of occurrences
1550 // of bold and italics mark-ups.
1553 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1554 $thislen = strlen( $arr[$i] );
1555 // If there are ever four apostrophes, assume the first is supposed to
1556 // be text, and the remaining three constitute mark-up for bold text.
1557 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1558 if ( $thislen == 4 ) {
1559 $arr[$i - 1] .= "'";
1562 } elseif ( $thislen > 5 ) {
1563 // If there are more than 5 apostrophes in a row, assume they're all
1564 // text except for the last 5.
1565 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1566 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1570 // Count the number of occurrences of bold and italics mark-ups.
1571 if ( $thislen == 2 ) {
1573 } elseif ( $thislen == 3 ) {
1575 } elseif ( $thislen == 5 ) {
1581 // If there is an odd number of both bold and italics, it is likely
1582 // that one of the bold ones was meant to be an apostrophe followed
1583 // by italics. Which one we cannot know for certain, but it is more
1584 // likely to be one that has a single-letter word before it.
1585 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1586 $firstsingleletterword = -1;
1587 $firstmultiletterword = -1;
1589 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1590 if ( strlen( $arr[$i] ) == 3 ) {
1591 $x1 = substr( $arr[$i - 1], -1 );
1592 $x2 = substr( $arr[$i - 1], -2, 1 );
1593 if ( $x1 === ' ' ) {
1594 if ( $firstspace == -1 ) {
1597 } elseif ( $x2 === ' ' ) {
1598 if ( $firstsingleletterword == -1 ) {
1599 $firstsingleletterword = $i;
1600 // if $firstsingleletterword is set, we don't
1601 // look at the other options, so we can bail early.
1605 if ( $firstmultiletterword == -1 ) {
1606 $firstmultiletterword = $i;
1612 // If there is a single-letter word, use it!
1613 if ( $firstsingleletterword > -1 ) {
1614 $arr[$firstsingleletterword] = "''";
1615 $arr[$firstsingleletterword - 1] .= "'";
1616 } elseif ( $firstmultiletterword > -1 ) {
1617 // If not, but there's a multi-letter word, use that one.
1618 $arr[$firstmultiletterword] = "''";
1619 $arr[$firstmultiletterword - 1] .= "'";
1620 } elseif ( $firstspace > -1 ) {
1621 // ... otherwise use the first one that has neither.
1622 // (notice that it is possible for all three to be -1 if, for example,
1623 // there is only one pentuple-apostrophe in the line)
1624 $arr[$firstspace] = "''";
1625 $arr[$firstspace - 1] .= "'";
1629 // Now let's actually convert our apostrophic mush to HTML!
1634 foreach ( $arr as $r ) {
1635 if ( ( $i %
2 ) == 0 ) {
1636 if ( $state === 'both' ) {
1642 $thislen = strlen( $r );
1643 if ( $thislen == 2 ) {
1644 if ( $state === 'i' ) {
1647 } elseif ( $state === 'bi' ) {
1650 } elseif ( $state === 'ib' ) {
1651 $output .= '</b></i><b>';
1653 } elseif ( $state === 'both' ) {
1654 $output .= '<b><i>' . $buffer . '</i>';
1656 } else { // $state can be 'b' or ''
1660 } elseif ( $thislen == 3 ) {
1661 if ( $state === 'b' ) {
1664 } elseif ( $state === 'bi' ) {
1665 $output .= '</i></b><i>';
1667 } elseif ( $state === 'ib' ) {
1670 } elseif ( $state === 'both' ) {
1671 $output .= '<i><b>' . $buffer . '</b>';
1673 } else { // $state can be 'i' or ''
1677 } elseif ( $thislen == 5 ) {
1678 if ( $state === 'b' ) {
1679 $output .= '</b><i>';
1681 } elseif ( $state === 'i' ) {
1682 $output .= '</i><b>';
1684 } elseif ( $state === 'bi' ) {
1685 $output .= '</i></b>';
1687 } elseif ( $state === 'ib' ) {
1688 $output .= '</b></i>';
1690 } elseif ( $state === 'both' ) {
1691 $output .= '<i><b>' . $buffer . '</b></i>';
1693 } else { // ($state == '')
1701 // Now close all remaining tags. Notice that the order is important.
1702 if ( $state === 'b' ||
$state === 'ib' ) {
1705 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1708 if ( $state === 'bi' ) {
1711 // There might be lonely ''''', so make sure we have a buffer
1712 if ( $state === 'both' && $buffer ) {
1713 $output .= '<b><i>' . $buffer . '</i></b>';
1719 * Replace external links (REL)
1721 * Note: this is all very hackish and the order of execution matters a lot.
1722 * Make sure to run tests/parserTests.php if you change this code.
1726 * @param string $text
1728 * @throws MWException
1731 public function replaceExternalLinks( $text ) {
1732 wfProfileIn( __METHOD__
);
1734 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1735 if ( $bits === false ) {
1736 wfProfileOut( __METHOD__
);
1737 throw new MWException( "PCRE needs to be compiled with "
1738 . "--enable-unicode-properties in order for MediaWiki to function" );
1740 $s = array_shift( $bits );
1743 while ( $i < count( $bits ) ) {
1746 $text = $bits[$i++
];
1747 $trail = $bits[$i++
];
1749 # The characters '<' and '>' (which were escaped by
1750 # removeHTMLtags()) should not be included in
1751 # URLs, per RFC 2396.
1753 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1754 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1755 $url = substr( $url, 0, $m2[0][1] );
1758 # If the link text is an image URL, replace it with an <img> tag
1759 # This happened by accident in the original parser, but some people used it extensively
1760 $img = $this->maybeMakeExternalImage( $text );
1761 if ( $img !== false ) {
1767 # Set linktype for CSS - if URL==text, link is essentially free
1768 $linktype = ( $text === $url ) ?
'free' : 'text';
1770 # No link text, e.g. [http://domain.tld/some.link]
1771 if ( $text == '' ) {
1773 $langObj = $this->getTargetLanguage();
1774 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1775 $linktype = 'autonumber';
1777 # Have link text, e.g. [http://domain.tld/some.link text]s
1779 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1782 $text = $this->getConverterLanguage()->markNoConversion( $text );
1784 $url = Sanitizer
::cleanUrl( $url );
1786 # Use the encoded URL
1787 # This means that users can paste URLs directly into the text
1788 # Funny characters like ö aren't valid in URLs anyway
1789 # This was changed in August 2004
1790 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1791 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1793 # Register link in the output object.
1794 # Replace unnecessary URL escape codes with the referenced character
1795 # This prevents spammers from hiding links from the filters
1796 $pasteurized = self
::normalizeLinkUrl( $url );
1797 $this->mOutput
->addExternalLink( $pasteurized );
1800 wfProfileOut( __METHOD__
);
1805 * Get the rel attribute for a particular external link.
1808 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1809 * nofollow if appropriate
1810 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1811 * @return string|null Rel attribute for $url
1813 public static function getExternalLinkRel( $url = false, $title = null ) {
1814 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1815 $ns = $title ?
$title->getNamespace() : false;
1816 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1817 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1825 * Get an associative array of additional HTML attributes appropriate for a
1826 * particular external link. This currently may include rel => nofollow
1827 * (depending on configuration, namespace, and the URL's domain) and/or a
1828 * target attribute (depending on configuration).
1830 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1831 * nofollow if appropriate
1832 * @return array Associative array of HTML attributes
1834 public function getExternalLinkAttribs( $url = false ) {
1836 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1838 if ( $this->mOptions
->getExternalLinkTarget() ) {
1839 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1845 * Replace unusual escape codes in a URL with their equivalent characters
1847 * @deprecated since 1.24, use normalizeLinkUrl
1848 * @param string $url
1851 public static function replaceUnusualEscapes( $url ) {
1852 wfDeprecated( __METHOD__
, '1.24' );
1853 return self
::normalizeLinkUrl( $url );
1857 * Replace unusual escape codes in a URL with their equivalent characters
1859 * This generally follows the syntax defined in RFC 3986, with special
1860 * consideration for HTTP query strings.
1862 * @param string $url
1865 public static function normalizeLinkUrl( $url ) {
1866 # First, make sure unsafe characters are encoded
1867 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1869 return rawurlencode( $m[0] );
1875 $end = strlen( $url );
1877 # Fragment part - 'fragment'
1878 $start = strpos( $url, '#' );
1879 if ( $start !== false && $start < $end ) {
1880 $ret = self
::normalizeUrlComponent(
1881 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1885 # Query part - 'query' minus &=+;
1886 $start = strpos( $url, '?' );
1887 if ( $start !== false && $start < $end ) {
1888 $ret = self
::normalizeUrlComponent(
1889 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1893 # Scheme and path part - 'pchar'
1894 # (we assume no userinfo or encoded colons in the host)
1895 $ret = self
::normalizeUrlComponent(
1896 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1901 private static function normalizeUrlComponent( $component, $unsafe ) {
1902 $callback = function ( $matches ) use ( $unsafe ) {
1903 $char = urldecode( $matches[0] );
1904 $ord = ord( $char );
1905 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1909 # Leave it escaped, but use uppercase for a-f
1910 return strtoupper( $matches[0] );
1913 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1917 * make an image if it's allowed, either through the global
1918 * option, through the exception, or through the on-wiki whitelist
1920 * @param string $url
1924 private function maybeMakeExternalImage( $url ) {
1925 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1926 $imagesexception = !empty( $imagesfrom );
1928 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1929 if ( $imagesexception && is_array( $imagesfrom ) ) {
1930 $imagematch = false;
1931 foreach ( $imagesfrom as $match ) {
1932 if ( strpos( $url, $match ) === 0 ) {
1937 } elseif ( $imagesexception ) {
1938 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1940 $imagematch = false;
1943 if ( $this->mOptions
->getAllowExternalImages()
1944 ||
( $imagesexception && $imagematch )
1946 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1948 $text = Linker
::makeExternalImage( $url );
1951 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1952 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1954 $whitelist = explode(
1956 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1959 foreach ( $whitelist as $entry ) {
1960 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1961 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1964 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1965 # Image matches a whitelist entry
1966 $text = Linker
::makeExternalImage( $url );
1975 * Process [[ ]] wikilinks
1979 * @return string Processed text
1983 public function replaceInternalLinks( $s ) {
1984 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1989 * Process [[ ]] wikilinks (RIL)
1991 * @throws MWException
1992 * @return LinkHolderArray
1996 public function replaceInternalLinks2( &$s ) {
1997 global $wgExtraInterlanguageLinkPrefixes;
1998 wfProfileIn( __METHOD__
);
2000 wfProfileIn( __METHOD__
. '-setup' );
2001 static $tc = false, $e1, $e1_img;
2002 # the % is needed to support urlencoded titles as well
2004 $tc = Title
::legalChars() . '#%';
2005 # Match a link having the form [[namespace:link|alternate]]trail
2006 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2007 # Match cases where there is no "]]", which might still be images
2008 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2011 $holders = new LinkHolderArray( $this );
2013 # split the entire text string on occurrences of [[
2014 $a = StringUtils
::explode( '[[', ' ' . $s );
2015 # get the first element (all text up to first [[), and remove the space we added
2018 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2019 $s = substr( $s, 1 );
2021 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2023 if ( $useLinkPrefixExtension ) {
2024 # Match the end of a line for a word that's not followed by whitespace,
2025 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2027 $charset = $wgContLang->linkPrefixCharset();
2028 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2031 if ( is_null( $this->mTitle
) ) {
2032 wfProfileOut( __METHOD__
. '-setup' );
2033 wfProfileOut( __METHOD__
);
2034 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2036 $nottalk = !$this->mTitle
->isTalkPage();
2038 if ( $useLinkPrefixExtension ) {
2040 if ( preg_match( $e2, $s, $m ) ) {
2041 $first_prefix = $m[2];
2043 $first_prefix = false;
2049 $useSubpages = $this->areSubpagesAllowed();
2050 wfProfileOut( __METHOD__
. '-setup' );
2052 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2053 # Loop for each link
2054 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2055 // @codingStandardsIgnoreStart
2057 # Check for excessive memory usage
2058 if ( $holders->isBig() ) {
2060 # Do the existence check, replace the link holders and clear the array
2061 $holders->replace( $s );
2065 if ( $useLinkPrefixExtension ) {
2066 wfProfileIn( __METHOD__
. '-prefixhandling' );
2067 if ( preg_match( $e2, $s, $m ) ) {
2074 if ( $first_prefix ) {
2075 $prefix = $first_prefix;
2076 $first_prefix = false;
2078 wfProfileOut( __METHOD__
. '-prefixhandling' );
2081 $might_be_img = false;
2083 wfProfileIn( __METHOD__
. "-e1" );
2084 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2086 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2087 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2088 # the real problem is with the $e1 regex
2091 # Still some problems for cases where the ] is meant to be outside punctuation,
2092 # and no image is in sight. See bug 2095.
2095 && substr( $m[3], 0, 1 ) === ']'
2096 && strpos( $text, '[' ) !== false
2098 $text .= ']'; # so that replaceExternalLinks($text) works later
2099 $m[3] = substr( $m[3], 1 );
2101 # fix up urlencoded title texts
2102 if ( strpos( $m[1], '%' ) !== false ) {
2103 # Should anchors '#' also be rejected?
2104 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2107 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2108 # Invalid, but might be an image with a link in its caption
2109 $might_be_img = true;
2111 if ( strpos( $m[1], '%' ) !== false ) {
2112 $m[1] = rawurldecode( $m[1] );
2115 } else { # Invalid form; output directly
2116 $s .= $prefix . '[[' . $line;
2117 wfProfileOut( __METHOD__
. "-e1" );
2120 wfProfileOut( __METHOD__
. "-e1" );
2121 wfProfileIn( __METHOD__
. "-misc" );
2125 # Don't allow internal links to pages containing
2126 # PROTO: where PROTO is a valid URL protocol; these
2127 # should be external links.
2128 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2129 $s .= $prefix . '[[' . $line;
2130 wfProfileOut( __METHOD__
. "-misc" );
2134 # Make subpage if necessary
2135 if ( $useSubpages ) {
2136 $link = $this->maybeDoSubpageLink( $origLink, $text );
2141 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2143 # Strip off leading ':'
2144 $link = substr( $link, 1 );
2147 wfProfileOut( __METHOD__
. "-misc" );
2148 wfProfileIn( __METHOD__
. "-title" );
2149 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2150 if ( $nt === null ) {
2151 $s .= $prefix . '[[' . $line;
2152 wfProfileOut( __METHOD__
. "-title" );
2156 $ns = $nt->getNamespace();
2157 $iw = $nt->getInterwiki();
2158 wfProfileOut( __METHOD__
. "-title" );
2160 if ( $might_be_img ) { # if this is actually an invalid link
2161 wfProfileIn( __METHOD__
. "-might_be_img" );
2162 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2165 # look at the next 'line' to see if we can close it there
2167 $next_line = $a->current();
2168 if ( $next_line === false ||
$next_line === null ) {
2171 $m = explode( ']]', $next_line, 3 );
2172 if ( count( $m ) == 3 ) {
2173 # the first ]] closes the inner link, the second the image
2175 $text .= "[[{$m[0]}]]{$m[1]}";
2178 } elseif ( count( $m ) == 2 ) {
2179 # if there's exactly one ]] that's fine, we'll keep looking
2180 $text .= "[[{$m[0]}]]{$m[1]}";
2182 # if $next_line is invalid too, we need look no further
2183 $text .= '[[' . $next_line;
2188 # we couldn't find the end of this imageLink, so output it raw
2189 # but don't ignore what might be perfectly normal links in the text we've examined
2190 $holders->merge( $this->replaceInternalLinks2( $text ) );
2191 $s .= "{$prefix}[[$link|$text";
2192 # note: no $trail, because without an end, there *is* no trail
2193 wfProfileOut( __METHOD__
. "-might_be_img" );
2196 } else { # it's not an image, so output it raw
2197 $s .= "{$prefix}[[$link|$text";
2198 # note: no $trail, because without an end, there *is* no trail
2199 wfProfileOut( __METHOD__
. "-might_be_img" );
2202 wfProfileOut( __METHOD__
. "-might_be_img" );
2205 $wasblank = ( $text == '' );
2209 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2210 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2211 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2212 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2213 $text = $this->doQuotes( $text );
2216 # Link not escaped by : , create the various objects
2217 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2219 wfProfileIn( __METHOD__
. "-interwiki" );
2221 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2222 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2223 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2226 # Bug 24502: filter duplicates
2227 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2228 $this->mLangLinkLanguages
[$iw] = true;
2229 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2232 $s = rtrim( $s . $prefix );
2233 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2234 wfProfileOut( __METHOD__
. "-interwiki" );
2237 wfProfileOut( __METHOD__
. "-interwiki" );
2239 if ( $ns == NS_FILE
) {
2240 wfProfileIn( __METHOD__
. "-image" );
2241 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2243 # if no parameters were passed, $text
2244 # becomes something like "File:Foo.png",
2245 # which we don't want to pass on to the
2249 # recursively parse links inside the image caption
2250 # actually, this will parse them in any other parameters, too,
2251 # but it might be hard to fix that, and it doesn't matter ATM
2252 $text = $this->replaceExternalLinks( $text );
2253 $holders->merge( $this->replaceInternalLinks2( $text ) );
2255 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2256 $s .= $prefix . $this->armorLinks(
2257 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2259 $s .= $prefix . $trail;
2261 wfProfileOut( __METHOD__
. "-image" );
2265 if ( $ns == NS_CATEGORY
) {
2266 wfProfileIn( __METHOD__
. "-category" );
2267 $s = rtrim( $s . "\n" ); # bug 87
2270 $sortkey = $this->getDefaultSort();
2274 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2275 $sortkey = str_replace( "\n", '', $sortkey );
2276 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2277 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2280 * Strip the whitespace Category links produce, see bug 87
2282 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2284 wfProfileOut( __METHOD__
. "-category" );
2289 # Self-link checking. For some languages, variants of the title are checked in
2290 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2291 # for linking to a different variant.
2292 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2293 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2297 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2298 # @todo FIXME: Should do batch file existence checks, see comment below
2299 if ( $ns == NS_MEDIA
) {
2300 wfProfileIn( __METHOD__
. "-media" );
2301 # Give extensions a chance to select the file revision for us
2304 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2305 array( $this, $nt, &$options, &$descQuery ) );
2306 # Fetch and register the file (file title may be different via hooks)
2307 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2308 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2309 $s .= $prefix . $this->armorLinks(
2310 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2311 wfProfileOut( __METHOD__
. "-media" );
2315 wfProfileIn( __METHOD__
. "-always_known" );
2316 # Some titles, such as valid special pages or files in foreign repos, should
2317 # be shown as bluelinks even though they're not included in the page table
2319 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2320 # batch file existence checks for NS_FILE and NS_MEDIA
2321 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2322 $this->mOutput
->addLink( $nt );
2323 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2325 # Links will be added to the output link list after checking
2326 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2328 wfProfileOut( __METHOD__
. "-always_known" );
2330 wfProfileOut( __METHOD__
);
2335 * Render a forced-blue link inline; protect against double expansion of
2336 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2337 * Since this little disaster has to split off the trail text to avoid
2338 * breaking URLs in the following text without breaking trails on the
2339 * wiki links, it's been made into a horrible function.
2342 * @param string $text
2343 * @param array|string $query
2344 * @param string $trail
2345 * @param string $prefix
2346 * @return string HTML-wikitext mix oh yuck
2348 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2349 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2351 if ( is_string( $query ) ) {
2352 $query = wfCgiToArray( $query );
2354 if ( $text == '' ) {
2355 $text = htmlspecialchars( $nt->getPrefixedText() );
2358 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2360 return $this->armorLinks( $link ) . $trail;
2364 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2365 * going to go through further parsing steps before inline URL expansion.
2367 * Not needed quite as much as it used to be since free links are a bit
2368 * more sensible these days. But bracketed links are still an issue.
2370 * @param string $text More-or-less HTML
2371 * @return string Less-or-more HTML with NOPARSE bits
2373 public function armorLinks( $text ) {
2374 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2375 "{$this->mUniqPrefix}NOPARSE$1", $text );
2379 * Return true if subpage links should be expanded on this page.
2382 public function areSubpagesAllowed() {
2383 # Some namespaces don't allow subpages
2384 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2388 * Handle link to subpage if necessary
2390 * @param string $target The source of the link
2391 * @param string &$text The link text, modified as necessary
2392 * @return string The full name of the link
2395 public function maybeDoSubpageLink( $target, &$text ) {
2396 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2400 * Used by doBlockLevels()
2405 public function closeParagraph() {
2407 if ( $this->mLastSection
!= '' ) {
2408 $result = '</' . $this->mLastSection
. ">\n";
2410 $this->mInPre
= false;
2411 $this->mLastSection
= '';
2416 * getCommon() returns the length of the longest common substring
2417 * of both arguments, starting at the beginning of both.
2420 * @param string $st1
2421 * @param string $st2
2425 public function getCommon( $st1, $st2 ) {
2426 $fl = strlen( $st1 );
2427 $shorter = strlen( $st2 );
2428 if ( $fl < $shorter ) {
2432 for ( $i = 0; $i < $shorter; ++
$i ) {
2433 if ( $st1[$i] != $st2[$i] ) {
2441 * These next three functions open, continue, and close the list
2442 * element appropriate to the prefix character passed into them.
2445 * @param string $char
2449 public function openList( $char ) {
2450 $result = $this->closeParagraph();
2452 if ( '*' === $char ) {
2453 $result .= "<ul><li>";
2454 } elseif ( '#' === $char ) {
2455 $result .= "<ol><li>";
2456 } elseif ( ':' === $char ) {
2457 $result .= "<dl><dd>";
2458 } elseif ( ';' === $char ) {
2459 $result .= "<dl><dt>";
2460 $this->mDTopen
= true;
2462 $result = '<!-- ERR 1 -->';
2470 * @param string $char
2475 public function nextItem( $char ) {
2476 if ( '*' === $char ||
'#' === $char ) {
2477 return "</li>\n<li>";
2478 } elseif ( ':' === $char ||
';' === $char ) {
2480 if ( $this->mDTopen
) {
2483 if ( ';' === $char ) {
2484 $this->mDTopen
= true;
2485 return $close . '<dt>';
2487 $this->mDTopen
= false;
2488 return $close . '<dd>';
2491 return '<!-- ERR 2 -->';
2496 * @param string $char
2501 public function closeList( $char ) {
2502 if ( '*' === $char ) {
2503 $text = "</li></ul>";
2504 } elseif ( '#' === $char ) {
2505 $text = "</li></ol>";
2506 } elseif ( ':' === $char ) {
2507 if ( $this->mDTopen
) {
2508 $this->mDTopen
= false;
2509 $text = "</dt></dl>";
2511 $text = "</dd></dl>";
2514 return '<!-- ERR 3 -->';
2521 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2523 * @param string $text
2524 * @param bool $linestart Whether or not this is at the start of a line.
2526 * @return string The lists rendered as HTML
2528 public function doBlockLevels( $text, $linestart ) {
2529 wfProfileIn( __METHOD__
);
2531 # Parsing through the text line by line. The main thing
2532 # happening here is handling of block-level elements p, pre,
2533 # and making lists from lines starting with * # : etc.
2535 $textLines = StringUtils
::explode( "\n", $text );
2537 $lastPrefix = $output = '';
2538 $this->mDTopen
= $inBlockElem = false;
2540 $paragraphStack = false;
2541 $inBlockquote = false;
2543 foreach ( $textLines as $oLine ) {
2545 if ( !$linestart ) {
2555 $lastPrefixLength = strlen( $lastPrefix );
2556 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2557 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2558 # If not in a <pre> element, scan for and figure out what prefixes are there.
2559 if ( !$this->mInPre
) {
2560 # Multiple prefixes may abut each other for nested lists.
2561 $prefixLength = strspn( $oLine, '*#:;' );
2562 $prefix = substr( $oLine, 0, $prefixLength );
2565 # ; and : are both from definition-lists, so they're equivalent
2566 # for the purposes of determining whether or not we need to open/close
2568 $prefix2 = str_replace( ';', ':', $prefix );
2569 $t = substr( $oLine, $prefixLength );
2570 $this->mInPre
= (bool)$preOpenMatch;
2572 # Don't interpret any other prefixes in preformatted text
2574 $prefix = $prefix2 = '';
2579 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2580 # Same as the last item, so no need to deal with nesting or opening stuff
2581 $output .= $this->nextItem( substr( $prefix, -1 ) );
2582 $paragraphStack = false;
2584 if ( substr( $prefix, -1 ) === ';' ) {
2585 # The one nasty exception: definition lists work like this:
2586 # ; title : definition text
2587 # So we check for : in the remainder text to split up the
2588 # title and definition, without b0rking links.
2590 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2592 $output .= $term . $this->nextItem( ':' );
2595 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2596 # We need to open or close prefixes, or both.
2598 # Either open or close a level...
2599 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2600 $paragraphStack = false;
2602 # Close all the prefixes which aren't shared.
2603 while ( $commonPrefixLength < $lastPrefixLength ) {
2604 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2605 --$lastPrefixLength;
2608 # Continue the current prefix if appropriate.
2609 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2610 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2613 # Open prefixes where appropriate.
2614 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2617 while ( $prefixLength > $commonPrefixLength ) {
2618 $char = substr( $prefix, $commonPrefixLength, 1 );
2619 $output .= $this->openList( $char );
2621 if ( ';' === $char ) {
2622 # @todo FIXME: This is dupe of code above
2623 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2625 $output .= $term . $this->nextItem( ':' );
2628 ++
$commonPrefixLength;
2630 if ( !$prefixLength && $lastPrefix ) {
2633 $lastPrefix = $prefix2;
2636 # If we have no prefixes, go to paragraph mode.
2637 if ( 0 == $prefixLength ) {
2638 wfProfileIn( __METHOD__
. "-paragraph" );
2639 # No prefix (not in list)--go to paragraph mode
2640 # XXX: use a stack for nestable elements like span, table and div
2641 $openmatch = preg_match(
2642 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2643 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2646 $closematch = preg_match(
2647 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2648 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2649 . $this->mUniqPrefix
2650 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2654 if ( $openmatch ||
$closematch ) {
2655 $paragraphStack = false;
2656 # @todo bug 5718: paragraph closed
2657 $output .= $this->closeParagraph();
2658 if ( $preOpenMatch && !$preCloseMatch ) {
2659 $this->mInPre
= true;
2662 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2663 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2664 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2666 $inBlockElem = !$closematch;
2667 } elseif ( !$inBlockElem && !$this->mInPre
) {
2668 if ( ' ' == substr( $t, 0, 1 )
2669 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2673 if ( $this->mLastSection
!== 'pre' ) {
2674 $paragraphStack = false;
2675 $output .= $this->closeParagraph() . '<pre>';
2676 $this->mLastSection
= 'pre';
2678 $t = substr( $t, 1 );
2681 if ( trim( $t ) === '' ) {
2682 if ( $paragraphStack ) {
2683 $output .= $paragraphStack . '<br />';
2684 $paragraphStack = false;
2685 $this->mLastSection
= 'p';
2687 if ( $this->mLastSection
!== 'p' ) {
2688 $output .= $this->closeParagraph();
2689 $this->mLastSection
= '';
2690 $paragraphStack = '<p>';
2692 $paragraphStack = '</p><p>';
2696 if ( $paragraphStack ) {
2697 $output .= $paragraphStack;
2698 $paragraphStack = false;
2699 $this->mLastSection
= 'p';
2700 } elseif ( $this->mLastSection
!== 'p' ) {
2701 $output .= $this->closeParagraph() . '<p>';
2702 $this->mLastSection
= 'p';
2707 wfProfileOut( __METHOD__
. "-paragraph" );
2709 # somewhere above we forget to get out of pre block (bug 785)
2710 if ( $preCloseMatch && $this->mInPre
) {
2711 $this->mInPre
= false;
2713 if ( $paragraphStack === false ) {
2715 if ( $prefixLength === 0 ) {
2720 while ( $prefixLength ) {
2721 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2723 if ( !$prefixLength ) {
2727 if ( $this->mLastSection
!= '' ) {
2728 $output .= '</' . $this->mLastSection
. '>';
2729 $this->mLastSection
= '';
2732 wfProfileOut( __METHOD__
);
2737 * Split up a string on ':', ignoring any occurrences inside tags
2738 * to prevent illegal overlapping.
2740 * @param string $str The string to split
2741 * @param string &$before Set to everything before the ':'
2742 * @param string &$after Set to everything after the ':'
2743 * @throws MWException
2744 * @return string The position of the ':', or false if none found
2746 public function findColonNoLinks( $str, &$before, &$after ) {
2747 wfProfileIn( __METHOD__
);
2749 $pos = strpos( $str, ':' );
2750 if ( $pos === false ) {
2752 wfProfileOut( __METHOD__
);
2756 $lt = strpos( $str, '<' );
2757 if ( $lt === false ||
$lt > $pos ) {
2758 # Easy; no tag nesting to worry about
2759 $before = substr( $str, 0, $pos );
2760 $after = substr( $str, $pos +
1 );
2761 wfProfileOut( __METHOD__
);
2765 # Ugly state machine to walk through avoiding tags.
2766 $state = self
::COLON_STATE_TEXT
;
2768 $len = strlen( $str );
2769 for ( $i = 0; $i < $len; $i++
) {
2773 # (Using the number is a performance hack for common cases)
2774 case 0: # self::COLON_STATE_TEXT:
2777 # Could be either a <start> tag or an </end> tag
2778 $state = self
::COLON_STATE_TAGSTART
;
2781 if ( $stack == 0 ) {
2783 $before = substr( $str, 0, $i );
2784 $after = substr( $str, $i +
1 );
2785 wfProfileOut( __METHOD__
);
2788 # Embedded in a tag; don't break it.
2791 # Skip ahead looking for something interesting
2792 $colon = strpos( $str, ':', $i );
2793 if ( $colon === false ) {
2794 # Nothing else interesting
2795 wfProfileOut( __METHOD__
);
2798 $lt = strpos( $str, '<', $i );
2799 if ( $stack === 0 ) {
2800 if ( $lt === false ||
$colon < $lt ) {
2802 $before = substr( $str, 0, $colon );
2803 $after = substr( $str, $colon +
1 );
2804 wfProfileOut( __METHOD__
);
2808 if ( $lt === false ) {
2809 # Nothing else interesting to find; abort!
2810 # We're nested, but there's no close tags left. Abort!
2813 # Skip ahead to next tag start
2815 $state = self
::COLON_STATE_TAGSTART
;
2818 case 1: # self::COLON_STATE_TAG:
2823 $state = self
::COLON_STATE_TEXT
;
2826 # Slash may be followed by >?
2827 $state = self
::COLON_STATE_TAGSLASH
;
2833 case 2: # self::COLON_STATE_TAGSTART:
2836 $state = self
::COLON_STATE_CLOSETAG
;
2839 $state = self
::COLON_STATE_COMMENT
;
2842 # Illegal early close? This shouldn't happen D:
2843 $state = self
::COLON_STATE_TEXT
;
2846 $state = self
::COLON_STATE_TAG
;
2849 case 3: # self::COLON_STATE_CLOSETAG:
2854 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2855 wfProfileOut( __METHOD__
);
2858 $state = self
::COLON_STATE_TEXT
;
2861 case self
::COLON_STATE_TAGSLASH
:
2863 # Yes, a self-closed tag <blah/>
2864 $state = self
::COLON_STATE_TEXT
;
2866 # Probably we're jumping the gun, and this is an attribute
2867 $state = self
::COLON_STATE_TAG
;
2870 case 5: # self::COLON_STATE_COMMENT:
2872 $state = self
::COLON_STATE_COMMENTDASH
;
2875 case self
::COLON_STATE_COMMENTDASH
:
2877 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2879 $state = self
::COLON_STATE_COMMENT
;
2882 case self
::COLON_STATE_COMMENTDASHDASH
:
2884 $state = self
::COLON_STATE_TEXT
;
2886 $state = self
::COLON_STATE_COMMENT
;
2890 wfProfileOut( __METHOD__
);
2891 throw new MWException( "State machine error in " . __METHOD__
);
2895 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2896 wfProfileOut( __METHOD__
);
2899 wfProfileOut( __METHOD__
);
2904 * Return value of a magic variable (like PAGENAME)
2909 * @param bool|PPFrame $frame
2911 * @throws MWException
2914 public function getVariableValue( $index, $frame = false ) {
2915 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2916 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2918 if ( is_null( $this->mTitle
) ) {
2919 // If no title set, bad things are going to happen
2920 // later. Title should always be set since this
2921 // should only be called in the middle of a parse
2922 // operation (but the unit-tests do funky stuff)
2923 throw new MWException( __METHOD__
. ' Should only be '
2924 . ' called while parsing (no title set)' );
2928 * Some of these require message or data lookups and can be
2929 * expensive to check many times.
2931 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2932 if ( isset( $this->mVarCache
[$index] ) ) {
2933 return $this->mVarCache
[$index];
2937 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2938 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2940 $pageLang = $this->getFunctionLang();
2946 case 'currentmonth':
2947 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2949 case 'currentmonth1':
2950 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2952 case 'currentmonthname':
2953 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2955 case 'currentmonthnamegen':
2956 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2958 case 'currentmonthabbrev':
2959 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2962 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2965 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2968 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2971 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2973 case 'localmonthname':
2974 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2976 case 'localmonthnamegen':
2977 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2979 case 'localmonthabbrev':
2980 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2983 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2986 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2989 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2992 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2994 case 'fullpagename':
2995 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2997 case 'fullpagenamee':
2998 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
3001 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
3003 case 'subpagenamee':
3004 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3006 case 'rootpagename':
3007 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3009 case 'rootpagenamee':
3010 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3013 $this->mTitle
->getRootText()
3016 case 'basepagename':
3017 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3019 case 'basepagenamee':
3020 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3023 $this->mTitle
->getBaseText()
3026 case 'talkpagename':
3027 if ( $this->mTitle
->canTalk() ) {
3028 $talkPage = $this->mTitle
->getTalkPage();
3029 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3034 case 'talkpagenamee':
3035 if ( $this->mTitle
->canTalk() ) {
3036 $talkPage = $this->mTitle
->getTalkPage();
3037 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3042 case 'subjectpagename':
3043 $subjPage = $this->mTitle
->getSubjectPage();
3044 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3046 case 'subjectpagenamee':
3047 $subjPage = $this->mTitle
->getSubjectPage();
3048 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3050 case 'pageid': // requested in bug 23427
3051 $pageid = $this->getTitle()->getArticleID();
3052 if ( $pageid == 0 ) {
3053 # 0 means the page doesn't exist in the database,
3054 # which means the user is previewing a new page.
3055 # The vary-revision flag must be set, because the magic word
3056 # will have a different value once the page is saved.
3057 $this->mOutput
->setFlag( 'vary-revision' );
3058 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3060 $value = $pageid ?
$pageid : null;
3063 # Let the edit saving system know we should parse the page
3064 # *after* a revision ID has been assigned.
3065 $this->mOutput
->setFlag( 'vary-revision' );
3066 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3067 $value = $this->mRevisionId
;
3070 # Let the edit saving system know we should parse the page
3071 # *after* a revision ID has been assigned. This is for null edits.
3072 $this->mOutput
->setFlag( 'vary-revision' );
3073 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3074 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3076 case 'revisionday2':
3077 # Let the edit saving system know we should parse the page
3078 # *after* a revision ID has been assigned. This is for null edits.
3079 $this->mOutput
->setFlag( 'vary-revision' );
3080 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3081 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3083 case 'revisionmonth':
3084 # Let the edit saving system know we should parse the page
3085 # *after* a revision ID has been assigned. This is for null edits.
3086 $this->mOutput
->setFlag( 'vary-revision' );
3087 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3088 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3090 case 'revisionmonth1':
3091 # Let the edit saving system know we should parse the page
3092 # *after* a revision ID has been assigned. This is for null edits.
3093 $this->mOutput
->setFlag( 'vary-revision' );
3094 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3095 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3097 case 'revisionyear':
3098 # Let the edit saving system know we should parse the page
3099 # *after* a revision ID has been assigned. This is for null edits.
3100 $this->mOutput
->setFlag( 'vary-revision' );
3101 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3102 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3104 case 'revisiontimestamp':
3105 # Let the edit saving system know we should parse the page
3106 # *after* a revision ID has been assigned. This is for null edits.
3107 $this->mOutput
->setFlag( 'vary-revision' );
3108 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3109 $value = $this->getRevisionTimestamp();
3111 case 'revisionuser':
3112 # Let the edit saving system know we should parse the page
3113 # *after* a revision ID has been assigned. This is for null edits.
3114 $this->mOutput
->setFlag( 'vary-revision' );
3115 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3116 $value = $this->getRevisionUser();
3118 case 'revisionsize':
3119 # Let the edit saving system know we should parse the page
3120 # *after* a revision ID has been assigned. This is for null edits.
3121 $this->mOutput
->setFlag( 'vary-revision' );
3122 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3123 $value = $this->getRevisionSize();
3126 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3129 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3131 case 'namespacenumber':
3132 $value = $this->mTitle
->getNamespace();
3135 $value = $this->mTitle
->canTalk()
3136 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3140 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3142 case 'subjectspace':
3143 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3145 case 'subjectspacee':
3146 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3148 case 'currentdayname':
3149 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3152 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3155 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3158 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3161 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3162 # int to remove the padding
3163 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3166 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3168 case 'localdayname':
3169 $value = $pageLang->getWeekdayName(
3170 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3174 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3177 $value = $pageLang->time(
3178 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3184 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3187 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3188 # int to remove the padding
3189 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3192 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3194 case 'numberofarticles':
3195 $value = $pageLang->formatNum( SiteStats
::articles() );
3197 case 'numberoffiles':
3198 $value = $pageLang->formatNum( SiteStats
::images() );
3200 case 'numberofusers':
3201 $value = $pageLang->formatNum( SiteStats
::users() );
3203 case 'numberofactiveusers':
3204 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3206 case 'numberofpages':
3207 $value = $pageLang->formatNum( SiteStats
::pages() );
3209 case 'numberofadmins':
3210 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3212 case 'numberofedits':
3213 $value = $pageLang->formatNum( SiteStats
::edits() );
3215 case 'currenttimestamp':
3216 $value = wfTimestamp( TS_MW
, $ts );
3218 case 'localtimestamp':
3219 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3221 case 'currentversion':
3222 $value = SpecialVersion
::getVersion();
3225 return $wgArticlePath;
3231 return $wgServerName;
3233 return $wgScriptPath;
3235 return $wgStylePath;
3236 case 'directionmark':
3237 return $pageLang->getDirMark();
3238 case 'contentlanguage':
3239 global $wgLanguageCode;
3240 return $wgLanguageCode;
3241 case 'cascadingsources':
3242 $value = CoreParserFunctions
::cascadingsources( $this );
3247 'ParserGetVariableValueSwitch',
3248 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3255 $this->mVarCache
[$index] = $value;
3262 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3266 public function initialiseVariables() {
3267 wfProfileIn( __METHOD__
);
3268 $variableIDs = MagicWord
::getVariableIDs();
3269 $substIDs = MagicWord
::getSubstIDs();
3271 $this->mVariables
= new MagicWordArray( $variableIDs );
3272 $this->mSubstWords
= new MagicWordArray( $substIDs );
3273 wfProfileOut( __METHOD__
);
3277 * Preprocess some wikitext and return the document tree.
3278 * This is the ghost of replace_variables().
3280 * @param string $text The text to parse
3281 * @param int $flags Bitwise combination of:
3282 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3283 * included. Default is to assume a direct page view.
3285 * The generated DOM tree must depend only on the input text and the flags.
3286 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3288 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3289 * change in the DOM tree for a given text, must be passed through the section identifier
3290 * in the section edit link and thus back to extractSections().
3292 * The output of this function is currently only cached in process memory, but a persistent
3293 * cache may be implemented at a later date which takes further advantage of these strict
3294 * dependency requirements.
3298 public function preprocessToDom( $text, $flags = 0 ) {
3299 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3304 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3310 public static function splitWhitespace( $s ) {
3311 $ltrimmed = ltrim( $s );
3312 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3313 $trimmed = rtrim( $ltrimmed );
3314 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3316 $w2 = substr( $ltrimmed, -$diff );
3320 return array( $w1, $trimmed, $w2 );
3324 * Replace magic variables, templates, and template arguments
3325 * with the appropriate text. Templates are substituted recursively,
3326 * taking care to avoid infinite loops.
3328 * Note that the substitution depends on value of $mOutputType:
3329 * self::OT_WIKI: only {{subst:}} templates
3330 * self::OT_PREPROCESS: templates but not extension tags
3331 * self::OT_HTML: all templates and extension tags
3333 * @param string $text The text to transform
3334 * @param bool|PPFrame $frame Object describing the arguments passed to the
3335 * template. Arguments may also be provided as an associative array, as
3336 * was the usual case before MW1.12. Providing arguments this way may be
3337 * useful for extensions wishing to perform variable replacement
3339 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3340 * double-brace expansion.
3343 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3344 # Is there any text? Also, Prevent too big inclusions!
3345 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3348 wfProfileIn( __METHOD__
);
3350 if ( $frame === false ) {
3351 $frame = $this->getPreprocessor()->newFrame();
3352 } elseif ( !( $frame instanceof PPFrame
) ) {
3353 wfDebug( __METHOD__
. " called using plain parameters instead of "
3354 . "a PPFrame instance. Creating custom frame.\n" );
3355 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3358 $dom = $this->preprocessToDom( $text );
3359 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3360 $text = $frame->expand( $dom, $flags );
3362 wfProfileOut( __METHOD__
);
3367 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3369 * @param array $args
3373 public static function createAssocArgs( $args ) {
3374 $assocArgs = array();
3376 foreach ( $args as $arg ) {
3377 $eqpos = strpos( $arg, '=' );
3378 if ( $eqpos === false ) {
3379 $assocArgs[$index++
] = $arg;
3381 $name = trim( substr( $arg, 0, $eqpos ) );
3382 $value = trim( substr( $arg, $eqpos +
1 ) );
3383 if ( $value === false ) {
3386 if ( $name !== false ) {
3387 $assocArgs[$name] = $value;
3396 * Warn the user when a parser limitation is reached
3397 * Will warn at most once the user per limitation type
3399 * @param string $limitationType Should be one of:
3400 * 'expensive-parserfunction' (corresponding messages:
3401 * 'expensive-parserfunction-warning',
3402 * 'expensive-parserfunction-category')
3403 * 'post-expand-template-argument' (corresponding messages:
3404 * 'post-expand-template-argument-warning',
3405 * 'post-expand-template-argument-category')
3406 * 'post-expand-template-inclusion' (corresponding messages:
3407 * 'post-expand-template-inclusion-warning',
3408 * 'post-expand-template-inclusion-category')
3409 * 'node-count-exceeded' (corresponding messages:
3410 * 'node-count-exceeded-warning',
3411 * 'node-count-exceeded-category')
3412 * 'expansion-depth-exceeded' (corresponding messages:
3413 * 'expansion-depth-exceeded-warning',
3414 * 'expansion-depth-exceeded-category')
3415 * @param string|int|null $current Current value
3416 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3417 * exceeded, provide the values (optional)
3419 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3420 # does no harm if $current and $max are present but are unnecessary for the message
3421 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3422 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3423 $this->mOutput
->addWarning( $warning );
3424 $this->addTrackingCategory( "$limitationType-category" );
3428 * Return the text of a template, after recursively
3429 * replacing any variables or templates within the template.
3431 * @param array $piece The parts of the template
3432 * $piece['title']: the title, i.e. the part before the |
3433 * $piece['parts']: the parameter array
3434 * $piece['lineStart']: whether the brace was at the start of a line
3435 * @param PPFrame $frame The current frame, contains template arguments
3437 * @return string The text of the template
3439 public function braceSubstitution( $piece, $frame ) {
3440 wfProfileIn( __METHOD__
);
3441 wfProfileIn( __METHOD__
. '-setup' );
3445 // $text has been filled
3447 // wiki markup in $text should be escaped
3449 // $text is HTML, armour it against wikitext transformation
3451 // Force interwiki transclusion to be done in raw mode not rendered
3452 $forceRawInterwiki = false;
3453 // $text is a DOM node needing expansion in a child frame
3454 $isChildObj = false;
3455 // $text is a DOM node needing expansion in the current frame
3456 $isLocalObj = false;
3458 # Title object, where $text came from
3461 # $part1 is the bit before the first |, and must contain only title characters.
3462 # Various prefixes will be stripped from it later.
3463 $titleWithSpaces = $frame->expand( $piece['title'] );
3464 $part1 = trim( $titleWithSpaces );
3467 # Original title text preserved for various purposes
3468 $originalTitle = $part1;
3470 # $args is a list of argument nodes, starting from index 0, not including $part1
3471 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3472 # below won't work b/c this $args isn't an object
3473 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3474 wfProfileOut( __METHOD__
. '-setup' );
3476 $titleProfileIn = null; // profile templates
3479 wfProfileIn( __METHOD__
. '-modifiers' );
3482 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3484 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3485 # Decide whether to expand template or keep wikitext as-is.
3486 if ( $this->ot
['wiki'] ) {
3487 if ( $substMatch === false ) {
3488 $literal = true; # literal when in PST with no prefix
3490 $literal = false; # expand when in PST with subst: or safesubst:
3493 if ( $substMatch == 'subst' ) {
3494 $literal = true; # literal when not in PST with plain subst:
3496 $literal = false; # expand when not in PST with safesubst: or no prefix
3500 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3507 if ( !$found && $args->getLength() == 0 ) {
3508 $id = $this->mVariables
->matchStartToEnd( $part1 );
3509 if ( $id !== false ) {
3510 $text = $this->getVariableValue( $id, $frame );
3511 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3512 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3518 # MSG, MSGNW and RAW
3521 $mwMsgnw = MagicWord
::get( 'msgnw' );
3522 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3525 # Remove obsolete MSG:
3526 $mwMsg = MagicWord
::get( 'msg' );
3527 $mwMsg->matchStartAndRemove( $part1 );
3531 $mwRaw = MagicWord
::get( 'raw' );
3532 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3533 $forceRawInterwiki = true;
3536 wfProfileOut( __METHOD__
. '-modifiers' );
3540 wfProfileIn( __METHOD__
. '-pfunc' );
3542 $colonPos = strpos( $part1, ':' );
3543 if ( $colonPos !== false ) {
3544 $func = substr( $part1, 0, $colonPos );
3545 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3546 for ( $i = 0; $i < $args->getLength(); $i++
) {
3547 $funcArgs[] = $args->item( $i );
3550 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3551 } catch ( Exception
$ex ) {
3552 wfProfileOut( __METHOD__
. '-pfunc' );
3553 wfProfileOut( __METHOD__
);
3557 # The interface for parser functions allows for extracting
3558 # flags into the local scope. Extract any forwarded flags
3562 wfProfileOut( __METHOD__
. '-pfunc' );
3565 # Finish mangling title and then check for loops.
3566 # Set $title to a Title object and $titleText to the PDBK
3569 # Split the title into page and subpage
3571 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3572 if ( $part1 !== $relative ) {
3574 $ns = $this->mTitle
->getNamespace();
3576 $title = Title
::newFromText( $part1, $ns );
3578 $titleText = $title->getPrefixedText();
3579 # Check for language variants if the template is not found
3580 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3581 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3583 # Do recursion depth check
3584 $limit = $this->mOptions
->getMaxTemplateDepth();
3585 if ( $frame->depth
>= $limit ) {
3587 $text = '<span class="error">'
3588 . wfMessage( 'parser-template-recursion-depth-warning' )
3589 ->numParams( $limit )->inContentLanguage()->text()
3595 # Load from database
3596 if ( !$found && $title ) {
3597 if ( !Profiler
::instance()->isPersistent() ) {
3598 # Too many unique items can kill profiling DBs/collectors
3599 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3600 wfProfileIn( $titleProfileIn ); // template in
3602 wfProfileIn( __METHOD__
. '-loadtpl' );
3603 if ( !$title->isExternal() ) {
3604 if ( $title->isSpecialPage()
3605 && $this->mOptions
->getAllowSpecialInclusion()
3606 && $this->ot
['html']
3608 // Pass the template arguments as URL parameters.
3609 // "uselang" will have no effect since the Language object
3610 // is forced to the one defined in ParserOptions.
3611 $pageArgs = array();
3612 $argsLength = $args->getLength();
3613 for ( $i = 0; $i < $argsLength; $i++
) {
3614 $bits = $args->item( $i )->splitArg();
3615 if ( strval( $bits['index'] ) === '' ) {
3616 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3617 $value = trim( $frame->expand( $bits['value'] ) );
3618 $pageArgs[$name] = $value;
3622 // Create a new context to execute the special page
3623 $context = new RequestContext
;
3624 $context->setTitle( $title );
3625 $context->setRequest( new FauxRequest( $pageArgs ) );
3626 $context->setUser( $this->getUser() );
3627 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3628 $ret = SpecialPageFactory
::capturePath( $title, $context );
3630 $text = $context->getOutput()->getHTML();
3631 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3634 $this->disableCache();
3636 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3637 $found = false; # access denied
3638 wfDebug( __METHOD__
. ": template inclusion denied for " .
3639 $title->getPrefixedDBkey() . "\n" );
3641 list( $text, $title ) = $this->getTemplateDom( $title );
3642 if ( $text !== false ) {
3648 # If the title is valid but undisplayable, make a link to it
3649 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3650 $text = "[[:$titleText]]";
3653 } elseif ( $title->isTrans() ) {
3654 # Interwiki transclusion
3655 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3656 $text = $this->interwikiTransclude( $title, 'render' );
3659 $text = $this->interwikiTransclude( $title, 'raw' );
3660 # Preprocess it like a template
3661 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3667 # Do infinite loop check
3668 # This has to be done after redirect resolution to avoid infinite loops via redirects
3669 if ( !$frame->loopCheck( $title ) ) {
3671 $text = '<span class="error">'
3672 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3674 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3676 wfProfileOut( __METHOD__
. '-loadtpl' );
3679 # If we haven't found text to substitute by now, we're done
3680 # Recover the source wikitext and return it
3682 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3683 if ( $titleProfileIn ) {
3684 wfProfileOut( $titleProfileIn ); // template out
3686 wfProfileOut( __METHOD__
);
3687 return array( 'object' => $text );
3690 # Expand DOM-style return values in a child frame
3691 if ( $isChildObj ) {
3692 # Clean up argument array
3693 $newFrame = $frame->newChild( $args, $title );
3696 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3697 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3698 # Expansion is eligible for the empty-frame cache
3699 $text = $newFrame->cachedExpand( $titleText, $text );
3701 # Uncached expansion
3702 $text = $newFrame->expand( $text );
3705 if ( $isLocalObj && $nowiki ) {
3706 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3707 $isLocalObj = false;
3710 if ( $titleProfileIn ) {
3711 wfProfileOut( $titleProfileIn ); // template out
3714 # Replace raw HTML by a placeholder
3716 $text = $this->insertStripItem( $text );
3717 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3718 # Escape nowiki-style return values
3719 $text = wfEscapeWikiText( $text );
3720 } elseif ( is_string( $text )
3721 && !$piece['lineStart']
3722 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3724 # Bug 529: if the template begins with a table or block-level
3725 # element, it should be treated as beginning a new line.
3726 # This behavior is somewhat controversial.
3727 $text = "\n" . $text;
3730 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3731 # Error, oversize inclusion
3732 if ( $titleText !== false ) {
3733 # Make a working, properly escaped link if possible (bug 23588)
3734 $text = "[[:$titleText]]";
3736 # This will probably not be a working link, but at least it may
3737 # provide some hint of where the problem is
3738 preg_replace( '/^:/', '', $originalTitle );
3739 $text = "[[:$originalTitle]]";
3741 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3742 . 'post-expand include size too large -->' );
3743 $this->limitationWarn( 'post-expand-template-inclusion' );
3746 if ( $isLocalObj ) {
3747 $ret = array( 'object' => $text );
3749 $ret = array( 'text' => $text );
3752 wfProfileOut( __METHOD__
);
3757 * Call a parser function and return an array with text and flags.
3759 * The returned array will always contain a boolean 'found', indicating
3760 * whether the parser function was found or not. It may also contain the
3762 * text: string|object, resulting wikitext or PP DOM object
3763 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3764 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3765 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3766 * nowiki: bool, wiki markup in $text should be escaped
3769 * @param PPFrame $frame The current frame, contains template arguments
3770 * @param string $function Function name
3771 * @param array $args Arguments to the function
3772 * @throws MWException
3775 public function callParserFunction( $frame, $function, array $args = array() ) {
3778 wfProfileIn( __METHOD__
);
3780 # Case sensitive functions
3781 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3782 $function = $this->mFunctionSynonyms
[1][$function];
3784 # Case insensitive functions
3785 $function = $wgContLang->lc( $function );
3786 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3787 $function = $this->mFunctionSynonyms
[0][$function];
3789 wfProfileOut( __METHOD__
);
3790 return array( 'found' => false );
3794 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3795 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3797 # Workaround for PHP bug 35229 and similar
3798 if ( !is_callable( $callback ) ) {
3799 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3800 wfProfileOut( __METHOD__
);
3801 throw new MWException( "Tag hook for $function is not callable\n" );
3804 $allArgs = array( &$this );
3805 if ( $flags & SFH_OBJECT_ARGS
) {
3806 # Convert arguments to PPNodes and collect for appending to $allArgs
3807 $funcArgs = array();
3808 foreach ( $args as $k => $v ) {
3809 if ( $v instanceof PPNode ||
$k === 0 ) {
3812 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3816 # Add a frame parameter, and pass the arguments as an array
3817 $allArgs[] = $frame;
3818 $allArgs[] = $funcArgs;
3820 # Convert arguments to plain text and append to $allArgs
3821 foreach ( $args as $k => $v ) {
3822 if ( $v instanceof PPNode
) {
3823 $allArgs[] = trim( $frame->expand( $v ) );
3824 } elseif ( is_int( $k ) && $k >= 0 ) {
3825 $allArgs[] = trim( $v );
3827 $allArgs[] = trim( "$k=$v" );
3832 $result = call_user_func_array( $callback, $allArgs );
3834 # The interface for function hooks allows them to return a wikitext
3835 # string or an array containing the string and any flags. This mungs
3836 # things around to match what this method should return.
3837 if ( !is_array( $result ) ) {
3843 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3844 $result['text'] = $result[0];
3846 unset( $result[0] );
3853 $preprocessFlags = 0;
3854 if ( isset( $result['noparse'] ) ) {
3855 $noparse = $result['noparse'];
3857 if ( isset( $result['preprocessFlags'] ) ) {
3858 $preprocessFlags = $result['preprocessFlags'];
3862 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3863 $result['isChildObj'] = true;
3865 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3866 wfProfileOut( __METHOD__
);
3872 * Get the semi-parsed DOM representation of a template with a given title,
3873 * and its redirect destination title. Cached.
3875 * @param Title $title
3879 public function getTemplateDom( $title ) {
3880 $cacheTitle = $title;
3881 $titleText = $title->getPrefixedDBkey();
3883 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3884 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3885 $title = Title
::makeTitle( $ns, $dbk );
3886 $titleText = $title->getPrefixedDBkey();
3888 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3889 return array( $this->mTplDomCache
[$titleText], $title );
3892 # Cache miss, go to the database
3893 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3895 if ( $text === false ) {
3896 $this->mTplDomCache
[$titleText] = false;
3897 return array( false, $title );
3900 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3901 $this->mTplDomCache
[$titleText] = $dom;
3903 if ( !$title->equals( $cacheTitle ) ) {
3904 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3905 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3908 return array( $dom, $title );
3912 * Fetch the current revision of a given title. Note that the revision
3913 * (and even the title) may not exist in the database, so everything
3914 * contributing to the output of the parser should use this method
3915 * where possible, rather than getting the revisions themselves. This
3916 * method also caches its results, so using it benefits performance.
3919 * @param Title $title
3922 public function fetchCurrentRevisionOfTitle( $title ) {
3923 $cacheKey = $title->getPrefixedDBkey();
3924 if ( !$this->currentRevisionCache
) {
3925 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3927 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3928 $this->currentRevisionCache
->set( $cacheKey,
3929 // Defaults to Parser::statelessFetchRevision()
3930 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3933 return $this->currentRevisionCache
->get( $cacheKey );
3937 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3938 * without passing them on to it.
3941 * @param Title $title
3942 * @param Parser|bool $parser
3945 public static function statelessFetchRevision( $title, $parser = false ) {
3946 return Revision
::newFromTitle( $title );
3950 * Fetch the unparsed text of a template and register a reference to it.
3951 * @param Title $title
3952 * @return array ( string or false, Title )
3954 public function fetchTemplateAndTitle( $title ) {
3955 // Defaults to Parser::statelessFetchTemplate()
3956 $templateCb = $this->mOptions
->getTemplateCallback();
3957 $stuff = call_user_func( $templateCb, $title, $this );
3958 $text = $stuff['text'];
3959 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3960 if ( isset( $stuff['deps'] ) ) {
3961 foreach ( $stuff['deps'] as $dep ) {
3962 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3963 if ( $dep['title']->equals( $this->getTitle() ) ) {
3964 // If we transclude ourselves, the final result
3965 // will change based on the new version of the page
3966 $this->mOutput
->setFlag( 'vary-revision' );
3970 return array( $text, $finalTitle );
3974 * Fetch the unparsed text of a template and register a reference to it.
3975 * @param Title $title
3976 * @return string|bool
3978 public function fetchTemplate( $title ) {
3979 $rv = $this->fetchTemplateAndTitle( $title );
3984 * Static function to get a template
3985 * Can be overridden via ParserOptions::setTemplateCallback().
3987 * @param Title $title
3988 * @param bool|Parser $parser
3992 public static function statelessFetchTemplate( $title, $parser = false ) {
3993 $text = $skip = false;
3994 $finalTitle = $title;
3997 # Loop to fetch the article, with up to 1 redirect
3998 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3999 # Give extensions a chance to select the revision instead
4000 $id = false; # Assume current
4001 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
4002 array( $parser, $title, &$skip, &$id ) );
4008 'page_id' => $title->getArticleID(),
4015 $rev = Revision
::newFromId( $id );
4016 } elseif ( $parser ) {
4017 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
4019 $rev = Revision
::newFromTitle( $title );
4021 $rev_id = $rev ?
$rev->getId() : 0;
4022 # If there is no current revision, there is no page
4023 if ( $id === false && !$rev ) {
4024 $linkCache = LinkCache
::singleton();
4025 $linkCache->addBadLinkObj( $title );
4030 'page_id' => $title->getArticleID(),
4031 'rev_id' => $rev_id );
4032 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4033 # We fetched a rev from a different title; register it too...
4035 'title' => $rev->getTitle(),
4036 'page_id' => $rev->getPage(),
4037 'rev_id' => $rev_id );
4041 $content = $rev->getContent();
4042 $text = $content ?
$content->getWikitextForTransclusion() : null;
4044 if ( $text === false ||
$text === null ) {
4048 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4050 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4051 if ( !$message->exists() ) {
4055 $content = $message->content();
4056 $text = $message->plain();
4064 $finalTitle = $title;
4065 $title = $content->getRedirectTarget();
4069 'finalTitle' => $finalTitle,
4074 * Fetch a file and its title and register a reference to it.
4075 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4076 * @param Title $title
4077 * @param array $options Array of options to RepoGroup::findFile
4080 public function fetchFile( $title, $options = array() ) {
4081 $res = $this->fetchFileAndTitle( $title, $options );
4086 * Fetch a file and its title and register a reference to it.
4087 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4088 * @param Title $title
4089 * @param array $options Array of options to RepoGroup::findFile
4090 * @return array ( File or false, Title of file )
4092 public function fetchFileAndTitle( $title, $options = array() ) {
4093 $file = $this->fetchFileNoRegister( $title, $options );
4095 $time = $file ?
$file->getTimestamp() : false;
4096 $sha1 = $file ?
$file->getSha1() : false;
4097 # Register the file as a dependency...
4098 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4099 if ( $file && !$title->equals( $file->getTitle() ) ) {
4100 # Update fetched file title
4101 $title = $file->getTitle();
4102 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4104 return array( $file, $title );
4108 * Helper function for fetchFileAndTitle.
4110 * Also useful if you need to fetch a file but not use it yet,
4111 * for example to get the file's handler.
4113 * @param Title $title
4114 * @param array $options Array of options to RepoGroup::findFile
4117 protected function fetchFileNoRegister( $title, $options = array() ) {
4118 if ( isset( $options['broken'] ) ) {
4119 $file = false; // broken thumbnail forced by hook
4120 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4121 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4122 } else { // get by (name,timestamp)
4123 $file = wfFindFile( $title, $options );
4129 * Transclude an interwiki link.
4131 * @param Title $title
4132 * @param string $action
4136 public function interwikiTransclude( $title, $action ) {
4137 global $wgEnableScaryTranscluding;
4139 if ( !$wgEnableScaryTranscluding ) {
4140 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4143 $url = $title->getFullURL( array( 'action' => $action ) );
4145 if ( strlen( $url ) > 255 ) {
4146 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4148 return $this->fetchScaryTemplateMaybeFromCache( $url );
4152 * @param string $url
4153 * @return mixed|string
4155 public function fetchScaryTemplateMaybeFromCache( $url ) {
4156 global $wgTranscludeCacheExpiry;
4157 $dbr = wfGetDB( DB_SLAVE
);
4158 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4159 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4160 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4162 return $obj->tc_contents
;
4165 $req = MWHttpRequest
::factory( $url );
4166 $status = $req->execute(); // Status object
4167 if ( $status->isOK() ) {
4168 $text = $req->getContent();
4169 } elseif ( $req->getStatus() != 200 ) {
4170 // Though we failed to fetch the content, this status is useless.
4171 return wfMessage( 'scarytranscludefailed-httpstatus' )
4172 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4174 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4177 $dbw = wfGetDB( DB_MASTER
);
4178 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4180 'tc_time' => $dbw->timestamp( time() ),
4181 'tc_contents' => $text
4187 * Triple brace replacement -- used for template arguments
4190 * @param array $piece
4191 * @param PPFrame $frame
4195 public function argSubstitution( $piece, $frame ) {
4196 wfProfileIn( __METHOD__
);
4199 $parts = $piece['parts'];
4200 $nameWithSpaces = $frame->expand( $piece['title'] );
4201 $argName = trim( $nameWithSpaces );
4203 $text = $frame->getArgument( $argName );
4204 if ( $text === false && $parts->getLength() > 0
4205 && ( $this->ot
['html']
4207 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4210 # No match in frame, use the supplied default
4211 $object = $parts->item( 0 )->getChildren();
4213 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4214 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4215 $this->limitationWarn( 'post-expand-template-argument' );
4218 if ( $text === false && $object === false ) {
4220 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4222 if ( $error !== false ) {
4225 if ( $object !== false ) {
4226 $ret = array( 'object' => $object );
4228 $ret = array( 'text' => $text );
4231 wfProfileOut( __METHOD__
);
4236 * Return the text to be used for a given extension tag.
4237 * This is the ghost of strip().
4239 * @param array $params Associative array of parameters:
4240 * name PPNode for the tag name
4241 * attr PPNode for unparsed text where tag attributes are thought to be
4242 * attributes Optional associative array of parsed attributes
4243 * inner Contents of extension element
4244 * noClose Original text did not have a close tag
4245 * @param PPFrame $frame
4247 * @throws MWException
4250 public function extensionSubstitution( $params, $frame ) {
4251 $name = $frame->expand( $params['name'] );
4252 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4253 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4254 $marker = "{$this->mUniqPrefix}-$name-"
4255 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4257 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4258 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4259 if ( $isFunctionTag ) {
4260 $markerType = 'none';
4262 $markerType = 'general';
4264 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4265 $name = strtolower( $name );
4266 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4267 if ( isset( $params['attributes'] ) ) {
4268 $attributes = $attributes +
$params['attributes'];
4271 if ( isset( $this->mTagHooks
[$name] ) ) {
4272 # Workaround for PHP bug 35229 and similar
4273 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4274 throw new MWException( "Tag hook for $name is not callable\n" );
4276 $output = call_user_func_array( $this->mTagHooks
[$name],
4277 array( $content, $attributes, $this, $frame ) );
4278 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4279 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4280 if ( !is_callable( $callback ) ) {
4281 throw new MWException( "Tag hook for $name is not callable\n" );
4284 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4286 $output = '<span class="error">Invalid tag extension name: ' .
4287 htmlspecialchars( $name ) . '</span>';
4290 if ( is_array( $output ) ) {
4291 # Extract flags to local scope (to override $markerType)
4293 $output = $flags[0];
4298 if ( is_null( $attrText ) ) {
4301 if ( isset( $params['attributes'] ) ) {
4302 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4303 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4304 htmlspecialchars( $attrValue ) . '"';
4307 if ( $content === null ) {
4308 $output = "<$name$attrText/>";
4310 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4311 $output = "<$name$attrText>$content$close";
4315 if ( $markerType === 'none' ) {
4317 } elseif ( $markerType === 'nowiki' ) {
4318 $this->mStripState
->addNoWiki( $marker, $output );
4319 } elseif ( $markerType === 'general' ) {
4320 $this->mStripState
->addGeneral( $marker, $output );
4322 throw new MWException( __METHOD__
. ': invalid marker type' );
4328 * Increment an include size counter
4330 * @param string $type The type of expansion
4331 * @param int $size The size of the text
4332 * @return bool False if this inclusion would take it over the maximum, true otherwise
4334 public function incrementIncludeSize( $type, $size ) {
4335 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4338 $this->mIncludeSizes
[$type] +
= $size;
4344 * Increment the expensive function count
4346 * @return bool False if the limit has been exceeded
4348 public function incrementExpensiveFunctionCount() {
4349 $this->mExpensiveFunctionCount++
;
4350 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4354 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4355 * Fills $this->mDoubleUnderscores, returns the modified text
4357 * @param string $text
4361 public function doDoubleUnderscore( $text ) {
4362 wfProfileIn( __METHOD__
);
4364 # The position of __TOC__ needs to be recorded
4365 $mw = MagicWord
::get( 'toc' );
4366 if ( $mw->match( $text ) ) {
4367 $this->mShowToc
= true;
4368 $this->mForceTocPosition
= true;
4370 # Set a placeholder. At the end we'll fill it in with the TOC.
4371 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4373 # Only keep the first one.
4374 $text = $mw->replace( '', $text );
4377 # Now match and remove the rest of them
4378 $mwa = MagicWord
::getDoubleUnderscoreArray();
4379 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4381 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4382 $this->mOutput
->mNoGallery
= true;
4384 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4385 $this->mShowToc
= false;
4387 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4388 && $this->mTitle
->getNamespace() == NS_CATEGORY
4390 $this->addTrackingCategory( 'hidden-category-category' );
4392 # (bug 8068) Allow control over whether robots index a page.
4394 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4395 # is not desirable, the last one on the page should win.
4396 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4397 $this->mOutput
->setIndexPolicy( 'noindex' );
4398 $this->addTrackingCategory( 'noindex-category' );
4400 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4401 $this->mOutput
->setIndexPolicy( 'index' );
4402 $this->addTrackingCategory( 'index-category' );
4405 # Cache all double underscores in the database
4406 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4407 $this->mOutput
->setProperty( $key, '' );
4410 wfProfileOut( __METHOD__
);
4415 * @see ParserOutput::addTrackingCategory()
4416 * @param string $msg Message key
4417 * @return bool Whether the addition was successful
4419 public function addTrackingCategory( $msg ) {
4420 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4424 * This function accomplishes several tasks:
4425 * 1) Auto-number headings if that option is enabled
4426 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4427 * 3) Add a Table of contents on the top for users who have enabled the option
4428 * 4) Auto-anchor headings
4430 * It loops through all headlines, collects the necessary data, then splits up the
4431 * string and re-inserts the newly formatted headlines.
4433 * @param string $text
4434 * @param string $origText Original, untouched wikitext
4435 * @param bool $isMain
4436 * @return mixed|string
4439 public function formatHeadings( $text, $origText, $isMain = true ) {
4440 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4442 # Inhibit editsection links if requested in the page
4443 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4444 $maybeShowEditLink = $showEditLink = false;
4446 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4447 $showEditLink = $this->mOptions
->getEditSection();
4449 if ( $showEditLink ) {
4450 $this->mOutput
->setEditSectionTokens( true );
4453 # Get all headlines for numbering them and adding funky stuff like [edit]
4454 # links - this is for later, but we need the number of headlines right now
4456 $numMatches = preg_match_all(
4457 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4462 # if there are fewer than 4 headlines in the article, do not show TOC
4463 # unless it's been explicitly enabled.
4464 $enoughToc = $this->mShowToc
&&
4465 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4467 # Allow user to stipulate that a page should have a "new section"
4468 # link added via __NEWSECTIONLINK__
4469 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4470 $this->mOutput
->setNewSection( true );
4473 # Allow user to remove the "new section"
4474 # link via __NONEWSECTIONLINK__
4475 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4476 $this->mOutput
->hideNewSection( true );
4479 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4480 # override above conditions and always show TOC above first header
4481 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4482 $this->mShowToc
= true;
4490 # Ugh .. the TOC should have neat indentation levels which can be
4491 # passed to the skin functions. These are determined here
4495 $sublevelCount = array();
4496 $levelCount = array();
4501 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4502 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4503 $oldType = $this->mOutputType
;
4504 $this->setOutputType( self
::OT_WIKI
);
4505 $frame = $this->getPreprocessor()->newFrame();
4506 $root = $this->preprocessToDom( $origText );
4507 $node = $root->getFirstChild();
4512 foreach ( $matches[3] as $headline ) {
4513 $isTemplate = false;
4515 $sectionIndex = false;
4517 $markerMatches = array();
4518 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4519 $serial = $markerMatches[1];
4520 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4521 $isTemplate = ( $titleText != $baseTitleText );
4522 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4526 $prevlevel = $level;
4528 $level = $matches[1][$headlineCount];
4530 if ( $level > $prevlevel ) {
4531 # Increase TOC level
4533 $sublevelCount[$toclevel] = 0;
4534 if ( $toclevel < $wgMaxTocLevel ) {
4535 $prevtoclevel = $toclevel;
4536 $toc .= Linker
::tocIndent();
4539 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4540 # Decrease TOC level, find level to jump to
4542 for ( $i = $toclevel; $i > 0; $i-- ) {
4543 if ( $levelCount[$i] == $level ) {
4544 # Found last matching level
4547 } elseif ( $levelCount[$i] < $level ) {
4548 # Found first matching level below current level
4556 if ( $toclevel < $wgMaxTocLevel ) {
4557 if ( $prevtoclevel < $wgMaxTocLevel ) {
4558 # Unindent only if the previous toc level was shown :p
4559 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4560 $prevtoclevel = $toclevel;
4562 $toc .= Linker
::tocLineEnd();
4566 # No change in level, end TOC line
4567 if ( $toclevel < $wgMaxTocLevel ) {
4568 $toc .= Linker
::tocLineEnd();
4572 $levelCount[$toclevel] = $level;
4574 # count number of headlines for each level
4575 $sublevelCount[$toclevel]++
;
4577 for ( $i = 1; $i <= $toclevel; $i++
) {
4578 if ( !empty( $sublevelCount[$i] ) ) {
4582 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4587 # The safe header is a version of the header text safe to use for links
4589 # Remove link placeholders by the link text.
4590 # <!--LINK number-->
4592 # link text with suffix
4593 # Do this before unstrip since link text can contain strip markers
4594 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4596 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4597 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4599 # Strip out HTML (first regex removes any tag not allowed)
4601 # * <sup> and <sub> (bug 8393)
4604 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4606 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4607 # to allow setting directionality in toc items.
4608 $tocline = preg_replace(
4610 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4611 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4613 array( '', '<$1>' ),
4616 $tocline = trim( $tocline );
4618 # For the anchor, strip out HTML-y stuff period
4619 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4620 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4622 # Save headline for section edit hint before it's escaped
4623 $headlineHint = $safeHeadline;
4625 if ( $wgExperimentalHtmlIds ) {
4626 # For reverse compatibility, provide an id that's
4627 # HTML4-compatible, like we used to.
4629 # It may be worth noting, academically, that it's possible for
4630 # the legacy anchor to conflict with a non-legacy headline
4631 # anchor on the page. In this case likely the "correct" thing
4632 # would be to either drop the legacy anchors or make sure
4633 # they're numbered first. However, this would require people
4634 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4635 # manually, so let's not bother worrying about it.
4636 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4637 array( 'noninitial', 'legacy' ) );
4638 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4640 if ( $legacyHeadline == $safeHeadline ) {
4641 # No reason to have both (in fact, we can't)
4642 $legacyHeadline = false;
4645 $legacyHeadline = false;
4646 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4650 # HTML names must be case-insensitively unique (bug 10721).
4651 # This does not apply to Unicode characters per
4652 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4653 # @todo FIXME: We may be changing them depending on the current locale.
4654 $arrayKey = strtolower( $safeHeadline );
4655 if ( $legacyHeadline === false ) {
4656 $legacyArrayKey = false;
4658 $legacyArrayKey = strtolower( $legacyHeadline );
4661 # count how many in assoc. array so we can track dupes in anchors
4662 if ( isset( $refers[$arrayKey] ) ) {
4663 $refers[$arrayKey]++
;
4665 $refers[$arrayKey] = 1;
4667 if ( isset( $refers[$legacyArrayKey] ) ) {
4668 $refers[$legacyArrayKey]++
;
4670 $refers[$legacyArrayKey] = 1;
4673 # Don't number the heading if it is the only one (looks silly)
4674 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4675 # the two are different if the line contains a link
4676 $headline = Html
::element(
4678 array( 'class' => 'mw-headline-number' ),
4680 ) . ' ' . $headline;
4683 # Create the anchor for linking from the TOC to the section
4684 $anchor = $safeHeadline;
4685 $legacyAnchor = $legacyHeadline;
4686 if ( $refers[$arrayKey] > 1 ) {
4687 $anchor .= '_' . $refers[$arrayKey];
4689 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4690 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4692 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4693 $toc .= Linker
::tocLine( $anchor, $tocline,
4694 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4697 # Add the section to the section tree
4698 # Find the DOM node for this header
4699 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4700 while ( $node && !$noOffset ) {
4701 if ( $node->getName() === 'h' ) {
4702 $bits = $node->splitHeading();
4703 if ( $bits['i'] == $sectionIndex ) {
4707 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4708 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4709 $node = $node->getNextSibling();
4712 'toclevel' => $toclevel,
4715 'number' => $numbering,
4716 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4717 'fromtitle' => $titleText,
4718 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4719 'anchor' => $anchor,
4722 # give headline the correct <h#> tag
4723 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4724 // Output edit section links as markers with styles that can be customized by skins
4725 if ( $isTemplate ) {
4726 # Put a T flag in the section identifier, to indicate to extractSections()
4727 # that sections inside <includeonly> should be counted.
4728 $editsectionPage = $titleText;
4729 $editsectionSection = "T-$sectionIndex";
4730 $editsectionContent = null;
4732 $editsectionPage = $this->mTitle
->getPrefixedText();
4733 $editsectionSection = $sectionIndex;
4734 $editsectionContent = $headlineHint;
4736 // We use a bit of pesudo-xml for editsection markers. The
4737 // language converter is run later on. Using a UNIQ style marker
4738 // leads to the converter screwing up the tokens when it
4739 // converts stuff. And trying to insert strip tags fails too. At
4740 // this point all real inputted tags have already been escaped,
4741 // so we don't have to worry about a user trying to input one of
4742 // these markers directly. We use a page and section attribute
4743 // to stop the language converter from converting these
4744 // important bits of data, but put the headline hint inside a
4745 // content block because the language converter is supposed to
4746 // be able to convert that piece of data.
4747 // Gets replaced with html in ParserOutput::getText
4748 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4749 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4750 if ( $editsectionContent !== null ) {
4751 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4758 $head[$headlineCount] = Linker
::makeHeadline( $level,
4759 $matches['attrib'][$headlineCount], $anchor, $headline,
4760 $editlink, $legacyAnchor );
4765 $this->setOutputType( $oldType );
4767 # Never ever show TOC if no headers
4768 if ( $numVisible < 1 ) {
4773 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4774 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4776 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4777 $this->mOutput
->setTOCHTML( $toc );
4778 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4779 $this->mOutput
->addModules( 'mediawiki.toc' );
4783 $this->mOutput
->setSections( $tocraw );
4786 # split up and insert constructed headlines
4787 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4790 // build an array of document sections
4791 $sections = array();
4792 foreach ( $blocks as $block ) {
4793 // $head is zero-based, sections aren't.
4794 if ( empty( $head[$i - 1] ) ) {
4795 $sections[$i] = $block;
4797 $sections[$i] = $head[$i - 1] . $block;
4801 * Send a hook, one per section.
4802 * The idea here is to be able to make section-level DIVs, but to do so in a
4803 * lower-impact, more correct way than r50769
4806 * $section : the section number
4807 * &$sectionContent : ref to the content of the section
4808 * $showEditLinks : boolean describing whether this section has an edit link
4810 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4815 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4816 // append the TOC at the beginning
4817 // Top anchor now in skin
4818 $sections[0] = $sections[0] . $toc . "\n";
4821 $full .= join( '', $sections );
4823 if ( $this->mForceTocPosition
) {
4824 return str_replace( '<!--MWTOC-->', $toc, $full );
4831 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4832 * conversion, substituting signatures, {{subst:}} templates, etc.
4834 * @param string $text The text to transform
4835 * @param Title $title The Title object for the current article
4836 * @param User $user The User object describing the current user
4837 * @param ParserOptions $options Parsing options
4838 * @param bool $clearState Whether to clear the parser state first
4839 * @return string The altered wiki markup
4841 public function preSaveTransform( $text, Title
$title, User
$user,
4842 ParserOptions
$options, $clearState = true
4844 if ( $clearState ) {
4845 $magicScopeVariable = $this->lock();
4847 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4848 $this->setUser( $user );
4853 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4854 if ( $options->getPreSaveTransform() ) {
4855 $text = $this->pstPass2( $text, $user );
4857 $text = $this->mStripState
->unstripBoth( $text );
4859 $this->setUser( null ); #Reset
4865 * Pre-save transform helper function
4867 * @param string $text
4872 private function pstPass2( $text, $user ) {
4875 # Note: This is the timestamp saved as hardcoded wikitext to
4876 # the database, we use $wgContLang here in order to give
4877 # everyone the same signature and use the default one rather
4878 # than the one selected in each user's preferences.
4879 # (see also bug 12815)
4880 $ts = $this->mOptions
->getTimestamp();
4881 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4882 $ts = $timestamp->format( 'YmdHis' );
4883 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4885 # Allow translation of timezones through wiki. format() can return
4886 # whatever crap the system uses, localised or not, so we cannot
4887 # ship premade translations.
4888 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4889 $msg = wfMessage( $key )->inContentLanguage();
4890 if ( $msg->exists() ) {
4891 $tzMsg = $msg->text();
4894 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4896 # Variable replacement
4897 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4898 $text = $this->replaceVariables( $text );
4900 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4901 # which may corrupt this parser instance via its wfMessage()->text() call-
4904 $sigText = $this->getUserSig( $user );
4905 $text = strtr( $text, array(
4907 '~~~~' => "$sigText $d",
4911 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4912 $tc = '[' . Title
::legalChars() . ']';
4913 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4915 // [[ns:page (context)|]]
4916 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4917 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4918 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4919 // [[ns:page (context), context|]] (using either single or double-width comma)
4920 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4921 // [[|page]] (reverse pipe trick: add context from page title)
4922 $p2 = "/\[\[\\|($tc+)]]/";
4924 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4925 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4926 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4927 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4929 $t = $this->mTitle
->getText();
4931 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4932 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4933 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4934 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4936 # if there's no context, don't bother duplicating the title
4937 $text = preg_replace( $p2, '[[\\1]]', $text );
4940 # Trim trailing whitespace
4941 $text = rtrim( $text );
4947 * Fetch the user's signature text, if any, and normalize to
4948 * validated, ready-to-insert wikitext.
4949 * If you have pre-fetched the nickname or the fancySig option, you can
4950 * specify them here to save a database query.
4951 * Do not reuse this parser instance after calling getUserSig(),
4952 * as it may have changed if it's the $wgParser.
4955 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4956 * @param bool|null $fancySig whether the nicknname is the complete signature
4957 * or null to use default value
4960 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4961 global $wgMaxSigChars;
4963 $username = $user->getName();
4965 # If not given, retrieve from the user object.
4966 if ( $nickname === false ) {
4967 $nickname = $user->getOption( 'nickname' );
4970 if ( is_null( $fancySig ) ) {
4971 $fancySig = $user->getBoolOption( 'fancysig' );
4974 $nickname = $nickname == null ?
$username : $nickname;
4976 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4977 $nickname = $username;
4978 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4979 } elseif ( $fancySig !== false ) {
4980 # Sig. might contain markup; validate this
4981 if ( $this->validateSig( $nickname ) !== false ) {
4982 # Validated; clean up (if needed) and return it
4983 return $this->cleanSig( $nickname, true );
4985 # Failed to validate; fall back to the default
4986 $nickname = $username;
4987 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4991 # Make sure nickname doesnt get a sig in a sig
4992 $nickname = self
::cleanSigInSig( $nickname );
4994 # If we're still here, make it a link to the user page
4995 $userText = wfEscapeWikiText( $username );
4996 $nickText = wfEscapeWikiText( $nickname );
4997 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4999 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
5000 ->title( $this->getTitle() )->text();
5004 * Check that the user's signature contains no bad XML
5006 * @param string $text
5007 * @return string|bool An expanded string, or false if invalid.
5009 public function validateSig( $text ) {
5010 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
5014 * Clean up signature text
5016 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
5017 * 2) Substitute all transclusions
5019 * @param string $text
5020 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5021 * @return string Signature text
5023 public function cleanSig( $text, $parsing = false ) {
5026 $magicScopeVariable = $this->lock();
5027 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5030 # Option to disable this feature
5031 if ( !$this->mOptions
->getCleanSignatures() ) {
5035 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5036 # => Move this logic to braceSubstitution()
5037 $substWord = MagicWord
::get( 'subst' );
5038 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5039 $substText = '{{' . $substWord->getSynonym( 0 );
5041 $text = preg_replace( $substRegex, $substText, $text );
5042 $text = self
::cleanSigInSig( $text );
5043 $dom = $this->preprocessToDom( $text );
5044 $frame = $this->getPreprocessor()->newFrame();
5045 $text = $frame->expand( $dom );
5048 $text = $this->mStripState
->unstripBoth( $text );
5055 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5057 * @param string $text
5058 * @return string Signature text with /~{3,5}/ removed
5060 public static function cleanSigInSig( $text ) {
5061 $text = preg_replace( '/~{3,5}/', '', $text );
5066 * Set up some variables which are usually set up in parse()
5067 * so that an external function can call some class members with confidence
5069 * @param Title|null $title
5070 * @param ParserOptions $options
5071 * @param int $outputType
5072 * @param bool $clearState
5074 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5075 $outputType, $clearState = true
5077 $this->startParse( $title, $options, $outputType, $clearState );
5081 * @param Title|null $title
5082 * @param ParserOptions $options
5083 * @param int $outputType
5084 * @param bool $clearState
5086 private function startParse( Title
$title = null, ParserOptions
$options,
5087 $outputType, $clearState = true
5089 $this->setTitle( $title );
5090 $this->mOptions
= $options;
5091 $this->setOutputType( $outputType );
5092 if ( $clearState ) {
5093 $this->clearState();
5098 * Wrapper for preprocess()
5100 * @param string $text The text to preprocess
5101 * @param ParserOptions $options Options
5102 * @param Title|null $title Title object or null to use $wgTitle
5105 public function transformMsg( $text, $options, $title = null ) {
5106 static $executing = false;
5108 # Guard against infinite recursion
5114 wfProfileIn( __METHOD__
);
5120 $text = $this->preprocess( $text, $title, $options );
5123 wfProfileOut( __METHOD__
);
5128 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5129 * The callback should have the following form:
5130 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5132 * Transform and return $text. Use $parser for any required context, e.g. use
5133 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5135 * Hooks may return extended information by returning an array, of which the
5136 * first numbered element (index 0) must be the return string, and all other
5137 * entries are extracted into local variables within an internal function
5138 * in the Parser class.
5140 * This interface (introduced r61913) appears to be undocumented, but
5141 * 'markerName' is used by some core tag hooks to override which strip
5142 * array their results are placed in. **Use great caution if attempting
5143 * this interface, as it is not documented and injudicious use could smash
5144 * private variables.**
5146 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5147 * @param callable $callback The callback function (and object) to use for the tag
5148 * @throws MWException
5149 * @return callable|null The old value of the mTagHooks array associated with the hook
5151 public function setHook( $tag, $callback ) {
5152 $tag = strtolower( $tag );
5153 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5154 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5156 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5157 $this->mTagHooks
[$tag] = $callback;
5158 if ( !in_array( $tag, $this->mStripList
) ) {
5159 $this->mStripList
[] = $tag;
5166 * As setHook(), but letting the contents be parsed.
5168 * Transparent tag hooks are like regular XML-style tag hooks, except they
5169 * operate late in the transformation sequence, on HTML instead of wikitext.
5171 * This is probably obsoleted by things dealing with parser frames?
5172 * The only extension currently using it is geoserver.
5175 * @todo better document or deprecate this
5177 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5178 * @param callable $callback The callback function (and object) to use for the tag
5179 * @throws MWException
5180 * @return callable|null The old value of the mTagHooks array associated with the hook
5182 public function setTransparentTagHook( $tag, $callback ) {
5183 $tag = strtolower( $tag );
5184 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5185 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5187 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5188 $this->mTransparentTagHooks
[$tag] = $callback;
5194 * Remove all tag hooks
5196 public function clearTagHooks() {
5197 $this->mTagHooks
= array();
5198 $this->mFunctionTagHooks
= array();
5199 $this->mStripList
= $this->mDefaultStripList
;
5203 * Create a function, e.g. {{sum:1|2|3}}
5204 * The callback function should have the form:
5205 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5207 * Or with SFH_OBJECT_ARGS:
5208 * function myParserFunction( $parser, $frame, $args ) { ... }
5210 * The callback may either return the text result of the function, or an array with the text
5211 * in element 0, and a number of flags in the other elements. The names of the flags are
5212 * specified in the keys. Valid flags are:
5213 * found The text returned is valid, stop processing the template. This
5215 * nowiki Wiki markup in the return value should be escaped
5216 * isHTML The returned text is HTML, armour it against wikitext transformation
5218 * @param string $id The magic word ID
5219 * @param callable $callback The callback function (and object) to use
5220 * @param int $flags A combination of the following flags:
5221 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5223 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5224 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5225 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5226 * the arguments, and to control the way they are expanded.
5228 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5229 * arguments, for instance:
5230 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5232 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5233 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5234 * working if/when this is changed.
5236 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5239 * Please read the documentation in includes/parser/Preprocessor.php for more information
5240 * about the methods available in PPFrame and PPNode.
5242 * @throws MWException
5243 * @return string|callable The old callback function for this name, if any
5245 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5248 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5249 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5251 # Add to function cache
5252 $mw = MagicWord
::get( $id );
5254 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5257 $synonyms = $mw->getSynonyms();
5258 $sensitive = intval( $mw->isCaseSensitive() );
5260 foreach ( $synonyms as $syn ) {
5262 if ( !$sensitive ) {
5263 $syn = $wgContLang->lc( $syn );
5266 if ( !( $flags & SFH_NO_HASH
) ) {
5269 # Remove trailing colon
5270 if ( substr( $syn, -1, 1 ) === ':' ) {
5271 $syn = substr( $syn, 0, -1 );
5273 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5279 * Get all registered function hook identifiers
5283 public function getFunctionHooks() {
5284 return array_keys( $this->mFunctionHooks
);
5288 * Create a tag function, e.g. "<test>some stuff</test>".
5289 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5290 * Unlike parser functions, their content is not preprocessed.
5291 * @param string $tag
5292 * @param callable $callback
5294 * @throws MWException
5297 public function setFunctionTagHook( $tag, $callback, $flags ) {
5298 $tag = strtolower( $tag );
5299 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5300 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5302 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5303 $this->mFunctionTagHooks
[$tag] : null;
5304 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5306 if ( !in_array( $tag, $this->mStripList
) ) {
5307 $this->mStripList
[] = $tag;
5314 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5315 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5316 * Placeholders created in Skin::makeLinkObj()
5318 * @param string $text
5319 * @param int $options
5321 public function replaceLinkHolders( &$text, $options = 0 ) {
5322 $this->mLinkHolders
->replace( $text );
5326 * Replace "<!--LINK-->" link placeholders with plain text of links
5327 * (not HTML-formatted).
5329 * @param string $text
5332 public function replaceLinkHoldersText( $text ) {
5333 return $this->mLinkHolders
->replaceText( $text );
5337 * Renders an image gallery from a text with one line per image.
5338 * text labels may be given by using |-style alternative text. E.g.
5339 * Image:one.jpg|The number "1"
5340 * Image:tree.jpg|A tree
5341 * given as text will return the HTML of a gallery with two images,
5342 * labeled 'The number "1"' and
5345 * @param string $text
5346 * @param array $params
5347 * @return string HTML
5349 public function renderImageGallery( $text, $params ) {
5350 wfProfileIn( __METHOD__
);
5353 if ( isset( $params['mode'] ) ) {
5354 $mode = $params['mode'];
5358 $ig = ImageGalleryBase
::factory( $mode );
5359 } catch ( MWException
$e ) {
5360 // If invalid type set, fallback to default.
5361 $ig = ImageGalleryBase
::factory( false );
5364 $ig->setContextTitle( $this->mTitle
);
5365 $ig->setShowBytes( false );
5366 $ig->setShowFilename( false );
5367 $ig->setParser( $this );
5368 $ig->setHideBadImages();
5369 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5371 if ( isset( $params['showfilename'] ) ) {
5372 $ig->setShowFilename( true );
5374 $ig->setShowFilename( false );
5376 if ( isset( $params['caption'] ) ) {
5377 $caption = $params['caption'];
5378 $caption = htmlspecialchars( $caption );
5379 $caption = $this->replaceInternalLinks( $caption );
5380 $ig->setCaptionHtml( $caption );
5382 if ( isset( $params['perrow'] ) ) {
5383 $ig->setPerRow( $params['perrow'] );
5385 if ( isset( $params['widths'] ) ) {
5386 $ig->setWidths( $params['widths'] );
5388 if ( isset( $params['heights'] ) ) {
5389 $ig->setHeights( $params['heights'] );
5391 $ig->setAdditionalOptions( $params );
5393 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5395 $lines = StringUtils
::explode( "\n", $text );
5396 foreach ( $lines as $line ) {
5397 # match lines like these:
5398 # Image:someimage.jpg|This is some image
5400 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5402 if ( count( $matches ) == 0 ) {
5406 if ( strpos( $matches[0], '%' ) !== false ) {
5407 $matches[1] = rawurldecode( $matches[1] );
5409 $title = Title
::newFromText( $matches[1], NS_FILE
);
5410 if ( is_null( $title ) ) {
5411 # Bogus title. Ignore these so we don't bomb out later.
5415 # We need to get what handler the file uses, to figure out parameters.
5416 # Note, a hook can overide the file name, and chose an entirely different
5417 # file (which potentially could be of a different type and have different handler).
5420 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5421 array( $this, $title, &$options, &$descQuery ) );
5422 # Don't register it now, as ImageGallery does that later.
5423 $file = $this->fetchFileNoRegister( $title, $options );
5424 $handler = $file ?
$file->getHandler() : false;
5426 wfProfileIn( __METHOD__
. '-getMagicWord' );
5428 'img_alt' => 'gallery-internal-alt',
5429 'img_link' => 'gallery-internal-link',
5432 $paramMap = $paramMap +
$handler->getParamMap();
5433 // We don't want people to specify per-image widths.
5434 // Additionally the width parameter would need special casing anyhow.
5435 unset( $paramMap['img_width'] );
5438 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5439 wfProfileOut( __METHOD__
. '-getMagicWord' );
5444 $handlerOptions = array();
5445 if ( isset( $matches[3] ) ) {
5446 // look for an |alt= definition while trying not to break existing
5447 // captions with multiple pipes (|) in it, until a more sensible grammar
5448 // is defined for images in galleries
5450 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5451 // splitting on '|' is a bit odd, and different from makeImage.
5452 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5453 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5455 foreach ( $parameterMatches as $parameterMatch ) {
5456 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5458 $paramName = $paramMap[$magicName];
5460 switch ( $paramName ) {
5461 case 'gallery-internal-alt':
5462 $alt = $this->stripAltText( $match, false );
5464 case 'gallery-internal-link':
5465 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5466 $chars = self
::EXT_LINK_URL_CLASS
;
5467 $prots = $this->mUrlProtocols
;
5468 //check to see if link matches an absolute url, if not then it must be a wiki link.
5469 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5472 $localLinkTitle = Title
::newFromText( $linkValue );
5473 if ( $localLinkTitle !== null ) {
5474 $link = $localLinkTitle->getLinkURL();
5479 // Must be a handler specific parameter.
5480 if ( $handler->validateParam( $paramName, $match ) ) {
5481 $handlerOptions[$paramName] = $match;
5483 // Guess not. Append it to the caption.
5484 wfDebug( "$parameterMatch failed parameter validation\n" );
5485 $label .= '|' . $parameterMatch;
5490 // concatenate all other pipes
5491 $label .= '|' . $parameterMatch;
5494 // remove the first pipe
5495 $label = substr( $label, 1 );
5498 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5500 $html = $ig->toHTML();
5501 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5502 wfProfileOut( __METHOD__
);
5507 * @param string $handler
5510 public function getImageParams( $handler ) {
5512 $handlerClass = get_class( $handler );
5516 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5517 # Initialise static lists
5518 static $internalParamNames = array(
5519 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5520 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5521 'bottom', 'text-bottom' ),
5522 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5523 'upright', 'border', 'link', 'alt', 'class' ),
5525 static $internalParamMap;
5526 if ( !$internalParamMap ) {
5527 $internalParamMap = array();
5528 foreach ( $internalParamNames as $type => $names ) {
5529 foreach ( $names as $name ) {
5530 $magicName = str_replace( '-', '_', "img_$name" );
5531 $internalParamMap[$magicName] = array( $type, $name );
5536 # Add handler params
5537 $paramMap = $internalParamMap;
5539 $handlerParamMap = $handler->getParamMap();
5540 foreach ( $handlerParamMap as $magic => $paramName ) {
5541 $paramMap[$magic] = array( 'handler', $paramName );
5544 $this->mImageParams
[$handlerClass] = $paramMap;
5545 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5547 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5551 * Parse image options text and use it to make an image
5553 * @param Title $title
5554 * @param string $options
5555 * @param LinkHolderArray|bool $holders
5556 * @return string HTML
5558 public function makeImage( $title, $options, $holders = false ) {
5559 # Check if the options text is of the form "options|alt text"
5561 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5562 # * left no resizing, just left align. label is used for alt= only
5563 # * right same, but right aligned
5564 # * none same, but not aligned
5565 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5566 # * center center the image
5567 # * frame Keep original image size, no magnify-button.
5568 # * framed Same as "frame"
5569 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5570 # * upright reduce width for upright images, rounded to full __0 px
5571 # * border draw a 1px border around the image
5572 # * alt Text for HTML alt attribute (defaults to empty)
5573 # * class Set a class for img node
5574 # * link Set the target of the image link. Can be external, interwiki, or local
5575 # vertical-align values (no % or length right now):
5585 $parts = StringUtils
::explode( "|", $options );
5587 # Give extensions a chance to select the file revision for us
5590 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5591 array( $this, $title, &$options, &$descQuery ) );
5592 # Fetch and register the file (file title may be different via hooks)
5593 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5596 $handler = $file ?
$file->getHandler() : false;
5598 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5601 $this->addTrackingCategory( 'broken-file-category' );
5604 # Process the input parameters
5606 $params = array( 'frame' => array(), 'handler' => array(),
5607 'horizAlign' => array(), 'vertAlign' => array() );
5608 $seenformat = false;
5609 foreach ( $parts as $part ) {
5610 $part = trim( $part );
5611 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5613 if ( isset( $paramMap[$magicName] ) ) {
5614 list( $type, $paramName ) = $paramMap[$magicName];
5616 # Special case; width and height come in one variable together
5617 if ( $type === 'handler' && $paramName === 'width' ) {
5618 $parsedWidthParam = $this->parseWidthParam( $value );
5619 if ( isset( $parsedWidthParam['width'] ) ) {
5620 $width = $parsedWidthParam['width'];
5621 if ( $handler->validateParam( 'width', $width ) ) {
5622 $params[$type]['width'] = $width;
5626 if ( isset( $parsedWidthParam['height'] ) ) {
5627 $height = $parsedWidthParam['height'];
5628 if ( $handler->validateParam( 'height', $height ) ) {
5629 $params[$type]['height'] = $height;
5633 # else no validation -- bug 13436
5635 if ( $type === 'handler' ) {
5636 # Validate handler parameter
5637 $validated = $handler->validateParam( $paramName, $value );
5639 # Validate internal parameters
5640 switch ( $paramName ) {
5644 # @todo FIXME: Possibly check validity here for
5645 # manualthumb? downstream behavior seems odd with
5646 # missing manual thumbs.
5648 $value = $this->stripAltText( $value, $holders );
5651 $chars = self
::EXT_LINK_URL_CLASS
;
5652 $prots = $this->mUrlProtocols
;
5653 if ( $value === '' ) {
5654 $paramName = 'no-link';
5657 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5658 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5659 $paramName = 'link-url';
5660 $this->mOutput
->addExternalLink( $value );
5661 if ( $this->mOptions
->getExternalLinkTarget() ) {
5662 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5667 $linkTitle = Title
::newFromText( $value );
5669 $paramName = 'link-title';
5670 $value = $linkTitle;
5671 $this->mOutput
->addLink( $linkTitle );
5679 // use first appearing option, discard others.
5680 $validated = ! $seenformat;
5684 # Most other things appear to be empty or numeric...
5685 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5690 $params[$type][$paramName] = $value;
5694 if ( !$validated ) {
5699 # Process alignment parameters
5700 if ( $params['horizAlign'] ) {
5701 $params['frame']['align'] = key( $params['horizAlign'] );
5703 if ( $params['vertAlign'] ) {
5704 $params['frame']['valign'] = key( $params['vertAlign'] );
5707 $params['frame']['caption'] = $caption;
5709 # Will the image be presented in a frame, with the caption below?
5710 $imageIsFramed = isset( $params['frame']['frame'] )
5711 ||
isset( $params['frame']['framed'] )
5712 ||
isset( $params['frame']['thumbnail'] )
5713 ||
isset( $params['frame']['manualthumb'] );
5715 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5716 # came to also set the caption, ordinary text after the image -- which
5717 # makes no sense, because that just repeats the text multiple times in
5718 # screen readers. It *also* came to set the title attribute.
5720 # Now that we have an alt attribute, we should not set the alt text to
5721 # equal the caption: that's worse than useless, it just repeats the
5722 # text. This is the framed/thumbnail case. If there's no caption, we
5723 # use the unnamed parameter for alt text as well, just for the time be-
5724 # ing, if the unnamed param is set and the alt param is not.
5726 # For the future, we need to figure out if we want to tweak this more,
5727 # e.g., introducing a title= parameter for the title; ignoring the un-
5728 # named parameter entirely for images without a caption; adding an ex-
5729 # plicit caption= parameter and preserving the old magic unnamed para-
5731 if ( $imageIsFramed ) { # Framed image
5732 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5733 # No caption or alt text, add the filename as the alt text so
5734 # that screen readers at least get some description of the image
5735 $params['frame']['alt'] = $title->getText();
5737 # Do not set $params['frame']['title'] because tooltips don't make sense
5739 } else { # Inline image
5740 if ( !isset( $params['frame']['alt'] ) ) {
5741 # No alt text, use the "caption" for the alt text
5742 if ( $caption !== '' ) {
5743 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5745 # No caption, fall back to using the filename for the
5747 $params['frame']['alt'] = $title->getText();
5750 # Use the "caption" for the tooltip text
5751 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5754 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5756 # Linker does the rest
5757 $time = isset( $options['time'] ) ?
$options['time'] : false;
5758 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5759 $time, $descQuery, $this->mOptions
->getThumbSize() );
5761 # Give the handler a chance to modify the parser object
5763 $handler->parserTransformHook( $this, $file );
5770 * @param string $caption
5771 * @param LinkHolderArray|bool $holders
5772 * @return mixed|string
5774 protected function stripAltText( $caption, $holders ) {
5775 # Strip bad stuff out of the title (tooltip). We can't just use
5776 # replaceLinkHoldersText() here, because if this function is called
5777 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5779 $tooltip = $holders->replaceText( $caption );
5781 $tooltip = $this->replaceLinkHoldersText( $caption );
5784 # make sure there are no placeholders in thumbnail attributes
5785 # that are later expanded to html- so expand them now and
5787 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5788 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5794 * Set a flag in the output object indicating that the content is dynamic and
5795 * shouldn't be cached.
5797 public function disableCache() {
5798 wfDebug( "Parser output marked as uncacheable.\n" );
5799 if ( !$this->mOutput
) {
5800 throw new MWException( __METHOD__
.
5801 " can only be called when actually parsing something" );
5803 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5804 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5808 * Callback from the Sanitizer for expanding items found in HTML attribute
5809 * values, so they can be safely tested and escaped.
5811 * @param string $text
5812 * @param bool|PPFrame $frame
5815 public function attributeStripCallback( &$text, $frame = false ) {
5816 $text = $this->replaceVariables( $text, $frame );
5817 $text = $this->mStripState
->unstripBoth( $text );
5826 public function getTags() {
5828 array_keys( $this->mTransparentTagHooks
),
5829 array_keys( $this->mTagHooks
),
5830 array_keys( $this->mFunctionTagHooks
)
5835 * Replace transparent tags in $text with the values given by the callbacks.
5837 * Transparent tag hooks are like regular XML-style tag hooks, except they
5838 * operate late in the transformation sequence, on HTML instead of wikitext.
5840 * @param string $text
5844 public function replaceTransparentTags( $text ) {
5846 $elements = array_keys( $this->mTransparentTagHooks
);
5847 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5848 $replacements = array();
5850 foreach ( $matches as $marker => $data ) {
5851 list( $element, $content, $params, $tag ) = $data;
5852 $tagName = strtolower( $element );
5853 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5854 $output = call_user_func_array(
5855 $this->mTransparentTagHooks
[$tagName],
5856 array( $content, $params, $this )
5861 $replacements[$marker] = $output;
5863 return strtr( $text, $replacements );
5867 * Break wikitext input into sections, and either pull or replace
5868 * some particular section's text.
5870 * External callers should use the getSection and replaceSection methods.
5872 * @param string $text Page wikitext
5873 * @param string|number $sectionId A section identifier string of the form:
5874 * "<flag1> - <flag2> - ... - <section number>"
5876 * Currently the only recognised flag is "T", which means the target section number
5877 * was derived during a template inclusion parse, in other words this is a template
5878 * section edit link. If no flags are given, it was an ordinary section edit link.
5879 * This flag is required to avoid a section numbering mismatch when a section is
5880 * enclosed by "<includeonly>" (bug 6563).
5882 * The section number 0 pulls the text before the first heading; other numbers will
5883 * pull the given section along with its lower-level subsections. If the section is
5884 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5886 * Section 0 is always considered to exist, even if it only contains the empty
5887 * string. If $text is the empty string and section 0 is replaced, $newText is
5890 * @param string $mode One of "get" or "replace"
5891 * @param string $newText Replacement text for section data.
5892 * @return string For "get", the extracted section text.
5893 * for "replace", the whole page with the section replaced.
5895 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5896 global $wgTitle; # not generally used but removes an ugly failure mode
5898 $magicScopeVariable = $this->lock();
5899 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5901 $frame = $this->getPreprocessor()->newFrame();
5903 # Process section extraction flags
5905 $sectionParts = explode( '-', $sectionId );
5906 $sectionIndex = array_pop( $sectionParts );
5907 foreach ( $sectionParts as $part ) {
5908 if ( $part === 'T' ) {
5909 $flags |
= self
::PTD_FOR_INCLUSION
;
5913 # Check for empty input
5914 if ( strval( $text ) === '' ) {
5915 # Only sections 0 and T-0 exist in an empty document
5916 if ( $sectionIndex == 0 ) {
5917 if ( $mode === 'get' ) {
5923 if ( $mode === 'get' ) {
5931 # Preprocess the text
5932 $root = $this->preprocessToDom( $text, $flags );
5934 # <h> nodes indicate section breaks
5935 # They can only occur at the top level, so we can find them by iterating the root's children
5936 $node = $root->getFirstChild();
5938 # Find the target section
5939 if ( $sectionIndex == 0 ) {
5940 # Section zero doesn't nest, level=big
5941 $targetLevel = 1000;
5944 if ( $node->getName() === 'h' ) {
5945 $bits = $node->splitHeading();
5946 if ( $bits['i'] == $sectionIndex ) {
5947 $targetLevel = $bits['level'];
5951 if ( $mode === 'replace' ) {
5952 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5954 $node = $node->getNextSibling();
5960 if ( $mode === 'get' ) {
5967 # Find the end of the section, including nested sections
5969 if ( $node->getName() === 'h' ) {
5970 $bits = $node->splitHeading();
5971 $curLevel = $bits['level'];
5972 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5976 if ( $mode === 'get' ) {
5977 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5979 $node = $node->getNextSibling();
5982 # Write out the remainder (in replace mode only)
5983 if ( $mode === 'replace' ) {
5984 # Output the replacement text
5985 # Add two newlines on -- trailing whitespace in $newText is conventionally
5986 # stripped by the editor, so we need both newlines to restore the paragraph gap
5987 # Only add trailing whitespace if there is newText
5988 if ( $newText != "" ) {
5989 $outText .= $newText . "\n\n";
5993 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5994 $node = $node->getNextSibling();
5998 if ( is_string( $outText ) ) {
5999 # Re-insert stripped tags
6000 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
6007 * This function returns the text of a section, specified by a number ($section).
6008 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
6009 * the first section before any such heading (section 0).
6011 * If a section contains subsections, these are also returned.
6013 * @param string $text Text to look in
6014 * @param string|number $sectionId Section identifier as a number or string
6015 * (e.g. 0, 1 or 'T-1').
6016 * @param string $defaultText Default to return if section is not found
6018 * @return string Text of the requested section
6020 public function getSection( $text, $sectionId, $defaultText = '' ) {
6021 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6025 * This function returns $oldtext after the content of the section
6026 * specified by $section has been replaced with $text. If the target
6027 * section does not exist, $oldtext is returned unchanged.
6029 * @param string $oldText Former text of the article
6030 * @param string|number $sectionId Section identifier as a number or string
6031 * (e.g. 0, 1 or 'T-1').
6032 * @param string $newText Replacing text
6034 * @return string Modified text
6036 public function replaceSection( $oldText, $sectionId, $newText ) {
6037 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6041 * Get the ID of the revision we are parsing
6045 public function getRevisionId() {
6046 return $this->mRevisionId
;
6050 * Get the revision object for $this->mRevisionId
6052 * @return Revision|null Either a Revision object or null
6053 * @since 1.23 (public since 1.23)
6055 public function getRevisionObject() {
6056 if ( !is_null( $this->mRevisionObject
) ) {
6057 return $this->mRevisionObject
;
6059 if ( is_null( $this->mRevisionId
) ) {
6063 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6064 return $this->mRevisionObject
;
6068 * Get the timestamp associated with the current revision, adjusted for
6069 * the default server-local timestamp
6072 public function getRevisionTimestamp() {
6073 if ( is_null( $this->mRevisionTimestamp
) ) {
6074 wfProfileIn( __METHOD__
);
6078 $revObject = $this->getRevisionObject();
6079 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6081 # The cryptic '' timezone parameter tells to use the site-default
6082 # timezone offset instead of the user settings.
6084 # Since this value will be saved into the parser cache, served
6085 # to other users, and potentially even used inside links and such,
6086 # it needs to be consistent for all visitors.
6087 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6089 wfProfileOut( __METHOD__
);
6091 return $this->mRevisionTimestamp
;
6095 * Get the name of the user that edited the last revision
6097 * @return string User name
6099 public function getRevisionUser() {
6100 if ( is_null( $this->mRevisionUser
) ) {
6101 $revObject = $this->getRevisionObject();
6103 # if this template is subst: the revision id will be blank,
6104 # so just use the current user's name
6106 $this->mRevisionUser
= $revObject->getUserText();
6107 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6108 $this->mRevisionUser
= $this->getUser()->getName();
6111 return $this->mRevisionUser
;
6115 * Get the size of the revision
6117 * @return int|null Revision size
6119 public function getRevisionSize() {
6120 if ( is_null( $this->mRevisionSize
) ) {
6121 $revObject = $this->getRevisionObject();
6123 # if this variable is subst: the revision id will be blank,
6124 # so just use the parser input size, because the own substituation
6125 # will change the size.
6127 $this->mRevisionSize
= $revObject->getSize();
6128 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6129 $this->mRevisionSize
= $this->mInputSize
;
6132 return $this->mRevisionSize
;
6136 * Mutator for $mDefaultSort
6138 * @param string $sort New value
6140 public function setDefaultSort( $sort ) {
6141 $this->mDefaultSort
= $sort;
6142 $this->mOutput
->setProperty( 'defaultsort', $sort );
6146 * Accessor for $mDefaultSort
6147 * Will use the empty string if none is set.
6149 * This value is treated as a prefix, so the
6150 * empty string is equivalent to sorting by
6155 public function getDefaultSort() {
6156 if ( $this->mDefaultSort
!== false ) {
6157 return $this->mDefaultSort
;
6164 * Accessor for $mDefaultSort
6165 * Unlike getDefaultSort(), will return false if none is set
6167 * @return string|bool
6169 public function getCustomDefaultSort() {
6170 return $this->mDefaultSort
;
6174 * Try to guess the section anchor name based on a wikitext fragment
6175 * presumably extracted from a heading, for example "Header" from
6178 * @param string $text
6182 public function guessSectionNameFromWikiText( $text ) {
6183 # Strip out wikitext links(they break the anchor)
6184 $text = $this->stripSectionName( $text );
6185 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6186 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6190 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6191 * instead. For use in redirects, since IE6 interprets Redirect: headers
6192 * as something other than UTF-8 (apparently?), resulting in breakage.
6194 * @param string $text The section name
6195 * @return string An anchor
6197 public function guessLegacySectionNameFromWikiText( $text ) {
6198 # Strip out wikitext links(they break the anchor)
6199 $text = $this->stripSectionName( $text );
6200 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6201 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6205 * Strips a text string of wikitext for use in a section anchor
6207 * Accepts a text string and then removes all wikitext from the
6208 * string and leaves only the resultant text (i.e. the result of
6209 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6210 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6211 * to create valid section anchors by mimicing the output of the
6212 * parser when headings are parsed.
6214 * @param string $text Text string to be stripped of wikitext
6215 * for use in a Section anchor
6216 * @return string Filtered text string
6218 public function stripSectionName( $text ) {
6219 # Strip internal link markup
6220 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6221 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6223 # Strip external link markup
6224 # @todo FIXME: Not tolerant to blank link text
6225 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6226 # on how many empty links there are on the page - need to figure that out.
6227 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6229 # Parse wikitext quotes (italics & bold)
6230 $text = $this->doQuotes( $text );
6233 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6238 * strip/replaceVariables/unstrip for preprocessor regression testing
6240 * @param string $text
6241 * @param Title $title
6242 * @param ParserOptions $options
6243 * @param int $outputType
6247 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6248 $magicScopeVariable = $this->lock();
6249 $this->startParse( $title, $options, $outputType, true );
6251 $text = $this->replaceVariables( $text );
6252 $text = $this->mStripState
->unstripBoth( $text );
6253 $text = Sanitizer
::removeHTMLtags( $text );
6258 * @param string $text
6259 * @param Title $title
6260 * @param ParserOptions $options
6263 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6264 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6268 * @param string $text
6269 * @param Title $title
6270 * @param ParserOptions $options
6273 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6274 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6278 * Call a callback function on all regions of the given text that are not
6279 * inside strip markers, and replace those regions with the return value
6280 * of the callback. For example, with input:
6284 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6285 * two strings will be replaced with the value returned by the callback in
6289 * @param callable $callback
6293 public function markerSkipCallback( $s, $callback ) {
6296 while ( $i < strlen( $s ) ) {
6297 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6298 if ( $markerStart === false ) {
6299 $out .= call_user_func( $callback, substr( $s, $i ) );
6302 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6303 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6304 if ( $markerEnd === false ) {
6305 $out .= substr( $s, $markerStart );
6308 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6309 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6318 * Remove any strip markers found in the given text.
6320 * @param string $text Input string
6323 public function killMarkers( $text ) {
6324 return $this->mStripState
->killMarkers( $text );
6328 * Save the parser state required to convert the given half-parsed text to
6329 * HTML. "Half-parsed" in this context means the output of
6330 * recursiveTagParse() or internalParse(). This output has strip markers
6331 * from replaceVariables (extensionSubstitution() etc.), and link
6332 * placeholders from replaceLinkHolders().
6334 * Returns an array which can be serialized and stored persistently. This
6335 * array can later be loaded into another parser instance with
6336 * unserializeHalfParsedText(). The text can then be safely incorporated into
6337 * the return value of a parser hook.
6339 * @param string $text
6343 public function serializeHalfParsedText( $text ) {
6344 wfProfileIn( __METHOD__
);
6347 'version' => self
::HALF_PARSED_VERSION
,
6348 'stripState' => $this->mStripState
->getSubState( $text ),
6349 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6351 wfProfileOut( __METHOD__
);
6356 * Load the parser state given in the $data array, which is assumed to
6357 * have been generated by serializeHalfParsedText(). The text contents is
6358 * extracted from the array, and its markers are transformed into markers
6359 * appropriate for the current Parser instance. This transformed text is
6360 * returned, and can be safely included in the return value of a parser
6363 * If the $data array has been stored persistently, the caller should first
6364 * check whether it is still valid, by calling isValidHalfParsedText().
6366 * @param array $data Serialized data
6367 * @throws MWException
6370 public function unserializeHalfParsedText( $data ) {
6371 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6372 throw new MWException( __METHOD__
. ': invalid version' );
6375 # First, extract the strip state.
6376 $texts = array( $data['text'] );
6377 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6379 # Now renumber links
6380 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6382 # Should be good to go.
6387 * Returns true if the given array, presumed to be generated by
6388 * serializeHalfParsedText(), is compatible with the current version of the
6391 * @param array $data
6395 public function isValidHalfParsedText( $data ) {
6396 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6400 * Parsed a width param of imagelink like 300px or 200x300px
6402 * @param string $value
6407 public function parseWidthParam( $value ) {
6408 $parsedWidthParam = array();
6409 if ( $value === '' ) {
6410 return $parsedWidthParam;
6413 # (bug 13500) In both cases (width/height and width only),
6414 # permit trailing "px" for backward compatibility.
6415 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6416 $width = intval( $m[1] );
6417 $height = intval( $m[2] );
6418 $parsedWidthParam['width'] = $width;
6419 $parsedWidthParam['height'] = $height;
6420 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6421 $width = intval( $value );
6422 $parsedWidthParam['width'] = $width;
6424 return $parsedWidthParam;
6428 * Lock the current instance of the parser.
6430 * This is meant to stop someone from calling the parser
6431 * recursively and messing up all the strip state.
6433 * @throws MWException If parser is in a parse
6434 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6436 protected function lock() {
6437 if ( $this->mInParse
) {
6438 throw new MWException( "Parser state cleared while parsing. "
6439 . "Did you call Parser::parse recursively?" );
6441 $this->mInParse
= true;
6444 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6445 $that->mInParse
= false;
6448 return $recursiveCheck;
6452 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6454 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6455 * or if there is more than one <p/> tag in the input HTML.
6457 * @param string $html
6461 public static function stripOuterParagraph( $html ) {
6463 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6464 if ( strpos( $m[1], '</p>' ) === false ) {
6473 * Return this parser if it is not doing anything, otherwise
6474 * get a fresh parser. You can use this method by doing
6475 * $myParser = $wgParser->getFreshParser(), or more simply
6476 * $wgParser->getFreshParser()->parse( ... );
6477 * if you're unsure if $wgParser is safe to use.
6480 * @return Parser A parser object that is not parsing anything
6482 public function getFreshParser() {
6483 global $wgParserConf;
6484 if ( $this->mInParse
) {
6485 return new $wgParserConf['class']( $wgParserConf );