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 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
89 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
90 # Simplified expression to match an IPv4 or IPv6 address, or
91 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
92 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}])';
93 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
94 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
95 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
97 # Regular expression for a non-newline space
98 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
100 # State constants for the definition list colon extraction
101 const COLON_STATE_TEXT
= 0;
102 const COLON_STATE_TAG
= 1;
103 const COLON_STATE_TAGSTART
= 2;
104 const COLON_STATE_CLOSETAG
= 3;
105 const COLON_STATE_TAGSLASH
= 4;
106 const COLON_STATE_COMMENT
= 5;
107 const COLON_STATE_COMMENTDASH
= 6;
108 const COLON_STATE_COMMENTDASHDASH
= 7;
110 # Flags for preprocessToDom
111 const PTD_FOR_INCLUSION
= 1;
113 # Allowed values for $this->mOutputType
114 # Parameter to startExternalParse().
115 const OT_HTML
= 1; # like parse()
116 const OT_WIKI
= 2; # like preSaveTransform()
117 const OT_PREPROCESS
= 3; # like preprocess()
119 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
122 * @var string Prefix and suffix for temporary replacement strings
123 * for the multipass parser.
125 * \x7f should never appear in input as it's disallowed in XML.
126 * Using it at the front also gives us a little extra robustness
127 * since it shouldn't match when butted up against identifier-like
130 * Must not consist of all title characters, or else it will change
131 * the behavior of <nowiki> in a link.
133 const MARKER_SUFFIX
= "-QINU\x7f";
134 const MARKER_PREFIX
= "\x7fUNIQ-";
136 # Markers used for wrapping the table of contents
137 const TOC_START
= '<mw:toc>';
138 const TOC_END
= '</mw:toc>';
141 public $mTagHooks = array();
142 public $mTransparentTagHooks = array();
143 public $mFunctionHooks = array();
144 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
145 public $mFunctionTagHooks = array();
146 public $mStripList = array();
147 public $mDefaultStripList = array();
148 public $mVarCache = array();
149 public $mImageParams = array();
150 public $mImageParamsMagicArray = array();
151 public $mMarkerIndex = 0;
152 public $mFirstCall = true;
154 # Initialised by initialiseVariables()
157 * @var MagicWordArray
162 * @var MagicWordArray
165 # Initialised in constructor
166 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
168 # Initialized in getPreprocessor()
169 /** @var Preprocessor */
170 public $mPreprocessor;
172 # Cleared with clearState():
177 public $mAutonumber, $mDTopen;
184 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
186 * @var LinkHolderArray
188 public $mLinkHolders;
191 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
192 public $mDefaultSort;
193 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
194 public $mExpensiveFunctionCount; # number of expensive parser function calls
195 public $mShowToc, $mForceTocPosition;
200 public $mUser; # User object; only used when doing pre-save transform
203 # These are variables reset at least once per parse regardless of $clearState
213 public $mTitle; # Title context, used for self-link rendering and similar things
214 public $mOutputType; # Output type, one of the OT_xxx constants
215 public $ot; # Shortcut alias, see setOutputType()
216 public $mRevisionObject; # The revision object of the specified revision ID
217 public $mRevisionId; # ID to display in {{REVISIONID}} tags
218 public $mRevisionTimestamp; # The timestamp of the specified revision ID
219 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
220 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
221 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
222 public $mInputSize = false; # For {{PAGESIZE}} on current page.
225 * @var string Deprecated accessor for the strip marker prefix.
226 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
228 public $mUniqPrefix = Parser
::MARKER_PREFIX
;
231 * @var array Array with the language name of each language link (i.e. the
232 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
233 * duplicate language links to the ParserOutput.
235 public $mLangLinkLanguages;
238 * @var MapCacheLRU|null
241 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
243 public $currentRevisionCache;
246 * @var bool Recursive call protection.
247 * This variable should be treated as if it were private.
249 public $mInParse = false;
251 /** @var SectionProfiler */
252 protected $mProfiler;
257 public function __construct( $conf = array() ) {
258 $this->mConf
= $conf;
259 $this->mUrlProtocols
= wfUrlProtocols();
260 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
261 self
::EXT_LINK_ADDR
.
262 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
263 if ( isset( $conf['preprocessorClass'] ) ) {
264 $this->mPreprocessorClass
= $conf['preprocessorClass'];
265 } elseif ( defined( 'HPHP_VERSION' ) ) {
266 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
267 $this->mPreprocessorClass
= 'Preprocessor_Hash';
268 } elseif ( extension_loaded( 'domxml' ) ) {
269 # PECL extension that conflicts with the core DOM extension (bug 13770)
270 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
271 $this->mPreprocessorClass
= 'Preprocessor_Hash';
272 } elseif ( extension_loaded( 'dom' ) ) {
273 $this->mPreprocessorClass
= 'Preprocessor_DOM';
275 $this->mPreprocessorClass
= 'Preprocessor_Hash';
277 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
281 * Reduce memory usage to reduce the impact of circular references
283 public function __destruct() {
284 if ( isset( $this->mLinkHolders
) ) {
285 unset( $this->mLinkHolders
);
287 foreach ( $this as $name => $value ) {
288 unset( $this->$name );
293 * Allow extensions to clean up when the parser is cloned
295 public function __clone() {
296 $this->mInParse
= false;
298 // Bug 56226: When you create a reference "to" an object field, that
299 // makes the object field itself be a reference too (until the other
300 // reference goes out of scope). When cloning, any field that's a
301 // reference is copied as a reference in the new object. Both of these
302 // are defined PHP5 behaviors, as inconvenient as it is for us when old
303 // hooks from PHP4 days are passing fields by reference.
304 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
305 // Make a non-reference copy of the field, then rebind the field to
306 // reference the new copy.
312 Hooks
::run( 'ParserCloned', array( $this ) );
316 * Do various kinds of initialisation on the first call of the parser
318 public function firstCallInit() {
319 if ( !$this->mFirstCall
) {
322 $this->mFirstCall
= false;
324 CoreParserFunctions
::register( $this );
325 CoreTagHooks
::register( $this );
326 $this->initialiseVariables();
328 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
336 public function clearState() {
337 if ( $this->mFirstCall
) {
338 $this->firstCallInit();
340 $this->mOutput
= new ParserOutput
;
341 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
342 $this->mAutonumber
= 0;
343 $this->mLastSection
= '';
344 $this->mDTopen
= false;
345 $this->mIncludeCount
= array();
346 $this->mArgStack
= false;
347 $this->mInPre
= false;
348 $this->mLinkHolders
= new LinkHolderArray( $this );
350 $this->mRevisionObject
= $this->mRevisionTimestamp
=
351 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
352 $this->mVarCache
= array();
354 $this->mLangLinkLanguages
= array();
355 $this->currentRevisionCache
= null;
357 $this->mStripState
= new StripState
;
359 # Clear these on every parse, bug 4549
360 $this->mTplRedirCache
= $this->mTplDomCache
= array();
362 $this->mShowToc
= true;
363 $this->mForceTocPosition
= false;
364 $this->mIncludeSizes
= array(
368 $this->mPPNodeCount
= 0;
369 $this->mGeneratedPPNodeCount
= 0;
370 $this->mHighestExpansionDepth
= 0;
371 $this->mDefaultSort
= false;
372 $this->mHeadings
= array();
373 $this->mDoubleUnderscores
= array();
374 $this->mExpensiveFunctionCount
= 0;
377 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
378 $this->mPreprocessor
= null;
381 $this->mProfiler
= new SectionProfiler();
383 Hooks
::run( 'ParserClearState', array( &$this ) );
387 * Convert wikitext to HTML
388 * Do not call this function recursively.
390 * @param string $text Text we want to parse
391 * @param Title $title
392 * @param ParserOptions $options
393 * @param bool $linestart
394 * @param bool $clearState
395 * @param int $revid Number to pass in {{REVISIONID}}
396 * @return ParserOutput A ParserOutput
398 public function parse( $text, Title
$title, ParserOptions
$options,
399 $linestart = true, $clearState = true, $revid = null
402 * First pass--just handle <nowiki> sections, pass the rest off
403 * to internalParse() which does all the real work.
406 global $wgShowHostnames;
409 // We use U+007F DELETE to construct strip markers, so we have to make
410 // sure that this character does not occur in the input text.
411 $text = strtr( $text, "\x7f", "?" );
412 $magicScopeVariable = $this->lock();
415 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
417 $this->currentRevisionCache
= null;
418 $this->mInputSize
= strlen( $text );
419 if ( $this->mOptions
->getEnableLimitReport() ) {
420 $this->mOutput
->resetParseStartTime();
423 $oldRevisionId = $this->mRevisionId
;
424 $oldRevisionObject = $this->mRevisionObject
;
425 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
426 $oldRevisionUser = $this->mRevisionUser
;
427 $oldRevisionSize = $this->mRevisionSize
;
428 if ( $revid !== null ) {
429 $this->mRevisionId
= $revid;
430 $this->mRevisionObject
= null;
431 $this->mRevisionTimestamp
= null;
432 $this->mRevisionUser
= null;
433 $this->mRevisionSize
= null;
436 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
438 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
439 $text = $this->internalParse( $text );
440 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
442 $text = $this->internalParseHalfParsed( $text, true, $linestart );
445 * A converted title will be provided in the output object if title and
446 * content conversion are enabled, the article text does not contain
447 * a conversion-suppressing double-underscore tag, and no
448 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
449 * automatic link conversion.
451 if ( !( $options->getDisableTitleConversion()
452 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
453 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
454 ||
$this->mOutput
->getDisplayTitle() !== false )
456 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
457 if ( $convruletitle ) {
458 $this->mOutput
->setTitleText( $convruletitle );
460 $titleText = $this->getConverterLanguage()->convertTitle( $title );
461 $this->mOutput
->setTitleText( $titleText );
465 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
466 $this->limitationWarn( 'expensive-parserfunction',
467 $this->mExpensiveFunctionCount
,
468 $this->mOptions
->getExpensiveParserFunctionLimit()
472 # Information on include size limits, for the benefit of users who try to skirt them
473 if ( $this->mOptions
->getEnableLimitReport() ) {
474 $max = $this->mOptions
->getMaxIncludeSize();
476 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
477 if ( $cpuTime !== null ) {
478 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
479 sprintf( "%.3f", $cpuTime )
483 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
484 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
485 sprintf( "%.3f", $wallTime )
488 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
489 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
491 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
492 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
494 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
495 array( $this->mIncludeSizes
['post-expand'], $max )
497 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
498 array( $this->mIncludeSizes
['arg'], $max )
500 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
501 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
503 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
504 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
506 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
508 $limitReport = "NewPP limit report\n";
509 if ( $wgShowHostnames ) {
510 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
512 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
513 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
514 $limitReport .= 'Dynamic content: ' .
515 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
518 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
519 if ( Hooks
::run( 'ParserLimitReportFormat',
520 array( $key, &$value, &$limitReport, false, false )
522 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
523 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
524 ->inLanguage( 'en' )->useDatabase( false );
525 if ( !$valueMsg->exists() ) {
526 $valueMsg = new RawMessage( '$1' );
528 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
529 $valueMsg->params( $value );
530 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
534 // Since we're not really outputting HTML, decode the entities and
535 // then re-encode the things that need hiding inside HTML comments.
536 $limitReport = htmlspecialchars_decode( $limitReport );
537 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
539 // Sanitize for comment. Note '‐' in the replacement is U+2010,
540 // which looks much like the problematic '-'.
541 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
542 $text .= "\n<!-- \n$limitReport-->\n";
544 // Add on template profiling data
545 $dataByFunc = $this->mProfiler
->getFunctionStats();
546 uasort( $dataByFunc, function ( $a, $b ) {
547 return $a['real'] < $b['real']; // descending order
549 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
550 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
551 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
552 $item['%real'], $item['real'], $item['calls'],
553 htmlspecialchars( $item['name'] ) );
555 $text .= "\n<!-- \n$profileReport-->\n";
557 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
558 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
559 $this->mTitle
->getPrefixedDBkey() );
562 $this->mOutput
->setText( $text );
564 $this->mRevisionId
= $oldRevisionId;
565 $this->mRevisionObject
= $oldRevisionObject;
566 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
567 $this->mRevisionUser
= $oldRevisionUser;
568 $this->mRevisionSize
= $oldRevisionSize;
569 $this->mInputSize
= false;
570 $this->currentRevisionCache
= null;
572 return $this->mOutput
;
576 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
577 * can be called from an extension tag hook.
579 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
580 * instead, which means that lists and links have not been fully parsed yet,
581 * and strip markers are still present.
583 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
585 * Use this function if you're a parser tag hook and you want to parse
586 * wikitext before or after applying additional transformations, and you
587 * intend to *return the result as hook output*, which will cause it to go
588 * through the rest of parsing process automatically.
590 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
591 * $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 UNSAFE half-parsed HTML
597 public function recursiveTagParse( $text, $frame = false ) {
598 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
599 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
600 $text = $this->internalParse( $text, false, $frame );
605 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
606 * point can be called from an extension tag hook.
608 * The output of this function is fully-parsed HTML that is safe for output.
609 * If you're a parser tag hook, you might want to use recursiveTagParse()
612 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
613 * $text are not expanded
617 * @param string $text Text extension wants to have parsed
618 * @param bool|PPFrame $frame The frame to use for expanding any template variables
619 * @return string Fully parsed HTML
621 public function recursiveTagParseFully( $text, $frame = false ) {
622 $text = $this->recursiveTagParse( $text, $frame );
623 $text = $this->internalParseHalfParsed( $text, false );
628 * Expand templates and variables in the text, producing valid, static wikitext.
629 * Also removes comments.
630 * Do not call this function recursively.
631 * @param string $text
632 * @param Title $title
633 * @param ParserOptions $options
634 * @param int|null $revid
635 * @param bool|PPFrame $frame
636 * @return mixed|string
638 public function preprocess( $text, Title
$title = null,
639 ParserOptions
$options, $revid = null, $frame = false
641 $magicScopeVariable = $this->lock();
642 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
643 if ( $revid !== null ) {
644 $this->mRevisionId
= $revid;
646 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
647 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
648 $text = $this->replaceVariables( $text, $frame );
649 $text = $this->mStripState
->unstripBoth( $text );
654 * Recursive parser entry point that can be called from an extension tag
657 * @param string $text Text to be expanded
658 * @param bool|PPFrame $frame The frame to use for expanding any template variables
662 public function recursivePreprocess( $text, $frame = false ) {
663 $text = $this->replaceVariables( $text, $frame );
664 $text = $this->mStripState
->unstripBoth( $text );
669 * Process the wikitext for the "?preload=" feature. (bug 5210)
671 * "<noinclude>", "<includeonly>" etc. are parsed as for template
672 * transclusion, comments, templates, arguments, tags hooks and parser
673 * functions are untouched.
675 * @param string $text
676 * @param Title $title
677 * @param ParserOptions $options
678 * @param array $params
681 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
682 $msg = new RawMessage( $text );
683 $text = $msg->params( $params )->plain();
685 # Parser (re)initialisation
686 $magicScopeVariable = $this->lock();
687 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
689 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
690 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
691 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
692 $text = $this->mStripState
->unstripBoth( $text );
697 * Get a random string
700 * @deprecated since 1.26; use wfRandomString() instead.
702 public static function getRandomString() {
703 wfDeprecated( __METHOD__
, '1.26' );
704 return wfRandomString( 16 );
708 * Set the current user.
709 * Should only be used when doing pre-save transform.
711 * @param User|null $user User object or null (to reset)
713 public function setUser( $user ) {
714 $this->mUser
= $user;
718 * Accessor for mUniqPrefix.
721 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
723 public function uniqPrefix() {
724 wfDeprecated( __METHOD__
, '1.26' );
725 return self
::MARKER_PREFIX
;
729 * Set the context title
733 public function setTitle( $t ) {
735 $t = Title
::newFromText( 'NO TITLE' );
738 if ( $t->hasFragment() ) {
739 # Strip the fragment to avoid various odd effects
740 $this->mTitle
= clone $t;
741 $this->mTitle
->setFragment( '' );
748 * Accessor for the Title object
752 public function getTitle() {
753 return $this->mTitle
;
757 * Accessor/mutator for the Title object
759 * @param Title $x Title object or null to just get the current one
762 public function Title( $x = null ) {
763 return wfSetVar( $this->mTitle
, $x );
767 * Set the output type
769 * @param int $ot New value
771 public function setOutputType( $ot ) {
772 $this->mOutputType
= $ot;
775 'html' => $ot == self
::OT_HTML
,
776 'wiki' => $ot == self
::OT_WIKI
,
777 'pre' => $ot == self
::OT_PREPROCESS
,
778 'plain' => $ot == self
::OT_PLAIN
,
783 * Accessor/mutator for the output type
785 * @param int|null $x New value or null to just get the current one
788 public function OutputType( $x = null ) {
789 return wfSetVar( $this->mOutputType
, $x );
793 * Get the ParserOutput object
795 * @return ParserOutput
797 public function getOutput() {
798 return $this->mOutput
;
802 * Get the ParserOptions object
804 * @return ParserOptions
806 public function getOptions() {
807 return $this->mOptions
;
811 * Accessor/mutator for the ParserOptions object
813 * @param ParserOptions $x New value or null to just get the current one
814 * @return ParserOptions Current ParserOptions object
816 public function Options( $x = null ) {
817 return wfSetVar( $this->mOptions
, $x );
823 public function nextLinkID() {
824 return $this->mLinkID++
;
830 public function setLinkID( $id ) {
831 $this->mLinkID
= $id;
835 * Get a language object for use in parser functions such as {{FORMATNUM:}}
838 public function getFunctionLang() {
839 return $this->getTargetLanguage();
843 * Get the target language for the content being parsed. This is usually the
844 * language that the content is in.
848 * @throws MWException
851 public function getTargetLanguage() {
852 $target = $this->mOptions
->getTargetLanguage();
854 if ( $target !== null ) {
856 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
857 return $this->mOptions
->getUserLangObj();
858 } elseif ( is_null( $this->mTitle
) ) {
859 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
862 return $this->mTitle
->getPageLanguage();
866 * Get the language object for language conversion
867 * @return Language|null
869 public function getConverterLanguage() {
870 return $this->getTargetLanguage();
874 * Get a User object either from $this->mUser, if set, or from the
875 * ParserOptions object otherwise
879 public function getUser() {
880 if ( !is_null( $this->mUser
) ) {
883 return $this->mOptions
->getUser();
887 * Get a preprocessor object
889 * @return Preprocessor
891 public function getPreprocessor() {
892 if ( !isset( $this->mPreprocessor
) ) {
893 $class = $this->mPreprocessorClass
;
894 $this->mPreprocessor
= new $class( $this );
896 return $this->mPreprocessor
;
900 * Replaces all occurrences of HTML-style comments and the given tags
901 * in the text with a random marker and returns the next text. The output
902 * parameter $matches will be an associative array filled with data in
906 * 'UNIQ-xxxxx' => array(
909 * array( 'param' => 'x' ),
910 * '<element param="x">tag content</element>' ) )
913 * @param array $elements List of element names. Comments are always extracted.
914 * @param string $text Source text string.
915 * @param array $matches Out parameter, Array: extracted tags
916 * @param string|null $uniq_prefix
917 * @return string Stripped text
918 * @since 1.26 The uniq_prefix argument is deprecated.
920 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
921 if ( $uniq_prefix !== null ) {
922 wfDeprecated( __METHOD__
. ' called with $prefix argument', '1.26' );
928 $taglist = implode( '|', $elements );
929 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
931 while ( $text != '' ) {
932 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
934 if ( count( $p ) < 5 ) {
937 if ( count( $p ) > 5 ) {
951 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
952 $stripped .= $marker;
954 if ( $close === '/>' ) {
955 # Empty element tag, <tag />
960 if ( $element === '!--' ) {
963 $end = "/(<\\/$element\\s*>)/i";
965 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
967 if ( count( $q ) < 3 ) {
968 # No end tag -- let it run out to the end of the text.
977 $matches[$marker] = array( $element,
979 Sanitizer
::decodeTagAttributes( $attributes ),
980 "<$element$attributes$close$content$tail" );
986 * Get a list of strippable XML-like elements
990 public function getStripList() {
991 return $this->mStripList
;
995 * Add an item to the strip state
996 * Returns the unique tag which must be inserted into the stripped text
997 * The tag will be replaced with the original text in unstrip()
999 * @param string $text
1003 public function insertStripItem( $text ) {
1004 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1005 $this->mMarkerIndex++
;
1006 $this->mStripState
->addGeneral( $marker, $text );
1011 * parse the wiki syntax used to render tables
1014 * @param string $text
1017 public function doTableStuff( $text ) {
1019 $lines = StringUtils
::explode( "\n", $text );
1021 $td_history = array(); # Is currently a td tag open?
1022 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1023 $tr_history = array(); # Is currently a tr tag open?
1024 $tr_attributes = array(); # history of tr attributes
1025 $has_opened_tr = array(); # Did this table open a <tr> element?
1026 $indent_level = 0; # indent level of the table
1028 foreach ( $lines as $outLine ) {
1029 $line = trim( $outLine );
1031 if ( $line === '' ) { # empty line, go to next line
1032 $out .= $outLine . "\n";
1036 $first_character = $line[0];
1037 $first_two = substr( $line, 0, 2 );
1040 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1041 # First check if we are starting a new table
1042 $indent_level = strlen( $matches[1] );
1044 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1045 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1047 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1048 array_push( $td_history, false );
1049 array_push( $last_tag_history, '' );
1050 array_push( $tr_history, false );
1051 array_push( $tr_attributes, '' );
1052 array_push( $has_opened_tr, false );
1053 } elseif ( count( $td_history ) == 0 ) {
1054 # Don't do any of the following
1055 $out .= $outLine . "\n";
1057 } elseif ( $first_two === '|}' ) {
1058 # We are ending a table
1059 $line = '</table>' . substr( $line, 2 );
1060 $last_tag = array_pop( $last_tag_history );
1062 if ( !array_pop( $has_opened_tr ) ) {
1063 $line = "<tr><td></td></tr>{$line}";
1066 if ( array_pop( $tr_history ) ) {
1067 $line = "</tr>{$line}";
1070 if ( array_pop( $td_history ) ) {
1071 $line = "</{$last_tag}>{$line}";
1073 array_pop( $tr_attributes );
1074 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1075 } elseif ( $first_two === '|-' ) {
1076 # Now we have a table row
1077 $line = preg_replace( '#^\|-+#', '', $line );
1079 # Whats after the tag is now only attributes
1080 $attributes = $this->mStripState
->unstripBoth( $line );
1081 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1082 array_pop( $tr_attributes );
1083 array_push( $tr_attributes, $attributes );
1086 $last_tag = array_pop( $last_tag_history );
1087 array_pop( $has_opened_tr );
1088 array_push( $has_opened_tr, true );
1090 if ( array_pop( $tr_history ) ) {
1094 if ( array_pop( $td_history ) ) {
1095 $line = "</{$last_tag}>{$line}";
1099 array_push( $tr_history, false );
1100 array_push( $td_history, false );
1101 array_push( $last_tag_history, '' );
1102 } elseif ( $first_character === '|'
1103 ||
$first_character === '!'
1104 ||
$first_two === '|+'
1106 # This might be cell elements, td, th or captions
1107 if ( $first_two === '|+' ) {
1108 $first_character = '+';
1109 $line = substr( $line, 2 );
1111 $line = substr( $line, 1 );
1114 if ( $first_character === '!' ) {
1115 $line = str_replace( '!!', '||', $line );
1118 # Split up multiple cells on the same line.
1119 # FIXME : This can result in improper nesting of tags processed
1120 # by earlier parser steps, but should avoid splitting up eg
1121 # attribute values containing literal "||".
1122 $cells = StringUtils
::explodeMarkup( '||', $line );
1126 # Loop through each table cell
1127 foreach ( $cells as $cell ) {
1129 if ( $first_character !== '+' ) {
1130 $tr_after = array_pop( $tr_attributes );
1131 if ( !array_pop( $tr_history ) ) {
1132 $previous = "<tr{$tr_after}>\n";
1134 array_push( $tr_history, true );
1135 array_push( $tr_attributes, '' );
1136 array_pop( $has_opened_tr );
1137 array_push( $has_opened_tr, true );
1140 $last_tag = array_pop( $last_tag_history );
1142 if ( array_pop( $td_history ) ) {
1143 $previous = "</{$last_tag}>\n{$previous}";
1146 if ( $first_character === '|' ) {
1148 } elseif ( $first_character === '!' ) {
1150 } elseif ( $first_character === '+' ) {
1151 $last_tag = 'caption';
1156 array_push( $last_tag_history, $last_tag );
1158 # A cell could contain both parameters and data
1159 $cell_data = explode( '|', $cell, 2 );
1161 # Bug 553: Note that a '|' inside an invalid link should not
1162 # be mistaken as delimiting cell parameters
1163 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1164 $cell = "{$previous}<{$last_tag}>{$cell}";
1165 } elseif ( count( $cell_data ) == 1 ) {
1166 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1168 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1169 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1170 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1174 array_push( $td_history, true );
1177 $out .= $outLine . "\n";
1180 # Closing open td, tr && table
1181 while ( count( $td_history ) > 0 ) {
1182 if ( array_pop( $td_history ) ) {
1185 if ( array_pop( $tr_history ) ) {
1188 if ( !array_pop( $has_opened_tr ) ) {
1189 $out .= "<tr><td></td></tr>\n";
1192 $out .= "</table>\n";
1195 # Remove trailing line-ending (b/c)
1196 if ( substr( $out, -1 ) === "\n" ) {
1197 $out = substr( $out, 0, -1 );
1200 # special case: don't return empty table
1201 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1209 * Helper function for parse() that transforms wiki markup into half-parsed
1210 * HTML. Only called for $mOutputType == self::OT_HTML.
1214 * @param string $text
1215 * @param bool $isMain
1216 * @param PPFrame|bool $frame
1220 public function internalParse( $text, $isMain = true, $frame = false ) {
1224 # Hook to suspend the parser in this state
1225 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1229 # if $frame is provided, then use $frame for replacing any variables
1231 # use frame depth to infer how include/noinclude tags should be handled
1232 # depth=0 means this is the top-level document; otherwise it's an included document
1233 if ( !$frame->depth
) {
1236 $flag = Parser
::PTD_FOR_INCLUSION
;
1238 $dom = $this->preprocessToDom( $text, $flag );
1239 $text = $frame->expand( $dom );
1241 # if $frame is not provided, then use old-style replaceVariables
1242 $text = $this->replaceVariables( $text );
1245 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1246 $text = Sanitizer
::removeHTMLtags(
1248 array( &$this, 'attributeStripCallback' ),
1250 array_keys( $this->mTransparentTagHooks
)
1252 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1254 # Tables need to come after variable replacement for things to work
1255 # properly; putting them before other transformations should keep
1256 # exciting things like link expansions from showing up in surprising
1258 $text = $this->doTableStuff( $text );
1260 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1262 $text = $this->doDoubleUnderscore( $text );
1264 $text = $this->doHeadings( $text );
1265 $text = $this->replaceInternalLinks( $text );
1266 $text = $this->doAllQuotes( $text );
1267 $text = $this->replaceExternalLinks( $text );
1269 # replaceInternalLinks may sometimes leave behind
1270 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1271 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1273 $text = $this->doMagicLinks( $text );
1274 $text = $this->formatHeadings( $text, $origText, $isMain );
1280 * Helper function for parse() that transforms half-parsed HTML into fully
1283 * @param string $text
1284 * @param bool $isMain
1285 * @param bool $linestart
1288 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1289 $text = $this->mStripState
->unstripGeneral( $text );
1292 Hooks
::run( 'ParserAfterUnstrip', array( &$this, &$text ) );
1295 # Clean up special characters, only run once, next-to-last before doBlockLevels
1297 # french spaces, last one Guillemet-left
1298 # only if there is something before the space
1299 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1300 # french spaces, Guillemet-right
1301 '/(\\302\\253) /' => '\\1 ',
1302 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1304 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1306 $text = $this->doBlockLevels( $text, $linestart );
1308 $this->replaceLinkHolders( $text );
1311 * The input doesn't get language converted if
1313 * b) Content isn't converted
1314 * c) It's a conversion table
1315 * d) it is an interface message (which is in the user language)
1317 if ( !( $this->mOptions
->getDisableContentConversion()
1318 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1320 if ( !$this->mOptions
->getInterfaceMessage() ) {
1321 # The position of the convert() call should not be changed. it
1322 # assumes that the links are all replaced and the only thing left
1323 # is the <nowiki> mark.
1324 $text = $this->getConverterLanguage()->convert( $text );
1328 $text = $this->mStripState
->unstripNoWiki( $text );
1331 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1334 $text = $this->replaceTransparentTags( $text );
1335 $text = $this->mStripState
->unstripGeneral( $text );
1337 $text = Sanitizer
::normalizeCharReferences( $text );
1339 if ( MWTidy
::isEnabled() && $this->mOptions
->getTidy() ) {
1340 $text = MWTidy
::tidy( $text );
1342 # attempt to sanitize at least some nesting problems
1343 # (bug #2702 and quite a few others)
1345 # ''Something [http://www.cool.com cool''] -->
1346 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1347 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1348 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1349 # fix up an anchor inside another anchor, only
1350 # at least for a single single nested link (bug 3695)
1351 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1352 '\\1\\2</a>\\3</a>\\1\\4</a>',
1353 # fix div inside inline elements- doBlockLevels won't wrap a line which
1354 # contains a div, so fix it up here; replace
1355 # div with escaped text
1356 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1357 '\\1\\3<div\\5>\\6</div>\\8\\9',
1358 # remove empty italic or bold tag pairs, some
1359 # introduced by rules above
1360 '/<([bi])><\/\\1>/' => '',
1363 $text = preg_replace(
1364 array_keys( $tidyregs ),
1365 array_values( $tidyregs ),
1370 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1377 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1378 * magic external links.
1383 * @param string $text
1387 public function doMagicLinks( $text ) {
1388 $prots = wfUrlProtocolsWithoutProtRel();
1389 $urlChar = self
::EXT_LINK_URL_CLASS
;
1390 $addr = self
::EXT_LINK_ADDR
;
1391 $space = self
::SPACE_NOT_NL
; # non-newline space
1392 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1393 $spaces = "$space++"; # possessive match of 1 or more spaces
1394 $text = preg_replace_callback(
1396 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1397 (<.*?>) | # m[2]: Skip stuff inside
1398 # HTML elements' . "
1399 (\b(?i:$prots)($addr$urlChar*)) | # m[3]: Free external links
1400 # m[4]: Post-protocol path
1401 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1403 \bISBN $spaces ( # m[6]: ISBN, capture number
1404 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1405 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1406 [0-9Xx] # check digit
1408 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1413 * @throws MWException
1415 * @return HTML|string
1417 public function magicLinkCallback( $m ) {
1418 if ( isset( $m[1] ) && $m[1] !== '' ) {
1421 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1424 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1425 # Free external link
1426 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1427 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1429 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1432 $cssClass = 'mw-magiclink-rfc';
1434 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1436 $urlmsg = 'pubmedurl';
1437 $cssClass = 'mw-magiclink-pmid';
1440 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1441 substr( $m[0], 0, 20 ) . '"' );
1443 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1444 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1445 } elseif ( isset( $m[6] ) && $m[6] !== '' ) {
1448 $space = self
::SPACE_NOT_NL
; # non-newline space
1449 $isbn = preg_replace( "/$space/", ' ', $isbn );
1450 $num = strtr( $isbn, array(
1455 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1456 return '<a href="' .
1457 htmlspecialchars( $titleObj->getLocalURL() ) .
1458 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1465 * Make a free external link, given a user-supplied URL
1467 * @param string $url
1468 * @param int $numPostProto
1469 * The number of characters after the protocol.
1470 * @return string HTML
1473 public function makeFreeExternalLink( $url, $numPostProto ) {
1476 # The characters '<' and '>' (which were escaped by
1477 # removeHTMLtags()) should not be included in
1478 # URLs, per RFC 2396.
1479 # Make terminate a URL as well (bug T84937)
1482 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1487 $trail = substr( $url, $m2[0][1] ) . $trail;
1488 $url = substr( $url, 0, $m2[0][1] );
1491 # Move trailing punctuation to $trail
1493 # If there is no left bracket, then consider right brackets fair game too
1494 if ( strpos( $url, '(' ) === false ) {
1498 $urlRev = strrev( $url );
1499 $numSepChars = strspn( $urlRev, $sep );
1500 # Don't break a trailing HTML entity by moving the ; into $trail
1501 # This is in hot code, so use substr_compare to avoid having to
1502 # create a new string object for the comparison
1503 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1504 # more optimization: instead of running preg_match with a $
1505 # anchor, which can be slow, do the match on the reversed
1506 # string starting at the desired offset.
1507 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1508 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1512 if ( $numSepChars ) {
1513 $trail = substr( $url, -$numSepChars ) . $trail;
1514 $url = substr( $url, 0, -$numSepChars );
1517 # Verify that we still have a real URL after trail removal, and
1518 # not just lone protocol
1519 if ( strlen( $trail ) >= $numPostProto ) {
1520 return $url . $trail;
1523 $url = Sanitizer
::cleanUrl( $url );
1525 # Is this an external image?
1526 $text = $this->maybeMakeExternalImage( $url );
1527 if ( $text === false ) {
1528 # Not an image, make a link
1529 $text = Linker
::makeExternalLink( $url,
1530 $this->getConverterLanguage()->markNoConversion( $url, true ),
1532 $this->getExternalLinkAttribs( $url ) );
1533 # Register it in the output object...
1534 # Replace unnecessary URL escape codes with their equivalent characters
1535 $pasteurized = self
::normalizeLinkUrl( $url );
1536 $this->mOutput
->addExternalLink( $pasteurized );
1538 return $text . $trail;
1542 * Parse headers and return html
1546 * @param string $text
1550 public function doHeadings( $text ) {
1551 for ( $i = 6; $i >= 1; --$i ) {
1552 $h = str_repeat( '=', $i );
1553 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1559 * Replace single quotes with HTML markup
1562 * @param string $text
1564 * @return string The altered text
1566 public function doAllQuotes( $text ) {
1568 $lines = StringUtils
::explode( "\n", $text );
1569 foreach ( $lines as $line ) {
1570 $outtext .= $this->doQuotes( $line ) . "\n";
1572 $outtext = substr( $outtext, 0, -1 );
1577 * Helper function for doAllQuotes()
1579 * @param string $text
1583 public function doQuotes( $text ) {
1584 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1585 $countarr = count( $arr );
1586 if ( $countarr == 1 ) {
1590 // First, do some preliminary work. This may shift some apostrophes from
1591 // being mark-up to being text. It also counts the number of occurrences
1592 // of bold and italics mark-ups.
1595 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1596 $thislen = strlen( $arr[$i] );
1597 // If there are ever four apostrophes, assume the first is supposed to
1598 // be text, and the remaining three constitute mark-up for bold text.
1599 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1600 if ( $thislen == 4 ) {
1601 $arr[$i - 1] .= "'";
1604 } elseif ( $thislen > 5 ) {
1605 // If there are more than 5 apostrophes in a row, assume they're all
1606 // text except for the last 5.
1607 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1608 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1612 // Count the number of occurrences of bold and italics mark-ups.
1613 if ( $thislen == 2 ) {
1615 } elseif ( $thislen == 3 ) {
1617 } elseif ( $thislen == 5 ) {
1623 // If there is an odd number of both bold and italics, it is likely
1624 // that one of the bold ones was meant to be an apostrophe followed
1625 // by italics. Which one we cannot know for certain, but it is more
1626 // likely to be one that has a single-letter word before it.
1627 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1628 $firstsingleletterword = -1;
1629 $firstmultiletterword = -1;
1631 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1632 if ( strlen( $arr[$i] ) == 3 ) {
1633 $x1 = substr( $arr[$i - 1], -1 );
1634 $x2 = substr( $arr[$i - 1], -2, 1 );
1635 if ( $x1 === ' ' ) {
1636 if ( $firstspace == -1 ) {
1639 } elseif ( $x2 === ' ' ) {
1640 $firstsingleletterword = $i;
1641 // if $firstsingleletterword is set, we don't
1642 // look at the other options, so we can bail early.
1645 if ( $firstmultiletterword == -1 ) {
1646 $firstmultiletterword = $i;
1652 // If there is a single-letter word, use it!
1653 if ( $firstsingleletterword > -1 ) {
1654 $arr[$firstsingleletterword] = "''";
1655 $arr[$firstsingleletterword - 1] .= "'";
1656 } elseif ( $firstmultiletterword > -1 ) {
1657 // If not, but there's a multi-letter word, use that one.
1658 $arr[$firstmultiletterword] = "''";
1659 $arr[$firstmultiletterword - 1] .= "'";
1660 } elseif ( $firstspace > -1 ) {
1661 // ... otherwise use the first one that has neither.
1662 // (notice that it is possible for all three to be -1 if, for example,
1663 // there is only one pentuple-apostrophe in the line)
1664 $arr[$firstspace] = "''";
1665 $arr[$firstspace - 1] .= "'";
1669 // Now let's actually convert our apostrophic mush to HTML!
1674 foreach ( $arr as $r ) {
1675 if ( ( $i %
2 ) == 0 ) {
1676 if ( $state === 'both' ) {
1682 $thislen = strlen( $r );
1683 if ( $thislen == 2 ) {
1684 if ( $state === 'i' ) {
1687 } elseif ( $state === 'bi' ) {
1690 } elseif ( $state === 'ib' ) {
1691 $output .= '</b></i><b>';
1693 } elseif ( $state === 'both' ) {
1694 $output .= '<b><i>' . $buffer . '</i>';
1696 } else { // $state can be 'b' or ''
1700 } elseif ( $thislen == 3 ) {
1701 if ( $state === 'b' ) {
1704 } elseif ( $state === 'bi' ) {
1705 $output .= '</i></b><i>';
1707 } elseif ( $state === 'ib' ) {
1710 } elseif ( $state === 'both' ) {
1711 $output .= '<i><b>' . $buffer . '</b>';
1713 } else { // $state can be 'i' or ''
1717 } elseif ( $thislen == 5 ) {
1718 if ( $state === 'b' ) {
1719 $output .= '</b><i>';
1721 } elseif ( $state === 'i' ) {
1722 $output .= '</i><b>';
1724 } elseif ( $state === 'bi' ) {
1725 $output .= '</i></b>';
1727 } elseif ( $state === 'ib' ) {
1728 $output .= '</b></i>';
1730 } elseif ( $state === 'both' ) {
1731 $output .= '<i><b>' . $buffer . '</b></i>';
1733 } else { // ($state == '')
1741 // Now close all remaining tags. Notice that the order is important.
1742 if ( $state === 'b' ||
$state === 'ib' ) {
1745 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1748 if ( $state === 'bi' ) {
1751 // There might be lonely ''''', so make sure we have a buffer
1752 if ( $state === 'both' && $buffer ) {
1753 $output .= '<b><i>' . $buffer . '</i></b>';
1759 * Replace external links (REL)
1761 * Note: this is all very hackish and the order of execution matters a lot.
1762 * Make sure to run tests/parserTests.php if you change this code.
1766 * @param string $text
1768 * @throws MWException
1771 public function replaceExternalLinks( $text ) {
1773 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1774 if ( $bits === false ) {
1775 throw new MWException( "PCRE needs to be compiled with "
1776 . "--enable-unicode-properties in order for MediaWiki to function" );
1778 $s = array_shift( $bits );
1781 while ( $i < count( $bits ) ) {
1784 $text = $bits[$i++
];
1785 $trail = $bits[$i++
];
1787 # The characters '<' and '>' (which were escaped by
1788 # removeHTMLtags()) should not be included in
1789 # URLs, per RFC 2396.
1791 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1792 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1793 $url = substr( $url, 0, $m2[0][1] );
1796 # If the link text is an image URL, replace it with an <img> tag
1797 # This happened by accident in the original parser, but some people used it extensively
1798 $img = $this->maybeMakeExternalImage( $text );
1799 if ( $img !== false ) {
1805 # Set linktype for CSS - if URL==text, link is essentially free
1806 $linktype = ( $text === $url ) ?
'free' : 'text';
1808 # No link text, e.g. [http://domain.tld/some.link]
1809 if ( $text == '' ) {
1811 $langObj = $this->getTargetLanguage();
1812 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1813 $linktype = 'autonumber';
1815 # Have link text, e.g. [http://domain.tld/some.link text]s
1817 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1820 $text = $this->getConverterLanguage()->markNoConversion( $text );
1822 $url = Sanitizer
::cleanUrl( $url );
1824 # Use the encoded URL
1825 # This means that users can paste URLs directly into the text
1826 # Funny characters like ö aren't valid in URLs anyway
1827 # This was changed in August 2004
1828 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1829 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1831 # Register link in the output object.
1832 # Replace unnecessary URL escape codes with the referenced character
1833 # This prevents spammers from hiding links from the filters
1834 $pasteurized = self
::normalizeLinkUrl( $url );
1835 $this->mOutput
->addExternalLink( $pasteurized );
1842 * Get the rel attribute for a particular external link.
1845 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1846 * nofollow if appropriate
1847 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1848 * @return string|null Rel attribute for $url
1850 public static function getExternalLinkRel( $url = false, $title = null ) {
1851 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1852 $ns = $title ?
$title->getNamespace() : false;
1853 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1854 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1862 * Get an associative array of additional HTML attributes appropriate for a
1863 * particular external link. This currently may include rel => nofollow
1864 * (depending on configuration, namespace, and the URL's domain) and/or a
1865 * target attribute (depending on configuration).
1867 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1868 * nofollow if appropriate
1869 * @return array Associative array of HTML attributes
1871 public function getExternalLinkAttribs( $url = false ) {
1873 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1875 if ( $this->mOptions
->getExternalLinkTarget() ) {
1876 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1882 * Replace unusual escape codes in a URL with their equivalent characters
1884 * @deprecated since 1.24, use normalizeLinkUrl
1885 * @param string $url
1888 public static function replaceUnusualEscapes( $url ) {
1889 wfDeprecated( __METHOD__
, '1.24' );
1890 return self
::normalizeLinkUrl( $url );
1894 * Replace unusual escape codes in a URL with their equivalent characters
1896 * This generally follows the syntax defined in RFC 3986, with special
1897 * consideration for HTTP query strings.
1899 * @param string $url
1902 public static function normalizeLinkUrl( $url ) {
1903 # First, make sure unsafe characters are encoded
1904 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1906 return rawurlencode( $m[0] );
1912 $end = strlen( $url );
1914 # Fragment part - 'fragment'
1915 $start = strpos( $url, '#' );
1916 if ( $start !== false && $start < $end ) {
1917 $ret = self
::normalizeUrlComponent(
1918 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1922 # Query part - 'query' minus &=+;
1923 $start = strpos( $url, '?' );
1924 if ( $start !== false && $start < $end ) {
1925 $ret = self
::normalizeUrlComponent(
1926 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1930 # Scheme and path part - 'pchar'
1931 # (we assume no userinfo or encoded colons in the host)
1932 $ret = self
::normalizeUrlComponent(
1933 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1938 private static function normalizeUrlComponent( $component, $unsafe ) {
1939 $callback = function ( $matches ) use ( $unsafe ) {
1940 $char = urldecode( $matches[0] );
1941 $ord = ord( $char );
1942 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1946 # Leave it escaped, but use uppercase for a-f
1947 return strtoupper( $matches[0] );
1950 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1954 * make an image if it's allowed, either through the global
1955 * option, through the exception, or through the on-wiki whitelist
1957 * @param string $url
1961 private function maybeMakeExternalImage( $url ) {
1962 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1963 $imagesexception = !empty( $imagesfrom );
1965 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1966 if ( $imagesexception && is_array( $imagesfrom ) ) {
1967 $imagematch = false;
1968 foreach ( $imagesfrom as $match ) {
1969 if ( strpos( $url, $match ) === 0 ) {
1974 } elseif ( $imagesexception ) {
1975 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1977 $imagematch = false;
1980 if ( $this->mOptions
->getAllowExternalImages()
1981 ||
( $imagesexception && $imagematch )
1983 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1985 $text = Linker
::makeExternalImage( $url );
1988 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1989 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1991 $whitelist = explode(
1993 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1996 foreach ( $whitelist as $entry ) {
1997 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1998 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2001 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2002 # Image matches a whitelist entry
2003 $text = Linker
::makeExternalImage( $url );
2012 * Process [[ ]] wikilinks
2016 * @return string Processed text
2020 public function replaceInternalLinks( $s ) {
2021 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2026 * Process [[ ]] wikilinks (RIL)
2028 * @throws MWException
2029 * @return LinkHolderArray
2033 public function replaceInternalLinks2( &$s ) {
2034 global $wgExtraInterlanguageLinkPrefixes;
2036 static $tc = false, $e1, $e1_img;
2037 # the % is needed to support urlencoded titles as well
2039 $tc = Title
::legalChars() . '#%';
2040 # Match a link having the form [[namespace:link|alternate]]trail
2041 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2042 # Match cases where there is no "]]", which might still be images
2043 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2046 $holders = new LinkHolderArray( $this );
2048 # split the entire text string on occurrences of [[
2049 $a = StringUtils
::explode( '[[', ' ' . $s );
2050 # get the first element (all text up to first [[), and remove the space we added
2053 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2054 $s = substr( $s, 1 );
2056 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2058 if ( $useLinkPrefixExtension ) {
2059 # Match the end of a line for a word that's not followed by whitespace,
2060 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2062 $charset = $wgContLang->linkPrefixCharset();
2063 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2066 if ( is_null( $this->mTitle
) ) {
2067 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2069 $nottalk = !$this->mTitle
->isTalkPage();
2071 if ( $useLinkPrefixExtension ) {
2073 if ( preg_match( $e2, $s, $m ) ) {
2074 $first_prefix = $m[2];
2076 $first_prefix = false;
2082 $useSubpages = $this->areSubpagesAllowed();
2084 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2085 # Loop for each link
2086 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2087 // @codingStandardsIgnoreStart
2089 # Check for excessive memory usage
2090 if ( $holders->isBig() ) {
2092 # Do the existence check, replace the link holders and clear the array
2093 $holders->replace( $s );
2097 if ( $useLinkPrefixExtension ) {
2098 if ( preg_match( $e2, $s, $m ) ) {
2105 if ( $first_prefix ) {
2106 $prefix = $first_prefix;
2107 $first_prefix = false;
2111 $might_be_img = false;
2113 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2115 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2116 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2117 # the real problem is with the $e1 regex
2120 # Still some problems for cases where the ] is meant to be outside punctuation,
2121 # and no image is in sight. See bug 2095.
2124 && substr( $m[3], 0, 1 ) === ']'
2125 && strpos( $text, '[' ) !== false
2127 $text .= ']'; # so that replaceExternalLinks($text) works later
2128 $m[3] = substr( $m[3], 1 );
2130 # fix up urlencoded title texts
2131 if ( strpos( $m[1], '%' ) !== false ) {
2132 # Should anchors '#' also be rejected?
2133 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2136 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2137 # Invalid, but might be an image with a link in its caption
2138 $might_be_img = true;
2140 if ( strpos( $m[1], '%' ) !== false ) {
2141 $m[1] = rawurldecode( $m[1] );
2144 } else { # Invalid form; output directly
2145 $s .= $prefix . '[[' . $line;
2151 # Don't allow internal links to pages containing
2152 # PROTO: where PROTO is a valid URL protocol; these
2153 # should be external links.
2154 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2155 $s .= $prefix . '[[' . $line;
2159 # Make subpage if necessary
2160 if ( $useSubpages ) {
2161 $link = $this->maybeDoSubpageLink( $origLink, $text );
2166 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2168 # Strip off leading ':'
2169 $link = substr( $link, 1 );
2172 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2173 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2174 if ( $nt === null ) {
2175 $s .= $prefix . '[[' . $line;
2179 $ns = $nt->getNamespace();
2180 $iw = $nt->getInterwiki();
2182 if ( $might_be_img ) { # if this is actually an invalid link
2183 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2186 # look at the next 'line' to see if we can close it there
2188 $next_line = $a->current();
2189 if ( $next_line === false ||
$next_line === null ) {
2192 $m = explode( ']]', $next_line, 3 );
2193 if ( count( $m ) == 3 ) {
2194 # the first ]] closes the inner link, the second the image
2196 $text .= "[[{$m[0]}]]{$m[1]}";
2199 } elseif ( count( $m ) == 2 ) {
2200 # if there's exactly one ]] that's fine, we'll keep looking
2201 $text .= "[[{$m[0]}]]{$m[1]}";
2203 # if $next_line is invalid too, we need look no further
2204 $text .= '[[' . $next_line;
2209 # we couldn't find the end of this imageLink, so output it raw
2210 # but don't ignore what might be perfectly normal links in the text we've examined
2211 $holders->merge( $this->replaceInternalLinks2( $text ) );
2212 $s .= "{$prefix}[[$link|$text";
2213 # note: no $trail, because without an end, there *is* no trail
2216 } else { # it's not an image, so output it raw
2217 $s .= "{$prefix}[[$link|$text";
2218 # note: no $trail, because without an end, there *is* no trail
2223 $wasblank = ( $text == '' );
2227 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2228 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2229 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2230 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2231 $text = $this->doQuotes( $text );
2234 # Link not escaped by : , create the various objects
2235 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2238 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2239 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2240 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2243 # Bug 24502: filter duplicates
2244 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2245 $this->mLangLinkLanguages
[$iw] = true;
2246 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2249 $s = rtrim( $s . $prefix );
2250 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2254 if ( $ns == NS_FILE
) {
2255 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2257 # if no parameters were passed, $text
2258 # becomes something like "File:Foo.png",
2259 # which we don't want to pass on to the
2263 # recursively parse links inside the image caption
2264 # actually, this will parse them in any other parameters, too,
2265 # but it might be hard to fix that, and it doesn't matter ATM
2266 $text = $this->replaceExternalLinks( $text );
2267 $holders->merge( $this->replaceInternalLinks2( $text ) );
2269 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2270 $s .= $prefix . $this->armorLinks(
2271 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2273 $s .= $prefix . $trail;
2278 if ( $ns == NS_CATEGORY
) {
2279 $s = rtrim( $s . "\n" ); # bug 87
2282 $sortkey = $this->getDefaultSort();
2286 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2287 $sortkey = str_replace( "\n", '', $sortkey );
2288 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2289 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2292 * Strip the whitespace Category links produce, see bug 87
2294 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2300 # Self-link checking. For some languages, variants of the title are checked in
2301 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2302 # for linking to a different variant.
2303 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2304 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2308 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2309 # @todo FIXME: Should do batch file existence checks, see comment below
2310 if ( $ns == NS_MEDIA
) {
2311 # Give extensions a chance to select the file revision for us
2314 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2315 array( $this, $nt, &$options, &$descQuery ) );
2316 # Fetch and register the file (file title may be different via hooks)
2317 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2318 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2319 $s .= $prefix . $this->armorLinks(
2320 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2324 # Some titles, such as valid special pages or files in foreign repos, should
2325 # be shown as bluelinks even though they're not included in the page table
2327 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2328 # batch file existence checks for NS_FILE and NS_MEDIA
2329 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2330 $this->mOutput
->addLink( $nt );
2331 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2333 # Links will be added to the output link list after checking
2334 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2341 * Render a forced-blue link inline; protect against double expansion of
2342 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2343 * Since this little disaster has to split off the trail text to avoid
2344 * breaking URLs in the following text without breaking trails on the
2345 * wiki links, it's been made into a horrible function.
2348 * @param string $text
2349 * @param array|string $query
2350 * @param string $trail
2351 * @param string $prefix
2352 * @return string HTML-wikitext mix oh yuck
2354 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2355 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2357 if ( is_string( $query ) ) {
2358 $query = wfCgiToArray( $query );
2360 if ( $text == '' ) {
2361 $text = htmlspecialchars( $nt->getPrefixedText() );
2364 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2366 return $this->armorLinks( $link ) . $trail;
2370 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2371 * going to go through further parsing steps before inline URL expansion.
2373 * Not needed quite as much as it used to be since free links are a bit
2374 * more sensible these days. But bracketed links are still an issue.
2376 * @param string $text More-or-less HTML
2377 * @return string Less-or-more HTML with NOPARSE bits
2379 public function armorLinks( $text ) {
2380 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2381 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2385 * Return true if subpage links should be expanded on this page.
2388 public function areSubpagesAllowed() {
2389 # Some namespaces don't allow subpages
2390 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2394 * Handle link to subpage if necessary
2396 * @param string $target The source of the link
2397 * @param string &$text The link text, modified as necessary
2398 * @return string The full name of the link
2401 public function maybeDoSubpageLink( $target, &$text ) {
2402 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2406 * Used by doBlockLevels()
2411 public function closeParagraph() {
2413 if ( $this->mLastSection
!= '' ) {
2414 $result = '</' . $this->mLastSection
. ">\n";
2416 $this->mInPre
= false;
2417 $this->mLastSection
= '';
2422 * getCommon() returns the length of the longest common substring
2423 * of both arguments, starting at the beginning of both.
2426 * @param string $st1
2427 * @param string $st2
2431 public function getCommon( $st1, $st2 ) {
2432 $fl = strlen( $st1 );
2433 $shorter = strlen( $st2 );
2434 if ( $fl < $shorter ) {
2438 for ( $i = 0; $i < $shorter; ++
$i ) {
2439 if ( $st1[$i] != $st2[$i] ) {
2447 * These next three functions open, continue, and close the list
2448 * element appropriate to the prefix character passed into them.
2451 * @param string $char
2455 public function openList( $char ) {
2456 $result = $this->closeParagraph();
2458 if ( '*' === $char ) {
2459 $result .= "<ul><li>";
2460 } elseif ( '#' === $char ) {
2461 $result .= "<ol><li>";
2462 } elseif ( ':' === $char ) {
2463 $result .= "<dl><dd>";
2464 } elseif ( ';' === $char ) {
2465 $result .= "<dl><dt>";
2466 $this->mDTopen
= true;
2468 $result = '<!-- ERR 1 -->';
2476 * @param string $char
2481 public function nextItem( $char ) {
2482 if ( '*' === $char ||
'#' === $char ) {
2483 return "</li>\n<li>";
2484 } elseif ( ':' === $char ||
';' === $char ) {
2486 if ( $this->mDTopen
) {
2489 if ( ';' === $char ) {
2490 $this->mDTopen
= true;
2491 return $close . '<dt>';
2493 $this->mDTopen
= false;
2494 return $close . '<dd>';
2497 return '<!-- ERR 2 -->';
2502 * @param string $char
2507 public function closeList( $char ) {
2508 if ( '*' === $char ) {
2509 $text = "</li></ul>";
2510 } elseif ( '#' === $char ) {
2511 $text = "</li></ol>";
2512 } elseif ( ':' === $char ) {
2513 if ( $this->mDTopen
) {
2514 $this->mDTopen
= false;
2515 $text = "</dt></dl>";
2517 $text = "</dd></dl>";
2520 return '<!-- ERR 3 -->';
2527 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2529 * @param string $text
2530 * @param bool $linestart Whether or not this is at the start of a line.
2532 * @return string The lists rendered as HTML
2534 public function doBlockLevels( $text, $linestart ) {
2536 # Parsing through the text line by line. The main thing
2537 # happening here is handling of block-level elements p, pre,
2538 # and making lists from lines starting with * # : etc.
2540 $textLines = StringUtils
::explode( "\n", $text );
2542 $lastPrefix = $output = '';
2543 $this->mDTopen
= $inBlockElem = false;
2545 $paragraphStack = false;
2546 $inBlockquote = false;
2548 foreach ( $textLines as $oLine ) {
2550 if ( !$linestart ) {
2560 $lastPrefixLength = strlen( $lastPrefix );
2561 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2562 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2563 # If not in a <pre> element, scan for and figure out what prefixes are there.
2564 if ( !$this->mInPre
) {
2565 # Multiple prefixes may abut each other for nested lists.
2566 $prefixLength = strspn( $oLine, '*#:;' );
2567 $prefix = substr( $oLine, 0, $prefixLength );
2570 # ; and : are both from definition-lists, so they're equivalent
2571 # for the purposes of determining whether or not we need to open/close
2573 $prefix2 = str_replace( ';', ':', $prefix );
2574 $t = substr( $oLine, $prefixLength );
2575 $this->mInPre
= (bool)$preOpenMatch;
2577 # Don't interpret any other prefixes in preformatted text
2579 $prefix = $prefix2 = '';
2584 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2585 # Same as the last item, so no need to deal with nesting or opening stuff
2586 $output .= $this->nextItem( substr( $prefix, -1 ) );
2587 $paragraphStack = false;
2589 if ( substr( $prefix, -1 ) === ';' ) {
2590 # The one nasty exception: definition lists work like this:
2591 # ; title : definition text
2592 # So we check for : in the remainder text to split up the
2593 # title and definition, without b0rking links.
2595 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2597 $output .= $term . $this->nextItem( ':' );
2600 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2601 # We need to open or close prefixes, or both.
2603 # Either open or close a level...
2604 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2605 $paragraphStack = false;
2607 # Close all the prefixes which aren't shared.
2608 while ( $commonPrefixLength < $lastPrefixLength ) {
2609 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2610 --$lastPrefixLength;
2613 # Continue the current prefix if appropriate.
2614 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2615 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2618 # Open prefixes where appropriate.
2619 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2622 while ( $prefixLength > $commonPrefixLength ) {
2623 $char = substr( $prefix, $commonPrefixLength, 1 );
2624 $output .= $this->openList( $char );
2626 if ( ';' === $char ) {
2627 # @todo FIXME: This is dupe of code above
2628 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2630 $output .= $term . $this->nextItem( ':' );
2633 ++
$commonPrefixLength;
2635 if ( !$prefixLength && $lastPrefix ) {
2638 $lastPrefix = $prefix2;
2641 # If we have no prefixes, go to paragraph mode.
2642 if ( 0 == $prefixLength ) {
2643 # No prefix (not in list)--go to paragraph mode
2644 # XXX: use a stack for nestable elements like span, table and div
2645 $openmatch = preg_match(
2646 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2647 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2650 $closematch = preg_match(
2651 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2652 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2653 . self
::MARKER_PREFIX
2654 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2658 if ( $openmatch ||
$closematch ) {
2659 $paragraphStack = false;
2660 # @todo bug 5718: paragraph closed
2661 $output .= $this->closeParagraph();
2662 if ( $preOpenMatch && !$preCloseMatch ) {
2663 $this->mInPre
= true;
2666 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2667 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2668 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2670 $inBlockElem = !$closematch;
2671 } elseif ( !$inBlockElem && !$this->mInPre
) {
2672 if ( ' ' == substr( $t, 0, 1 )
2673 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2677 if ( $this->mLastSection
!== 'pre' ) {
2678 $paragraphStack = false;
2679 $output .= $this->closeParagraph() . '<pre>';
2680 $this->mLastSection
= 'pre';
2682 $t = substr( $t, 1 );
2685 if ( trim( $t ) === '' ) {
2686 if ( $paragraphStack ) {
2687 $output .= $paragraphStack . '<br />';
2688 $paragraphStack = false;
2689 $this->mLastSection
= 'p';
2691 if ( $this->mLastSection
!== 'p' ) {
2692 $output .= $this->closeParagraph();
2693 $this->mLastSection
= '';
2694 $paragraphStack = '<p>';
2696 $paragraphStack = '</p><p>';
2700 if ( $paragraphStack ) {
2701 $output .= $paragraphStack;
2702 $paragraphStack = false;
2703 $this->mLastSection
= 'p';
2704 } elseif ( $this->mLastSection
!== 'p' ) {
2705 $output .= $this->closeParagraph() . '<p>';
2706 $this->mLastSection
= 'p';
2712 # somewhere above we forget to get out of pre block (bug 785)
2713 if ( $preCloseMatch && $this->mInPre
) {
2714 $this->mInPre
= false;
2716 if ( $paragraphStack === false ) {
2718 if ( $prefixLength === 0 ) {
2723 while ( $prefixLength ) {
2724 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2726 if ( !$prefixLength ) {
2730 if ( $this->mLastSection
!= '' ) {
2731 $output .= '</' . $this->mLastSection
. '>';
2732 $this->mLastSection
= '';
2739 * Split up a string on ':', ignoring any occurrences inside tags
2740 * to prevent illegal overlapping.
2742 * @param string $str The string to split
2743 * @param string &$before Set to everything before the ':'
2744 * @param string &$after Set to everything after the ':'
2745 * @throws MWException
2746 * @return string The position of the ':', or false if none found
2748 public function findColonNoLinks( $str, &$before, &$after ) {
2750 $pos = strpos( $str, ':' );
2751 if ( $pos === false ) {
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 );
2764 # Ugly state machine to walk through avoiding tags.
2765 $state = self
::COLON_STATE_TEXT
;
2767 $len = strlen( $str );
2768 for ( $i = 0; $i < $len; $i++
) {
2772 # (Using the number is a performance hack for common cases)
2773 case 0: # self::COLON_STATE_TEXT:
2776 # Could be either a <start> tag or an </end> tag
2777 $state = self
::COLON_STATE_TAGSTART
;
2780 if ( $stack == 0 ) {
2782 $before = substr( $str, 0, $i );
2783 $after = substr( $str, $i +
1 );
2786 # Embedded in a tag; don't break it.
2789 # Skip ahead looking for something interesting
2790 $colon = strpos( $str, ':', $i );
2791 if ( $colon === false ) {
2792 # Nothing else interesting
2795 $lt = strpos( $str, '<', $i );
2796 if ( $stack === 0 ) {
2797 if ( $lt === false ||
$colon < $lt ) {
2799 $before = substr( $str, 0, $colon );
2800 $after = substr( $str, $colon +
1 );
2804 if ( $lt === false ) {
2805 # Nothing else interesting to find; abort!
2806 # We're nested, but there's no close tags left. Abort!
2809 # Skip ahead to next tag start
2811 $state = self
::COLON_STATE_TAGSTART
;
2814 case 1: # self::COLON_STATE_TAG:
2819 $state = self
::COLON_STATE_TEXT
;
2822 # Slash may be followed by >?
2823 $state = self
::COLON_STATE_TAGSLASH
;
2829 case 2: # self::COLON_STATE_TAGSTART:
2832 $state = self
::COLON_STATE_CLOSETAG
;
2835 $state = self
::COLON_STATE_COMMENT
;
2838 # Illegal early close? This shouldn't happen D:
2839 $state = self
::COLON_STATE_TEXT
;
2842 $state = self
::COLON_STATE_TAG
;
2845 case 3: # self::COLON_STATE_CLOSETAG:
2850 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2853 $state = self
::COLON_STATE_TEXT
;
2856 case self
::COLON_STATE_TAGSLASH
:
2858 # Yes, a self-closed tag <blah/>
2859 $state = self
::COLON_STATE_TEXT
;
2861 # Probably we're jumping the gun, and this is an attribute
2862 $state = self
::COLON_STATE_TAG
;
2865 case 5: # self::COLON_STATE_COMMENT:
2867 $state = self
::COLON_STATE_COMMENTDASH
;
2870 case self
::COLON_STATE_COMMENTDASH
:
2872 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2874 $state = self
::COLON_STATE_COMMENT
;
2877 case self
::COLON_STATE_COMMENTDASHDASH
:
2879 $state = self
::COLON_STATE_TEXT
;
2881 $state = self
::COLON_STATE_COMMENT
;
2885 throw new MWException( "State machine error in " . __METHOD__
);
2889 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2896 * Return value of a magic variable (like PAGENAME)
2901 * @param bool|PPFrame $frame
2903 * @throws MWException
2906 public function getVariableValue( $index, $frame = false ) {
2907 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2908 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2910 if ( is_null( $this->mTitle
) ) {
2911 // If no title set, bad things are going to happen
2912 // later. Title should always be set since this
2913 // should only be called in the middle of a parse
2914 // operation (but the unit-tests do funky stuff)
2915 throw new MWException( __METHOD__
. ' Should only be '
2916 . ' called while parsing (no title set)' );
2920 * Some of these require message or data lookups and can be
2921 * expensive to check many times.
2923 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2924 if ( isset( $this->mVarCache
[$index] ) ) {
2925 return $this->mVarCache
[$index];
2929 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2930 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2932 $pageLang = $this->getFunctionLang();
2938 case 'currentmonth':
2939 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2941 case 'currentmonth1':
2942 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2944 case 'currentmonthname':
2945 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2947 case 'currentmonthnamegen':
2948 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2950 case 'currentmonthabbrev':
2951 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2954 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2957 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2960 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2963 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2965 case 'localmonthname':
2966 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2968 case 'localmonthnamegen':
2969 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2971 case 'localmonthabbrev':
2972 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2975 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2978 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2981 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2984 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2986 case 'fullpagename':
2987 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2989 case 'fullpagenamee':
2990 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2993 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2995 case 'subpagenamee':
2996 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2998 case 'rootpagename':
2999 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3001 case 'rootpagenamee':
3002 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3005 $this->mTitle
->getRootText()
3008 case 'basepagename':
3009 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3011 case 'basepagenamee':
3012 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3015 $this->mTitle
->getBaseText()
3018 case 'talkpagename':
3019 if ( $this->mTitle
->canTalk() ) {
3020 $talkPage = $this->mTitle
->getTalkPage();
3021 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3026 case 'talkpagenamee':
3027 if ( $this->mTitle
->canTalk() ) {
3028 $talkPage = $this->mTitle
->getTalkPage();
3029 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3034 case 'subjectpagename':
3035 $subjPage = $this->mTitle
->getSubjectPage();
3036 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3038 case 'subjectpagenamee':
3039 $subjPage = $this->mTitle
->getSubjectPage();
3040 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3042 case 'pageid': // requested in bug 23427
3043 $pageid = $this->getTitle()->getArticleID();
3044 if ( $pageid == 0 ) {
3045 # 0 means the page doesn't exist in the database,
3046 # which means the user is previewing a new page.
3047 # The vary-revision flag must be set, because the magic word
3048 # will have a different value once the page is saved.
3049 $this->mOutput
->setFlag( 'vary-revision' );
3050 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3052 $value = $pageid ?
$pageid : null;
3055 # Let the edit saving system know we should parse the page
3056 # *after* a revision ID has been assigned.
3057 $this->mOutput
->setFlag( 'vary-revision' );
3058 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3059 $value = $this->mRevisionId
;
3062 # Let the edit saving system know we should parse the page
3063 # *after* a revision ID has been assigned. This is for null edits.
3064 $this->mOutput
->setFlag( 'vary-revision' );
3065 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3066 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3068 case 'revisionday2':
3069 # Let the edit saving system know we should parse the page
3070 # *after* a revision ID has been assigned. This is for null edits.
3071 $this->mOutput
->setFlag( 'vary-revision' );
3072 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3073 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3075 case 'revisionmonth':
3076 # Let the edit saving system know we should parse the page
3077 # *after* a revision ID has been assigned. This is for null edits.
3078 $this->mOutput
->setFlag( 'vary-revision' );
3079 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3080 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3082 case 'revisionmonth1':
3083 # Let the edit saving system know we should parse the page
3084 # *after* a revision ID has been assigned. This is for null edits.
3085 $this->mOutput
->setFlag( 'vary-revision' );
3086 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3087 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3089 case 'revisionyear':
3090 # Let the edit saving system know we should parse the page
3091 # *after* a revision ID has been assigned. This is for null edits.
3092 $this->mOutput
->setFlag( 'vary-revision' );
3093 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3094 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3096 case 'revisiontimestamp':
3097 # Let the edit saving system know we should parse the page
3098 # *after* a revision ID has been assigned. This is for null edits.
3099 $this->mOutput
->setFlag( 'vary-revision' );
3100 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3101 $value = $this->getRevisionTimestamp();
3103 case 'revisionuser':
3104 # Let the edit saving system know we should parse the page
3105 # *after* a revision ID has been assigned. This is for null edits.
3106 $this->mOutput
->setFlag( 'vary-revision' );
3107 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3108 $value = $this->getRevisionUser();
3110 case 'revisionsize':
3111 # Let the edit saving system know we should parse the page
3112 # *after* a revision ID has been assigned. This is for null edits.
3113 $this->mOutput
->setFlag( 'vary-revision' );
3114 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3115 $value = $this->getRevisionSize();
3118 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3121 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3123 case 'namespacenumber':
3124 $value = $this->mTitle
->getNamespace();
3127 $value = $this->mTitle
->canTalk()
3128 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3132 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3134 case 'subjectspace':
3135 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3137 case 'subjectspacee':
3138 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3140 case 'currentdayname':
3141 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3144 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3147 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3150 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3153 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3154 # int to remove the padding
3155 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3158 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3160 case 'localdayname':
3161 $value = $pageLang->getWeekdayName(
3162 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3166 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3169 $value = $pageLang->time(
3170 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3176 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3179 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3180 # int to remove the padding
3181 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3184 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3186 case 'numberofarticles':
3187 $value = $pageLang->formatNum( SiteStats
::articles() );
3189 case 'numberoffiles':
3190 $value = $pageLang->formatNum( SiteStats
::images() );
3192 case 'numberofusers':
3193 $value = $pageLang->formatNum( SiteStats
::users() );
3195 case 'numberofactiveusers':
3196 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3198 case 'numberofpages':
3199 $value = $pageLang->formatNum( SiteStats
::pages() );
3201 case 'numberofadmins':
3202 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3204 case 'numberofedits':
3205 $value = $pageLang->formatNum( SiteStats
::edits() );
3207 case 'currenttimestamp':
3208 $value = wfTimestamp( TS_MW
, $ts );
3210 case 'localtimestamp':
3211 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3213 case 'currentversion':
3214 $value = SpecialVersion
::getVersion();
3217 return $wgArticlePath;
3223 return $wgServerName;
3225 return $wgScriptPath;
3227 return $wgStylePath;
3228 case 'directionmark':
3229 return $pageLang->getDirMark();
3230 case 'contentlanguage':
3231 global $wgLanguageCode;
3232 return $wgLanguageCode;
3233 case 'cascadingsources':
3234 $value = CoreParserFunctions
::cascadingsources( $this );
3239 'ParserGetVariableValueSwitch',
3240 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3247 $this->mVarCache
[$index] = $value;
3254 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3258 public function initialiseVariables() {
3259 $variableIDs = MagicWord
::getVariableIDs();
3260 $substIDs = MagicWord
::getSubstIDs();
3262 $this->mVariables
= new MagicWordArray( $variableIDs );
3263 $this->mSubstWords
= new MagicWordArray( $substIDs );
3267 * Preprocess some wikitext and return the document tree.
3268 * This is the ghost of replace_variables().
3270 * @param string $text The text to parse
3271 * @param int $flags Bitwise combination of:
3272 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3273 * included. Default is to assume a direct page view.
3275 * The generated DOM tree must depend only on the input text and the flags.
3276 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3278 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3279 * change in the DOM tree for a given text, must be passed through the section identifier
3280 * in the section edit link and thus back to extractSections().
3282 * The output of this function is currently only cached in process memory, but a persistent
3283 * cache may be implemented at a later date which takes further advantage of these strict
3284 * dependency requirements.
3288 public function preprocessToDom( $text, $flags = 0 ) {
3289 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3294 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3300 public static function splitWhitespace( $s ) {
3301 $ltrimmed = ltrim( $s );
3302 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3303 $trimmed = rtrim( $ltrimmed );
3304 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3306 $w2 = substr( $ltrimmed, -$diff );
3310 return array( $w1, $trimmed, $w2 );
3314 * Replace magic variables, templates, and template arguments
3315 * with the appropriate text. Templates are substituted recursively,
3316 * taking care to avoid infinite loops.
3318 * Note that the substitution depends on value of $mOutputType:
3319 * self::OT_WIKI: only {{subst:}} templates
3320 * self::OT_PREPROCESS: templates but not extension tags
3321 * self::OT_HTML: all templates and extension tags
3323 * @param string $text The text to transform
3324 * @param bool|PPFrame $frame Object describing the arguments passed to the
3325 * template. Arguments may also be provided as an associative array, as
3326 * was the usual case before MW1.12. Providing arguments this way may be
3327 * useful for extensions wishing to perform variable replacement
3329 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3330 * double-brace expansion.
3333 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3334 # Is there any text? Also, Prevent too big inclusions!
3335 $textSize = strlen( $text );
3336 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3340 if ( $frame === false ) {
3341 $frame = $this->getPreprocessor()->newFrame();
3342 } elseif ( !( $frame instanceof PPFrame
) ) {
3343 wfDebug( __METHOD__
. " called using plain parameters instead of "
3344 . "a PPFrame instance. Creating custom frame.\n" );
3345 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3348 $dom = $this->preprocessToDom( $text );
3349 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3350 $text = $frame->expand( $dom, $flags );
3356 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3358 * @param array $args
3362 public static function createAssocArgs( $args ) {
3363 $assocArgs = array();
3365 foreach ( $args as $arg ) {
3366 $eqpos = strpos( $arg, '=' );
3367 if ( $eqpos === false ) {
3368 $assocArgs[$index++
] = $arg;
3370 $name = trim( substr( $arg, 0, $eqpos ) );
3371 $value = trim( substr( $arg, $eqpos +
1 ) );
3372 if ( $value === false ) {
3375 if ( $name !== false ) {
3376 $assocArgs[$name] = $value;
3385 * Warn the user when a parser limitation is reached
3386 * Will warn at most once the user per limitation type
3388 * @param string $limitationType Should be one of:
3389 * 'expensive-parserfunction' (corresponding messages:
3390 * 'expensive-parserfunction-warning',
3391 * 'expensive-parserfunction-category')
3392 * 'post-expand-template-argument' (corresponding messages:
3393 * 'post-expand-template-argument-warning',
3394 * 'post-expand-template-argument-category')
3395 * 'post-expand-template-inclusion' (corresponding messages:
3396 * 'post-expand-template-inclusion-warning',
3397 * 'post-expand-template-inclusion-category')
3398 * 'node-count-exceeded' (corresponding messages:
3399 * 'node-count-exceeded-warning',
3400 * 'node-count-exceeded-category')
3401 * 'expansion-depth-exceeded' (corresponding messages:
3402 * 'expansion-depth-exceeded-warning',
3403 * 'expansion-depth-exceeded-category')
3404 * @param string|int|null $current Current value
3405 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3406 * exceeded, provide the values (optional)
3408 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3409 # does no harm if $current and $max are present but are unnecessary for the message
3410 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3411 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3412 $this->mOutput
->addWarning( $warning );
3413 $this->addTrackingCategory( "$limitationType-category" );
3417 * Return the text of a template, after recursively
3418 * replacing any variables or templates within the template.
3420 * @param array $piece The parts of the template
3421 * $piece['title']: the title, i.e. the part before the |
3422 * $piece['parts']: the parameter array
3423 * $piece['lineStart']: whether the brace was at the start of a line
3424 * @param PPFrame $frame The current frame, contains template arguments
3426 * @return string The text of the template
3428 public function braceSubstitution( $piece, $frame ) {
3432 // $text has been filled
3434 // wiki markup in $text should be escaped
3436 // $text is HTML, armour it against wikitext transformation
3438 // Force interwiki transclusion to be done in raw mode not rendered
3439 $forceRawInterwiki = false;
3440 // $text is a DOM node needing expansion in a child frame
3441 $isChildObj = false;
3442 // $text is a DOM node needing expansion in the current frame
3443 $isLocalObj = false;
3445 # Title object, where $text came from
3448 # $part1 is the bit before the first |, and must contain only title characters.
3449 # Various prefixes will be stripped from it later.
3450 $titleWithSpaces = $frame->expand( $piece['title'] );
3451 $part1 = trim( $titleWithSpaces );
3454 # Original title text preserved for various purposes
3455 $originalTitle = $part1;
3457 # $args is a list of argument nodes, starting from index 0, not including $part1
3458 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3459 # below won't work b/c this $args isn't an object
3460 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3462 $profileSection = null; // profile templates
3466 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3468 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3469 # Decide whether to expand template or keep wikitext as-is.
3470 if ( $this->ot
['wiki'] ) {
3471 if ( $substMatch === false ) {
3472 $literal = true; # literal when in PST with no prefix
3474 $literal = false; # expand when in PST with subst: or safesubst:
3477 if ( $substMatch == 'subst' ) {
3478 $literal = true; # literal when not in PST with plain subst:
3480 $literal = false; # expand when not in PST with safesubst: or no prefix
3484 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3491 if ( !$found && $args->getLength() == 0 ) {
3492 $id = $this->mVariables
->matchStartToEnd( $part1 );
3493 if ( $id !== false ) {
3494 $text = $this->getVariableValue( $id, $frame );
3495 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3496 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3502 # MSG, MSGNW and RAW
3505 $mwMsgnw = MagicWord
::get( 'msgnw' );
3506 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3509 # Remove obsolete MSG:
3510 $mwMsg = MagicWord
::get( 'msg' );
3511 $mwMsg->matchStartAndRemove( $part1 );
3515 $mwRaw = MagicWord
::get( 'raw' );
3516 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3517 $forceRawInterwiki = true;
3523 $colonPos = strpos( $part1, ':' );
3524 if ( $colonPos !== false ) {
3525 $func = substr( $part1, 0, $colonPos );
3526 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3527 for ( $i = 0; $i < $args->getLength(); $i++
) {
3528 $funcArgs[] = $args->item( $i );
3531 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3532 } catch ( Exception
$ex ) {
3536 # The interface for parser functions allows for extracting
3537 # flags into the local scope. Extract any forwarded flags
3543 # Finish mangling title and then check for loops.
3544 # Set $title to a Title object and $titleText to the PDBK
3547 # Split the title into page and subpage
3549 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3550 if ( $part1 !== $relative ) {
3552 $ns = $this->mTitle
->getNamespace();
3554 $title = Title
::newFromText( $part1, $ns );
3556 $titleText = $title->getPrefixedText();
3557 # Check for language variants if the template is not found
3558 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3559 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3561 # Do recursion depth check
3562 $limit = $this->mOptions
->getMaxTemplateDepth();
3563 if ( $frame->depth
>= $limit ) {
3565 $text = '<span class="error">'
3566 . wfMessage( 'parser-template-recursion-depth-warning' )
3567 ->numParams( $limit )->inContentLanguage()->text()
3573 # Load from database
3574 if ( !$found && $title ) {
3575 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3576 if ( !$title->isExternal() ) {
3577 if ( $title->isSpecialPage()
3578 && $this->mOptions
->getAllowSpecialInclusion()
3579 && $this->ot
['html']
3581 // Pass the template arguments as URL parameters.
3582 // "uselang" will have no effect since the Language object
3583 // is forced to the one defined in ParserOptions.
3584 $pageArgs = array();
3585 $argsLength = $args->getLength();
3586 for ( $i = 0; $i < $argsLength; $i++
) {
3587 $bits = $args->item( $i )->splitArg();
3588 if ( strval( $bits['index'] ) === '' ) {
3589 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3590 $value = trim( $frame->expand( $bits['value'] ) );
3591 $pageArgs[$name] = $value;
3595 // Create a new context to execute the special page
3596 $context = new RequestContext
;
3597 $context->setTitle( $title );
3598 $context->setRequest( new FauxRequest( $pageArgs ) );
3599 $context->setUser( $this->getUser() );
3600 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3601 $ret = SpecialPageFactory
::capturePath( $title, $context );
3603 $text = $context->getOutput()->getHTML();
3604 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3607 $this->disableCache();
3609 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3610 $found = false; # access denied
3611 wfDebug( __METHOD__
. ": template inclusion denied for " .
3612 $title->getPrefixedDBkey() . "\n" );
3614 list( $text, $title ) = $this->getTemplateDom( $title );
3615 if ( $text !== false ) {
3621 # If the title is valid but undisplayable, make a link to it
3622 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3623 $text = "[[:$titleText]]";
3626 } elseif ( $title->isTrans() ) {
3627 # Interwiki transclusion
3628 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3629 $text = $this->interwikiTransclude( $title, 'render' );
3632 $text = $this->interwikiTransclude( $title, 'raw' );
3633 # Preprocess it like a template
3634 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3640 # Do infinite loop check
3641 # This has to be done after redirect resolution to avoid infinite loops via redirects
3642 if ( !$frame->loopCheck( $title ) ) {
3644 $text = '<span class="error">'
3645 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3647 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3651 # If we haven't found text to substitute by now, we're done
3652 # Recover the source wikitext and return it
3654 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3655 if ( $profileSection ) {
3656 $this->mProfiler
->scopedProfileOut( $profileSection );
3658 return array( 'object' => $text );
3661 # Expand DOM-style return values in a child frame
3662 if ( $isChildObj ) {
3663 # Clean up argument array
3664 $newFrame = $frame->newChild( $args, $title );
3667 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3668 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3669 # Expansion is eligible for the empty-frame cache
3670 $text = $newFrame->cachedExpand( $titleText, $text );
3672 # Uncached expansion
3673 $text = $newFrame->expand( $text );
3676 if ( $isLocalObj && $nowiki ) {
3677 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3678 $isLocalObj = false;
3681 if ( $profileSection ) {
3682 $this->mProfiler
->scopedProfileOut( $profileSection );
3685 # Replace raw HTML by a placeholder
3687 $text = $this->insertStripItem( $text );
3688 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3689 # Escape nowiki-style return values
3690 $text = wfEscapeWikiText( $text );
3691 } elseif ( is_string( $text )
3692 && !$piece['lineStart']
3693 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3695 # Bug 529: if the template begins with a table or block-level
3696 # element, it should be treated as beginning a new line.
3697 # This behavior is somewhat controversial.
3698 $text = "\n" . $text;
3701 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3702 # Error, oversize inclusion
3703 if ( $titleText !== false ) {
3704 # Make a working, properly escaped link if possible (bug 23588)
3705 $text = "[[:$titleText]]";
3707 # This will probably not be a working link, but at least it may
3708 # provide some hint of where the problem is
3709 preg_replace( '/^:/', '', $originalTitle );
3710 $text = "[[:$originalTitle]]";
3712 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3713 . 'post-expand include size too large -->' );
3714 $this->limitationWarn( 'post-expand-template-inclusion' );
3717 if ( $isLocalObj ) {
3718 $ret = array( 'object' => $text );
3720 $ret = array( 'text' => $text );
3727 * Call a parser function and return an array with text and flags.
3729 * The returned array will always contain a boolean 'found', indicating
3730 * whether the parser function was found or not. It may also contain the
3732 * text: string|object, resulting wikitext or PP DOM object
3733 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3734 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3735 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3736 * nowiki: bool, wiki markup in $text should be escaped
3739 * @param PPFrame $frame The current frame, contains template arguments
3740 * @param string $function Function name
3741 * @param array $args Arguments to the function
3742 * @throws MWException
3745 public function callParserFunction( $frame, $function, array $args = array() ) {
3749 # Case sensitive functions
3750 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3751 $function = $this->mFunctionSynonyms
[1][$function];
3753 # Case insensitive functions
3754 $function = $wgContLang->lc( $function );
3755 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3756 $function = $this->mFunctionSynonyms
[0][$function];
3758 return array( 'found' => false );
3762 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3764 # Workaround for PHP bug 35229 and similar
3765 if ( !is_callable( $callback ) ) {
3766 throw new MWException( "Tag hook for $function is not callable\n" );
3769 $allArgs = array( &$this );
3770 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3771 # Convert arguments to PPNodes and collect for appending to $allArgs
3772 $funcArgs = array();
3773 foreach ( $args as $k => $v ) {
3774 if ( $v instanceof PPNode ||
$k === 0 ) {
3777 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3781 # Add a frame parameter, and pass the arguments as an array
3782 $allArgs[] = $frame;
3783 $allArgs[] = $funcArgs;
3785 # Convert arguments to plain text and append to $allArgs
3786 foreach ( $args as $k => $v ) {
3787 if ( $v instanceof PPNode
) {
3788 $allArgs[] = trim( $frame->expand( $v ) );
3789 } elseif ( is_int( $k ) && $k >= 0 ) {
3790 $allArgs[] = trim( $v );
3792 $allArgs[] = trim( "$k=$v" );
3797 $result = call_user_func_array( $callback, $allArgs );
3799 # The interface for function hooks allows them to return a wikitext
3800 # string or an array containing the string and any flags. This mungs
3801 # things around to match what this method should return.
3802 if ( !is_array( $result ) ) {
3808 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3809 $result['text'] = $result[0];
3811 unset( $result[0] );
3818 $preprocessFlags = 0;
3819 if ( isset( $result['noparse'] ) ) {
3820 $noparse = $result['noparse'];
3822 if ( isset( $result['preprocessFlags'] ) ) {
3823 $preprocessFlags = $result['preprocessFlags'];
3827 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3828 $result['isChildObj'] = true;
3835 * Get the semi-parsed DOM representation of a template with a given title,
3836 * and its redirect destination title. Cached.
3838 * @param Title $title
3842 public function getTemplateDom( $title ) {
3843 $cacheTitle = $title;
3844 $titleText = $title->getPrefixedDBkey();
3846 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3847 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3848 $title = Title
::makeTitle( $ns, $dbk );
3849 $titleText = $title->getPrefixedDBkey();
3851 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3852 return array( $this->mTplDomCache
[$titleText], $title );
3855 # Cache miss, go to the database
3856 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3858 if ( $text === false ) {
3859 $this->mTplDomCache
[$titleText] = false;
3860 return array( false, $title );
3863 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3864 $this->mTplDomCache
[$titleText] = $dom;
3866 if ( !$title->equals( $cacheTitle ) ) {
3867 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3868 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3871 return array( $dom, $title );
3875 * Fetch the current revision of a given title. Note that the revision
3876 * (and even the title) may not exist in the database, so everything
3877 * contributing to the output of the parser should use this method
3878 * where possible, rather than getting the revisions themselves. This
3879 * method also caches its results, so using it benefits performance.
3882 * @param Title $title
3885 public function fetchCurrentRevisionOfTitle( $title ) {
3886 $cacheKey = $title->getPrefixedDBkey();
3887 if ( !$this->currentRevisionCache
) {
3888 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3890 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3891 $this->currentRevisionCache
->set( $cacheKey,
3892 // Defaults to Parser::statelessFetchRevision()
3893 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3896 return $this->currentRevisionCache
->get( $cacheKey );
3900 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3901 * without passing them on to it.
3904 * @param Title $title
3905 * @param Parser|bool $parser
3908 public static function statelessFetchRevision( $title, $parser = false ) {
3909 return Revision
::newFromTitle( $title );
3913 * Fetch the unparsed text of a template and register a reference to it.
3914 * @param Title $title
3915 * @return array ( string or false, Title )
3917 public function fetchTemplateAndTitle( $title ) {
3918 // Defaults to Parser::statelessFetchTemplate()
3919 $templateCb = $this->mOptions
->getTemplateCallback();
3920 $stuff = call_user_func( $templateCb, $title, $this );
3921 // We use U+007F DELETE to distinguish strip markers from regular text.
3922 $text = $stuff['text'];
3923 if ( is_string( $stuff['text'] ) ) {
3924 $text = strtr( $text, "\x7f", "?" );
3926 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3927 if ( isset( $stuff['deps'] ) ) {
3928 foreach ( $stuff['deps'] as $dep ) {
3929 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3930 if ( $dep['title']->equals( $this->getTitle() ) ) {
3931 // If we transclude ourselves, the final result
3932 // will change based on the new version of the page
3933 $this->mOutput
->setFlag( 'vary-revision' );
3937 return array( $text, $finalTitle );
3941 * Fetch the unparsed text of a template and register a reference to it.
3942 * @param Title $title
3943 * @return string|bool
3945 public function fetchTemplate( $title ) {
3946 $rv = $this->fetchTemplateAndTitle( $title );
3951 * Static function to get a template
3952 * Can be overridden via ParserOptions::setTemplateCallback().
3954 * @param Title $title
3955 * @param bool|Parser $parser
3959 public static function statelessFetchTemplate( $title, $parser = false ) {
3960 $text = $skip = false;
3961 $finalTitle = $title;
3964 # Loop to fetch the article, with up to 1 redirect
3965 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3966 # Give extensions a chance to select the revision instead
3967 $id = false; # Assume current
3968 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3969 array( $parser, $title, &$skip, &$id ) );
3975 'page_id' => $title->getArticleID(),
3982 $rev = Revision
::newFromId( $id );
3983 } elseif ( $parser ) {
3984 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3986 $rev = Revision
::newFromTitle( $title );
3988 $rev_id = $rev ?
$rev->getId() : 0;
3989 # If there is no current revision, there is no page
3990 if ( $id === false && !$rev ) {
3991 $linkCache = LinkCache
::singleton();
3992 $linkCache->addBadLinkObj( $title );
3997 'page_id' => $title->getArticleID(),
3998 'rev_id' => $rev_id );
3999 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4000 # We fetched a rev from a different title; register it too...
4002 'title' => $rev->getTitle(),
4003 'page_id' => $rev->getPage(),
4004 'rev_id' => $rev_id );
4008 $content = $rev->getContent();
4009 $text = $content ?
$content->getWikitextForTransclusion() : null;
4011 if ( $text === false ||
$text === null ) {
4015 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4017 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4018 if ( !$message->exists() ) {
4022 $content = $message->content();
4023 $text = $message->plain();
4031 $finalTitle = $title;
4032 $title = $content->getRedirectTarget();
4036 'finalTitle' => $finalTitle,
4041 * Fetch a file and its title and register a reference to it.
4042 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4043 * @param Title $title
4044 * @param array $options Array of options to RepoGroup::findFile
4047 public function fetchFile( $title, $options = array() ) {
4048 $res = $this->fetchFileAndTitle( $title, $options );
4053 * Fetch a file and its title and register a reference to it.
4054 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4055 * @param Title $title
4056 * @param array $options Array of options to RepoGroup::findFile
4057 * @return array ( File or false, Title of file )
4059 public function fetchFileAndTitle( $title, $options = array() ) {
4060 $file = $this->fetchFileNoRegister( $title, $options );
4062 $time = $file ?
$file->getTimestamp() : false;
4063 $sha1 = $file ?
$file->getSha1() : false;
4064 # Register the file as a dependency...
4065 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4066 if ( $file && !$title->equals( $file->getTitle() ) ) {
4067 # Update fetched file title
4068 $title = $file->getTitle();
4069 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4071 return array( $file, $title );
4075 * Helper function for fetchFileAndTitle.
4077 * Also useful if you need to fetch a file but not use it yet,
4078 * for example to get the file's handler.
4080 * @param Title $title
4081 * @param array $options Array of options to RepoGroup::findFile
4084 protected function fetchFileNoRegister( $title, $options = array() ) {
4085 if ( isset( $options['broken'] ) ) {
4086 $file = false; // broken thumbnail forced by hook
4087 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4088 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4089 } else { // get by (name,timestamp)
4090 $file = wfFindFile( $title, $options );
4096 * Transclude an interwiki link.
4098 * @param Title $title
4099 * @param string $action
4103 public function interwikiTransclude( $title, $action ) {
4104 global $wgEnableScaryTranscluding;
4106 if ( !$wgEnableScaryTranscluding ) {
4107 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4110 $url = $title->getFullURL( array( 'action' => $action ) );
4112 if ( strlen( $url ) > 255 ) {
4113 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4115 return $this->fetchScaryTemplateMaybeFromCache( $url );
4119 * @param string $url
4120 * @return mixed|string
4122 public function fetchScaryTemplateMaybeFromCache( $url ) {
4123 global $wgTranscludeCacheExpiry;
4124 $dbr = wfGetDB( DB_SLAVE
);
4125 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4126 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4127 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4129 return $obj->tc_contents
;
4132 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4133 $status = $req->execute(); // Status object
4134 if ( $status->isOK() ) {
4135 $text = $req->getContent();
4136 } elseif ( $req->getStatus() != 200 ) {
4137 // Though we failed to fetch the content, this status is useless.
4138 return wfMessage( 'scarytranscludefailed-httpstatus' )
4139 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4141 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4144 $dbw = wfGetDB( DB_MASTER
);
4145 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4147 'tc_time' => $dbw->timestamp( time() ),
4148 'tc_contents' => $text
4154 * Triple brace replacement -- used for template arguments
4157 * @param array $piece
4158 * @param PPFrame $frame
4162 public function argSubstitution( $piece, $frame ) {
4165 $parts = $piece['parts'];
4166 $nameWithSpaces = $frame->expand( $piece['title'] );
4167 $argName = trim( $nameWithSpaces );
4169 $text = $frame->getArgument( $argName );
4170 if ( $text === false && $parts->getLength() > 0
4171 && ( $this->ot
['html']
4173 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4176 # No match in frame, use the supplied default
4177 $object = $parts->item( 0 )->getChildren();
4179 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4180 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4181 $this->limitationWarn( 'post-expand-template-argument' );
4184 if ( $text === false && $object === false ) {
4186 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4188 if ( $error !== false ) {
4191 if ( $object !== false ) {
4192 $ret = array( 'object' => $object );
4194 $ret = array( 'text' => $text );
4201 * Return the text to be used for a given extension tag.
4202 * This is the ghost of strip().
4204 * @param array $params Associative array of parameters:
4205 * name PPNode for the tag name
4206 * attr PPNode for unparsed text where tag attributes are thought to be
4207 * attributes Optional associative array of parsed attributes
4208 * inner Contents of extension element
4209 * noClose Original text did not have a close tag
4210 * @param PPFrame $frame
4212 * @throws MWException
4215 public function extensionSubstitution( $params, $frame ) {
4216 $name = $frame->expand( $params['name'] );
4217 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4218 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4219 $marker = self
::MARKER_PREFIX
. "-$name-"
4220 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4222 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4223 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4224 if ( $isFunctionTag ) {
4225 $markerType = 'none';
4227 $markerType = 'general';
4229 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4230 $name = strtolower( $name );
4231 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4232 if ( isset( $params['attributes'] ) ) {
4233 $attributes = $attributes +
$params['attributes'];
4236 if ( isset( $this->mTagHooks
[$name] ) ) {
4237 # Workaround for PHP bug 35229 and similar
4238 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4239 throw new MWException( "Tag hook for $name is not callable\n" );
4241 $output = call_user_func_array( $this->mTagHooks
[$name],
4242 array( $content, $attributes, $this, $frame ) );
4243 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4244 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4245 if ( !is_callable( $callback ) ) {
4246 throw new MWException( "Tag hook for $name is not callable\n" );
4249 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4251 $output = '<span class="error">Invalid tag extension name: ' .
4252 htmlspecialchars( $name ) . '</span>';
4255 if ( is_array( $output ) ) {
4256 # Extract flags to local scope (to override $markerType)
4258 $output = $flags[0];
4263 if ( is_null( $attrText ) ) {
4266 if ( isset( $params['attributes'] ) ) {
4267 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4268 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4269 htmlspecialchars( $attrValue ) . '"';
4272 if ( $content === null ) {
4273 $output = "<$name$attrText/>";
4275 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4276 $output = "<$name$attrText>$content$close";
4280 if ( $markerType === 'none' ) {
4282 } elseif ( $markerType === 'nowiki' ) {
4283 $this->mStripState
->addNoWiki( $marker, $output );
4284 } elseif ( $markerType === 'general' ) {
4285 $this->mStripState
->addGeneral( $marker, $output );
4287 throw new MWException( __METHOD__
. ': invalid marker type' );
4293 * Increment an include size counter
4295 * @param string $type The type of expansion
4296 * @param int $size The size of the text
4297 * @return bool False if this inclusion would take it over the maximum, true otherwise
4299 public function incrementIncludeSize( $type, $size ) {
4300 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4303 $this->mIncludeSizes
[$type] +
= $size;
4309 * Increment the expensive function count
4311 * @return bool False if the limit has been exceeded
4313 public function incrementExpensiveFunctionCount() {
4314 $this->mExpensiveFunctionCount++
;
4315 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4319 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4320 * Fills $this->mDoubleUnderscores, returns the modified text
4322 * @param string $text
4326 public function doDoubleUnderscore( $text ) {
4328 # The position of __TOC__ needs to be recorded
4329 $mw = MagicWord
::get( 'toc' );
4330 if ( $mw->match( $text ) ) {
4331 $this->mShowToc
= true;
4332 $this->mForceTocPosition
= true;
4334 # Set a placeholder. At the end we'll fill it in with the TOC.
4335 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4337 # Only keep the first one.
4338 $text = $mw->replace( '', $text );
4341 # Now match and remove the rest of them
4342 $mwa = MagicWord
::getDoubleUnderscoreArray();
4343 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4345 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4346 $this->mOutput
->mNoGallery
= true;
4348 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4349 $this->mShowToc
= false;
4351 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4352 && $this->mTitle
->getNamespace() == NS_CATEGORY
4354 $this->addTrackingCategory( 'hidden-category-category' );
4356 # (bug 8068) Allow control over whether robots index a page.
4358 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4359 # is not desirable, the last one on the page should win.
4360 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4361 $this->mOutput
->setIndexPolicy( 'noindex' );
4362 $this->addTrackingCategory( 'noindex-category' );
4364 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4365 $this->mOutput
->setIndexPolicy( 'index' );
4366 $this->addTrackingCategory( 'index-category' );
4369 # Cache all double underscores in the database
4370 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4371 $this->mOutput
->setProperty( $key, '' );
4378 * @see ParserOutput::addTrackingCategory()
4379 * @param string $msg Message key
4380 * @return bool Whether the addition was successful
4382 public function addTrackingCategory( $msg ) {
4383 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4387 * This function accomplishes several tasks:
4388 * 1) Auto-number headings if that option is enabled
4389 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4390 * 3) Add a Table of contents on the top for users who have enabled the option
4391 * 4) Auto-anchor headings
4393 * It loops through all headlines, collects the necessary data, then splits up the
4394 * string and re-inserts the newly formatted headlines.
4396 * @param string $text
4397 * @param string $origText Original, untouched wikitext
4398 * @param bool $isMain
4399 * @return mixed|string
4402 public function formatHeadings( $text, $origText, $isMain = true ) {
4403 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4405 # Inhibit editsection links if requested in the page
4406 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4407 $maybeShowEditLink = $showEditLink = false;
4409 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4410 $showEditLink = $this->mOptions
->getEditSection();
4412 if ( $showEditLink ) {
4413 $this->mOutput
->setEditSectionTokens( true );
4416 # Get all headlines for numbering them and adding funky stuff like [edit]
4417 # links - this is for later, but we need the number of headlines right now
4419 $numMatches = preg_match_all(
4420 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4425 # if there are fewer than 4 headlines in the article, do not show TOC
4426 # unless it's been explicitly enabled.
4427 $enoughToc = $this->mShowToc
&&
4428 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4430 # Allow user to stipulate that a page should have a "new section"
4431 # link added via __NEWSECTIONLINK__
4432 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4433 $this->mOutput
->setNewSection( true );
4436 # Allow user to remove the "new section"
4437 # link via __NONEWSECTIONLINK__
4438 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4439 $this->mOutput
->hideNewSection( true );
4442 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4443 # override above conditions and always show TOC above first header
4444 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4445 $this->mShowToc
= true;
4453 # Ugh .. the TOC should have neat indentation levels which can be
4454 # passed to the skin functions. These are determined here
4458 $sublevelCount = array();
4459 $levelCount = array();
4464 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4465 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4466 $oldType = $this->mOutputType
;
4467 $this->setOutputType( self
::OT_WIKI
);
4468 $frame = $this->getPreprocessor()->newFrame();
4469 $root = $this->preprocessToDom( $origText );
4470 $node = $root->getFirstChild();
4475 $headlines = $numMatches !== false ?
$matches[3] : array();
4477 foreach ( $headlines as $headline ) {
4478 $isTemplate = false;
4480 $sectionIndex = false;
4482 $markerMatches = array();
4483 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4484 $serial = $markerMatches[1];
4485 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4486 $isTemplate = ( $titleText != $baseTitleText );
4487 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4491 $prevlevel = $level;
4493 $level = $matches[1][$headlineCount];
4495 if ( $level > $prevlevel ) {
4496 # Increase TOC level
4498 $sublevelCount[$toclevel] = 0;
4499 if ( $toclevel < $wgMaxTocLevel ) {
4500 $prevtoclevel = $toclevel;
4501 $toc .= Linker
::tocIndent();
4504 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4505 # Decrease TOC level, find level to jump to
4507 for ( $i = $toclevel; $i > 0; $i-- ) {
4508 if ( $levelCount[$i] == $level ) {
4509 # Found last matching level
4512 } elseif ( $levelCount[$i] < $level ) {
4513 # Found first matching level below current level
4521 if ( $toclevel < $wgMaxTocLevel ) {
4522 if ( $prevtoclevel < $wgMaxTocLevel ) {
4523 # Unindent only if the previous toc level was shown :p
4524 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4525 $prevtoclevel = $toclevel;
4527 $toc .= Linker
::tocLineEnd();
4531 # No change in level, end TOC line
4532 if ( $toclevel < $wgMaxTocLevel ) {
4533 $toc .= Linker
::tocLineEnd();
4537 $levelCount[$toclevel] = $level;
4539 # count number of headlines for each level
4540 $sublevelCount[$toclevel]++
;
4542 for ( $i = 1; $i <= $toclevel; $i++
) {
4543 if ( !empty( $sublevelCount[$i] ) ) {
4547 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4552 # The safe header is a version of the header text safe to use for links
4554 # Remove link placeholders by the link text.
4555 # <!--LINK number-->
4557 # link text with suffix
4558 # Do this before unstrip since link text can contain strip markers
4559 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4561 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4562 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4564 # Strip out HTML (first regex removes any tag not allowed)
4566 # * <sup> and <sub> (bug 8393)
4569 # * <bdi> (bug 72884)
4570 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4572 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4573 # to allow setting directionality in toc items.
4574 $tocline = preg_replace(
4576 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4577 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4579 array( '', '<$1>' ),
4583 # Strip '<span></span>', which is the result from the above if
4584 # <span id="foo"></span> is used to produce an additional anchor
4586 $tocline = str_replace( '<span></span>', '', $tocline );
4588 $tocline = trim( $tocline );
4590 # For the anchor, strip out HTML-y stuff period
4591 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4592 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4594 # Save headline for section edit hint before it's escaped
4595 $headlineHint = $safeHeadline;
4597 if ( $wgExperimentalHtmlIds ) {
4598 # For reverse compatibility, provide an id that's
4599 # HTML4-compatible, like we used to.
4601 # It may be worth noting, academically, that it's possible for
4602 # the legacy anchor to conflict with a non-legacy headline
4603 # anchor on the page. In this case likely the "correct" thing
4604 # would be to either drop the legacy anchors or make sure
4605 # they're numbered first. However, this would require people
4606 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4607 # manually, so let's not bother worrying about it.
4608 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4609 array( 'noninitial', 'legacy' ) );
4610 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4612 if ( $legacyHeadline == $safeHeadline ) {
4613 # No reason to have both (in fact, we can't)
4614 $legacyHeadline = false;
4617 $legacyHeadline = false;
4618 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4622 # HTML names must be case-insensitively unique (bug 10721).
4623 # This does not apply to Unicode characters per
4624 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4625 # @todo FIXME: We may be changing them depending on the current locale.
4626 $arrayKey = strtolower( $safeHeadline );
4627 if ( $legacyHeadline === false ) {
4628 $legacyArrayKey = false;
4630 $legacyArrayKey = strtolower( $legacyHeadline );
4633 # Create the anchor for linking from the TOC to the section
4634 $anchor = $safeHeadline;
4635 $legacyAnchor = $legacyHeadline;
4636 if ( isset( $refers[$arrayKey] ) ) {
4637 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4639 $refers["${arrayKey}_$i"] = true;
4641 $refers[$arrayKey] = true;
4643 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4644 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4645 $legacyAnchor .= "_$i";
4646 $refers["${legacyArrayKey}_$i"] = true;
4648 $refers[$legacyArrayKey] = true;
4651 # Don't number the heading if it is the only one (looks silly)
4652 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4653 # the two are different if the line contains a link
4654 $headline = Html
::element(
4656 array( 'class' => 'mw-headline-number' ),
4658 ) . ' ' . $headline;
4661 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4662 $toc .= Linker
::tocLine( $anchor, $tocline,
4663 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4666 # Add the section to the section tree
4667 # Find the DOM node for this header
4668 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4669 while ( $node && !$noOffset ) {
4670 if ( $node->getName() === 'h' ) {
4671 $bits = $node->splitHeading();
4672 if ( $bits['i'] == $sectionIndex ) {
4676 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4677 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4678 $node = $node->getNextSibling();
4681 'toclevel' => $toclevel,
4684 'number' => $numbering,
4685 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4686 'fromtitle' => $titleText,
4687 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4688 'anchor' => $anchor,
4691 # give headline the correct <h#> tag
4692 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4693 // Output edit section links as markers with styles that can be customized by skins
4694 if ( $isTemplate ) {
4695 # Put a T flag in the section identifier, to indicate to extractSections()
4696 # that sections inside <includeonly> should be counted.
4697 $editsectionPage = $titleText;
4698 $editsectionSection = "T-$sectionIndex";
4699 $editsectionContent = null;
4701 $editsectionPage = $this->mTitle
->getPrefixedText();
4702 $editsectionSection = $sectionIndex;
4703 $editsectionContent = $headlineHint;
4705 // We use a bit of pesudo-xml for editsection markers. The
4706 // language converter is run later on. Using a UNIQ style marker
4707 // leads to the converter screwing up the tokens when it
4708 // converts stuff. And trying to insert strip tags fails too. At
4709 // this point all real inputted tags have already been escaped,
4710 // so we don't have to worry about a user trying to input one of
4711 // these markers directly. We use a page and section attribute
4712 // to stop the language converter from converting these
4713 // important bits of data, but put the headline hint inside a
4714 // content block because the language converter is supposed to
4715 // be able to convert that piece of data.
4716 // Gets replaced with html in ParserOutput::getText
4717 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4718 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4719 if ( $editsectionContent !== null ) {
4720 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4727 $head[$headlineCount] = Linker
::makeHeadline( $level,
4728 $matches['attrib'][$headlineCount], $anchor, $headline,
4729 $editlink, $legacyAnchor );
4734 $this->setOutputType( $oldType );
4736 # Never ever show TOC if no headers
4737 if ( $numVisible < 1 ) {
4742 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4743 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4745 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4746 $this->mOutput
->setTOCHTML( $toc );
4747 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4748 $this->mOutput
->addModules( 'mediawiki.toc' );
4752 $this->mOutput
->setSections( $tocraw );
4755 # split up and insert constructed headlines
4756 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4759 // build an array of document sections
4760 $sections = array();
4761 foreach ( $blocks as $block ) {
4762 // $head is zero-based, sections aren't.
4763 if ( empty( $head[$i - 1] ) ) {
4764 $sections[$i] = $block;
4766 $sections[$i] = $head[$i - 1] . $block;
4770 * Send a hook, one per section.
4771 * The idea here is to be able to make section-level DIVs, but to do so in a
4772 * lower-impact, more correct way than r50769
4775 * $section : the section number
4776 * &$sectionContent : ref to the content of the section
4777 * $showEditLinks : boolean describing whether this section has an edit link
4779 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4784 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4785 // append the TOC at the beginning
4786 // Top anchor now in skin
4787 $sections[0] = $sections[0] . $toc . "\n";
4790 $full .= join( '', $sections );
4792 if ( $this->mForceTocPosition
) {
4793 return str_replace( '<!--MWTOC-->', $toc, $full );
4800 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4801 * conversion, substituting signatures, {{subst:}} templates, etc.
4803 * @param string $text The text to transform
4804 * @param Title $title The Title object for the current article
4805 * @param User $user The User object describing the current user
4806 * @param ParserOptions $options Parsing options
4807 * @param bool $clearState Whether to clear the parser state first
4808 * @return string The altered wiki markup
4810 public function preSaveTransform( $text, Title
$title, User
$user,
4811 ParserOptions
$options, $clearState = true
4813 if ( $clearState ) {
4814 $magicScopeVariable = $this->lock();
4816 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4817 $this->setUser( $user );
4823 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4824 if ( $options->getPreSaveTransform() ) {
4825 $text = $this->pstPass2( $text, $user );
4827 $text = $this->mStripState
->unstripBoth( $text );
4829 $this->setUser( null ); #Reset
4835 * Pre-save transform helper function
4837 * @param string $text
4842 private function pstPass2( $text, $user ) {
4845 # Note: This is the timestamp saved as hardcoded wikitext to
4846 # the database, we use $wgContLang here in order to give
4847 # everyone the same signature and use the default one rather
4848 # than the one selected in each user's preferences.
4849 # (see also bug 12815)
4850 $ts = $this->mOptions
->getTimestamp();
4851 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4852 $ts = $timestamp->format( 'YmdHis' );
4853 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4855 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4857 # Variable replacement
4858 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4859 $text = $this->replaceVariables( $text );
4861 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4862 # which may corrupt this parser instance via its wfMessage()->text() call-
4865 $sigText = $this->getUserSig( $user );
4866 $text = strtr( $text, array(
4868 '~~~~' => "$sigText $d",
4872 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4873 $tc = '[' . Title
::legalChars() . ']';
4874 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4876 // [[ns:page (context)|]]
4877 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4878 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4879 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4880 // [[ns:page (context), context|]] (using either single or double-width comma)
4881 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4882 // [[|page]] (reverse pipe trick: add context from page title)
4883 $p2 = "/\[\[\\|($tc+)]]/";
4885 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4886 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4887 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4888 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4890 $t = $this->mTitle
->getText();
4892 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4893 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4894 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4895 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4897 # if there's no context, don't bother duplicating the title
4898 $text = preg_replace( $p2, '[[\\1]]', $text );
4901 # Trim trailing whitespace
4902 $text = rtrim( $text );
4908 * Fetch the user's signature text, if any, and normalize to
4909 * validated, ready-to-insert wikitext.
4910 * If you have pre-fetched the nickname or the fancySig option, you can
4911 * specify them here to save a database query.
4912 * Do not reuse this parser instance after calling getUserSig(),
4913 * as it may have changed if it's the $wgParser.
4916 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4917 * @param bool|null $fancySig whether the nicknname is the complete signature
4918 * or null to use default value
4921 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4922 global $wgMaxSigChars;
4924 $username = $user->getName();
4926 # If not given, retrieve from the user object.
4927 if ( $nickname === false ) {
4928 $nickname = $user->getOption( 'nickname' );
4931 if ( is_null( $fancySig ) ) {
4932 $fancySig = $user->getBoolOption( 'fancysig' );
4935 $nickname = $nickname == null ?
$username : $nickname;
4937 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4938 $nickname = $username;
4939 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4940 } elseif ( $fancySig !== false ) {
4941 # Sig. might contain markup; validate this
4942 if ( $this->validateSig( $nickname ) !== false ) {
4943 # Validated; clean up (if needed) and return it
4944 return $this->cleanSig( $nickname, true );
4946 # Failed to validate; fall back to the default
4947 $nickname = $username;
4948 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4952 # Make sure nickname doesnt get a sig in a sig
4953 $nickname = self
::cleanSigInSig( $nickname );
4955 # If we're still here, make it a link to the user page
4956 $userText = wfEscapeWikiText( $username );
4957 $nickText = wfEscapeWikiText( $nickname );
4958 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4960 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4961 ->title( $this->getTitle() )->text();
4965 * Check that the user's signature contains no bad XML
4967 * @param string $text
4968 * @return string|bool An expanded string, or false if invalid.
4970 public function validateSig( $text ) {
4971 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4975 * Clean up signature text
4977 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4978 * 2) Substitute all transclusions
4980 * @param string $text
4981 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4982 * @return string Signature text
4984 public function cleanSig( $text, $parsing = false ) {
4987 $magicScopeVariable = $this->lock();
4988 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4991 # Option to disable this feature
4992 if ( !$this->mOptions
->getCleanSignatures() ) {
4996 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4997 # => Move this logic to braceSubstitution()
4998 $substWord = MagicWord
::get( 'subst' );
4999 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5000 $substText = '{{' . $substWord->getSynonym( 0 );
5002 $text = preg_replace( $substRegex, $substText, $text );
5003 $text = self
::cleanSigInSig( $text );
5004 $dom = $this->preprocessToDom( $text );
5005 $frame = $this->getPreprocessor()->newFrame();
5006 $text = $frame->expand( $dom );
5009 $text = $this->mStripState
->unstripBoth( $text );
5016 * Strip 3, 4 or 5 tildes out of signatures.
5018 * @param string $text
5019 * @return string Signature text with /~{3,5}/ removed
5021 public static function cleanSigInSig( $text ) {
5022 $text = preg_replace( '/~{3,5}/', '', $text );
5027 * Set up some variables which are usually set up in parse()
5028 * so that an external function can call some class members with confidence
5030 * @param Title|null $title
5031 * @param ParserOptions $options
5032 * @param int $outputType
5033 * @param bool $clearState
5035 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5036 $outputType, $clearState = true
5038 $this->startParse( $title, $options, $outputType, $clearState );
5042 * @param Title|null $title
5043 * @param ParserOptions $options
5044 * @param int $outputType
5045 * @param bool $clearState
5047 private function startParse( Title
$title = null, ParserOptions
$options,
5048 $outputType, $clearState = true
5050 $this->setTitle( $title );
5051 $this->mOptions
= $options;
5052 $this->setOutputType( $outputType );
5053 if ( $clearState ) {
5054 $this->clearState();
5059 * Wrapper for preprocess()
5061 * @param string $text The text to preprocess
5062 * @param ParserOptions $options Options
5063 * @param Title|null $title Title object or null to use $wgTitle
5066 public function transformMsg( $text, $options, $title = null ) {
5067 static $executing = false;
5069 # Guard against infinite recursion
5080 $text = $this->preprocess( $text, $title, $options );
5087 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5088 * The callback should have the following form:
5089 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5091 * Transform and return $text. Use $parser for any required context, e.g. use
5092 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5094 * Hooks may return extended information by returning an array, of which the
5095 * first numbered element (index 0) must be the return string, and all other
5096 * entries are extracted into local variables within an internal function
5097 * in the Parser class.
5099 * This interface (introduced r61913) appears to be undocumented, but
5100 * 'markerType' is used by some core tag hooks to override which strip
5101 * array their results are placed in. **Use great caution if attempting
5102 * this interface, as it is not documented and injudicious use could smash
5103 * private variables.**
5105 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5106 * @param callable $callback The callback function (and object) to use for the tag
5107 * @throws MWException
5108 * @return callable|null The old value of the mTagHooks array associated with the hook
5110 public function setHook( $tag, $callback ) {
5111 $tag = strtolower( $tag );
5112 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5113 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5115 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5116 $this->mTagHooks
[$tag] = $callback;
5117 if ( !in_array( $tag, $this->mStripList
) ) {
5118 $this->mStripList
[] = $tag;
5125 * As setHook(), but letting the contents be parsed.
5127 * Transparent tag hooks are like regular XML-style tag hooks, except they
5128 * operate late in the transformation sequence, on HTML instead of wikitext.
5130 * This is probably obsoleted by things dealing with parser frames?
5131 * The only extension currently using it is geoserver.
5134 * @todo better document or deprecate this
5136 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5137 * @param callable $callback The callback function (and object) to use for the tag
5138 * @throws MWException
5139 * @return callable|null The old value of the mTagHooks array associated with the hook
5141 public function setTransparentTagHook( $tag, $callback ) {
5142 $tag = strtolower( $tag );
5143 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5144 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5146 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5147 $this->mTransparentTagHooks
[$tag] = $callback;
5153 * Remove all tag hooks
5155 public function clearTagHooks() {
5156 $this->mTagHooks
= array();
5157 $this->mFunctionTagHooks
= array();
5158 $this->mStripList
= $this->mDefaultStripList
;
5162 * Create a function, e.g. {{sum:1|2|3}}
5163 * The callback function should have the form:
5164 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5166 * Or with Parser::SFH_OBJECT_ARGS:
5167 * function myParserFunction( $parser, $frame, $args ) { ... }
5169 * The callback may either return the text result of the function, or an array with the text
5170 * in element 0, and a number of flags in the other elements. The names of the flags are
5171 * specified in the keys. Valid flags are:
5172 * found The text returned is valid, stop processing the template. This
5174 * nowiki Wiki markup in the return value should be escaped
5175 * isHTML The returned text is HTML, armour it against wikitext transformation
5177 * @param string $id The magic word ID
5178 * @param callable $callback The callback function (and object) to use
5179 * @param int $flags A combination of the following flags:
5180 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5182 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5183 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5184 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5185 * the arguments, and to control the way they are expanded.
5187 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5188 * arguments, for instance:
5189 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5191 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5192 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5193 * working if/when this is changed.
5195 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5198 * Please read the documentation in includes/parser/Preprocessor.php for more information
5199 * about the methods available in PPFrame and PPNode.
5201 * @throws MWException
5202 * @return string|callable The old callback function for this name, if any
5204 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5207 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5208 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5210 # Add to function cache
5211 $mw = MagicWord
::get( $id );
5213 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5216 $synonyms = $mw->getSynonyms();
5217 $sensitive = intval( $mw->isCaseSensitive() );
5219 foreach ( $synonyms as $syn ) {
5221 if ( !$sensitive ) {
5222 $syn = $wgContLang->lc( $syn );
5225 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5228 # Remove trailing colon
5229 if ( substr( $syn, -1, 1 ) === ':' ) {
5230 $syn = substr( $syn, 0, -1 );
5232 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5238 * Get all registered function hook identifiers
5242 public function getFunctionHooks() {
5243 return array_keys( $this->mFunctionHooks
);
5247 * Create a tag function, e.g. "<test>some stuff</test>".
5248 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5249 * Unlike parser functions, their content is not preprocessed.
5250 * @param string $tag
5251 * @param callable $callback
5253 * @throws MWException
5256 public function setFunctionTagHook( $tag, $callback, $flags ) {
5257 $tag = strtolower( $tag );
5258 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5259 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5261 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5262 $this->mFunctionTagHooks
[$tag] : null;
5263 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5265 if ( !in_array( $tag, $this->mStripList
) ) {
5266 $this->mStripList
[] = $tag;
5273 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5274 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5275 * Placeholders created in Skin::makeLinkObj()
5277 * @param string $text
5278 * @param int $options
5280 public function replaceLinkHolders( &$text, $options = 0 ) {
5281 $this->mLinkHolders
->replace( $text );
5285 * Replace "<!--LINK-->" link placeholders with plain text of links
5286 * (not HTML-formatted).
5288 * @param string $text
5291 public function replaceLinkHoldersText( $text ) {
5292 return $this->mLinkHolders
->replaceText( $text );
5296 * Renders an image gallery from a text with one line per image.
5297 * text labels may be given by using |-style alternative text. E.g.
5298 * Image:one.jpg|The number "1"
5299 * Image:tree.jpg|A tree
5300 * given as text will return the HTML of a gallery with two images,
5301 * labeled 'The number "1"' and
5304 * @param string $text
5305 * @param array $params
5306 * @return string HTML
5308 public function renderImageGallery( $text, $params ) {
5311 if ( isset( $params['mode'] ) ) {
5312 $mode = $params['mode'];
5316 $ig = ImageGalleryBase
::factory( $mode );
5317 } catch ( Exception
$e ) {
5318 // If invalid type set, fallback to default.
5319 $ig = ImageGalleryBase
::factory( false );
5322 $ig->setContextTitle( $this->mTitle
);
5323 $ig->setShowBytes( false );
5324 $ig->setShowFilename( false );
5325 $ig->setParser( $this );
5326 $ig->setHideBadImages();
5327 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5329 if ( isset( $params['showfilename'] ) ) {
5330 $ig->setShowFilename( true );
5332 $ig->setShowFilename( false );
5334 if ( isset( $params['caption'] ) ) {
5335 $caption = $params['caption'];
5336 $caption = htmlspecialchars( $caption );
5337 $caption = $this->replaceInternalLinks( $caption );
5338 $ig->setCaptionHtml( $caption );
5340 if ( isset( $params['perrow'] ) ) {
5341 $ig->setPerRow( $params['perrow'] );
5343 if ( isset( $params['widths'] ) ) {
5344 $ig->setWidths( $params['widths'] );
5346 if ( isset( $params['heights'] ) ) {
5347 $ig->setHeights( $params['heights'] );
5349 $ig->setAdditionalOptions( $params );
5351 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5353 $lines = StringUtils
::explode( "\n", $text );
5354 foreach ( $lines as $line ) {
5355 # match lines like these:
5356 # Image:someimage.jpg|This is some image
5358 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5360 if ( count( $matches ) == 0 ) {
5364 if ( strpos( $matches[0], '%' ) !== false ) {
5365 $matches[1] = rawurldecode( $matches[1] );
5367 $title = Title
::newFromText( $matches[1], NS_FILE
);
5368 if ( is_null( $title ) ) {
5369 # Bogus title. Ignore these so we don't bomb out later.
5373 # We need to get what handler the file uses, to figure out parameters.
5374 # Note, a hook can overide the file name, and chose an entirely different
5375 # file (which potentially could be of a different type and have different handler).
5378 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5379 array( $this, $title, &$options, &$descQuery ) );
5380 # Don't register it now, as ImageGallery does that later.
5381 $file = $this->fetchFileNoRegister( $title, $options );
5382 $handler = $file ?
$file->getHandler() : false;
5385 'img_alt' => 'gallery-internal-alt',
5386 'img_link' => 'gallery-internal-link',
5389 $paramMap = $paramMap +
$handler->getParamMap();
5390 // We don't want people to specify per-image widths.
5391 // Additionally the width parameter would need special casing anyhow.
5392 unset( $paramMap['img_width'] );
5395 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5400 $handlerOptions = array();
5401 if ( isset( $matches[3] ) ) {
5402 // look for an |alt= definition while trying not to break existing
5403 // captions with multiple pipes (|) in it, until a more sensible grammar
5404 // is defined for images in galleries
5406 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5407 // splitting on '|' is a bit odd, and different from makeImage.
5408 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5409 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5411 foreach ( $parameterMatches as $parameterMatch ) {
5412 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5414 $paramName = $paramMap[$magicName];
5416 switch ( $paramName ) {
5417 case 'gallery-internal-alt':
5418 $alt = $this->stripAltText( $match, false );
5420 case 'gallery-internal-link':
5421 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5422 $chars = self
::EXT_LINK_URL_CLASS
;
5423 $addr = self
::EXT_LINK_ADDR
;
5424 $prots = $this->mUrlProtocols
;
5425 //check to see if link matches an absolute url, if not then it must be a wiki link.
5426 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5429 $localLinkTitle = Title
::newFromText( $linkValue );
5430 if ( $localLinkTitle !== null ) {
5431 $link = $localLinkTitle->getLinkURL();
5436 // Must be a handler specific parameter.
5437 if ( $handler->validateParam( $paramName, $match ) ) {
5438 $handlerOptions[$paramName] = $match;
5440 // Guess not. Append it to the caption.
5441 wfDebug( "$parameterMatch failed parameter validation\n" );
5442 $label .= '|' . $parameterMatch;
5447 // concatenate all other pipes
5448 $label .= '|' . $parameterMatch;
5451 // remove the first pipe
5452 $label = substr( $label, 1 );
5455 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5457 $html = $ig->toHTML();
5458 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5463 * @param MediaHandler $handler
5466 public function getImageParams( $handler ) {
5468 $handlerClass = get_class( $handler );
5472 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5473 # Initialise static lists
5474 static $internalParamNames = array(
5475 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5476 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5477 'bottom', 'text-bottom' ),
5478 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5479 'upright', 'border', 'link', 'alt', 'class' ),
5481 static $internalParamMap;
5482 if ( !$internalParamMap ) {
5483 $internalParamMap = array();
5484 foreach ( $internalParamNames as $type => $names ) {
5485 foreach ( $names as $name ) {
5486 $magicName = str_replace( '-', '_', "img_$name" );
5487 $internalParamMap[$magicName] = array( $type, $name );
5492 # Add handler params
5493 $paramMap = $internalParamMap;
5495 $handlerParamMap = $handler->getParamMap();
5496 foreach ( $handlerParamMap as $magic => $paramName ) {
5497 $paramMap[$magic] = array( 'handler', $paramName );
5500 $this->mImageParams
[$handlerClass] = $paramMap;
5501 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5503 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5507 * Parse image options text and use it to make an image
5509 * @param Title $title
5510 * @param string $options
5511 * @param LinkHolderArray|bool $holders
5512 * @return string HTML
5514 public function makeImage( $title, $options, $holders = false ) {
5515 # Check if the options text is of the form "options|alt text"
5517 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5518 # * left no resizing, just left align. label is used for alt= only
5519 # * right same, but right aligned
5520 # * none same, but not aligned
5521 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5522 # * center center the image
5523 # * frame Keep original image size, no magnify-button.
5524 # * framed Same as "frame"
5525 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5526 # * upright reduce width for upright images, rounded to full __0 px
5527 # * border draw a 1px border around the image
5528 # * alt Text for HTML alt attribute (defaults to empty)
5529 # * class Set a class for img node
5530 # * link Set the target of the image link. Can be external, interwiki, or local
5531 # vertical-align values (no % or length right now):
5541 $parts = StringUtils
::explode( "|", $options );
5543 # Give extensions a chance to select the file revision for us
5546 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5547 array( $this, $title, &$options, &$descQuery ) );
5548 # Fetch and register the file (file title may be different via hooks)
5549 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5552 $handler = $file ?
$file->getHandler() : false;
5554 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5557 $this->addTrackingCategory( 'broken-file-category' );
5560 # Process the input parameters
5562 $params = array( 'frame' => array(), 'handler' => array(),
5563 'horizAlign' => array(), 'vertAlign' => array() );
5564 $seenformat = false;
5565 foreach ( $parts as $part ) {
5566 $part = trim( $part );
5567 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5569 if ( isset( $paramMap[$magicName] ) ) {
5570 list( $type, $paramName ) = $paramMap[$magicName];
5572 # Special case; width and height come in one variable together
5573 if ( $type === 'handler' && $paramName === 'width' ) {
5574 $parsedWidthParam = $this->parseWidthParam( $value );
5575 if ( isset( $parsedWidthParam['width'] ) ) {
5576 $width = $parsedWidthParam['width'];
5577 if ( $handler->validateParam( 'width', $width ) ) {
5578 $params[$type]['width'] = $width;
5582 if ( isset( $parsedWidthParam['height'] ) ) {
5583 $height = $parsedWidthParam['height'];
5584 if ( $handler->validateParam( 'height', $height ) ) {
5585 $params[$type]['height'] = $height;
5589 # else no validation -- bug 13436
5591 if ( $type === 'handler' ) {
5592 # Validate handler parameter
5593 $validated = $handler->validateParam( $paramName, $value );
5595 # Validate internal parameters
5596 switch ( $paramName ) {
5600 # @todo FIXME: Possibly check validity here for
5601 # manualthumb? downstream behavior seems odd with
5602 # missing manual thumbs.
5604 $value = $this->stripAltText( $value, $holders );
5607 $chars = self
::EXT_LINK_URL_CLASS
;
5608 $addr = self
::EXT_LINK_ADDR
;
5609 $prots = $this->mUrlProtocols
;
5610 if ( $value === '' ) {
5611 $paramName = 'no-link';
5614 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5615 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5616 $paramName = 'link-url';
5617 $this->mOutput
->addExternalLink( $value );
5618 if ( $this->mOptions
->getExternalLinkTarget() ) {
5619 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5624 $linkTitle = Title
::newFromText( $value );
5626 $paramName = 'link-title';
5627 $value = $linkTitle;
5628 $this->mOutput
->addLink( $linkTitle );
5636 // use first appearing option, discard others.
5637 $validated = ! $seenformat;
5641 # Most other things appear to be empty or numeric...
5642 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5647 $params[$type][$paramName] = $value;
5651 if ( !$validated ) {
5656 # Process alignment parameters
5657 if ( $params['horizAlign'] ) {
5658 $params['frame']['align'] = key( $params['horizAlign'] );
5660 if ( $params['vertAlign'] ) {
5661 $params['frame']['valign'] = key( $params['vertAlign'] );
5664 $params['frame']['caption'] = $caption;
5666 # Will the image be presented in a frame, with the caption below?
5667 $imageIsFramed = isset( $params['frame']['frame'] )
5668 ||
isset( $params['frame']['framed'] )
5669 ||
isset( $params['frame']['thumbnail'] )
5670 ||
isset( $params['frame']['manualthumb'] );
5672 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5673 # came to also set the caption, ordinary text after the image -- which
5674 # makes no sense, because that just repeats the text multiple times in
5675 # screen readers. It *also* came to set the title attribute.
5677 # Now that we have an alt attribute, we should not set the alt text to
5678 # equal the caption: that's worse than useless, it just repeats the
5679 # text. This is the framed/thumbnail case. If there's no caption, we
5680 # use the unnamed parameter for alt text as well, just for the time be-
5681 # ing, if the unnamed param is set and the alt param is not.
5683 # For the future, we need to figure out if we want to tweak this more,
5684 # e.g., introducing a title= parameter for the title; ignoring the un-
5685 # named parameter entirely for images without a caption; adding an ex-
5686 # plicit caption= parameter and preserving the old magic unnamed para-
5688 if ( $imageIsFramed ) { # Framed image
5689 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5690 # No caption or alt text, add the filename as the alt text so
5691 # that screen readers at least get some description of the image
5692 $params['frame']['alt'] = $title->getText();
5694 # Do not set $params['frame']['title'] because tooltips don't make sense
5696 } else { # Inline image
5697 if ( !isset( $params['frame']['alt'] ) ) {
5698 # No alt text, use the "caption" for the alt text
5699 if ( $caption !== '' ) {
5700 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5702 # No caption, fall back to using the filename for the
5704 $params['frame']['alt'] = $title->getText();
5707 # Use the "caption" for the tooltip text
5708 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5711 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5713 # Linker does the rest
5714 $time = isset( $options['time'] ) ?
$options['time'] : false;
5715 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5716 $time, $descQuery, $this->mOptions
->getThumbSize() );
5718 # Give the handler a chance to modify the parser object
5720 $handler->parserTransformHook( $this, $file );
5727 * @param string $caption
5728 * @param LinkHolderArray|bool $holders
5729 * @return mixed|string
5731 protected function stripAltText( $caption, $holders ) {
5732 # Strip bad stuff out of the title (tooltip). We can't just use
5733 # replaceLinkHoldersText() here, because if this function is called
5734 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5736 $tooltip = $holders->replaceText( $caption );
5738 $tooltip = $this->replaceLinkHoldersText( $caption );
5741 # make sure there are no placeholders in thumbnail attributes
5742 # that are later expanded to html- so expand them now and
5744 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5745 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5751 * Set a flag in the output object indicating that the content is dynamic and
5752 * shouldn't be cached.
5754 public function disableCache() {
5755 wfDebug( "Parser output marked as uncacheable.\n" );
5756 if ( !$this->mOutput
) {
5757 throw new MWException( __METHOD__
.
5758 " can only be called when actually parsing something" );
5760 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5761 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5765 * Callback from the Sanitizer for expanding items found in HTML attribute
5766 * values, so they can be safely tested and escaped.
5768 * @param string $text
5769 * @param bool|PPFrame $frame
5772 public function attributeStripCallback( &$text, $frame = false ) {
5773 $text = $this->replaceVariables( $text, $frame );
5774 $text = $this->mStripState
->unstripBoth( $text );
5783 public function getTags() {
5785 array_keys( $this->mTransparentTagHooks
),
5786 array_keys( $this->mTagHooks
),
5787 array_keys( $this->mFunctionTagHooks
)
5792 * Replace transparent tags in $text with the values given by the callbacks.
5794 * Transparent tag hooks are like regular XML-style tag hooks, except they
5795 * operate late in the transformation sequence, on HTML instead of wikitext.
5797 * @param string $text
5801 public function replaceTransparentTags( $text ) {
5803 $elements = array_keys( $this->mTransparentTagHooks
);
5804 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5805 $replacements = array();
5807 foreach ( $matches as $marker => $data ) {
5808 list( $element, $content, $params, $tag ) = $data;
5809 $tagName = strtolower( $element );
5810 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5811 $output = call_user_func_array(
5812 $this->mTransparentTagHooks
[$tagName],
5813 array( $content, $params, $this )
5818 $replacements[$marker] = $output;
5820 return strtr( $text, $replacements );
5824 * Break wikitext input into sections, and either pull or replace
5825 * some particular section's text.
5827 * External callers should use the getSection and replaceSection methods.
5829 * @param string $text Page wikitext
5830 * @param string|number $sectionId A section identifier string of the form:
5831 * "<flag1> - <flag2> - ... - <section number>"
5833 * Currently the only recognised flag is "T", which means the target section number
5834 * was derived during a template inclusion parse, in other words this is a template
5835 * section edit link. If no flags are given, it was an ordinary section edit link.
5836 * This flag is required to avoid a section numbering mismatch when a section is
5837 * enclosed by "<includeonly>" (bug 6563).
5839 * The section number 0 pulls the text before the first heading; other numbers will
5840 * pull the given section along with its lower-level subsections. If the section is
5841 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5843 * Section 0 is always considered to exist, even if it only contains the empty
5844 * string. If $text is the empty string and section 0 is replaced, $newText is
5847 * @param string $mode One of "get" or "replace"
5848 * @param string $newText Replacement text for section data.
5849 * @return string For "get", the extracted section text.
5850 * for "replace", the whole page with the section replaced.
5852 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5853 global $wgTitle; # not generally used but removes an ugly failure mode
5855 $magicScopeVariable = $this->lock();
5856 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5858 $frame = $this->getPreprocessor()->newFrame();
5860 # Process section extraction flags
5862 $sectionParts = explode( '-', $sectionId );
5863 $sectionIndex = array_pop( $sectionParts );
5864 foreach ( $sectionParts as $part ) {
5865 if ( $part === 'T' ) {
5866 $flags |
= self
::PTD_FOR_INCLUSION
;
5870 # Check for empty input
5871 if ( strval( $text ) === '' ) {
5872 # Only sections 0 and T-0 exist in an empty document
5873 if ( $sectionIndex == 0 ) {
5874 if ( $mode === 'get' ) {
5880 if ( $mode === 'get' ) {
5888 # Preprocess the text
5889 $root = $this->preprocessToDom( $text, $flags );
5891 # <h> nodes indicate section breaks
5892 # They can only occur at the top level, so we can find them by iterating the root's children
5893 $node = $root->getFirstChild();
5895 # Find the target section
5896 if ( $sectionIndex == 0 ) {
5897 # Section zero doesn't nest, level=big
5898 $targetLevel = 1000;
5901 if ( $node->getName() === 'h' ) {
5902 $bits = $node->splitHeading();
5903 if ( $bits['i'] == $sectionIndex ) {
5904 $targetLevel = $bits['level'];
5908 if ( $mode === 'replace' ) {
5909 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5911 $node = $node->getNextSibling();
5917 if ( $mode === 'get' ) {
5924 # Find the end of the section, including nested sections
5926 if ( $node->getName() === 'h' ) {
5927 $bits = $node->splitHeading();
5928 $curLevel = $bits['level'];
5929 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5933 if ( $mode === 'get' ) {
5934 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5936 $node = $node->getNextSibling();
5939 # Write out the remainder (in replace mode only)
5940 if ( $mode === 'replace' ) {
5941 # Output the replacement text
5942 # Add two newlines on -- trailing whitespace in $newText is conventionally
5943 # stripped by the editor, so we need both newlines to restore the paragraph gap
5944 # Only add trailing whitespace if there is newText
5945 if ( $newText != "" ) {
5946 $outText .= $newText . "\n\n";
5950 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5951 $node = $node->getNextSibling();
5955 if ( is_string( $outText ) ) {
5956 # Re-insert stripped tags
5957 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5964 * This function returns the text of a section, specified by a number ($section).
5965 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5966 * the first section before any such heading (section 0).
5968 * If a section contains subsections, these are also returned.
5970 * @param string $text Text to look in
5971 * @param string|number $sectionId Section identifier as a number or string
5972 * (e.g. 0, 1 or 'T-1').
5973 * @param string $defaultText Default to return if section is not found
5975 * @return string Text of the requested section
5977 public function getSection( $text, $sectionId, $defaultText = '' ) {
5978 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5982 * This function returns $oldtext after the content of the section
5983 * specified by $section has been replaced with $text. If the target
5984 * section does not exist, $oldtext is returned unchanged.
5986 * @param string $oldText Former text of the article
5987 * @param string|number $sectionId Section identifier as a number or string
5988 * (e.g. 0, 1 or 'T-1').
5989 * @param string $newText Replacing text
5991 * @return string Modified text
5993 public function replaceSection( $oldText, $sectionId, $newText ) {
5994 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5998 * Get the ID of the revision we are parsing
6002 public function getRevisionId() {
6003 return $this->mRevisionId
;
6007 * Get the revision object for $this->mRevisionId
6009 * @return Revision|null Either a Revision object or null
6010 * @since 1.23 (public since 1.23)
6012 public function getRevisionObject() {
6013 if ( !is_null( $this->mRevisionObject
) ) {
6014 return $this->mRevisionObject
;
6016 if ( is_null( $this->mRevisionId
) ) {
6020 $rev = call_user_func(
6021 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
6024 # If the parse is for a new revision, then the callback should have
6025 # already been set to force the object and should match mRevisionId.
6026 # If not, try to fetch by mRevisionId for sanity.
6027 if ( $rev && $rev->getId() != $this->mRevisionId
) {
6028 $rev = Revision
::newFromId( $this->mRevisionId
);
6031 $this->mRevisionObject
= $rev;
6033 return $this->mRevisionObject
;
6037 * Get the timestamp associated with the current revision, adjusted for
6038 * the default server-local timestamp
6041 public function getRevisionTimestamp() {
6042 if ( is_null( $this->mRevisionTimestamp
) ) {
6045 $revObject = $this->getRevisionObject();
6046 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6048 # The cryptic '' timezone parameter tells to use the site-default
6049 # timezone offset instead of the user settings.
6051 # Since this value will be saved into the parser cache, served
6052 # to other users, and potentially even used inside links and such,
6053 # it needs to be consistent for all visitors.
6054 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6057 return $this->mRevisionTimestamp
;
6061 * Get the name of the user that edited the last revision
6063 * @return string User name
6065 public function getRevisionUser() {
6066 if ( is_null( $this->mRevisionUser
) ) {
6067 $revObject = $this->getRevisionObject();
6069 # if this template is subst: the revision id will be blank,
6070 # so just use the current user's name
6072 $this->mRevisionUser
= $revObject->getUserText();
6073 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6074 $this->mRevisionUser
= $this->getUser()->getName();
6077 return $this->mRevisionUser
;
6081 * Get the size of the revision
6083 * @return int|null Revision size
6085 public function getRevisionSize() {
6086 if ( is_null( $this->mRevisionSize
) ) {
6087 $revObject = $this->getRevisionObject();
6089 # if this variable is subst: the revision id will be blank,
6090 # so just use the parser input size, because the own substituation
6091 # will change the size.
6093 $this->mRevisionSize
= $revObject->getSize();
6094 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6095 $this->mRevisionSize
= $this->mInputSize
;
6098 return $this->mRevisionSize
;
6102 * Mutator for $mDefaultSort
6104 * @param string $sort New value
6106 public function setDefaultSort( $sort ) {
6107 $this->mDefaultSort
= $sort;
6108 $this->mOutput
->setProperty( 'defaultsort', $sort );
6112 * Accessor for $mDefaultSort
6113 * Will use the empty string if none is set.
6115 * This value is treated as a prefix, so the
6116 * empty string is equivalent to sorting by
6121 public function getDefaultSort() {
6122 if ( $this->mDefaultSort
!== false ) {
6123 return $this->mDefaultSort
;
6130 * Accessor for $mDefaultSort
6131 * Unlike getDefaultSort(), will return false if none is set
6133 * @return string|bool
6135 public function getCustomDefaultSort() {
6136 return $this->mDefaultSort
;
6140 * Try to guess the section anchor name based on a wikitext fragment
6141 * presumably extracted from a heading, for example "Header" from
6144 * @param string $text
6148 public function guessSectionNameFromWikiText( $text ) {
6149 # Strip out wikitext links(they break the anchor)
6150 $text = $this->stripSectionName( $text );
6151 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6152 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6156 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6157 * instead. For use in redirects, since IE6 interprets Redirect: headers
6158 * as something other than UTF-8 (apparently?), resulting in breakage.
6160 * @param string $text The section name
6161 * @return string An anchor
6163 public function guessLegacySectionNameFromWikiText( $text ) {
6164 # Strip out wikitext links(they break the anchor)
6165 $text = $this->stripSectionName( $text );
6166 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6167 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6171 * Strips a text string of wikitext for use in a section anchor
6173 * Accepts a text string and then removes all wikitext from the
6174 * string and leaves only the resultant text (i.e. the result of
6175 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6176 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6177 * to create valid section anchors by mimicing the output of the
6178 * parser when headings are parsed.
6180 * @param string $text Text string to be stripped of wikitext
6181 * for use in a Section anchor
6182 * @return string Filtered text string
6184 public function stripSectionName( $text ) {
6185 # Strip internal link markup
6186 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6187 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6189 # Strip external link markup
6190 # @todo FIXME: Not tolerant to blank link text
6191 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6192 # on how many empty links there are on the page - need to figure that out.
6193 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6195 # Parse wikitext quotes (italics & bold)
6196 $text = $this->doQuotes( $text );
6199 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6204 * strip/replaceVariables/unstrip for preprocessor regression testing
6206 * @param string $text
6207 * @param Title $title
6208 * @param ParserOptions $options
6209 * @param int $outputType
6213 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6214 $magicScopeVariable = $this->lock();
6215 $this->startParse( $title, $options, $outputType, true );
6217 $text = $this->replaceVariables( $text );
6218 $text = $this->mStripState
->unstripBoth( $text );
6219 $text = Sanitizer
::removeHTMLtags( $text );
6224 * @param string $text
6225 * @param Title $title
6226 * @param ParserOptions $options
6229 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6230 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6234 * @param string $text
6235 * @param Title $title
6236 * @param ParserOptions $options
6239 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6240 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6244 * Call a callback function on all regions of the given text that are not
6245 * inside strip markers, and replace those regions with the return value
6246 * of the callback. For example, with input:
6250 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6251 * two strings will be replaced with the value returned by the callback in
6255 * @param callable $callback
6259 public function markerSkipCallback( $s, $callback ) {
6262 while ( $i < strlen( $s ) ) {
6263 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6264 if ( $markerStart === false ) {
6265 $out .= call_user_func( $callback, substr( $s, $i ) );
6268 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6269 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6270 if ( $markerEnd === false ) {
6271 $out .= substr( $s, $markerStart );
6274 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6275 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6284 * Remove any strip markers found in the given text.
6286 * @param string $text Input string
6289 public function killMarkers( $text ) {
6290 return $this->mStripState
->killMarkers( $text );
6294 * Save the parser state required to convert the given half-parsed text to
6295 * HTML. "Half-parsed" in this context means the output of
6296 * recursiveTagParse() or internalParse(). This output has strip markers
6297 * from replaceVariables (extensionSubstitution() etc.), and link
6298 * placeholders from replaceLinkHolders().
6300 * Returns an array which can be serialized and stored persistently. This
6301 * array can later be loaded into another parser instance with
6302 * unserializeHalfParsedText(). The text can then be safely incorporated into
6303 * the return value of a parser hook.
6305 * @param string $text
6309 public function serializeHalfParsedText( $text ) {
6312 'version' => self
::HALF_PARSED_VERSION
,
6313 'stripState' => $this->mStripState
->getSubState( $text ),
6314 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6320 * Load the parser state given in the $data array, which is assumed to
6321 * have been generated by serializeHalfParsedText(). The text contents is
6322 * extracted from the array, and its markers are transformed into markers
6323 * appropriate for the current Parser instance. This transformed text is
6324 * returned, and can be safely included in the return value of a parser
6327 * If the $data array has been stored persistently, the caller should first
6328 * check whether it is still valid, by calling isValidHalfParsedText().
6330 * @param array $data Serialized data
6331 * @throws MWException
6334 public function unserializeHalfParsedText( $data ) {
6335 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6336 throw new MWException( __METHOD__
. ': invalid version' );
6339 # First, extract the strip state.
6340 $texts = array( $data['text'] );
6341 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6343 # Now renumber links
6344 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6346 # Should be good to go.
6351 * Returns true if the given array, presumed to be generated by
6352 * serializeHalfParsedText(), is compatible with the current version of the
6355 * @param array $data
6359 public function isValidHalfParsedText( $data ) {
6360 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6364 * Parsed a width param of imagelink like 300px or 200x300px
6366 * @param string $value
6371 public function parseWidthParam( $value ) {
6372 $parsedWidthParam = array();
6373 if ( $value === '' ) {
6374 return $parsedWidthParam;
6377 # (bug 13500) In both cases (width/height and width only),
6378 # permit trailing "px" for backward compatibility.
6379 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6380 $width = intval( $m[1] );
6381 $height = intval( $m[2] );
6382 $parsedWidthParam['width'] = $width;
6383 $parsedWidthParam['height'] = $height;
6384 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6385 $width = intval( $value );
6386 $parsedWidthParam['width'] = $width;
6388 return $parsedWidthParam;
6392 * Lock the current instance of the parser.
6394 * This is meant to stop someone from calling the parser
6395 * recursively and messing up all the strip state.
6397 * @throws MWException If parser is in a parse
6398 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6400 protected function lock() {
6401 if ( $this->mInParse
) {
6402 throw new MWException( "Parser state cleared while parsing. "
6403 . "Did you call Parser::parse recursively?" );
6405 $this->mInParse
= true;
6408 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6409 $that->mInParse
= false;
6412 return $recursiveCheck;
6416 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6418 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6419 * or if there is more than one <p/> tag in the input HTML.
6421 * @param string $html
6425 public static function stripOuterParagraph( $html ) {
6427 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6428 if ( strpos( $m[1], '</p>' ) === false ) {
6437 * Return this parser if it is not doing anything, otherwise
6438 * get a fresh parser. You can use this method by doing
6439 * $myParser = $wgParser->getFreshParser(), or more simply
6440 * $wgParser->getFreshParser()->parse( ... );
6441 * if you're unsure if $wgParser is safe to use.
6444 * @return Parser A parser object that is not parsing anything
6446 public function getFreshParser() {
6447 global $wgParserConf;
6448 if ( $this->mInParse
) {
6449 return new $wgParserConf['class']( $wgParserConf );
6456 * Set's up the PHP implementation of OOUI for use in this request
6457 * and instructs OutputPage to enable OOUI for itself.
6461 public function enableOOUI() {
6462 OutputPage
::setupOOUI();
6463 $this->mOutput
->setEnableOOUI( true );