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 // @codingStandardsIgnoreStart Generic.Files.LineLength
95 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
96 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
97 // @codingStandardsIgnoreEnd
99 # Regular expression for a non-newline space
100 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
102 # State constants for the definition list colon extraction
103 const COLON_STATE_TEXT
= 0;
104 const COLON_STATE_TAG
= 1;
105 const COLON_STATE_TAGSTART
= 2;
106 const COLON_STATE_CLOSETAG
= 3;
107 const COLON_STATE_TAGSLASH
= 4;
108 const COLON_STATE_COMMENT
= 5;
109 const COLON_STATE_COMMENTDASH
= 6;
110 const COLON_STATE_COMMENTDASHDASH
= 7;
112 # Flags for preprocessToDom
113 const PTD_FOR_INCLUSION
= 1;
115 # Allowed values for $this->mOutputType
116 # Parameter to startExternalParse().
117 const OT_HTML
= 1; # like parse()
118 const OT_WIKI
= 2; # like preSaveTransform()
119 const OT_PREPROCESS
= 3; # like preprocess()
121 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
124 * @var string Prefix and suffix for temporary replacement strings
125 * for the multipass parser.
127 * \x7f should never appear in input as it's disallowed in XML.
128 * Using it at the front also gives us a little extra robustness
129 * since it shouldn't match when butted up against identifier-like
132 * Must not consist of all title characters, or else it will change
133 * the behavior of <nowiki> in a link.
135 const MARKER_SUFFIX
= "-QINU\x7f";
136 const MARKER_PREFIX
= "\x7fUNIQ-";
138 # Markers used for wrapping the table of contents
139 const TOC_START
= '<mw:toc>';
140 const TOC_END
= '</mw:toc>';
143 public $mTagHooks = array();
144 public $mTransparentTagHooks = array();
145 public $mFunctionHooks = array();
146 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
147 public $mFunctionTagHooks = array();
148 public $mStripList = array();
149 public $mDefaultStripList = array();
150 public $mVarCache = array();
151 public $mImageParams = array();
152 public $mImageParamsMagicArray = array();
153 public $mMarkerIndex = 0;
154 public $mFirstCall = true;
156 # Initialised by initialiseVariables()
159 * @var MagicWordArray
164 * @var MagicWordArray
167 # Initialised in constructor
168 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
170 # Initialized in getPreprocessor()
171 /** @var Preprocessor */
172 public $mPreprocessor;
174 # Cleared with clearState():
179 public $mAutonumber, $mDTopen;
186 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
188 * @var LinkHolderArray
190 public $mLinkHolders;
193 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
194 public $mDefaultSort;
195 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
196 public $mExpensiveFunctionCount; # number of expensive parser function calls
197 public $mShowToc, $mForceTocPosition;
202 public $mUser; # User object; only used when doing pre-save transform
205 # These are variables reset at least once per parse regardless of $clearState
215 public $mTitle; # Title context, used for self-link rendering and similar things
216 public $mOutputType; # Output type, one of the OT_xxx constants
217 public $ot; # Shortcut alias, see setOutputType()
218 public $mRevisionObject; # The revision object of the specified revision ID
219 public $mRevisionId; # ID to display in {{REVISIONID}} tags
220 public $mRevisionTimestamp; # The timestamp of the specified revision ID
221 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
222 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
223 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
224 public $mInputSize = false; # For {{PAGESIZE}} on current page.
227 * @var string Deprecated accessor for the strip marker prefix.
228 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
230 public $mUniqPrefix = Parser
::MARKER_PREFIX
;
233 * @var array Array with the language name of each language link (i.e. the
234 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
235 * duplicate language links to the ParserOutput.
237 public $mLangLinkLanguages;
240 * @var MapCacheLRU|null
243 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
245 public $currentRevisionCache;
248 * @var bool Recursive call protection.
249 * This variable should be treated as if it were private.
251 public $mInParse = false;
253 /** @var SectionProfiler */
254 protected $mProfiler;
259 public function __construct( $conf = array() ) {
260 $this->mConf
= $conf;
261 $this->mUrlProtocols
= wfUrlProtocols();
262 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
263 self
::EXT_LINK_ADDR
.
264 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
265 if ( isset( $conf['preprocessorClass'] ) ) {
266 $this->mPreprocessorClass
= $conf['preprocessorClass'];
267 } elseif ( defined( 'HPHP_VERSION' ) ) {
268 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
269 $this->mPreprocessorClass
= 'Preprocessor_Hash';
270 } elseif ( extension_loaded( 'domxml' ) ) {
271 # PECL extension that conflicts with the core DOM extension (bug 13770)
272 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
273 $this->mPreprocessorClass
= 'Preprocessor_Hash';
274 } elseif ( extension_loaded( 'dom' ) ) {
275 $this->mPreprocessorClass
= 'Preprocessor_DOM';
277 $this->mPreprocessorClass
= 'Preprocessor_Hash';
279 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
283 * Reduce memory usage to reduce the impact of circular references
285 public function __destruct() {
286 if ( isset( $this->mLinkHolders
) ) {
287 unset( $this->mLinkHolders
);
289 foreach ( $this as $name => $value ) {
290 unset( $this->$name );
295 * Allow extensions to clean up when the parser is cloned
297 public function __clone() {
298 $this->mInParse
= false;
300 // Bug 56226: When you create a reference "to" an object field, that
301 // makes the object field itself be a reference too (until the other
302 // reference goes out of scope). When cloning, any field that's a
303 // reference is copied as a reference in the new object. Both of these
304 // are defined PHP5 behaviors, as inconvenient as it is for us when old
305 // hooks from PHP4 days are passing fields by reference.
306 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
307 // Make a non-reference copy of the field, then rebind the field to
308 // reference the new copy.
314 Hooks
::run( 'ParserCloned', array( $this ) );
318 * Do various kinds of initialisation on the first call of the parser
320 public function firstCallInit() {
321 if ( !$this->mFirstCall
) {
324 $this->mFirstCall
= false;
326 CoreParserFunctions
::register( $this );
327 CoreTagHooks
::register( $this );
328 $this->initialiseVariables();
330 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
338 public function clearState() {
339 if ( $this->mFirstCall
) {
340 $this->firstCallInit();
342 $this->mOutput
= new ParserOutput
;
343 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
344 $this->mAutonumber
= 0;
345 $this->mLastSection
= '';
346 $this->mDTopen
= false;
347 $this->mIncludeCount
= array();
348 $this->mArgStack
= false;
349 $this->mInPre
= false;
350 $this->mLinkHolders
= new LinkHolderArray( $this );
352 $this->mRevisionObject
= $this->mRevisionTimestamp
=
353 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
354 $this->mVarCache
= array();
356 $this->mLangLinkLanguages
= array();
357 $this->currentRevisionCache
= null;
359 $this->mStripState
= new StripState
;
361 # Clear these on every parse, bug 4549
362 $this->mTplRedirCache
= $this->mTplDomCache
= array();
364 $this->mShowToc
= true;
365 $this->mForceTocPosition
= false;
366 $this->mIncludeSizes
= array(
370 $this->mPPNodeCount
= 0;
371 $this->mGeneratedPPNodeCount
= 0;
372 $this->mHighestExpansionDepth
= 0;
373 $this->mDefaultSort
= false;
374 $this->mHeadings
= array();
375 $this->mDoubleUnderscores
= array();
376 $this->mExpensiveFunctionCount
= 0;
379 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
380 $this->mPreprocessor
= null;
383 $this->mProfiler
= new SectionProfiler();
385 Hooks
::run( 'ParserClearState', array( &$this ) );
389 * Convert wikitext to HTML
390 * Do not call this function recursively.
392 * @param string $text Text we want to parse
393 * @param Title $title
394 * @param ParserOptions $options
395 * @param bool $linestart
396 * @param bool $clearState
397 * @param int $revid Number to pass in {{REVISIONID}}
398 * @return ParserOutput A ParserOutput
400 public function parse( $text, Title
$title, ParserOptions
$options,
401 $linestart = true, $clearState = true, $revid = null
404 * First pass--just handle <nowiki> sections, pass the rest off
405 * to internalParse() which does all the real work.
408 global $wgShowHostnames;
411 // We use U+007F DELETE to construct strip markers, so we have to make
412 // sure that this character does not occur in the input text.
413 $text = strtr( $text, "\x7f", "?" );
414 $magicScopeVariable = $this->lock();
417 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
419 $this->currentRevisionCache
= null;
420 $this->mInputSize
= strlen( $text );
421 if ( $this->mOptions
->getEnableLimitReport() ) {
422 $this->mOutput
->resetParseStartTime();
425 $oldRevisionId = $this->mRevisionId
;
426 $oldRevisionObject = $this->mRevisionObject
;
427 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
428 $oldRevisionUser = $this->mRevisionUser
;
429 $oldRevisionSize = $this->mRevisionSize
;
430 if ( $revid !== null ) {
431 $this->mRevisionId
= $revid;
432 $this->mRevisionObject
= null;
433 $this->mRevisionTimestamp
= null;
434 $this->mRevisionUser
= null;
435 $this->mRevisionSize
= null;
438 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
440 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
441 $text = $this->internalParse( $text );
442 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParseHalfParsed( $text, true, $linestart );
447 * A converted title will be provided in the output object if title and
448 * content conversion are enabled, the article text does not contain
449 * a conversion-suppressing double-underscore tag, and no
450 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
451 * automatic link conversion.
453 if ( !( $options->getDisableTitleConversion()
454 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
455 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
456 ||
$this->mOutput
->getDisplayTitle() !== false )
458 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
459 if ( $convruletitle ) {
460 $this->mOutput
->setTitleText( $convruletitle );
462 $titleText = $this->getConverterLanguage()->convertTitle( $title );
463 $this->mOutput
->setTitleText( $titleText );
467 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
468 $this->limitationWarn( 'expensive-parserfunction',
469 $this->mExpensiveFunctionCount
,
470 $this->mOptions
->getExpensiveParserFunctionLimit()
474 # Information on include size limits, for the benefit of users who try to skirt them
475 if ( $this->mOptions
->getEnableLimitReport() ) {
476 $max = $this->mOptions
->getMaxIncludeSize();
478 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
479 if ( $cpuTime !== null ) {
480 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
481 sprintf( "%.3f", $cpuTime )
485 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
486 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
487 sprintf( "%.3f", $wallTime )
490 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
491 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
493 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
494 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
496 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
497 array( $this->mIncludeSizes
['post-expand'], $max )
499 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
500 array( $this->mIncludeSizes
['arg'], $max )
502 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
503 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
505 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
506 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
508 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
510 $limitReport = "NewPP limit report\n";
511 if ( $wgShowHostnames ) {
512 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
514 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
515 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
516 $limitReport .= 'Dynamic content: ' .
517 ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) .
520 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
521 if ( Hooks
::run( 'ParserLimitReportFormat',
522 array( $key, &$value, &$limitReport, false, false )
524 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
525 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
526 ->inLanguage( 'en' )->useDatabase( false );
527 if ( !$valueMsg->exists() ) {
528 $valueMsg = new RawMessage( '$1' );
530 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
531 $valueMsg->params( $value );
532 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
536 // Since we're not really outputting HTML, decode the entities and
537 // then re-encode the things that need hiding inside HTML comments.
538 $limitReport = htmlspecialchars_decode( $limitReport );
539 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
541 // Sanitize for comment. Note '‐' in the replacement is U+2010,
542 // which looks much like the problematic '-'.
543 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
544 $text .= "\n<!-- \n$limitReport-->\n";
546 // Add on template profiling data
547 $dataByFunc = $this->mProfiler
->getFunctionStats();
548 uasort( $dataByFunc, function ( $a, $b ) {
549 return $a['real'] < $b['real']; // descending order
551 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
552 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
553 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
554 $item['%real'], $item['real'], $item['calls'],
555 htmlspecialchars( $item['name'] ) );
557 $text .= "\n<!-- \n$profileReport-->\n";
559 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
560 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
561 $this->mTitle
->getPrefixedDBkey() );
564 $this->mOutput
->setText( $text );
566 $this->mRevisionId
= $oldRevisionId;
567 $this->mRevisionObject
= $oldRevisionObject;
568 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
569 $this->mRevisionUser
= $oldRevisionUser;
570 $this->mRevisionSize
= $oldRevisionSize;
571 $this->mInputSize
= false;
572 $this->currentRevisionCache
= null;
574 return $this->mOutput
;
578 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
579 * can be called from an extension tag hook.
581 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
582 * instead, which means that lists and links have not been fully parsed yet,
583 * and strip markers are still present.
585 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
587 * Use this function if you're a parser tag hook and you want to parse
588 * wikitext before or after applying additional transformations, and you
589 * intend to *return the result as hook output*, which will cause it to go
590 * through the rest of parsing process automatically.
592 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
593 * $text are not expanded
595 * @param string $text Text extension wants to have parsed
596 * @param bool|PPFrame $frame The frame to use for expanding any template variables
597 * @return string UNSAFE half-parsed HTML
599 public function recursiveTagParse( $text, $frame = false ) {
600 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
601 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
602 $text = $this->internalParse( $text, false, $frame );
607 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
608 * point can be called from an extension tag hook.
610 * The output of this function is fully-parsed HTML that is safe for output.
611 * If you're a parser tag hook, you might want to use recursiveTagParse()
614 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
615 * $text are not expanded
619 * @param string $text Text extension wants to have parsed
620 * @param bool|PPFrame $frame The frame to use for expanding any template variables
621 * @return string Fully parsed HTML
623 public function recursiveTagParseFully( $text, $frame = false ) {
624 $text = $this->recursiveTagParse( $text, $frame );
625 $text = $this->internalParseHalfParsed( $text, false );
630 * Expand templates and variables in the text, producing valid, static wikitext.
631 * Also removes comments.
632 * Do not call this function recursively.
633 * @param string $text
634 * @param Title $title
635 * @param ParserOptions $options
636 * @param int|null $revid
637 * @param bool|PPFrame $frame
638 * @return mixed|string
640 public function preprocess( $text, Title
$title = null,
641 ParserOptions
$options, $revid = null, $frame = false
643 $magicScopeVariable = $this->lock();
644 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
645 if ( $revid !== null ) {
646 $this->mRevisionId
= $revid;
648 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
649 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
650 $text = $this->replaceVariables( $text, $frame );
651 $text = $this->mStripState
->unstripBoth( $text );
656 * Recursive parser entry point that can be called from an extension tag
659 * @param string $text Text to be expanded
660 * @param bool|PPFrame $frame The frame to use for expanding any template variables
664 public function recursivePreprocess( $text, $frame = false ) {
665 $text = $this->replaceVariables( $text, $frame );
666 $text = $this->mStripState
->unstripBoth( $text );
671 * Process the wikitext for the "?preload=" feature. (bug 5210)
673 * "<noinclude>", "<includeonly>" etc. are parsed as for template
674 * transclusion, comments, templates, arguments, tags hooks and parser
675 * functions are untouched.
677 * @param string $text
678 * @param Title $title
679 * @param ParserOptions $options
680 * @param array $params
683 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
684 $msg = new RawMessage( $text );
685 $text = $msg->params( $params )->plain();
687 # Parser (re)initialisation
688 $magicScopeVariable = $this->lock();
689 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
691 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
692 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
693 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
694 $text = $this->mStripState
->unstripBoth( $text );
699 * Get a random string
702 * @deprecated since 1.26; use wfRandomString() instead.
704 public static function getRandomString() {
705 wfDeprecated( __METHOD__
, '1.26' );
706 return wfRandomString( 16 );
710 * Set the current user.
711 * Should only be used when doing pre-save transform.
713 * @param User|null $user User object or null (to reset)
715 public function setUser( $user ) {
716 $this->mUser
= $user;
720 * Accessor for mUniqPrefix.
723 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
725 public function uniqPrefix() {
726 wfDeprecated( __METHOD__
, '1.26' );
727 return self
::MARKER_PREFIX
;
731 * Set the context title
735 public function setTitle( $t ) {
737 $t = Title
::newFromText( 'NO TITLE' );
740 if ( $t->hasFragment() ) {
741 # Strip the fragment to avoid various odd effects
742 $this->mTitle
= clone $t;
743 $this->mTitle
->setFragment( '' );
750 * Accessor for the Title object
754 public function getTitle() {
755 return $this->mTitle
;
759 * Accessor/mutator for the Title object
761 * @param Title $x Title object or null to just get the current one
764 public function Title( $x = null ) {
765 return wfSetVar( $this->mTitle
, $x );
769 * Set the output type
771 * @param int $ot New value
773 public function setOutputType( $ot ) {
774 $this->mOutputType
= $ot;
777 'html' => $ot == self
::OT_HTML
,
778 'wiki' => $ot == self
::OT_WIKI
,
779 'pre' => $ot == self
::OT_PREPROCESS
,
780 'plain' => $ot == self
::OT_PLAIN
,
785 * Accessor/mutator for the output type
787 * @param int|null $x New value or null to just get the current one
790 public function OutputType( $x = null ) {
791 return wfSetVar( $this->mOutputType
, $x );
795 * Get the ParserOutput object
797 * @return ParserOutput
799 public function getOutput() {
800 return $this->mOutput
;
804 * Get the ParserOptions object
806 * @return ParserOptions
808 public function getOptions() {
809 return $this->mOptions
;
813 * Accessor/mutator for the ParserOptions object
815 * @param ParserOptions $x New value or null to just get the current one
816 * @return ParserOptions Current ParserOptions object
818 public function Options( $x = null ) {
819 return wfSetVar( $this->mOptions
, $x );
825 public function nextLinkID() {
826 return $this->mLinkID++
;
832 public function setLinkID( $id ) {
833 $this->mLinkID
= $id;
837 * Get a language object for use in parser functions such as {{FORMATNUM:}}
840 public function getFunctionLang() {
841 return $this->getTargetLanguage();
845 * Get the target language for the content being parsed. This is usually the
846 * language that the content is in.
850 * @throws MWException
853 public function getTargetLanguage() {
854 $target = $this->mOptions
->getTargetLanguage();
856 if ( $target !== null ) {
858 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
859 return $this->mOptions
->getUserLangObj();
860 } elseif ( is_null( $this->mTitle
) ) {
861 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
864 return $this->mTitle
->getPageLanguage();
868 * Get the language object for language conversion
869 * @return Language|null
871 public function getConverterLanguage() {
872 return $this->getTargetLanguage();
876 * Get a User object either from $this->mUser, if set, or from the
877 * ParserOptions object otherwise
881 public function getUser() {
882 if ( !is_null( $this->mUser
) ) {
885 return $this->mOptions
->getUser();
889 * Get a preprocessor object
891 * @return Preprocessor
893 public function getPreprocessor() {
894 if ( !isset( $this->mPreprocessor
) ) {
895 $class = $this->mPreprocessorClass
;
896 $this->mPreprocessor
= new $class( $this );
898 return $this->mPreprocessor
;
902 * Replaces all occurrences of HTML-style comments and the given tags
903 * in the text with a random marker and returns the next text. The output
904 * parameter $matches will be an associative array filled with data in
908 * 'UNIQ-xxxxx' => array(
911 * array( 'param' => 'x' ),
912 * '<element param="x">tag content</element>' ) )
915 * @param array $elements List of element names. Comments are always extracted.
916 * @param string $text Source text string.
917 * @param array $matches Out parameter, Array: extracted tags
918 * @param string|null $uniq_prefix
919 * @return string Stripped text
920 * @since 1.26 The uniq_prefix argument is deprecated.
922 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
923 if ( $uniq_prefix !== null ) {
924 wfDeprecated( __METHOD__
. ' called with $prefix argument', '1.26' );
930 $taglist = implode( '|', $elements );
931 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
933 while ( $text != '' ) {
934 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
936 if ( count( $p ) < 5 ) {
939 if ( count( $p ) > 5 ) {
953 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
954 $stripped .= $marker;
956 if ( $close === '/>' ) {
957 # Empty element tag, <tag />
962 if ( $element === '!--' ) {
965 $end = "/(<\\/$element\\s*>)/i";
967 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
969 if ( count( $q ) < 3 ) {
970 # No end tag -- let it run out to the end of the text.
979 $matches[$marker] = array( $element,
981 Sanitizer
::decodeTagAttributes( $attributes ),
982 "<$element$attributes$close$content$tail" );
988 * Get a list of strippable XML-like elements
992 public function getStripList() {
993 return $this->mStripList
;
997 * Add an item to the strip state
998 * Returns the unique tag which must be inserted into the stripped text
999 * The tag will be replaced with the original text in unstrip()
1001 * @param string $text
1005 public function insertStripItem( $text ) {
1006 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1007 $this->mMarkerIndex++
;
1008 $this->mStripState
->addGeneral( $marker, $text );
1013 * parse the wiki syntax used to render tables
1016 * @param string $text
1019 public function doTableStuff( $text ) {
1021 $lines = StringUtils
::explode( "\n", $text );
1023 $td_history = array(); # Is currently a td tag open?
1024 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1025 $tr_history = array(); # Is currently a tr tag open?
1026 $tr_attributes = array(); # history of tr attributes
1027 $has_opened_tr = array(); # Did this table open a <tr> element?
1028 $indent_level = 0; # indent level of the table
1030 foreach ( $lines as $outLine ) {
1031 $line = trim( $outLine );
1033 if ( $line === '' ) { # empty line, go to next line
1034 $out .= $outLine . "\n";
1038 $first_character = $line[0];
1039 $first_two = substr( $line, 0, 2 );
1042 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1043 # First check if we are starting a new table
1044 $indent_level = strlen( $matches[1] );
1046 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1047 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1049 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1050 array_push( $td_history, false );
1051 array_push( $last_tag_history, '' );
1052 array_push( $tr_history, false );
1053 array_push( $tr_attributes, '' );
1054 array_push( $has_opened_tr, false );
1055 } elseif ( count( $td_history ) == 0 ) {
1056 # Don't do any of the following
1057 $out .= $outLine . "\n";
1059 } elseif ( $first_two === '|}' ) {
1060 # We are ending a table
1061 $line = '</table>' . substr( $line, 2 );
1062 $last_tag = array_pop( $last_tag_history );
1064 if ( !array_pop( $has_opened_tr ) ) {
1065 $line = "<tr><td></td></tr>{$line}";
1068 if ( array_pop( $tr_history ) ) {
1069 $line = "</tr>{$line}";
1072 if ( array_pop( $td_history ) ) {
1073 $line = "</{$last_tag}>{$line}";
1075 array_pop( $tr_attributes );
1076 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1077 } elseif ( $first_two === '|-' ) {
1078 # Now we have a table row
1079 $line = preg_replace( '#^\|-+#', '', $line );
1081 # Whats after the tag is now only attributes
1082 $attributes = $this->mStripState
->unstripBoth( $line );
1083 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1084 array_pop( $tr_attributes );
1085 array_push( $tr_attributes, $attributes );
1088 $last_tag = array_pop( $last_tag_history );
1089 array_pop( $has_opened_tr );
1090 array_push( $has_opened_tr, true );
1092 if ( array_pop( $tr_history ) ) {
1096 if ( array_pop( $td_history ) ) {
1097 $line = "</{$last_tag}>{$line}";
1101 array_push( $tr_history, false );
1102 array_push( $td_history, false );
1103 array_push( $last_tag_history, '' );
1104 } elseif ( $first_character === '|'
1105 ||
$first_character === '!'
1106 ||
$first_two === '|+'
1108 # This might be cell elements, td, th or captions
1109 if ( $first_two === '|+' ) {
1110 $first_character = '+';
1111 $line = substr( $line, 2 );
1113 $line = substr( $line, 1 );
1116 if ( $first_character === '!' ) {
1117 $line = str_replace( '!!', '||', $line );
1120 # Split up multiple cells on the same line.
1121 # FIXME : This can result in improper nesting of tags processed
1122 # by earlier parser steps, but should avoid splitting up eg
1123 # attribute values containing literal "||".
1124 $cells = StringUtils
::explodeMarkup( '||', $line );
1128 # Loop through each table cell
1129 foreach ( $cells as $cell ) {
1131 if ( $first_character !== '+' ) {
1132 $tr_after = array_pop( $tr_attributes );
1133 if ( !array_pop( $tr_history ) ) {
1134 $previous = "<tr{$tr_after}>\n";
1136 array_push( $tr_history, true );
1137 array_push( $tr_attributes, '' );
1138 array_pop( $has_opened_tr );
1139 array_push( $has_opened_tr, true );
1142 $last_tag = array_pop( $last_tag_history );
1144 if ( array_pop( $td_history ) ) {
1145 $previous = "</{$last_tag}>\n{$previous}";
1148 if ( $first_character === '|' ) {
1150 } elseif ( $first_character === '!' ) {
1152 } elseif ( $first_character === '+' ) {
1153 $last_tag = 'caption';
1158 array_push( $last_tag_history, $last_tag );
1160 # A cell could contain both parameters and data
1161 $cell_data = explode( '|', $cell, 2 );
1163 # Bug 553: Note that a '|' inside an invalid link should not
1164 # be mistaken as delimiting cell parameters
1165 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1166 $cell = "{$previous}<{$last_tag}>{$cell}";
1167 } elseif ( count( $cell_data ) == 1 ) {
1168 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1170 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1171 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1172 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1176 array_push( $td_history, true );
1179 $out .= $outLine . "\n";
1182 # Closing open td, tr && table
1183 while ( count( $td_history ) > 0 ) {
1184 if ( array_pop( $td_history ) ) {
1187 if ( array_pop( $tr_history ) ) {
1190 if ( !array_pop( $has_opened_tr ) ) {
1191 $out .= "<tr><td></td></tr>\n";
1194 $out .= "</table>\n";
1197 # Remove trailing line-ending (b/c)
1198 if ( substr( $out, -1 ) === "\n" ) {
1199 $out = substr( $out, 0, -1 );
1202 # special case: don't return empty table
1203 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1211 * Helper function for parse() that transforms wiki markup into half-parsed
1212 * HTML. Only called for $mOutputType == self::OT_HTML.
1216 * @param string $text
1217 * @param bool $isMain
1218 * @param PPFrame|bool $frame
1222 public function internalParse( $text, $isMain = true, $frame = false ) {
1226 # Hook to suspend the parser in this state
1227 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1231 # if $frame is provided, then use $frame for replacing any variables
1233 # use frame depth to infer how include/noinclude tags should be handled
1234 # depth=0 means this is the top-level document; otherwise it's an included document
1235 if ( !$frame->depth
) {
1238 $flag = Parser
::PTD_FOR_INCLUSION
;
1240 $dom = $this->preprocessToDom( $text, $flag );
1241 $text = $frame->expand( $dom );
1243 # if $frame is not provided, then use old-style replaceVariables
1244 $text = $this->replaceVariables( $text );
1247 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1248 $text = Sanitizer
::removeHTMLtags(
1250 array( &$this, 'attributeStripCallback' ),
1252 array_keys( $this->mTransparentTagHooks
)
1254 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1256 # Tables need to come after variable replacement for things to work
1257 # properly; putting them before other transformations should keep
1258 # exciting things like link expansions from showing up in surprising
1260 $text = $this->doTableStuff( $text );
1262 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1264 $text = $this->doDoubleUnderscore( $text );
1266 $text = $this->doHeadings( $text );
1267 $text = $this->replaceInternalLinks( $text );
1268 $text = $this->doAllQuotes( $text );
1269 $text = $this->replaceExternalLinks( $text );
1271 # replaceInternalLinks may sometimes leave behind
1272 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1273 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1275 $text = $this->doMagicLinks( $text );
1276 $text = $this->formatHeadings( $text, $origText, $isMain );
1282 * Helper function for parse() that transforms half-parsed HTML into fully
1285 * @param string $text
1286 * @param bool $isMain
1287 * @param bool $linestart
1290 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1291 $text = $this->mStripState
->unstripGeneral( $text );
1294 Hooks
::run( 'ParserAfterUnstrip', array( &$this, &$text ) );
1297 # Clean up special characters, only run once, next-to-last before doBlockLevels
1299 # french spaces, last one Guillemet-left
1300 # only if there is something before the space
1301 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1302 # french spaces, Guillemet-right
1303 '/(\\302\\253) /' => '\\1 ',
1304 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1306 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1308 $text = $this->doBlockLevels( $text, $linestart );
1310 $this->replaceLinkHolders( $text );
1313 * The input doesn't get language converted if
1315 * b) Content isn't converted
1316 * c) It's a conversion table
1317 * d) it is an interface message (which is in the user language)
1319 if ( !( $this->mOptions
->getDisableContentConversion()
1320 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1322 if ( !$this->mOptions
->getInterfaceMessage() ) {
1323 # The position of the convert() call should not be changed. it
1324 # assumes that the links are all replaced and the only thing left
1325 # is the <nowiki> mark.
1326 $text = $this->getConverterLanguage()->convert( $text );
1330 $text = $this->mStripState
->unstripNoWiki( $text );
1333 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1336 $text = $this->replaceTransparentTags( $text );
1337 $text = $this->mStripState
->unstripGeneral( $text );
1339 $text = Sanitizer
::normalizeCharReferences( $text );
1341 if ( MWTidy
::isEnabled() && $this->mOptions
->getTidy() ) {
1342 $text = MWTidy
::tidy( $text );
1343 $this->mOutput
->addModuleStyles( MWTidy
::getModuleStyles() );
1345 # attempt to sanitize at least some nesting problems
1346 # (bug #2702 and quite a few others)
1348 # ''Something [http://www.cool.com cool''] -->
1349 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1350 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1351 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1352 # fix up an anchor inside another anchor, only
1353 # at least for a single single nested link (bug 3695)
1354 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1355 '\\1\\2</a>\\3</a>\\1\\4</a>',
1356 # fix div inside inline elements- doBlockLevels won't wrap a line which
1357 # contains a div, so fix it up here; replace
1358 # div with escaped text
1359 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1360 '\\1\\3<div\\5>\\6</div>\\8\\9',
1361 # remove empty italic or bold tag pairs, some
1362 # introduced by rules above
1363 '/<([bi])><\/\\1>/' => '',
1366 $text = preg_replace(
1367 array_keys( $tidyregs ),
1368 array_values( $tidyregs ),
1373 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1380 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1381 * magic external links.
1386 * @param string $text
1390 public function doMagicLinks( $text ) {
1391 $prots = wfUrlProtocolsWithoutProtRel();
1392 $urlChar = self
::EXT_LINK_URL_CLASS
;
1393 $addr = self
::EXT_LINK_ADDR
;
1394 $space = self
::SPACE_NOT_NL
; # non-newline space
1395 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1396 $spaces = "$space++"; # possessive match of 1 or more spaces
1397 $text = preg_replace_callback(
1399 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1400 (<.*?>) | # m[2]: Skip stuff inside
1401 # HTML elements' . "
1402 (\b(?i:$prots)($addr$urlChar*)) | # m[3]: Free external links
1403 # m[4]: Post-protocol path
1404 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1406 \bISBN $spaces ( # m[6]: ISBN, capture number
1407 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1408 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1409 [0-9Xx] # check digit
1411 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1416 * @throws MWException
1418 * @return HTML|string
1420 public function magicLinkCallback( $m ) {
1421 if ( isset( $m[1] ) && $m[1] !== '' ) {
1424 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1427 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1428 # Free external link
1429 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1430 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1432 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1435 $cssClass = 'mw-magiclink-rfc';
1437 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1439 $urlmsg = 'pubmedurl';
1440 $cssClass = 'mw-magiclink-pmid';
1443 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1444 substr( $m[0], 0, 20 ) . '"' );
1446 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1447 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1448 } elseif ( isset( $m[6] ) && $m[6] !== '' ) {
1451 $space = self
::SPACE_NOT_NL
; # non-newline space
1452 $isbn = preg_replace( "/$space/", ' ', $isbn );
1453 $num = strtr( $isbn, array(
1458 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1459 return '<a href="' .
1460 htmlspecialchars( $titleObj->getLocalURL() ) .
1461 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1468 * Make a free external link, given a user-supplied URL
1470 * @param string $url
1471 * @param int $numPostProto
1472 * The number of characters after the protocol.
1473 * @return string HTML
1476 public function makeFreeExternalLink( $url, $numPostProto ) {
1479 # The characters '<' and '>' (which were escaped by
1480 # removeHTMLtags()) should not be included in
1481 # URLs, per RFC 2396.
1482 # Make terminate a URL as well (bug T84937)
1485 '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/',
1490 $trail = substr( $url, $m2[0][1] ) . $trail;
1491 $url = substr( $url, 0, $m2[0][1] );
1494 # Move trailing punctuation to $trail
1496 # If there is no left bracket, then consider right brackets fair game too
1497 if ( strpos( $url, '(' ) === false ) {
1501 $urlRev = strrev( $url );
1502 $numSepChars = strspn( $urlRev, $sep );
1503 # Don't break a trailing HTML entity by moving the ; into $trail
1504 # This is in hot code, so use substr_compare to avoid having to
1505 # create a new string object for the comparison
1506 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1507 # more optimization: instead of running preg_match with a $
1508 # anchor, which can be slow, do the match on the reversed
1509 # string starting at the desired offset.
1510 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1511 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1515 if ( $numSepChars ) {
1516 $trail = substr( $url, -$numSepChars ) . $trail;
1517 $url = substr( $url, 0, -$numSepChars );
1520 # Verify that we still have a real URL after trail removal, and
1521 # not just lone protocol
1522 if ( strlen( $trail ) >= $numPostProto ) {
1523 return $url . $trail;
1526 $url = Sanitizer
::cleanUrl( $url );
1528 # Is this an external image?
1529 $text = $this->maybeMakeExternalImage( $url );
1530 if ( $text === false ) {
1531 # Not an image, make a link
1532 $text = Linker
::makeExternalLink( $url,
1533 $this->getConverterLanguage()->markNoConversion( $url, true ),
1535 $this->getExternalLinkAttribs( $url ) );
1536 # Register it in the output object...
1537 # Replace unnecessary URL escape codes with their equivalent characters
1538 $pasteurized = self
::normalizeLinkUrl( $url );
1539 $this->mOutput
->addExternalLink( $pasteurized );
1541 return $text . $trail;
1545 * Parse headers and return html
1549 * @param string $text
1553 public function doHeadings( $text ) {
1554 for ( $i = 6; $i >= 1; --$i ) {
1555 $h = str_repeat( '=', $i );
1556 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1562 * Replace single quotes with HTML markup
1565 * @param string $text
1567 * @return string The altered text
1569 public function doAllQuotes( $text ) {
1571 $lines = StringUtils
::explode( "\n", $text );
1572 foreach ( $lines as $line ) {
1573 $outtext .= $this->doQuotes( $line ) . "\n";
1575 $outtext = substr( $outtext, 0, -1 );
1580 * Helper function for doAllQuotes()
1582 * @param string $text
1586 public function doQuotes( $text ) {
1587 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1588 $countarr = count( $arr );
1589 if ( $countarr == 1 ) {
1593 // First, do some preliminary work. This may shift some apostrophes from
1594 // being mark-up to being text. It also counts the number of occurrences
1595 // of bold and italics mark-ups.
1598 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1599 $thislen = strlen( $arr[$i] );
1600 // If there are ever four apostrophes, assume the first is supposed to
1601 // be text, and the remaining three constitute mark-up for bold text.
1602 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1603 if ( $thislen == 4 ) {
1604 $arr[$i - 1] .= "'";
1607 } elseif ( $thislen > 5 ) {
1608 // If there are more than 5 apostrophes in a row, assume they're all
1609 // text except for the last 5.
1610 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1611 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1615 // Count the number of occurrences of bold and italics mark-ups.
1616 if ( $thislen == 2 ) {
1618 } elseif ( $thislen == 3 ) {
1620 } elseif ( $thislen == 5 ) {
1626 // If there is an odd number of both bold and italics, it is likely
1627 // that one of the bold ones was meant to be an apostrophe followed
1628 // by italics. Which one we cannot know for certain, but it is more
1629 // likely to be one that has a single-letter word before it.
1630 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1631 $firstsingleletterword = -1;
1632 $firstmultiletterword = -1;
1634 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1635 if ( strlen( $arr[$i] ) == 3 ) {
1636 $x1 = substr( $arr[$i - 1], -1 );
1637 $x2 = substr( $arr[$i - 1], -2, 1 );
1638 if ( $x1 === ' ' ) {
1639 if ( $firstspace == -1 ) {
1642 } elseif ( $x2 === ' ' ) {
1643 $firstsingleletterword = $i;
1644 // if $firstsingleletterword is set, we don't
1645 // look at the other options, so we can bail early.
1648 if ( $firstmultiletterword == -1 ) {
1649 $firstmultiletterword = $i;
1655 // If there is a single-letter word, use it!
1656 if ( $firstsingleletterword > -1 ) {
1657 $arr[$firstsingleletterword] = "''";
1658 $arr[$firstsingleletterword - 1] .= "'";
1659 } elseif ( $firstmultiletterword > -1 ) {
1660 // If not, but there's a multi-letter word, use that one.
1661 $arr[$firstmultiletterword] = "''";
1662 $arr[$firstmultiletterword - 1] .= "'";
1663 } elseif ( $firstspace > -1 ) {
1664 // ... otherwise use the first one that has neither.
1665 // (notice that it is possible for all three to be -1 if, for example,
1666 // there is only one pentuple-apostrophe in the line)
1667 $arr[$firstspace] = "''";
1668 $arr[$firstspace - 1] .= "'";
1672 // Now let's actually convert our apostrophic mush to HTML!
1677 foreach ( $arr as $r ) {
1678 if ( ( $i %
2 ) == 0 ) {
1679 if ( $state === 'both' ) {
1685 $thislen = strlen( $r );
1686 if ( $thislen == 2 ) {
1687 if ( $state === 'i' ) {
1690 } elseif ( $state === 'bi' ) {
1693 } elseif ( $state === 'ib' ) {
1694 $output .= '</b></i><b>';
1696 } elseif ( $state === 'both' ) {
1697 $output .= '<b><i>' . $buffer . '</i>';
1699 } else { // $state can be 'b' or ''
1703 } elseif ( $thislen == 3 ) {
1704 if ( $state === 'b' ) {
1707 } elseif ( $state === 'bi' ) {
1708 $output .= '</i></b><i>';
1710 } elseif ( $state === 'ib' ) {
1713 } elseif ( $state === 'both' ) {
1714 $output .= '<i><b>' . $buffer . '</b>';
1716 } else { // $state can be 'i' or ''
1720 } elseif ( $thislen == 5 ) {
1721 if ( $state === 'b' ) {
1722 $output .= '</b><i>';
1724 } elseif ( $state === 'i' ) {
1725 $output .= '</i><b>';
1727 } elseif ( $state === 'bi' ) {
1728 $output .= '</i></b>';
1730 } elseif ( $state === 'ib' ) {
1731 $output .= '</b></i>';
1733 } elseif ( $state === 'both' ) {
1734 $output .= '<i><b>' . $buffer . '</b></i>';
1736 } else { // ($state == '')
1744 // Now close all remaining tags. Notice that the order is important.
1745 if ( $state === 'b' ||
$state === 'ib' ) {
1748 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1751 if ( $state === 'bi' ) {
1754 // There might be lonely ''''', so make sure we have a buffer
1755 if ( $state === 'both' && $buffer ) {
1756 $output .= '<b><i>' . $buffer . '</i></b>';
1762 * Replace external links (REL)
1764 * Note: this is all very hackish and the order of execution matters a lot.
1765 * Make sure to run tests/parserTests.php if you change this code.
1769 * @param string $text
1771 * @throws MWException
1774 public function replaceExternalLinks( $text ) {
1776 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1777 if ( $bits === false ) {
1778 throw new MWException( "PCRE needs to be compiled with "
1779 . "--enable-unicode-properties in order for MediaWiki to function" );
1781 $s = array_shift( $bits );
1784 while ( $i < count( $bits ) ) {
1787 $text = $bits[$i++
];
1788 $trail = $bits[$i++
];
1790 # The characters '<' and '>' (which were escaped by
1791 # removeHTMLtags()) should not be included in
1792 # URLs, per RFC 2396.
1794 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1795 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1796 $url = substr( $url, 0, $m2[0][1] );
1799 # If the link text is an image URL, replace it with an <img> tag
1800 # This happened by accident in the original parser, but some people used it extensively
1801 $img = $this->maybeMakeExternalImage( $text );
1802 if ( $img !== false ) {
1808 # Set linktype for CSS - if URL==text, link is essentially free
1809 $linktype = ( $text === $url ) ?
'free' : 'text';
1811 # No link text, e.g. [http://domain.tld/some.link]
1812 if ( $text == '' ) {
1814 $langObj = $this->getTargetLanguage();
1815 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1816 $linktype = 'autonumber';
1818 # Have link text, e.g. [http://domain.tld/some.link text]s
1820 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1823 $text = $this->getConverterLanguage()->markNoConversion( $text );
1825 $url = Sanitizer
::cleanUrl( $url );
1827 # Use the encoded URL
1828 # This means that users can paste URLs directly into the text
1829 # Funny characters like ö aren't valid in URLs anyway
1830 # This was changed in August 2004
1831 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1832 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1834 # Register link in the output object.
1835 # Replace unnecessary URL escape codes with the referenced character
1836 # This prevents spammers from hiding links from the filters
1837 $pasteurized = self
::normalizeLinkUrl( $url );
1838 $this->mOutput
->addExternalLink( $pasteurized );
1845 * Get the rel attribute for a particular external link.
1848 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1849 * nofollow if appropriate
1850 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1851 * @return string|null Rel attribute for $url
1853 public static function getExternalLinkRel( $url = false, $title = null ) {
1854 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1855 $ns = $title ?
$title->getNamespace() : false;
1856 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1857 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1865 * Get an associative array of additional HTML attributes appropriate for a
1866 * particular external link. This currently may include rel => nofollow
1867 * (depending on configuration, namespace, and the URL's domain) and/or a
1868 * target attribute (depending on configuration).
1870 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1871 * nofollow if appropriate
1872 * @return array Associative array of HTML attributes
1874 public function getExternalLinkAttribs( $url = false ) {
1876 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1878 if ( $this->mOptions
->getExternalLinkTarget() ) {
1879 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1885 * Replace unusual escape codes in a URL with their equivalent characters
1887 * @deprecated since 1.24, use normalizeLinkUrl
1888 * @param string $url
1891 public static function replaceUnusualEscapes( $url ) {
1892 wfDeprecated( __METHOD__
, '1.24' );
1893 return self
::normalizeLinkUrl( $url );
1897 * Replace unusual escape codes in a URL with their equivalent characters
1899 * This generally follows the syntax defined in RFC 3986, with special
1900 * consideration for HTTP query strings.
1902 * @param string $url
1905 public static function normalizeLinkUrl( $url ) {
1906 # First, make sure unsafe characters are encoded
1907 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1909 return rawurlencode( $m[0] );
1915 $end = strlen( $url );
1917 # Fragment part - 'fragment'
1918 $start = strpos( $url, '#' );
1919 if ( $start !== false && $start < $end ) {
1920 $ret = self
::normalizeUrlComponent(
1921 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1925 # Query part - 'query' minus &=+;
1926 $start = strpos( $url, '?' );
1927 if ( $start !== false && $start < $end ) {
1928 $ret = self
::normalizeUrlComponent(
1929 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1933 # Scheme and path part - 'pchar'
1934 # (we assume no userinfo or encoded colons in the host)
1935 $ret = self
::normalizeUrlComponent(
1936 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1941 private static function normalizeUrlComponent( $component, $unsafe ) {
1942 $callback = function ( $matches ) use ( $unsafe ) {
1943 $char = urldecode( $matches[0] );
1944 $ord = ord( $char );
1945 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1949 # Leave it escaped, but use uppercase for a-f
1950 return strtoupper( $matches[0] );
1953 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1957 * make an image if it's allowed, either through the global
1958 * option, through the exception, or through the on-wiki whitelist
1960 * @param string $url
1964 private function maybeMakeExternalImage( $url ) {
1965 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1966 $imagesexception = !empty( $imagesfrom );
1968 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1969 if ( $imagesexception && is_array( $imagesfrom ) ) {
1970 $imagematch = false;
1971 foreach ( $imagesfrom as $match ) {
1972 if ( strpos( $url, $match ) === 0 ) {
1977 } elseif ( $imagesexception ) {
1978 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1980 $imagematch = false;
1983 if ( $this->mOptions
->getAllowExternalImages()
1984 ||
( $imagesexception && $imagematch )
1986 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1988 $text = Linker
::makeExternalImage( $url );
1991 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1992 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1994 $whitelist = explode(
1996 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1999 foreach ( $whitelist as $entry ) {
2000 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
2001 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
2004 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
2005 # Image matches a whitelist entry
2006 $text = Linker
::makeExternalImage( $url );
2015 * Process [[ ]] wikilinks
2019 * @return string Processed text
2023 public function replaceInternalLinks( $s ) {
2024 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2029 * Process [[ ]] wikilinks (RIL)
2031 * @throws MWException
2032 * @return LinkHolderArray
2036 public function replaceInternalLinks2( &$s ) {
2037 global $wgExtraInterlanguageLinkPrefixes;
2039 static $tc = false, $e1, $e1_img;
2040 # the % is needed to support urlencoded titles as well
2042 $tc = Title
::legalChars() . '#%';
2043 # Match a link having the form [[namespace:link|alternate]]trail
2044 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2045 # Match cases where there is no "]]", which might still be images
2046 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2049 $holders = new LinkHolderArray( $this );
2051 # split the entire text string on occurrences of [[
2052 $a = StringUtils
::explode( '[[', ' ' . $s );
2053 # get the first element (all text up to first [[), and remove the space we added
2056 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2057 $s = substr( $s, 1 );
2059 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2061 if ( $useLinkPrefixExtension ) {
2062 # Match the end of a line for a word that's not followed by whitespace,
2063 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2065 $charset = $wgContLang->linkPrefixCharset();
2066 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2069 if ( is_null( $this->mTitle
) ) {
2070 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2072 $nottalk = !$this->mTitle
->isTalkPage();
2074 if ( $useLinkPrefixExtension ) {
2076 if ( preg_match( $e2, $s, $m ) ) {
2077 $first_prefix = $m[2];
2079 $first_prefix = false;
2085 $useSubpages = $this->areSubpagesAllowed();
2087 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2088 # Loop for each link
2089 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2090 // @codingStandardsIgnoreStart
2092 # Check for excessive memory usage
2093 if ( $holders->isBig() ) {
2095 # Do the existence check, replace the link holders and clear the array
2096 $holders->replace( $s );
2100 if ( $useLinkPrefixExtension ) {
2101 if ( preg_match( $e2, $s, $m ) ) {
2108 if ( $first_prefix ) {
2109 $prefix = $first_prefix;
2110 $first_prefix = false;
2114 $might_be_img = false;
2116 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2118 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2119 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2120 # the real problem is with the $e1 regex
2123 # Still some problems for cases where the ] is meant to be outside punctuation,
2124 # and no image is in sight. See bug 2095.
2127 && substr( $m[3], 0, 1 ) === ']'
2128 && strpos( $text, '[' ) !== false
2130 $text .= ']'; # so that replaceExternalLinks($text) works later
2131 $m[3] = substr( $m[3], 1 );
2133 # fix up urlencoded title texts
2134 if ( strpos( $m[1], '%' ) !== false ) {
2135 # Should anchors '#' also be rejected?
2136 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2139 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2140 # Invalid, but might be an image with a link in its caption
2141 $might_be_img = true;
2143 if ( strpos( $m[1], '%' ) !== false ) {
2144 $m[1] = rawurldecode( $m[1] );
2147 } else { # Invalid form; output directly
2148 $s .= $prefix . '[[' . $line;
2154 # Don't allow internal links to pages containing
2155 # PROTO: where PROTO is a valid URL protocol; these
2156 # should be external links.
2157 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2158 $s .= $prefix . '[[' . $line;
2162 # Make subpage if necessary
2163 if ( $useSubpages ) {
2164 $link = $this->maybeDoSubpageLink( $origLink, $text );
2169 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2171 # Strip off leading ':'
2172 $link = substr( $link, 1 );
2175 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2176 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2177 if ( $nt === null ) {
2178 $s .= $prefix . '[[' . $line;
2182 $ns = $nt->getNamespace();
2183 $iw = $nt->getInterwiki();
2185 if ( $might_be_img ) { # if this is actually an invalid link
2186 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2189 # look at the next 'line' to see if we can close it there
2191 $next_line = $a->current();
2192 if ( $next_line === false ||
$next_line === null ) {
2195 $m = explode( ']]', $next_line, 3 );
2196 if ( count( $m ) == 3 ) {
2197 # the first ]] closes the inner link, the second the image
2199 $text .= "[[{$m[0]}]]{$m[1]}";
2202 } elseif ( count( $m ) == 2 ) {
2203 # if there's exactly one ]] that's fine, we'll keep looking
2204 $text .= "[[{$m[0]}]]{$m[1]}";
2206 # if $next_line is invalid too, we need look no further
2207 $text .= '[[' . $next_line;
2212 # we couldn't find the end of this imageLink, so output it raw
2213 # but don't ignore what might be perfectly normal links in the text we've examined
2214 $holders->merge( $this->replaceInternalLinks2( $text ) );
2215 $s .= "{$prefix}[[$link|$text";
2216 # note: no $trail, because without an end, there *is* no trail
2219 } else { # it's not an image, so output it raw
2220 $s .= "{$prefix}[[$link|$text";
2221 # note: no $trail, because without an end, there *is* no trail
2226 $wasblank = ( $text == '' );
2230 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2231 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2232 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2233 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2234 $text = $this->doQuotes( $text );
2237 # Link not escaped by : , create the various objects
2238 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2241 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2242 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2243 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2246 # Bug 24502: filter duplicates
2247 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2248 $this->mLangLinkLanguages
[$iw] = true;
2249 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2252 $s = rtrim( $s . $prefix );
2253 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2257 if ( $ns == NS_FILE
) {
2258 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2260 # if no parameters were passed, $text
2261 # becomes something like "File:Foo.png",
2262 # which we don't want to pass on to the
2266 # recursively parse links inside the image caption
2267 # actually, this will parse them in any other parameters, too,
2268 # but it might be hard to fix that, and it doesn't matter ATM
2269 $text = $this->replaceExternalLinks( $text );
2270 $holders->merge( $this->replaceInternalLinks2( $text ) );
2272 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2273 $s .= $prefix . $this->armorLinks(
2274 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2276 $s .= $prefix . $trail;
2281 if ( $ns == NS_CATEGORY
) {
2282 $s = rtrim( $s . "\n" ); # bug 87
2285 $sortkey = $this->getDefaultSort();
2289 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2290 $sortkey = str_replace( "\n", '', $sortkey );
2291 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2292 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2295 * Strip the whitespace Category links produce, see bug 87
2297 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2303 # Self-link checking. For some languages, variants of the title are checked in
2304 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2305 # for linking to a different variant.
2306 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2307 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2311 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2312 # @todo FIXME: Should do batch file existence checks, see comment below
2313 if ( $ns == NS_MEDIA
) {
2314 # Give extensions a chance to select the file revision for us
2317 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2318 array( $this, $nt, &$options, &$descQuery ) );
2319 # Fetch and register the file (file title may be different via hooks)
2320 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2321 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2322 $s .= $prefix . $this->armorLinks(
2323 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2327 # Some titles, such as valid special pages or files in foreign repos, should
2328 # be shown as bluelinks even though they're not included in the page table
2330 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2331 # batch file existence checks for NS_FILE and NS_MEDIA
2332 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2333 $this->mOutput
->addLink( $nt );
2334 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2336 # Links will be added to the output link list after checking
2337 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2344 * Render a forced-blue link inline; protect against double expansion of
2345 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2346 * Since this little disaster has to split off the trail text to avoid
2347 * breaking URLs in the following text without breaking trails on the
2348 * wiki links, it's been made into a horrible function.
2351 * @param string $text
2352 * @param array|string $query
2353 * @param string $trail
2354 * @param string $prefix
2355 * @return string HTML-wikitext mix oh yuck
2357 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2358 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2360 if ( is_string( $query ) ) {
2361 $query = wfCgiToArray( $query );
2363 if ( $text == '' ) {
2364 $text = htmlspecialchars( $nt->getPrefixedText() );
2367 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2369 return $this->armorLinks( $link ) . $trail;
2373 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2374 * going to go through further parsing steps before inline URL expansion.
2376 * Not needed quite as much as it used to be since free links are a bit
2377 * more sensible these days. But bracketed links are still an issue.
2379 * @param string $text More-or-less HTML
2380 * @return string Less-or-more HTML with NOPARSE bits
2382 public function armorLinks( $text ) {
2383 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2384 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2388 * Return true if subpage links should be expanded on this page.
2391 public function areSubpagesAllowed() {
2392 # Some namespaces don't allow subpages
2393 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2397 * Handle link to subpage if necessary
2399 * @param string $target The source of the link
2400 * @param string &$text The link text, modified as necessary
2401 * @return string The full name of the link
2404 public function maybeDoSubpageLink( $target, &$text ) {
2405 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2409 * Used by doBlockLevels()
2414 public function closeParagraph() {
2416 if ( $this->mLastSection
!= '' ) {
2417 $result = '</' . $this->mLastSection
. ">\n";
2419 $this->mInPre
= false;
2420 $this->mLastSection
= '';
2425 * getCommon() returns the length of the longest common substring
2426 * of both arguments, starting at the beginning of both.
2429 * @param string $st1
2430 * @param string $st2
2434 public function getCommon( $st1, $st2 ) {
2435 $fl = strlen( $st1 );
2436 $shorter = strlen( $st2 );
2437 if ( $fl < $shorter ) {
2441 for ( $i = 0; $i < $shorter; ++
$i ) {
2442 if ( $st1[$i] != $st2[$i] ) {
2450 * These next three functions open, continue, and close the list
2451 * element appropriate to the prefix character passed into them.
2454 * @param string $char
2458 public function openList( $char ) {
2459 $result = $this->closeParagraph();
2461 if ( '*' === $char ) {
2462 $result .= "<ul><li>";
2463 } elseif ( '#' === $char ) {
2464 $result .= "<ol><li>";
2465 } elseif ( ':' === $char ) {
2466 $result .= "<dl><dd>";
2467 } elseif ( ';' === $char ) {
2468 $result .= "<dl><dt>";
2469 $this->mDTopen
= true;
2471 $result = '<!-- ERR 1 -->';
2479 * @param string $char
2484 public function nextItem( $char ) {
2485 if ( '*' === $char ||
'#' === $char ) {
2486 return "</li>\n<li>";
2487 } elseif ( ':' === $char ||
';' === $char ) {
2489 if ( $this->mDTopen
) {
2492 if ( ';' === $char ) {
2493 $this->mDTopen
= true;
2494 return $close . '<dt>';
2496 $this->mDTopen
= false;
2497 return $close . '<dd>';
2500 return '<!-- ERR 2 -->';
2505 * @param string $char
2510 public function closeList( $char ) {
2511 if ( '*' === $char ) {
2512 $text = "</li></ul>";
2513 } elseif ( '#' === $char ) {
2514 $text = "</li></ol>";
2515 } elseif ( ':' === $char ) {
2516 if ( $this->mDTopen
) {
2517 $this->mDTopen
= false;
2518 $text = "</dt></dl>";
2520 $text = "</dd></dl>";
2523 return '<!-- ERR 3 -->';
2530 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2532 * @param string $text
2533 * @param bool $linestart Whether or not this is at the start of a line.
2535 * @return string The lists rendered as HTML
2537 public function doBlockLevels( $text, $linestart ) {
2539 # Parsing through the text line by line. The main thing
2540 # happening here is handling of block-level elements p, pre,
2541 # and making lists from lines starting with * # : etc.
2543 $textLines = StringUtils
::explode( "\n", $text );
2545 $lastPrefix = $output = '';
2546 $this->mDTopen
= $inBlockElem = false;
2548 $paragraphStack = false;
2549 $inBlockquote = false;
2551 foreach ( $textLines as $oLine ) {
2553 if ( !$linestart ) {
2563 $lastPrefixLength = strlen( $lastPrefix );
2564 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2565 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2566 # If not in a <pre> element, scan for and figure out what prefixes are there.
2567 if ( !$this->mInPre
) {
2568 # Multiple prefixes may abut each other for nested lists.
2569 $prefixLength = strspn( $oLine, '*#:;' );
2570 $prefix = substr( $oLine, 0, $prefixLength );
2573 # ; and : are both from definition-lists, so they're equivalent
2574 # for the purposes of determining whether or not we need to open/close
2576 $prefix2 = str_replace( ';', ':', $prefix );
2577 $t = substr( $oLine, $prefixLength );
2578 $this->mInPre
= (bool)$preOpenMatch;
2580 # Don't interpret any other prefixes in preformatted text
2582 $prefix = $prefix2 = '';
2587 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2588 # Same as the last item, so no need to deal with nesting or opening stuff
2589 $output .= $this->nextItem( substr( $prefix, -1 ) );
2590 $paragraphStack = false;
2592 if ( substr( $prefix, -1 ) === ';' ) {
2593 # The one nasty exception: definition lists work like this:
2594 # ; title : definition text
2595 # So we check for : in the remainder text to split up the
2596 # title and definition, without b0rking links.
2598 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2600 $output .= $term . $this->nextItem( ':' );
2603 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2604 # We need to open or close prefixes, or both.
2606 # Either open or close a level...
2607 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2608 $paragraphStack = false;
2610 # Close all the prefixes which aren't shared.
2611 while ( $commonPrefixLength < $lastPrefixLength ) {
2612 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2613 --$lastPrefixLength;
2616 # Continue the current prefix if appropriate.
2617 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2618 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2621 # Open prefixes where appropriate.
2622 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2625 while ( $prefixLength > $commonPrefixLength ) {
2626 $char = substr( $prefix, $commonPrefixLength, 1 );
2627 $output .= $this->openList( $char );
2629 if ( ';' === $char ) {
2630 # @todo FIXME: This is dupe of code above
2631 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2633 $output .= $term . $this->nextItem( ':' );
2636 ++
$commonPrefixLength;
2638 if ( !$prefixLength && $lastPrefix ) {
2641 $lastPrefix = $prefix2;
2644 # If we have no prefixes, go to paragraph mode.
2645 if ( 0 == $prefixLength ) {
2646 # No prefix (not in list)--go to paragraph mode
2647 # XXX: use a stack for nestable elements like span, table and div
2648 $openmatch = preg_match(
2649 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2650 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2653 $closematch = preg_match(
2654 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2655 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2656 . self
::MARKER_PREFIX
2657 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2661 if ( $openmatch ||
$closematch ) {
2662 $paragraphStack = false;
2663 # @todo bug 5718: paragraph closed
2664 $output .= $this->closeParagraph();
2665 if ( $preOpenMatch && !$preCloseMatch ) {
2666 $this->mInPre
= true;
2669 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2670 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2671 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2673 $inBlockElem = !$closematch;
2674 } elseif ( !$inBlockElem && !$this->mInPre
) {
2675 if ( ' ' == substr( $t, 0, 1 )
2676 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2680 if ( $this->mLastSection
!== 'pre' ) {
2681 $paragraphStack = false;
2682 $output .= $this->closeParagraph() . '<pre>';
2683 $this->mLastSection
= 'pre';
2685 $t = substr( $t, 1 );
2688 if ( trim( $t ) === '' ) {
2689 if ( $paragraphStack ) {
2690 $output .= $paragraphStack . '<br />';
2691 $paragraphStack = false;
2692 $this->mLastSection
= 'p';
2694 if ( $this->mLastSection
!== 'p' ) {
2695 $output .= $this->closeParagraph();
2696 $this->mLastSection
= '';
2697 $paragraphStack = '<p>';
2699 $paragraphStack = '</p><p>';
2703 if ( $paragraphStack ) {
2704 $output .= $paragraphStack;
2705 $paragraphStack = false;
2706 $this->mLastSection
= 'p';
2707 } elseif ( $this->mLastSection
!== 'p' ) {
2708 $output .= $this->closeParagraph() . '<p>';
2709 $this->mLastSection
= 'p';
2715 # somewhere above we forget to get out of pre block (bug 785)
2716 if ( $preCloseMatch && $this->mInPre
) {
2717 $this->mInPre
= false;
2719 if ( $paragraphStack === false ) {
2721 if ( $prefixLength === 0 ) {
2726 while ( $prefixLength ) {
2727 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2729 if ( !$prefixLength ) {
2733 if ( $this->mLastSection
!= '' ) {
2734 $output .= '</' . $this->mLastSection
. '>';
2735 $this->mLastSection
= '';
2742 * Split up a string on ':', ignoring any occurrences inside tags
2743 * to prevent illegal overlapping.
2745 * @param string $str The string to split
2746 * @param string &$before Set to everything before the ':'
2747 * @param string &$after Set to everything after the ':'
2748 * @throws MWException
2749 * @return string The position of the ':', or false if none found
2751 public function findColonNoLinks( $str, &$before, &$after ) {
2753 $pos = strpos( $str, ':' );
2754 if ( $pos === false ) {
2759 $lt = strpos( $str, '<' );
2760 if ( $lt === false ||
$lt > $pos ) {
2761 # Easy; no tag nesting to worry about
2762 $before = substr( $str, 0, $pos );
2763 $after = substr( $str, $pos +
1 );
2767 # Ugly state machine to walk through avoiding tags.
2768 $state = self
::COLON_STATE_TEXT
;
2770 $len = strlen( $str );
2771 for ( $i = 0; $i < $len; $i++
) {
2775 # (Using the number is a performance hack for common cases)
2776 case 0: # self::COLON_STATE_TEXT:
2779 # Could be either a <start> tag or an </end> tag
2780 $state = self
::COLON_STATE_TAGSTART
;
2783 if ( $stack == 0 ) {
2785 $before = substr( $str, 0, $i );
2786 $after = substr( $str, $i +
1 );
2789 # Embedded in a tag; don't break it.
2792 # Skip ahead looking for something interesting
2793 $colon = strpos( $str, ':', $i );
2794 if ( $colon === false ) {
2795 # Nothing else interesting
2798 $lt = strpos( $str, '<', $i );
2799 if ( $stack === 0 ) {
2800 if ( $lt === false ||
$colon < $lt ) {
2802 $before = substr( $str, 0, $colon );
2803 $after = substr( $str, $colon +
1 );
2807 if ( $lt === false ) {
2808 # Nothing else interesting to find; abort!
2809 # We're nested, but there's no close tags left. Abort!
2812 # Skip ahead to next tag start
2814 $state = self
::COLON_STATE_TAGSTART
;
2817 case 1: # self::COLON_STATE_TAG:
2822 $state = self
::COLON_STATE_TEXT
;
2825 # Slash may be followed by >?
2826 $state = self
::COLON_STATE_TAGSLASH
;
2832 case 2: # self::COLON_STATE_TAGSTART:
2835 $state = self
::COLON_STATE_CLOSETAG
;
2838 $state = self
::COLON_STATE_COMMENT
;
2841 # Illegal early close? This shouldn't happen D:
2842 $state = self
::COLON_STATE_TEXT
;
2845 $state = self
::COLON_STATE_TAG
;
2848 case 3: # self::COLON_STATE_CLOSETAG:
2853 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2856 $state = self
::COLON_STATE_TEXT
;
2859 case self
::COLON_STATE_TAGSLASH
:
2861 # Yes, a self-closed tag <blah/>
2862 $state = self
::COLON_STATE_TEXT
;
2864 # Probably we're jumping the gun, and this is an attribute
2865 $state = self
::COLON_STATE_TAG
;
2868 case 5: # self::COLON_STATE_COMMENT:
2870 $state = self
::COLON_STATE_COMMENTDASH
;
2873 case self
::COLON_STATE_COMMENTDASH
:
2875 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2877 $state = self
::COLON_STATE_COMMENT
;
2880 case self
::COLON_STATE_COMMENTDASHDASH
:
2882 $state = self
::COLON_STATE_TEXT
;
2884 $state = self
::COLON_STATE_COMMENT
;
2888 throw new MWException( "State machine error in " . __METHOD__
);
2892 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2899 * Return value of a magic variable (like PAGENAME)
2904 * @param bool|PPFrame $frame
2906 * @throws MWException
2909 public function getVariableValue( $index, $frame = false ) {
2910 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2911 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2913 if ( is_null( $this->mTitle
) ) {
2914 // If no title set, bad things are going to happen
2915 // later. Title should always be set since this
2916 // should only be called in the middle of a parse
2917 // operation (but the unit-tests do funky stuff)
2918 throw new MWException( __METHOD__
. ' Should only be '
2919 . ' called while parsing (no title set)' );
2923 * Some of these require message or data lookups and can be
2924 * expensive to check many times.
2926 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2927 if ( isset( $this->mVarCache
[$index] ) ) {
2928 return $this->mVarCache
[$index];
2932 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2933 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2935 $pageLang = $this->getFunctionLang();
2941 case 'currentmonth':
2942 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2944 case 'currentmonth1':
2945 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2947 case 'currentmonthname':
2948 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2950 case 'currentmonthnamegen':
2951 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2953 case 'currentmonthabbrev':
2954 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2957 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2960 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2963 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2966 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2968 case 'localmonthname':
2969 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2971 case 'localmonthnamegen':
2972 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2974 case 'localmonthabbrev':
2975 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2978 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2981 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2984 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2987 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2989 case 'fullpagename':
2990 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2992 case 'fullpagenamee':
2993 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2996 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2998 case 'subpagenamee':
2999 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3001 case 'rootpagename':
3002 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3004 case 'rootpagenamee':
3005 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3008 $this->mTitle
->getRootText()
3011 case 'basepagename':
3012 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3014 case 'basepagenamee':
3015 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3018 $this->mTitle
->getBaseText()
3021 case 'talkpagename':
3022 if ( $this->mTitle
->canTalk() ) {
3023 $talkPage = $this->mTitle
->getTalkPage();
3024 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3029 case 'talkpagenamee':
3030 if ( $this->mTitle
->canTalk() ) {
3031 $talkPage = $this->mTitle
->getTalkPage();
3032 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3037 case 'subjectpagename':
3038 $subjPage = $this->mTitle
->getSubjectPage();
3039 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3041 case 'subjectpagenamee':
3042 $subjPage = $this->mTitle
->getSubjectPage();
3043 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3045 case 'pageid': // requested in bug 23427
3046 $pageid = $this->getTitle()->getArticleID();
3047 if ( $pageid == 0 ) {
3048 # 0 means the page doesn't exist in the database,
3049 # which means the user is previewing a new page.
3050 # The vary-revision flag must be set, because the magic word
3051 # will have a different value once the page is saved.
3052 $this->mOutput
->setFlag( 'vary-revision' );
3053 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3055 $value = $pageid ?
$pageid : null;
3058 # Let the edit saving system know we should parse the page
3059 # *after* a revision ID has been assigned.
3060 $this->mOutput
->setFlag( 'vary-revision' );
3061 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3062 $value = $this->mRevisionId
;
3065 # Let the edit saving system know we should parse the page
3066 # *after* a revision ID has been assigned. This is for null edits.
3067 $this->mOutput
->setFlag( 'vary-revision' );
3068 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3069 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3071 case 'revisionday2':
3072 # Let the edit saving system know we should parse the page
3073 # *after* a revision ID has been assigned. This is for null edits.
3074 $this->mOutput
->setFlag( 'vary-revision' );
3075 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3076 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3078 case 'revisionmonth':
3079 # Let the edit saving system know we should parse the page
3080 # *after* a revision ID has been assigned. This is for null edits.
3081 $this->mOutput
->setFlag( 'vary-revision' );
3082 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3083 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3085 case 'revisionmonth1':
3086 # Let the edit saving system know we should parse the page
3087 # *after* a revision ID has been assigned. This is for null edits.
3088 $this->mOutput
->setFlag( 'vary-revision' );
3089 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3090 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3092 case 'revisionyear':
3093 # Let the edit saving system know we should parse the page
3094 # *after* a revision ID has been assigned. This is for null edits.
3095 $this->mOutput
->setFlag( 'vary-revision' );
3096 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3097 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3099 case 'revisiontimestamp':
3100 # Let the edit saving system know we should parse the page
3101 # *after* a revision ID has been assigned. This is for null edits.
3102 $this->mOutput
->setFlag( 'vary-revision' );
3103 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3104 $value = $this->getRevisionTimestamp();
3106 case 'revisionuser':
3107 # Let the edit saving system know we should parse the page
3108 # *after* a revision ID has been assigned. This is for null edits.
3109 $this->mOutput
->setFlag( 'vary-revision' );
3110 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3111 $value = $this->getRevisionUser();
3113 case 'revisionsize':
3114 # Let the edit saving system know we should parse the page
3115 # *after* a revision ID has been assigned. This is for null edits.
3116 $this->mOutput
->setFlag( 'vary-revision' );
3117 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3118 $value = $this->getRevisionSize();
3121 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3124 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3126 case 'namespacenumber':
3127 $value = $this->mTitle
->getNamespace();
3130 $value = $this->mTitle
->canTalk()
3131 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3135 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3137 case 'subjectspace':
3138 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3140 case 'subjectspacee':
3141 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3143 case 'currentdayname':
3144 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3147 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3150 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3153 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3156 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3157 # int to remove the padding
3158 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3161 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3163 case 'localdayname':
3164 $value = $pageLang->getWeekdayName(
3165 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3169 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3172 $value = $pageLang->time(
3173 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3179 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3182 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3183 # int to remove the padding
3184 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3187 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3189 case 'numberofarticles':
3190 $value = $pageLang->formatNum( SiteStats
::articles() );
3192 case 'numberoffiles':
3193 $value = $pageLang->formatNum( SiteStats
::images() );
3195 case 'numberofusers':
3196 $value = $pageLang->formatNum( SiteStats
::users() );
3198 case 'numberofactiveusers':
3199 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3201 case 'numberofpages':
3202 $value = $pageLang->formatNum( SiteStats
::pages() );
3204 case 'numberofadmins':
3205 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3207 case 'numberofedits':
3208 $value = $pageLang->formatNum( SiteStats
::edits() );
3210 case 'currenttimestamp':
3211 $value = wfTimestamp( TS_MW
, $ts );
3213 case 'localtimestamp':
3214 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3216 case 'currentversion':
3217 $value = SpecialVersion
::getVersion();
3220 return $wgArticlePath;
3226 return $wgServerName;
3228 return $wgScriptPath;
3230 return $wgStylePath;
3231 case 'directionmark':
3232 return $pageLang->getDirMark();
3233 case 'contentlanguage':
3234 global $wgLanguageCode;
3235 return $wgLanguageCode;
3236 case 'cascadingsources':
3237 $value = CoreParserFunctions
::cascadingsources( $this );
3242 'ParserGetVariableValueSwitch',
3243 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3250 $this->mVarCache
[$index] = $value;
3257 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3261 public function initialiseVariables() {
3262 $variableIDs = MagicWord
::getVariableIDs();
3263 $substIDs = MagicWord
::getSubstIDs();
3265 $this->mVariables
= new MagicWordArray( $variableIDs );
3266 $this->mSubstWords
= new MagicWordArray( $substIDs );
3270 * Preprocess some wikitext and return the document tree.
3271 * This is the ghost of replace_variables().
3273 * @param string $text The text to parse
3274 * @param int $flags Bitwise combination of:
3275 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3276 * included. Default is to assume a direct page view.
3278 * The generated DOM tree must depend only on the input text and the flags.
3279 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3281 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3282 * change in the DOM tree for a given text, must be passed through the section identifier
3283 * in the section edit link and thus back to extractSections().
3285 * The output of this function is currently only cached in process memory, but a persistent
3286 * cache may be implemented at a later date which takes further advantage of these strict
3287 * dependency requirements.
3291 public function preprocessToDom( $text, $flags = 0 ) {
3292 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3297 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3303 public static function splitWhitespace( $s ) {
3304 $ltrimmed = ltrim( $s );
3305 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3306 $trimmed = rtrim( $ltrimmed );
3307 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3309 $w2 = substr( $ltrimmed, -$diff );
3313 return array( $w1, $trimmed, $w2 );
3317 * Replace magic variables, templates, and template arguments
3318 * with the appropriate text. Templates are substituted recursively,
3319 * taking care to avoid infinite loops.
3321 * Note that the substitution depends on value of $mOutputType:
3322 * self::OT_WIKI: only {{subst:}} templates
3323 * self::OT_PREPROCESS: templates but not extension tags
3324 * self::OT_HTML: all templates and extension tags
3326 * @param string $text The text to transform
3327 * @param bool|PPFrame $frame Object describing the arguments passed to the
3328 * template. Arguments may also be provided as an associative array, as
3329 * was the usual case before MW1.12. Providing arguments this way may be
3330 * useful for extensions wishing to perform variable replacement
3332 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3333 * double-brace expansion.
3336 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3337 # Is there any text? Also, Prevent too big inclusions!
3338 $textSize = strlen( $text );
3339 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3343 if ( $frame === false ) {
3344 $frame = $this->getPreprocessor()->newFrame();
3345 } elseif ( !( $frame instanceof PPFrame
) ) {
3346 wfDebug( __METHOD__
. " called using plain parameters instead of "
3347 . "a PPFrame instance. Creating custom frame.\n" );
3348 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3351 $dom = $this->preprocessToDom( $text );
3352 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3353 $text = $frame->expand( $dom, $flags );
3359 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3361 * @param array $args
3365 public static function createAssocArgs( $args ) {
3366 $assocArgs = array();
3368 foreach ( $args as $arg ) {
3369 $eqpos = strpos( $arg, '=' );
3370 if ( $eqpos === false ) {
3371 $assocArgs[$index++
] = $arg;
3373 $name = trim( substr( $arg, 0, $eqpos ) );
3374 $value = trim( substr( $arg, $eqpos +
1 ) );
3375 if ( $value === false ) {
3378 if ( $name !== false ) {
3379 $assocArgs[$name] = $value;
3388 * Warn the user when a parser limitation is reached
3389 * Will warn at most once the user per limitation type
3391 * The results are shown during preview and run through the Parser (See EditPage.php)
3393 * @param string $limitationType Should be one of:
3394 * 'expensive-parserfunction' (corresponding messages:
3395 * 'expensive-parserfunction-warning',
3396 * 'expensive-parserfunction-category')
3397 * 'post-expand-template-argument' (corresponding messages:
3398 * 'post-expand-template-argument-warning',
3399 * 'post-expand-template-argument-category')
3400 * 'post-expand-template-inclusion' (corresponding messages:
3401 * 'post-expand-template-inclusion-warning',
3402 * 'post-expand-template-inclusion-category')
3403 * 'node-count-exceeded' (corresponding messages:
3404 * 'node-count-exceeded-warning',
3405 * 'node-count-exceeded-category')
3406 * 'expansion-depth-exceeded' (corresponding messages:
3407 * 'expansion-depth-exceeded-warning',
3408 * 'expansion-depth-exceeded-category')
3409 * @param string|int|null $current Current value
3410 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3411 * exceeded, provide the values (optional)
3413 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3414 # does no harm if $current and $max are present but are unnecessary for the message
3415 # Not doing ->inLanguage( $this->mOptions->getUserLangObj() ), since this is shown
3416 # only during preview, and that would split the parser cache unnecessarily.
3417 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3419 $this->mOutput
->addWarning( $warning );
3420 $this->addTrackingCategory( "$limitationType-category" );
3424 * Return the text of a template, after recursively
3425 * replacing any variables or templates within the template.
3427 * @param array $piece The parts of the template
3428 * $piece['title']: the title, i.e. the part before the |
3429 * $piece['parts']: the parameter array
3430 * $piece['lineStart']: whether the brace was at the start of a line
3431 * @param PPFrame $frame The current frame, contains template arguments
3433 * @return string The text of the template
3435 public function braceSubstitution( $piece, $frame ) {
3439 // $text has been filled
3441 // wiki markup in $text should be escaped
3443 // $text is HTML, armour it against wikitext transformation
3445 // Force interwiki transclusion to be done in raw mode not rendered
3446 $forceRawInterwiki = false;
3447 // $text is a DOM node needing expansion in a child frame
3448 $isChildObj = false;
3449 // $text is a DOM node needing expansion in the current frame
3450 $isLocalObj = false;
3452 # Title object, where $text came from
3455 # $part1 is the bit before the first |, and must contain only title characters.
3456 # Various prefixes will be stripped from it later.
3457 $titleWithSpaces = $frame->expand( $piece['title'] );
3458 $part1 = trim( $titleWithSpaces );
3461 # Original title text preserved for various purposes
3462 $originalTitle = $part1;
3464 # $args is a list of argument nodes, starting from index 0, not including $part1
3465 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3466 # below won't work b/c this $args isn't an object
3467 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3469 $profileSection = null; // profile templates
3473 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3475 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3476 # Decide whether to expand template or keep wikitext as-is.
3477 if ( $this->ot
['wiki'] ) {
3478 if ( $substMatch === false ) {
3479 $literal = true; # literal when in PST with no prefix
3481 $literal = false; # expand when in PST with subst: or safesubst:
3484 if ( $substMatch == 'subst' ) {
3485 $literal = true; # literal when not in PST with plain subst:
3487 $literal = false; # expand when not in PST with safesubst: or no prefix
3491 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3498 if ( !$found && $args->getLength() == 0 ) {
3499 $id = $this->mVariables
->matchStartToEnd( $part1 );
3500 if ( $id !== false ) {
3501 $text = $this->getVariableValue( $id, $frame );
3502 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3503 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3509 # MSG, MSGNW and RAW
3512 $mwMsgnw = MagicWord
::get( 'msgnw' );
3513 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3516 # Remove obsolete MSG:
3517 $mwMsg = MagicWord
::get( 'msg' );
3518 $mwMsg->matchStartAndRemove( $part1 );
3522 $mwRaw = MagicWord
::get( 'raw' );
3523 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3524 $forceRawInterwiki = true;
3530 $colonPos = strpos( $part1, ':' );
3531 if ( $colonPos !== false ) {
3532 $func = substr( $part1, 0, $colonPos );
3533 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3534 for ( $i = 0; $i < $args->getLength(); $i++
) {
3535 $funcArgs[] = $args->item( $i );
3538 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3539 } catch ( Exception
$ex ) {
3543 # The interface for parser functions allows for extracting
3544 # flags into the local scope. Extract any forwarded flags
3550 # Finish mangling title and then check for loops.
3551 # Set $title to a Title object and $titleText to the PDBK
3554 # Split the title into page and subpage
3556 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3557 if ( $part1 !== $relative ) {
3559 $ns = $this->mTitle
->getNamespace();
3561 $title = Title
::newFromText( $part1, $ns );
3563 $titleText = $title->getPrefixedText();
3564 # Check for language variants if the template is not found
3565 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3566 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3568 # Do recursion depth check
3569 $limit = $this->mOptions
->getMaxTemplateDepth();
3570 if ( $frame->depth
>= $limit ) {
3572 $text = '<span class="error">'
3573 . wfMessage( 'parser-template-recursion-depth-warning' )
3574 ->numParams( $limit )->inContentLanguage()->text()
3580 # Load from database
3581 if ( !$found && $title ) {
3582 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3583 if ( !$title->isExternal() ) {
3584 if ( $title->isSpecialPage()
3585 && $this->mOptions
->getAllowSpecialInclusion()
3586 && $this->ot
['html']
3588 // Pass the template arguments as URL parameters.
3589 // "uselang" will have no effect since the Language object
3590 // is forced to the one defined in ParserOptions.
3591 $pageArgs = array();
3592 $argsLength = $args->getLength();
3593 for ( $i = 0; $i < $argsLength; $i++
) {
3594 $bits = $args->item( $i )->splitArg();
3595 if ( strval( $bits['index'] ) === '' ) {
3596 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3597 $value = trim( $frame->expand( $bits['value'] ) );
3598 $pageArgs[$name] = $value;
3602 // Create a new context to execute the special page
3603 $context = new RequestContext
;
3604 $context->setTitle( $title );
3605 $context->setRequest( new FauxRequest( $pageArgs ) );
3606 $context->setUser( $this->getUser() );
3607 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3608 $ret = SpecialPageFactory
::capturePath( $title, $context );
3610 $text = $context->getOutput()->getHTML();
3611 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3614 $this->disableCache();
3616 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3617 $found = false; # access denied
3618 wfDebug( __METHOD__
. ": template inclusion denied for " .
3619 $title->getPrefixedDBkey() . "\n" );
3621 list( $text, $title ) = $this->getTemplateDom( $title );
3622 if ( $text !== false ) {
3628 # If the title is valid but undisplayable, make a link to it
3629 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3630 $text = "[[:$titleText]]";
3633 } elseif ( $title->isTrans() ) {
3634 # Interwiki transclusion
3635 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3636 $text = $this->interwikiTransclude( $title, 'render' );
3639 $text = $this->interwikiTransclude( $title, 'raw' );
3640 # Preprocess it like a template
3641 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3647 # Do infinite loop check
3648 # This has to be done after redirect resolution to avoid infinite loops via redirects
3649 if ( !$frame->loopCheck( $title ) ) {
3651 $text = '<span class="error">'
3652 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3654 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3658 # If we haven't found text to substitute by now, we're done
3659 # Recover the source wikitext and return it
3661 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3662 if ( $profileSection ) {
3663 $this->mProfiler
->scopedProfileOut( $profileSection );
3665 return array( 'object' => $text );
3668 # Expand DOM-style return values in a child frame
3669 if ( $isChildObj ) {
3670 # Clean up argument array
3671 $newFrame = $frame->newChild( $args, $title );
3674 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3675 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3676 # Expansion is eligible for the empty-frame cache
3677 $text = $newFrame->cachedExpand( $titleText, $text );
3679 # Uncached expansion
3680 $text = $newFrame->expand( $text );
3683 if ( $isLocalObj && $nowiki ) {
3684 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3685 $isLocalObj = false;
3688 if ( $profileSection ) {
3689 $this->mProfiler
->scopedProfileOut( $profileSection );
3692 # Replace raw HTML by a placeholder
3694 $text = $this->insertStripItem( $text );
3695 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3696 # Escape nowiki-style return values
3697 $text = wfEscapeWikiText( $text );
3698 } elseif ( is_string( $text )
3699 && !$piece['lineStart']
3700 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3702 # Bug 529: if the template begins with a table or block-level
3703 # element, it should be treated as beginning a new line.
3704 # This behavior is somewhat controversial.
3705 $text = "\n" . $text;
3708 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3709 # Error, oversize inclusion
3710 if ( $titleText !== false ) {
3711 # Make a working, properly escaped link if possible (bug 23588)
3712 $text = "[[:$titleText]]";
3714 # This will probably not be a working link, but at least it may
3715 # provide some hint of where the problem is
3716 preg_replace( '/^:/', '', $originalTitle );
3717 $text = "[[:$originalTitle]]";
3719 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3720 . 'post-expand include size too large -->' );
3721 $this->limitationWarn( 'post-expand-template-inclusion' );
3724 if ( $isLocalObj ) {
3725 $ret = array( 'object' => $text );
3727 $ret = array( 'text' => $text );
3734 * Call a parser function and return an array with text and flags.
3736 * The returned array will always contain a boolean 'found', indicating
3737 * whether the parser function was found or not. It may also contain the
3739 * text: string|object, resulting wikitext or PP DOM object
3740 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3741 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3742 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3743 * nowiki: bool, wiki markup in $text should be escaped
3746 * @param PPFrame $frame The current frame, contains template arguments
3747 * @param string $function Function name
3748 * @param array $args Arguments to the function
3749 * @throws MWException
3752 public function callParserFunction( $frame, $function, array $args = array() ) {
3755 # Case sensitive functions
3756 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3757 $function = $this->mFunctionSynonyms
[1][$function];
3759 # Case insensitive functions
3760 $function = $wgContLang->lc( $function );
3761 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3762 $function = $this->mFunctionSynonyms
[0][$function];
3764 return array( 'found' => false );
3768 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3770 # Workaround for PHP bug 35229 and similar
3771 if ( !is_callable( $callback ) ) {
3772 throw new MWException( "Tag hook for $function is not callable\n" );
3775 $allArgs = array( &$this );
3776 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3777 # Convert arguments to PPNodes and collect for appending to $allArgs
3778 $funcArgs = array();
3779 foreach ( $args as $k => $v ) {
3780 if ( $v instanceof PPNode ||
$k === 0 ) {
3783 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3787 # Add a frame parameter, and pass the arguments as an array
3788 $allArgs[] = $frame;
3789 $allArgs[] = $funcArgs;
3791 # Convert arguments to plain text and append to $allArgs
3792 foreach ( $args as $k => $v ) {
3793 if ( $v instanceof PPNode
) {
3794 $allArgs[] = trim( $frame->expand( $v ) );
3795 } elseif ( is_int( $k ) && $k >= 0 ) {
3796 $allArgs[] = trim( $v );
3798 $allArgs[] = trim( "$k=$v" );
3803 $result = call_user_func_array( $callback, $allArgs );
3805 # The interface for function hooks allows them to return a wikitext
3806 # string or an array containing the string and any flags. This mungs
3807 # things around to match what this method should return.
3808 if ( !is_array( $result ) ) {
3814 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3815 $result['text'] = $result[0];
3817 unset( $result[0] );
3824 $preprocessFlags = 0;
3825 if ( isset( $result['noparse'] ) ) {
3826 $noparse = $result['noparse'];
3828 if ( isset( $result['preprocessFlags'] ) ) {
3829 $preprocessFlags = $result['preprocessFlags'];
3833 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3834 $result['isChildObj'] = true;
3841 * Get the semi-parsed DOM representation of a template with a given title,
3842 * and its redirect destination title. Cached.
3844 * @param Title $title
3848 public function getTemplateDom( $title ) {
3849 $cacheTitle = $title;
3850 $titleText = $title->getPrefixedDBkey();
3852 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3853 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3854 $title = Title
::makeTitle( $ns, $dbk );
3855 $titleText = $title->getPrefixedDBkey();
3857 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3858 return array( $this->mTplDomCache
[$titleText], $title );
3861 # Cache miss, go to the database
3862 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3864 if ( $text === false ) {
3865 $this->mTplDomCache
[$titleText] = false;
3866 return array( false, $title );
3869 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3870 $this->mTplDomCache
[$titleText] = $dom;
3872 if ( !$title->equals( $cacheTitle ) ) {
3873 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3874 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3877 return array( $dom, $title );
3881 * Fetch the current revision of a given title. Note that the revision
3882 * (and even the title) may not exist in the database, so everything
3883 * contributing to the output of the parser should use this method
3884 * where possible, rather than getting the revisions themselves. This
3885 * method also caches its results, so using it benefits performance.
3888 * @param Title $title
3891 public function fetchCurrentRevisionOfTitle( $title ) {
3892 $cacheKey = $title->getPrefixedDBkey();
3893 if ( !$this->currentRevisionCache
) {
3894 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3896 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3897 $this->currentRevisionCache
->set( $cacheKey,
3898 // Defaults to Parser::statelessFetchRevision()
3899 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3902 return $this->currentRevisionCache
->get( $cacheKey );
3906 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3907 * without passing them on to it.
3910 * @param Title $title
3911 * @param Parser|bool $parser
3914 public static function statelessFetchRevision( $title, $parser = false ) {
3915 return Revision
::newFromTitle( $title );
3919 * Fetch the unparsed text of a template and register a reference to it.
3920 * @param Title $title
3921 * @return array ( string or false, Title )
3923 public function fetchTemplateAndTitle( $title ) {
3924 // Defaults to Parser::statelessFetchTemplate()
3925 $templateCb = $this->mOptions
->getTemplateCallback();
3926 $stuff = call_user_func( $templateCb, $title, $this );
3927 // We use U+007F DELETE to distinguish strip markers from regular text.
3928 $text = $stuff['text'];
3929 if ( is_string( $stuff['text'] ) ) {
3930 $text = strtr( $text, "\x7f", "?" );
3932 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3933 if ( isset( $stuff['deps'] ) ) {
3934 foreach ( $stuff['deps'] as $dep ) {
3935 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3936 if ( $dep['title']->equals( $this->getTitle() ) ) {
3937 // If we transclude ourselves, the final result
3938 // will change based on the new version of the page
3939 $this->mOutput
->setFlag( 'vary-revision' );
3943 return array( $text, $finalTitle );
3947 * Fetch the unparsed text of a template and register a reference to it.
3948 * @param Title $title
3949 * @return string|bool
3951 public function fetchTemplate( $title ) {
3952 $rv = $this->fetchTemplateAndTitle( $title );
3957 * Static function to get a template
3958 * Can be overridden via ParserOptions::setTemplateCallback().
3960 * @param Title $title
3961 * @param bool|Parser $parser
3965 public static function statelessFetchTemplate( $title, $parser = false ) {
3966 $text = $skip = false;
3967 $finalTitle = $title;
3970 # Loop to fetch the article, with up to 1 redirect
3971 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3972 # Give extensions a chance to select the revision instead
3973 $id = false; # Assume current
3974 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3975 array( $parser, $title, &$skip, &$id ) );
3981 'page_id' => $title->getArticleID(),
3988 $rev = Revision
::newFromId( $id );
3989 } elseif ( $parser ) {
3990 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3992 $rev = Revision
::newFromTitle( $title );
3994 $rev_id = $rev ?
$rev->getId() : 0;
3995 # If there is no current revision, there is no page
3996 if ( $id === false && !$rev ) {
3997 $linkCache = LinkCache
::singleton();
3998 $linkCache->addBadLinkObj( $title );
4003 'page_id' => $title->getArticleID(),
4004 'rev_id' => $rev_id );
4005 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4006 # We fetched a rev from a different title; register it too...
4008 'title' => $rev->getTitle(),
4009 'page_id' => $rev->getPage(),
4010 'rev_id' => $rev_id );
4014 $content = $rev->getContent();
4015 $text = $content ?
$content->getWikitextForTransclusion() : null;
4017 if ( $text === false ||
$text === null ) {
4021 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4023 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4024 if ( !$message->exists() ) {
4028 $content = $message->content();
4029 $text = $message->plain();
4037 $finalTitle = $title;
4038 $title = $content->getRedirectTarget();
4042 'finalTitle' => $finalTitle,
4047 * Fetch a file and its title and register a reference to it.
4048 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4049 * @param Title $title
4050 * @param array $options Array of options to RepoGroup::findFile
4053 public function fetchFile( $title, $options = array() ) {
4054 $res = $this->fetchFileAndTitle( $title, $options );
4059 * Fetch a file and its title and register a reference to it.
4060 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4061 * @param Title $title
4062 * @param array $options Array of options to RepoGroup::findFile
4063 * @return array ( File or false, Title of file )
4065 public function fetchFileAndTitle( $title, $options = array() ) {
4066 $file = $this->fetchFileNoRegister( $title, $options );
4068 $time = $file ?
$file->getTimestamp() : false;
4069 $sha1 = $file ?
$file->getSha1() : false;
4070 # Register the file as a dependency...
4071 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4072 if ( $file && !$title->equals( $file->getTitle() ) ) {
4073 # Update fetched file title
4074 $title = $file->getTitle();
4075 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4077 return array( $file, $title );
4081 * Helper function for fetchFileAndTitle.
4083 * Also useful if you need to fetch a file but not use it yet,
4084 * for example to get the file's handler.
4086 * @param Title $title
4087 * @param array $options Array of options to RepoGroup::findFile
4090 protected function fetchFileNoRegister( $title, $options = array() ) {
4091 if ( isset( $options['broken'] ) ) {
4092 $file = false; // broken thumbnail forced by hook
4093 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4094 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4095 } else { // get by (name,timestamp)
4096 $file = wfFindFile( $title, $options );
4102 * Transclude an interwiki link.
4104 * @param Title $title
4105 * @param string $action
4109 public function interwikiTransclude( $title, $action ) {
4110 global $wgEnableScaryTranscluding;
4112 if ( !$wgEnableScaryTranscluding ) {
4113 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4116 $url = $title->getFullURL( array( 'action' => $action ) );
4118 if ( strlen( $url ) > 255 ) {
4119 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4121 return $this->fetchScaryTemplateMaybeFromCache( $url );
4125 * @param string $url
4126 * @return mixed|string
4128 public function fetchScaryTemplateMaybeFromCache( $url ) {
4129 global $wgTranscludeCacheExpiry;
4130 $dbr = wfGetDB( DB_SLAVE
);
4131 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4132 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4133 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4135 return $obj->tc_contents
;
4138 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4139 $status = $req->execute(); // Status object
4140 if ( $status->isOK() ) {
4141 $text = $req->getContent();
4142 } elseif ( $req->getStatus() != 200 ) {
4143 // Though we failed to fetch the content, this status is useless.
4144 return wfMessage( 'scarytranscludefailed-httpstatus' )
4145 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4147 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4150 $dbw = wfGetDB( DB_MASTER
);
4151 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4153 'tc_time' => $dbw->timestamp( time() ),
4154 'tc_contents' => $text
4160 * Triple brace replacement -- used for template arguments
4163 * @param array $piece
4164 * @param PPFrame $frame
4168 public function argSubstitution( $piece, $frame ) {
4171 $parts = $piece['parts'];
4172 $nameWithSpaces = $frame->expand( $piece['title'] );
4173 $argName = trim( $nameWithSpaces );
4175 $text = $frame->getArgument( $argName );
4176 if ( $text === false && $parts->getLength() > 0
4177 && ( $this->ot
['html']
4179 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4182 # No match in frame, use the supplied default
4183 $object = $parts->item( 0 )->getChildren();
4185 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4186 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4187 $this->limitationWarn( 'post-expand-template-argument' );
4190 if ( $text === false && $object === false ) {
4192 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4194 if ( $error !== false ) {
4197 if ( $object !== false ) {
4198 $ret = array( 'object' => $object );
4200 $ret = array( 'text' => $text );
4207 * Return the text to be used for a given extension tag.
4208 * This is the ghost of strip().
4210 * @param array $params Associative array of parameters:
4211 * name PPNode for the tag name
4212 * attr PPNode for unparsed text where tag attributes are thought to be
4213 * attributes Optional associative array of parsed attributes
4214 * inner Contents of extension element
4215 * noClose Original text did not have a close tag
4216 * @param PPFrame $frame
4218 * @throws MWException
4221 public function extensionSubstitution( $params, $frame ) {
4222 $name = $frame->expand( $params['name'] );
4223 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4224 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4225 $marker = self
::MARKER_PREFIX
. "-$name-"
4226 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4228 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4229 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4230 if ( $isFunctionTag ) {
4231 $markerType = 'none';
4233 $markerType = 'general';
4235 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4236 $name = strtolower( $name );
4237 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4238 if ( isset( $params['attributes'] ) ) {
4239 $attributes = $attributes +
$params['attributes'];
4242 if ( isset( $this->mTagHooks
[$name] ) ) {
4243 # Workaround for PHP bug 35229 and similar
4244 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4245 throw new MWException( "Tag hook for $name is not callable\n" );
4247 $output = call_user_func_array( $this->mTagHooks
[$name],
4248 array( $content, $attributes, $this, $frame ) );
4249 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4250 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4251 if ( !is_callable( $callback ) ) {
4252 throw new MWException( "Tag hook for $name is not callable\n" );
4255 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4257 $output = '<span class="error">Invalid tag extension name: ' .
4258 htmlspecialchars( $name ) . '</span>';
4261 if ( is_array( $output ) ) {
4262 # Extract flags to local scope (to override $markerType)
4264 $output = $flags[0];
4269 if ( is_null( $attrText ) ) {
4272 if ( isset( $params['attributes'] ) ) {
4273 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4274 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4275 htmlspecialchars( $attrValue ) . '"';
4278 if ( $content === null ) {
4279 $output = "<$name$attrText/>";
4281 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4282 $output = "<$name$attrText>$content$close";
4286 if ( $markerType === 'none' ) {
4288 } elseif ( $markerType === 'nowiki' ) {
4289 $this->mStripState
->addNoWiki( $marker, $output );
4290 } elseif ( $markerType === 'general' ) {
4291 $this->mStripState
->addGeneral( $marker, $output );
4293 throw new MWException( __METHOD__
. ': invalid marker type' );
4299 * Increment an include size counter
4301 * @param string $type The type of expansion
4302 * @param int $size The size of the text
4303 * @return bool False if this inclusion would take it over the maximum, true otherwise
4305 public function incrementIncludeSize( $type, $size ) {
4306 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4309 $this->mIncludeSizes
[$type] +
= $size;
4315 * Increment the expensive function count
4317 * @return bool False if the limit has been exceeded
4319 public function incrementExpensiveFunctionCount() {
4320 $this->mExpensiveFunctionCount++
;
4321 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4325 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4326 * Fills $this->mDoubleUnderscores, returns the modified text
4328 * @param string $text
4332 public function doDoubleUnderscore( $text ) {
4334 # The position of __TOC__ needs to be recorded
4335 $mw = MagicWord
::get( 'toc' );
4336 if ( $mw->match( $text ) ) {
4337 $this->mShowToc
= true;
4338 $this->mForceTocPosition
= true;
4340 # Set a placeholder. At the end we'll fill it in with the TOC.
4341 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4343 # Only keep the first one.
4344 $text = $mw->replace( '', $text );
4347 # Now match and remove the rest of them
4348 $mwa = MagicWord
::getDoubleUnderscoreArray();
4349 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4351 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4352 $this->mOutput
->mNoGallery
= true;
4354 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4355 $this->mShowToc
= false;
4357 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4358 && $this->mTitle
->getNamespace() == NS_CATEGORY
4360 $this->addTrackingCategory( 'hidden-category-category' );
4362 # (bug 8068) Allow control over whether robots index a page.
4364 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4365 # is not desirable, the last one on the page should win.
4366 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4367 $this->mOutput
->setIndexPolicy( 'noindex' );
4368 $this->addTrackingCategory( 'noindex-category' );
4370 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4371 $this->mOutput
->setIndexPolicy( 'index' );
4372 $this->addTrackingCategory( 'index-category' );
4375 # Cache all double underscores in the database
4376 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4377 $this->mOutput
->setProperty( $key, '' );
4384 * @see ParserOutput::addTrackingCategory()
4385 * @param string $msg Message key
4386 * @return bool Whether the addition was successful
4388 public function addTrackingCategory( $msg ) {
4389 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4393 * This function accomplishes several tasks:
4394 * 1) Auto-number headings if that option is enabled
4395 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4396 * 3) Add a Table of contents on the top for users who have enabled the option
4397 * 4) Auto-anchor headings
4399 * It loops through all headlines, collects the necessary data, then splits up the
4400 * string and re-inserts the newly formatted headlines.
4402 * @param string $text
4403 * @param string $origText Original, untouched wikitext
4404 * @param bool $isMain
4405 * @return mixed|string
4408 public function formatHeadings( $text, $origText, $isMain = true ) {
4409 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4411 # Inhibit editsection links if requested in the page
4412 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4413 $maybeShowEditLink = $showEditLink = false;
4415 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4416 $showEditLink = $this->mOptions
->getEditSection();
4418 if ( $showEditLink ) {
4419 $this->mOutput
->setEditSectionTokens( true );
4422 # Get all headlines for numbering them and adding funky stuff like [edit]
4423 # links - this is for later, but we need the number of headlines right now
4425 $numMatches = preg_match_all(
4426 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4431 # if there are fewer than 4 headlines in the article, do not show TOC
4432 # unless it's been explicitly enabled.
4433 $enoughToc = $this->mShowToc
&&
4434 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4436 # Allow user to stipulate that a page should have a "new section"
4437 # link added via __NEWSECTIONLINK__
4438 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4439 $this->mOutput
->setNewSection( true );
4442 # Allow user to remove the "new section"
4443 # link via __NONEWSECTIONLINK__
4444 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4445 $this->mOutput
->hideNewSection( true );
4448 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4449 # override above conditions and always show TOC above first header
4450 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4451 $this->mShowToc
= true;
4459 # Ugh .. the TOC should have neat indentation levels which can be
4460 # passed to the skin functions. These are determined here
4464 $sublevelCount = array();
4465 $levelCount = array();
4470 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4471 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4472 $oldType = $this->mOutputType
;
4473 $this->setOutputType( self
::OT_WIKI
);
4474 $frame = $this->getPreprocessor()->newFrame();
4475 $root = $this->preprocessToDom( $origText );
4476 $node = $root->getFirstChild();
4481 $headlines = $numMatches !== false ?
$matches[3] : array();
4483 foreach ( $headlines as $headline ) {
4484 $isTemplate = false;
4486 $sectionIndex = false;
4488 $markerMatches = array();
4489 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4490 $serial = $markerMatches[1];
4491 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4492 $isTemplate = ( $titleText != $baseTitleText );
4493 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4497 $prevlevel = $level;
4499 $level = $matches[1][$headlineCount];
4501 if ( $level > $prevlevel ) {
4502 # Increase TOC level
4504 $sublevelCount[$toclevel] = 0;
4505 if ( $toclevel < $wgMaxTocLevel ) {
4506 $prevtoclevel = $toclevel;
4507 $toc .= Linker
::tocIndent();
4510 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4511 # Decrease TOC level, find level to jump to
4513 for ( $i = $toclevel; $i > 0; $i-- ) {
4514 if ( $levelCount[$i] == $level ) {
4515 # Found last matching level
4518 } elseif ( $levelCount[$i] < $level ) {
4519 # Found first matching level below current level
4527 if ( $toclevel < $wgMaxTocLevel ) {
4528 if ( $prevtoclevel < $wgMaxTocLevel ) {
4529 # Unindent only if the previous toc level was shown :p
4530 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4531 $prevtoclevel = $toclevel;
4533 $toc .= Linker
::tocLineEnd();
4537 # No change in level, end TOC line
4538 if ( $toclevel < $wgMaxTocLevel ) {
4539 $toc .= Linker
::tocLineEnd();
4543 $levelCount[$toclevel] = $level;
4545 # count number of headlines for each level
4546 $sublevelCount[$toclevel]++
;
4548 for ( $i = 1; $i <= $toclevel; $i++
) {
4549 if ( !empty( $sublevelCount[$i] ) ) {
4553 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4558 # The safe header is a version of the header text safe to use for links
4560 # Remove link placeholders by the link text.
4561 # <!--LINK number-->
4563 # link text with suffix
4564 # Do this before unstrip since link text can contain strip markers
4565 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4567 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4568 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4570 # Strip out HTML (first regex removes any tag not allowed)
4572 # * <sup> and <sub> (bug 8393)
4575 # * <bdi> (bug 72884)
4576 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4578 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4579 # to allow setting directionality in toc items.
4580 $tocline = preg_replace(
4582 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4583 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4585 array( '', '<$1>' ),
4589 # Strip '<span></span>', which is the result from the above if
4590 # <span id="foo"></span> is used to produce an additional anchor
4592 $tocline = str_replace( '<span></span>', '', $tocline );
4594 $tocline = trim( $tocline );
4596 # For the anchor, strip out HTML-y stuff period
4597 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4598 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4600 # Save headline for section edit hint before it's escaped
4601 $headlineHint = $safeHeadline;
4603 if ( $wgExperimentalHtmlIds ) {
4604 # For reverse compatibility, provide an id that's
4605 # HTML4-compatible, like we used to.
4607 # It may be worth noting, academically, that it's possible for
4608 # the legacy anchor to conflict with a non-legacy headline
4609 # anchor on the page. In this case likely the "correct" thing
4610 # would be to either drop the legacy anchors or make sure
4611 # they're numbered first. However, this would require people
4612 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4613 # manually, so let's not bother worrying about it.
4614 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4615 array( 'noninitial', 'legacy' ) );
4616 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4618 if ( $legacyHeadline == $safeHeadline ) {
4619 # No reason to have both (in fact, we can't)
4620 $legacyHeadline = false;
4623 $legacyHeadline = false;
4624 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4628 # HTML names must be case-insensitively unique (bug 10721).
4629 # This does not apply to Unicode characters per
4630 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4631 # @todo FIXME: We may be changing them depending on the current locale.
4632 $arrayKey = strtolower( $safeHeadline );
4633 if ( $legacyHeadline === false ) {
4634 $legacyArrayKey = false;
4636 $legacyArrayKey = strtolower( $legacyHeadline );
4639 # Create the anchor for linking from the TOC to the section
4640 $anchor = $safeHeadline;
4641 $legacyAnchor = $legacyHeadline;
4642 if ( isset( $refers[$arrayKey] ) ) {
4643 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4645 $refers["${arrayKey}_$i"] = true;
4647 $refers[$arrayKey] = true;
4649 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4650 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4651 $legacyAnchor .= "_$i";
4652 $refers["${legacyArrayKey}_$i"] = true;
4654 $refers[$legacyArrayKey] = true;
4657 # Don't number the heading if it is the only one (looks silly)
4658 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4659 # the two are different if the line contains a link
4660 $headline = Html
::element(
4662 array( 'class' => 'mw-headline-number' ),
4664 ) . ' ' . $headline;
4667 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4668 $toc .= Linker
::tocLine( $anchor, $tocline,
4669 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4672 # Add the section to the section tree
4673 # Find the DOM node for this header
4674 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4675 while ( $node && !$noOffset ) {
4676 if ( $node->getName() === 'h' ) {
4677 $bits = $node->splitHeading();
4678 if ( $bits['i'] == $sectionIndex ) {
4682 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4683 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4684 $node = $node->getNextSibling();
4687 'toclevel' => $toclevel,
4690 'number' => $numbering,
4691 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4692 'fromtitle' => $titleText,
4693 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4694 'anchor' => $anchor,
4697 # give headline the correct <h#> tag
4698 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4699 // Output edit section links as markers with styles that can be customized by skins
4700 if ( $isTemplate ) {
4701 # Put a T flag in the section identifier, to indicate to extractSections()
4702 # that sections inside <includeonly> should be counted.
4703 $editsectionPage = $titleText;
4704 $editsectionSection = "T-$sectionIndex";
4705 $editsectionContent = null;
4707 $editsectionPage = $this->mTitle
->getPrefixedText();
4708 $editsectionSection = $sectionIndex;
4709 $editsectionContent = $headlineHint;
4711 // We use a bit of pesudo-xml for editsection markers. The
4712 // language converter is run later on. Using a UNIQ style marker
4713 // leads to the converter screwing up the tokens when it
4714 // converts stuff. And trying to insert strip tags fails too. At
4715 // this point all real inputted tags have already been escaped,
4716 // so we don't have to worry about a user trying to input one of
4717 // these markers directly. We use a page and section attribute
4718 // to stop the language converter from converting these
4719 // important bits of data, but put the headline hint inside a
4720 // content block because the language converter is supposed to
4721 // be able to convert that piece of data.
4722 // Gets replaced with html in ParserOutput::getText
4723 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4724 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4725 if ( $editsectionContent !== null ) {
4726 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4733 $head[$headlineCount] = Linker
::makeHeadline( $level,
4734 $matches['attrib'][$headlineCount], $anchor, $headline,
4735 $editlink, $legacyAnchor );
4740 $this->setOutputType( $oldType );
4742 # Never ever show TOC if no headers
4743 if ( $numVisible < 1 ) {
4748 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4749 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4751 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4752 $this->mOutput
->setTOCHTML( $toc );
4753 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4754 $this->mOutput
->addModules( 'mediawiki.toc' );
4758 $this->mOutput
->setSections( $tocraw );
4761 # split up and insert constructed headlines
4762 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4765 // build an array of document sections
4766 $sections = array();
4767 foreach ( $blocks as $block ) {
4768 // $head is zero-based, sections aren't.
4769 if ( empty( $head[$i - 1] ) ) {
4770 $sections[$i] = $block;
4772 $sections[$i] = $head[$i - 1] . $block;
4776 * Send a hook, one per section.
4777 * The idea here is to be able to make section-level DIVs, but to do so in a
4778 * lower-impact, more correct way than r50769
4781 * $section : the section number
4782 * &$sectionContent : ref to the content of the section
4783 * $showEditLinks : boolean describing whether this section has an edit link
4785 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4790 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4791 // append the TOC at the beginning
4792 // Top anchor now in skin
4793 $sections[0] = $sections[0] . $toc . "\n";
4796 $full .= join( '', $sections );
4798 if ( $this->mForceTocPosition
) {
4799 return str_replace( '<!--MWTOC-->', $toc, $full );
4806 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4807 * conversion, substituting signatures, {{subst:}} templates, etc.
4809 * @param string $text The text to transform
4810 * @param Title $title The Title object for the current article
4811 * @param User $user The User object describing the current user
4812 * @param ParserOptions $options Parsing options
4813 * @param bool $clearState Whether to clear the parser state first
4814 * @return string The altered wiki markup
4816 public function preSaveTransform( $text, Title
$title, User
$user,
4817 ParserOptions
$options, $clearState = true
4819 if ( $clearState ) {
4820 $magicScopeVariable = $this->lock();
4822 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4823 $this->setUser( $user );
4829 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4830 if ( $options->getPreSaveTransform() ) {
4831 $text = $this->pstPass2( $text, $user );
4833 $text = $this->mStripState
->unstripBoth( $text );
4835 $this->setUser( null ); #Reset
4841 * Pre-save transform helper function
4843 * @param string $text
4848 private function pstPass2( $text, $user ) {
4851 # Note: This is the timestamp saved as hardcoded wikitext to
4852 # the database, we use $wgContLang here in order to give
4853 # everyone the same signature and use the default one rather
4854 # than the one selected in each user's preferences.
4855 # (see also bug 12815)
4856 $ts = $this->mOptions
->getTimestamp();
4857 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4858 $ts = $timestamp->format( 'YmdHis' );
4859 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4861 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4863 # Variable replacement
4864 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4865 $text = $this->replaceVariables( $text );
4867 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4868 # which may corrupt this parser instance via its wfMessage()->text() call-
4871 $sigText = $this->getUserSig( $user );
4872 $text = strtr( $text, array(
4874 '~~~~' => "$sigText $d",
4878 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4879 $tc = '[' . Title
::legalChars() . ']';
4880 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4882 // [[ns:page (context)|]]
4883 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4884 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4885 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4886 // [[ns:page (context), context|]] (using either single or double-width comma)
4887 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4888 // [[|page]] (reverse pipe trick: add context from page title)
4889 $p2 = "/\[\[\\|($tc+)]]/";
4891 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4892 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4893 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4894 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4896 $t = $this->mTitle
->getText();
4898 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4899 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4900 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4901 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4903 # if there's no context, don't bother duplicating the title
4904 $text = preg_replace( $p2, '[[\\1]]', $text );
4907 # Trim trailing whitespace
4908 $text = rtrim( $text );
4914 * Fetch the user's signature text, if any, and normalize to
4915 * validated, ready-to-insert wikitext.
4916 * If you have pre-fetched the nickname or the fancySig option, you can
4917 * specify them here to save a database query.
4918 * Do not reuse this parser instance after calling getUserSig(),
4919 * as it may have changed if it's the $wgParser.
4922 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4923 * @param bool|null $fancySig whether the nicknname is the complete signature
4924 * or null to use default value
4927 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4928 global $wgMaxSigChars;
4930 $username = $user->getName();
4932 # If not given, retrieve from the user object.
4933 if ( $nickname === false ) {
4934 $nickname = $user->getOption( 'nickname' );
4937 if ( is_null( $fancySig ) ) {
4938 $fancySig = $user->getBoolOption( 'fancysig' );
4941 $nickname = $nickname == null ?
$username : $nickname;
4943 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4944 $nickname = $username;
4945 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4946 } elseif ( $fancySig !== false ) {
4947 # Sig. might contain markup; validate this
4948 if ( $this->validateSig( $nickname ) !== false ) {
4949 # Validated; clean up (if needed) and return it
4950 return $this->cleanSig( $nickname, true );
4952 # Failed to validate; fall back to the default
4953 $nickname = $username;
4954 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4958 # Make sure nickname doesnt get a sig in a sig
4959 $nickname = self
::cleanSigInSig( $nickname );
4961 # If we're still here, make it a link to the user page
4962 $userText = wfEscapeWikiText( $username );
4963 $nickText = wfEscapeWikiText( $nickname );
4964 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4966 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4967 ->title( $this->getTitle() )->text();
4971 * Check that the user's signature contains no bad XML
4973 * @param string $text
4974 * @return string|bool An expanded string, or false if invalid.
4976 public function validateSig( $text ) {
4977 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4981 * Clean up signature text
4983 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4984 * 2) Substitute all transclusions
4986 * @param string $text
4987 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4988 * @return string Signature text
4990 public function cleanSig( $text, $parsing = false ) {
4993 $magicScopeVariable = $this->lock();
4994 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4997 # Option to disable this feature
4998 if ( !$this->mOptions
->getCleanSignatures() ) {
5002 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5003 # => Move this logic to braceSubstitution()
5004 $substWord = MagicWord
::get( 'subst' );
5005 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5006 $substText = '{{' . $substWord->getSynonym( 0 );
5008 $text = preg_replace( $substRegex, $substText, $text );
5009 $text = self
::cleanSigInSig( $text );
5010 $dom = $this->preprocessToDom( $text );
5011 $frame = $this->getPreprocessor()->newFrame();
5012 $text = $frame->expand( $dom );
5015 $text = $this->mStripState
->unstripBoth( $text );
5022 * Strip 3, 4 or 5 tildes out of signatures.
5024 * @param string $text
5025 * @return string Signature text with /~{3,5}/ removed
5027 public static function cleanSigInSig( $text ) {
5028 $text = preg_replace( '/~{3,5}/', '', $text );
5033 * Set up some variables which are usually set up in parse()
5034 * so that an external function can call some class members with confidence
5036 * @param Title|null $title
5037 * @param ParserOptions $options
5038 * @param int $outputType
5039 * @param bool $clearState
5041 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5042 $outputType, $clearState = true
5044 $this->startParse( $title, $options, $outputType, $clearState );
5048 * @param Title|null $title
5049 * @param ParserOptions $options
5050 * @param int $outputType
5051 * @param bool $clearState
5053 private function startParse( Title
$title = null, ParserOptions
$options,
5054 $outputType, $clearState = true
5056 $this->setTitle( $title );
5057 $this->mOptions
= $options;
5058 $this->setOutputType( $outputType );
5059 if ( $clearState ) {
5060 $this->clearState();
5065 * Wrapper for preprocess()
5067 * @param string $text The text to preprocess
5068 * @param ParserOptions $options Options
5069 * @param Title|null $title Title object or null to use $wgTitle
5072 public function transformMsg( $text, $options, $title = null ) {
5073 static $executing = false;
5075 # Guard against infinite recursion
5086 $text = $this->preprocess( $text, $title, $options );
5093 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5094 * The callback should have the following form:
5095 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5097 * Transform and return $text. Use $parser for any required context, e.g. use
5098 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5100 * Hooks may return extended information by returning an array, of which the
5101 * first numbered element (index 0) must be the return string, and all other
5102 * entries are extracted into local variables within an internal function
5103 * in the Parser class.
5105 * This interface (introduced r61913) appears to be undocumented, but
5106 * 'markerType' is used by some core tag hooks to override which strip
5107 * array their results are placed in. **Use great caution if attempting
5108 * this interface, as it is not documented and injudicious use could smash
5109 * private variables.**
5111 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5112 * @param callable $callback The callback function (and object) to use for the tag
5113 * @throws MWException
5114 * @return callable|null The old value of the mTagHooks array associated with the hook
5116 public function setHook( $tag, $callback ) {
5117 $tag = strtolower( $tag );
5118 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5119 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5121 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5122 $this->mTagHooks
[$tag] = $callback;
5123 if ( !in_array( $tag, $this->mStripList
) ) {
5124 $this->mStripList
[] = $tag;
5131 * As setHook(), but letting the contents be parsed.
5133 * Transparent tag hooks are like regular XML-style tag hooks, except they
5134 * operate late in the transformation sequence, on HTML instead of wikitext.
5136 * This is probably obsoleted by things dealing with parser frames?
5137 * The only extension currently using it is geoserver.
5140 * @todo better document or deprecate this
5142 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5143 * @param callable $callback The callback function (and object) to use for the tag
5144 * @throws MWException
5145 * @return callable|null The old value of the mTagHooks array associated with the hook
5147 public function setTransparentTagHook( $tag, $callback ) {
5148 $tag = strtolower( $tag );
5149 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5150 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5152 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5153 $this->mTransparentTagHooks
[$tag] = $callback;
5159 * Remove all tag hooks
5161 public function clearTagHooks() {
5162 $this->mTagHooks
= array();
5163 $this->mFunctionTagHooks
= array();
5164 $this->mStripList
= $this->mDefaultStripList
;
5168 * Create a function, e.g. {{sum:1|2|3}}
5169 * The callback function should have the form:
5170 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5172 * Or with Parser::SFH_OBJECT_ARGS:
5173 * function myParserFunction( $parser, $frame, $args ) { ... }
5175 * The callback may either return the text result of the function, or an array with the text
5176 * in element 0, and a number of flags in the other elements. The names of the flags are
5177 * specified in the keys. Valid flags are:
5178 * found The text returned is valid, stop processing the template. This
5180 * nowiki Wiki markup in the return value should be escaped
5181 * isHTML The returned text is HTML, armour it against wikitext transformation
5183 * @param string $id The magic word ID
5184 * @param callable $callback The callback function (and object) to use
5185 * @param int $flags A combination of the following flags:
5186 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5188 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5189 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5190 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5191 * the arguments, and to control the way they are expanded.
5193 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5194 * arguments, for instance:
5195 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5197 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5198 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5199 * working if/when this is changed.
5201 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5204 * Please read the documentation in includes/parser/Preprocessor.php for more information
5205 * about the methods available in PPFrame and PPNode.
5207 * @throws MWException
5208 * @return string|callable The old callback function for this name, if any
5210 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5213 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5214 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5216 # Add to function cache
5217 $mw = MagicWord
::get( $id );
5219 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5222 $synonyms = $mw->getSynonyms();
5223 $sensitive = intval( $mw->isCaseSensitive() );
5225 foreach ( $synonyms as $syn ) {
5227 if ( !$sensitive ) {
5228 $syn = $wgContLang->lc( $syn );
5231 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5234 # Remove trailing colon
5235 if ( substr( $syn, -1, 1 ) === ':' ) {
5236 $syn = substr( $syn, 0, -1 );
5238 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5244 * Get all registered function hook identifiers
5248 public function getFunctionHooks() {
5249 return array_keys( $this->mFunctionHooks
);
5253 * Create a tag function, e.g. "<test>some stuff</test>".
5254 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5255 * Unlike parser functions, their content is not preprocessed.
5256 * @param string $tag
5257 * @param callable $callback
5259 * @throws MWException
5262 public function setFunctionTagHook( $tag, $callback, $flags ) {
5263 $tag = strtolower( $tag );
5264 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5265 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5267 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5268 $this->mFunctionTagHooks
[$tag] : null;
5269 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5271 if ( !in_array( $tag, $this->mStripList
) ) {
5272 $this->mStripList
[] = $tag;
5279 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5280 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5281 * Placeholders created in Skin::makeLinkObj()
5283 * @param string $text
5284 * @param int $options
5286 public function replaceLinkHolders( &$text, $options = 0 ) {
5287 $this->mLinkHolders
->replace( $text );
5291 * Replace "<!--LINK-->" link placeholders with plain text of links
5292 * (not HTML-formatted).
5294 * @param string $text
5297 public function replaceLinkHoldersText( $text ) {
5298 return $this->mLinkHolders
->replaceText( $text );
5302 * Renders an image gallery from a text with one line per image.
5303 * text labels may be given by using |-style alternative text. E.g.
5304 * Image:one.jpg|The number "1"
5305 * Image:tree.jpg|A tree
5306 * given as text will return the HTML of a gallery with two images,
5307 * labeled 'The number "1"' and
5310 * @param string $text
5311 * @param array $params
5312 * @return string HTML
5314 public function renderImageGallery( $text, $params ) {
5317 if ( isset( $params['mode'] ) ) {
5318 $mode = $params['mode'];
5322 $ig = ImageGalleryBase
::factory( $mode );
5323 } catch ( Exception
$e ) {
5324 // If invalid type set, fallback to default.
5325 $ig = ImageGalleryBase
::factory( false );
5328 $ig->setContextTitle( $this->mTitle
);
5329 $ig->setShowBytes( false );
5330 $ig->setShowFilename( false );
5331 $ig->setParser( $this );
5332 $ig->setHideBadImages();
5333 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5335 if ( isset( $params['showfilename'] ) ) {
5336 $ig->setShowFilename( true );
5338 $ig->setShowFilename( false );
5340 if ( isset( $params['caption'] ) ) {
5341 $caption = $params['caption'];
5342 $caption = htmlspecialchars( $caption );
5343 $caption = $this->replaceInternalLinks( $caption );
5344 $ig->setCaptionHtml( $caption );
5346 if ( isset( $params['perrow'] ) ) {
5347 $ig->setPerRow( $params['perrow'] );
5349 if ( isset( $params['widths'] ) ) {
5350 $ig->setWidths( $params['widths'] );
5352 if ( isset( $params['heights'] ) ) {
5353 $ig->setHeights( $params['heights'] );
5355 $ig->setAdditionalOptions( $params );
5357 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5359 $lines = StringUtils
::explode( "\n", $text );
5360 foreach ( $lines as $line ) {
5361 # match lines like these:
5362 # Image:someimage.jpg|This is some image
5364 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5366 if ( count( $matches ) == 0 ) {
5370 if ( strpos( $matches[0], '%' ) !== false ) {
5371 $matches[1] = rawurldecode( $matches[1] );
5373 $title = Title
::newFromText( $matches[1], NS_FILE
);
5374 if ( is_null( $title ) ) {
5375 # Bogus title. Ignore these so we don't bomb out later.
5379 # We need to get what handler the file uses, to figure out parameters.
5380 # Note, a hook can overide the file name, and chose an entirely different
5381 # file (which potentially could be of a different type and have different handler).
5384 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5385 array( $this, $title, &$options, &$descQuery ) );
5386 # Don't register it now, as ImageGallery does that later.
5387 $file = $this->fetchFileNoRegister( $title, $options );
5388 $handler = $file ?
$file->getHandler() : false;
5391 'img_alt' => 'gallery-internal-alt',
5392 'img_link' => 'gallery-internal-link',
5395 $paramMap = $paramMap +
$handler->getParamMap();
5396 // We don't want people to specify per-image widths.
5397 // Additionally the width parameter would need special casing anyhow.
5398 unset( $paramMap['img_width'] );
5401 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5406 $handlerOptions = array();
5407 if ( isset( $matches[3] ) ) {
5408 // look for an |alt= definition while trying not to break existing
5409 // captions with multiple pipes (|) in it, until a more sensible grammar
5410 // is defined for images in galleries
5412 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5413 // splitting on '|' is a bit odd, and different from makeImage.
5414 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5415 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5417 foreach ( $parameterMatches as $parameterMatch ) {
5418 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5420 $paramName = $paramMap[$magicName];
5422 switch ( $paramName ) {
5423 case 'gallery-internal-alt':
5424 $alt = $this->stripAltText( $match, false );
5426 case 'gallery-internal-link':
5427 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5428 $chars = self
::EXT_LINK_URL_CLASS
;
5429 $addr = self
::EXT_LINK_ADDR
;
5430 $prots = $this->mUrlProtocols
;
5431 //check to see if link matches an absolute url, if not then it must be a wiki link.
5432 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5435 $localLinkTitle = Title
::newFromText( $linkValue );
5436 if ( $localLinkTitle !== null ) {
5437 $link = $localLinkTitle->getLinkURL();
5442 // Must be a handler specific parameter.
5443 if ( $handler->validateParam( $paramName, $match ) ) {
5444 $handlerOptions[$paramName] = $match;
5446 // Guess not. Append it to the caption.
5447 wfDebug( "$parameterMatch failed parameter validation\n" );
5448 $label .= '|' . $parameterMatch;
5453 // concatenate all other pipes
5454 $label .= '|' . $parameterMatch;
5457 // remove the first pipe
5458 $label = substr( $label, 1 );
5461 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5463 $html = $ig->toHTML();
5464 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5469 * @param MediaHandler $handler
5472 public function getImageParams( $handler ) {
5474 $handlerClass = get_class( $handler );
5478 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5479 # Initialise static lists
5480 static $internalParamNames = array(
5481 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5482 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5483 'bottom', 'text-bottom' ),
5484 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5485 'upright', 'border', 'link', 'alt', 'class' ),
5487 static $internalParamMap;
5488 if ( !$internalParamMap ) {
5489 $internalParamMap = array();
5490 foreach ( $internalParamNames as $type => $names ) {
5491 foreach ( $names as $name ) {
5492 $magicName = str_replace( '-', '_', "img_$name" );
5493 $internalParamMap[$magicName] = array( $type, $name );
5498 # Add handler params
5499 $paramMap = $internalParamMap;
5501 $handlerParamMap = $handler->getParamMap();
5502 foreach ( $handlerParamMap as $magic => $paramName ) {
5503 $paramMap[$magic] = array( 'handler', $paramName );
5506 $this->mImageParams
[$handlerClass] = $paramMap;
5507 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5509 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5513 * Parse image options text and use it to make an image
5515 * @param Title $title
5516 * @param string $options
5517 * @param LinkHolderArray|bool $holders
5518 * @return string HTML
5520 public function makeImage( $title, $options, $holders = false ) {
5521 # Check if the options text is of the form "options|alt text"
5523 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5524 # * left no resizing, just left align. label is used for alt= only
5525 # * right same, but right aligned
5526 # * none same, but not aligned
5527 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5528 # * center center the image
5529 # * frame Keep original image size, no magnify-button.
5530 # * framed Same as "frame"
5531 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5532 # * upright reduce width for upright images, rounded to full __0 px
5533 # * border draw a 1px border around the image
5534 # * alt Text for HTML alt attribute (defaults to empty)
5535 # * class Set a class for img node
5536 # * link Set the target of the image link. Can be external, interwiki, or local
5537 # vertical-align values (no % or length right now):
5547 $parts = StringUtils
::explode( "|", $options );
5549 # Give extensions a chance to select the file revision for us
5552 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5553 array( $this, $title, &$options, &$descQuery ) );
5554 # Fetch and register the file (file title may be different via hooks)
5555 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5558 $handler = $file ?
$file->getHandler() : false;
5560 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5563 $this->addTrackingCategory( 'broken-file-category' );
5566 # Process the input parameters
5568 $params = array( 'frame' => array(), 'handler' => array(),
5569 'horizAlign' => array(), 'vertAlign' => array() );
5570 $seenformat = false;
5571 foreach ( $parts as $part ) {
5572 $part = trim( $part );
5573 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5575 if ( isset( $paramMap[$magicName] ) ) {
5576 list( $type, $paramName ) = $paramMap[$magicName];
5578 # Special case; width and height come in one variable together
5579 if ( $type === 'handler' && $paramName === 'width' ) {
5580 $parsedWidthParam = $this->parseWidthParam( $value );
5581 if ( isset( $parsedWidthParam['width'] ) ) {
5582 $width = $parsedWidthParam['width'];
5583 if ( $handler->validateParam( 'width', $width ) ) {
5584 $params[$type]['width'] = $width;
5588 if ( isset( $parsedWidthParam['height'] ) ) {
5589 $height = $parsedWidthParam['height'];
5590 if ( $handler->validateParam( 'height', $height ) ) {
5591 $params[$type]['height'] = $height;
5595 # else no validation -- bug 13436
5597 if ( $type === 'handler' ) {
5598 # Validate handler parameter
5599 $validated = $handler->validateParam( $paramName, $value );
5601 # Validate internal parameters
5602 switch ( $paramName ) {
5606 # @todo FIXME: Possibly check validity here for
5607 # manualthumb? downstream behavior seems odd with
5608 # missing manual thumbs.
5610 $value = $this->stripAltText( $value, $holders );
5613 $chars = self
::EXT_LINK_URL_CLASS
;
5614 $addr = self
::EXT_LINK_ADDR
;
5615 $prots = $this->mUrlProtocols
;
5616 if ( $value === '' ) {
5617 $paramName = 'no-link';
5620 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5621 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5622 $paramName = 'link-url';
5623 $this->mOutput
->addExternalLink( $value );
5624 if ( $this->mOptions
->getExternalLinkTarget() ) {
5625 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5630 $linkTitle = Title
::newFromText( $value );
5632 $paramName = 'link-title';
5633 $value = $linkTitle;
5634 $this->mOutput
->addLink( $linkTitle );
5642 // use first appearing option, discard others.
5643 $validated = ! $seenformat;
5647 # Most other things appear to be empty or numeric...
5648 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5653 $params[$type][$paramName] = $value;
5657 if ( !$validated ) {
5662 # Process alignment parameters
5663 if ( $params['horizAlign'] ) {
5664 $params['frame']['align'] = key( $params['horizAlign'] );
5666 if ( $params['vertAlign'] ) {
5667 $params['frame']['valign'] = key( $params['vertAlign'] );
5670 $params['frame']['caption'] = $caption;
5672 # Will the image be presented in a frame, with the caption below?
5673 $imageIsFramed = isset( $params['frame']['frame'] )
5674 ||
isset( $params['frame']['framed'] )
5675 ||
isset( $params['frame']['thumbnail'] )
5676 ||
isset( $params['frame']['manualthumb'] );
5678 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5679 # came to also set the caption, ordinary text after the image -- which
5680 # makes no sense, because that just repeats the text multiple times in
5681 # screen readers. It *also* came to set the title attribute.
5683 # Now that we have an alt attribute, we should not set the alt text to
5684 # equal the caption: that's worse than useless, it just repeats the
5685 # text. This is the framed/thumbnail case. If there's no caption, we
5686 # use the unnamed parameter for alt text as well, just for the time be-
5687 # ing, if the unnamed param is set and the alt param is not.
5689 # For the future, we need to figure out if we want to tweak this more,
5690 # e.g., introducing a title= parameter for the title; ignoring the un-
5691 # named parameter entirely for images without a caption; adding an ex-
5692 # plicit caption= parameter and preserving the old magic unnamed para-
5694 if ( $imageIsFramed ) { # Framed image
5695 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5696 # No caption or alt text, add the filename as the alt text so
5697 # that screen readers at least get some description of the image
5698 $params['frame']['alt'] = $title->getText();
5700 # Do not set $params['frame']['title'] because tooltips don't make sense
5702 } else { # Inline image
5703 if ( !isset( $params['frame']['alt'] ) ) {
5704 # No alt text, use the "caption" for the alt text
5705 if ( $caption !== '' ) {
5706 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5708 # No caption, fall back to using the filename for the
5710 $params['frame']['alt'] = $title->getText();
5713 # Use the "caption" for the tooltip text
5714 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5717 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5719 # Linker does the rest
5720 $time = isset( $options['time'] ) ?
$options['time'] : false;
5721 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5722 $time, $descQuery, $this->mOptions
->getThumbSize() );
5724 # Give the handler a chance to modify the parser object
5726 $handler->parserTransformHook( $this, $file );
5733 * @param string $caption
5734 * @param LinkHolderArray|bool $holders
5735 * @return mixed|string
5737 protected function stripAltText( $caption, $holders ) {
5738 # Strip bad stuff out of the title (tooltip). We can't just use
5739 # replaceLinkHoldersText() here, because if this function is called
5740 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5742 $tooltip = $holders->replaceText( $caption );
5744 $tooltip = $this->replaceLinkHoldersText( $caption );
5747 # make sure there are no placeholders in thumbnail attributes
5748 # that are later expanded to html- so expand them now and
5750 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5751 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5757 * Set a flag in the output object indicating that the content is dynamic and
5758 * shouldn't be cached.
5760 public function disableCache() {
5761 wfDebug( "Parser output marked as uncacheable.\n" );
5762 if ( !$this->mOutput
) {
5763 throw new MWException( __METHOD__
.
5764 " can only be called when actually parsing something" );
5766 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5770 * Callback from the Sanitizer for expanding items found in HTML attribute
5771 * values, so they can be safely tested and escaped.
5773 * @param string $text
5774 * @param bool|PPFrame $frame
5777 public function attributeStripCallback( &$text, $frame = false ) {
5778 $text = $this->replaceVariables( $text, $frame );
5779 $text = $this->mStripState
->unstripBoth( $text );
5788 public function getTags() {
5790 array_keys( $this->mTransparentTagHooks
),
5791 array_keys( $this->mTagHooks
),
5792 array_keys( $this->mFunctionTagHooks
)
5797 * Replace transparent tags in $text with the values given by the callbacks.
5799 * Transparent tag hooks are like regular XML-style tag hooks, except they
5800 * operate late in the transformation sequence, on HTML instead of wikitext.
5802 * @param string $text
5806 public function replaceTransparentTags( $text ) {
5808 $elements = array_keys( $this->mTransparentTagHooks
);
5809 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5810 $replacements = array();
5812 foreach ( $matches as $marker => $data ) {
5813 list( $element, $content, $params, $tag ) = $data;
5814 $tagName = strtolower( $element );
5815 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5816 $output = call_user_func_array(
5817 $this->mTransparentTagHooks
[$tagName],
5818 array( $content, $params, $this )
5823 $replacements[$marker] = $output;
5825 return strtr( $text, $replacements );
5829 * Break wikitext input into sections, and either pull or replace
5830 * some particular section's text.
5832 * External callers should use the getSection and replaceSection methods.
5834 * @param string $text Page wikitext
5835 * @param string|number $sectionId A section identifier string of the form:
5836 * "<flag1> - <flag2> - ... - <section number>"
5838 * Currently the only recognised flag is "T", which means the target section number
5839 * was derived during a template inclusion parse, in other words this is a template
5840 * section edit link. If no flags are given, it was an ordinary section edit link.
5841 * This flag is required to avoid a section numbering mismatch when a section is
5842 * enclosed by "<includeonly>" (bug 6563).
5844 * The section number 0 pulls the text before the first heading; other numbers will
5845 * pull the given section along with its lower-level subsections. If the section is
5846 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5848 * Section 0 is always considered to exist, even if it only contains the empty
5849 * string. If $text is the empty string and section 0 is replaced, $newText is
5852 * @param string $mode One of "get" or "replace"
5853 * @param string $newText Replacement text for section data.
5854 * @return string For "get", the extracted section text.
5855 * for "replace", the whole page with the section replaced.
5857 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5858 global $wgTitle; # not generally used but removes an ugly failure mode
5860 $magicScopeVariable = $this->lock();
5861 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5863 $frame = $this->getPreprocessor()->newFrame();
5865 # Process section extraction flags
5867 $sectionParts = explode( '-', $sectionId );
5868 $sectionIndex = array_pop( $sectionParts );
5869 foreach ( $sectionParts as $part ) {
5870 if ( $part === 'T' ) {
5871 $flags |
= self
::PTD_FOR_INCLUSION
;
5875 # Check for empty input
5876 if ( strval( $text ) === '' ) {
5877 # Only sections 0 and T-0 exist in an empty document
5878 if ( $sectionIndex == 0 ) {
5879 if ( $mode === 'get' ) {
5885 if ( $mode === 'get' ) {
5893 # Preprocess the text
5894 $root = $this->preprocessToDom( $text, $flags );
5896 # <h> nodes indicate section breaks
5897 # They can only occur at the top level, so we can find them by iterating the root's children
5898 $node = $root->getFirstChild();
5900 # Find the target section
5901 if ( $sectionIndex == 0 ) {
5902 # Section zero doesn't nest, level=big
5903 $targetLevel = 1000;
5906 if ( $node->getName() === 'h' ) {
5907 $bits = $node->splitHeading();
5908 if ( $bits['i'] == $sectionIndex ) {
5909 $targetLevel = $bits['level'];
5913 if ( $mode === 'replace' ) {
5914 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5916 $node = $node->getNextSibling();
5922 if ( $mode === 'get' ) {
5929 # Find the end of the section, including nested sections
5931 if ( $node->getName() === 'h' ) {
5932 $bits = $node->splitHeading();
5933 $curLevel = $bits['level'];
5934 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5938 if ( $mode === 'get' ) {
5939 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5941 $node = $node->getNextSibling();
5944 # Write out the remainder (in replace mode only)
5945 if ( $mode === 'replace' ) {
5946 # Output the replacement text
5947 # Add two newlines on -- trailing whitespace in $newText is conventionally
5948 # stripped by the editor, so we need both newlines to restore the paragraph gap
5949 # Only add trailing whitespace if there is newText
5950 if ( $newText != "" ) {
5951 $outText .= $newText . "\n\n";
5955 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5956 $node = $node->getNextSibling();
5960 if ( is_string( $outText ) ) {
5961 # Re-insert stripped tags
5962 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5969 * This function returns the text of a section, specified by a number ($section).
5970 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5971 * the first section before any such heading (section 0).
5973 * If a section contains subsections, these are also returned.
5975 * @param string $text Text to look in
5976 * @param string|number $sectionId Section identifier as a number or string
5977 * (e.g. 0, 1 or 'T-1').
5978 * @param string $defaultText Default to return if section is not found
5980 * @return string Text of the requested section
5982 public function getSection( $text, $sectionId, $defaultText = '' ) {
5983 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5987 * This function returns $oldtext after the content of the section
5988 * specified by $section has been replaced with $text. If the target
5989 * section does not exist, $oldtext is returned unchanged.
5991 * @param string $oldText Former text of the article
5992 * @param string|number $sectionId Section identifier as a number or string
5993 * (e.g. 0, 1 or 'T-1').
5994 * @param string $newText Replacing text
5996 * @return string Modified text
5998 public function replaceSection( $oldText, $sectionId, $newText ) {
5999 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6003 * Get the ID of the revision we are parsing
6007 public function getRevisionId() {
6008 return $this->mRevisionId
;
6012 * Get the revision object for $this->mRevisionId
6014 * @return Revision|null Either a Revision object or null
6015 * @since 1.23 (public since 1.23)
6017 public function getRevisionObject() {
6018 if ( !is_null( $this->mRevisionObject
) ) {
6019 return $this->mRevisionObject
;
6021 if ( is_null( $this->mRevisionId
) ) {
6025 $rev = call_user_func(
6026 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
6029 # If the parse is for a new revision, then the callback should have
6030 # already been set to force the object and should match mRevisionId.
6031 # If not, try to fetch by mRevisionId for sanity.
6032 if ( $rev && $rev->getId() != $this->mRevisionId
) {
6033 $rev = Revision
::newFromId( $this->mRevisionId
);
6036 $this->mRevisionObject
= $rev;
6038 return $this->mRevisionObject
;
6042 * Get the timestamp associated with the current revision, adjusted for
6043 * the default server-local timestamp
6046 public function getRevisionTimestamp() {
6047 if ( is_null( $this->mRevisionTimestamp
) ) {
6050 $revObject = $this->getRevisionObject();
6051 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6053 # The cryptic '' timezone parameter tells to use the site-default
6054 # timezone offset instead of the user settings.
6056 # Since this value will be saved into the parser cache, served
6057 # to other users, and potentially even used inside links and such,
6058 # it needs to be consistent for all visitors.
6059 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6062 return $this->mRevisionTimestamp
;
6066 * Get the name of the user that edited the last revision
6068 * @return string User name
6070 public function getRevisionUser() {
6071 if ( is_null( $this->mRevisionUser
) ) {
6072 $revObject = $this->getRevisionObject();
6074 # if this template is subst: the revision id will be blank,
6075 # so just use the current user's name
6077 $this->mRevisionUser
= $revObject->getUserText();
6078 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6079 $this->mRevisionUser
= $this->getUser()->getName();
6082 return $this->mRevisionUser
;
6086 * Get the size of the revision
6088 * @return int|null Revision size
6090 public function getRevisionSize() {
6091 if ( is_null( $this->mRevisionSize
) ) {
6092 $revObject = $this->getRevisionObject();
6094 # if this variable is subst: the revision id will be blank,
6095 # so just use the parser input size, because the own substituation
6096 # will change the size.
6098 $this->mRevisionSize
= $revObject->getSize();
6099 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6100 $this->mRevisionSize
= $this->mInputSize
;
6103 return $this->mRevisionSize
;
6107 * Mutator for $mDefaultSort
6109 * @param string $sort New value
6111 public function setDefaultSort( $sort ) {
6112 $this->mDefaultSort
= $sort;
6113 $this->mOutput
->setProperty( 'defaultsort', $sort );
6117 * Accessor for $mDefaultSort
6118 * Will use the empty string if none is set.
6120 * This value is treated as a prefix, so the
6121 * empty string is equivalent to sorting by
6126 public function getDefaultSort() {
6127 if ( $this->mDefaultSort
!== false ) {
6128 return $this->mDefaultSort
;
6135 * Accessor for $mDefaultSort
6136 * Unlike getDefaultSort(), will return false if none is set
6138 * @return string|bool
6140 public function getCustomDefaultSort() {
6141 return $this->mDefaultSort
;
6145 * Try to guess the section anchor name based on a wikitext fragment
6146 * presumably extracted from a heading, for example "Header" from
6149 * @param string $text
6153 public function guessSectionNameFromWikiText( $text ) {
6154 # Strip out wikitext links(they break the anchor)
6155 $text = $this->stripSectionName( $text );
6156 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6157 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6161 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6162 * instead. For use in redirects, since IE6 interprets Redirect: headers
6163 * as something other than UTF-8 (apparently?), resulting in breakage.
6165 * @param string $text The section name
6166 * @return string An anchor
6168 public function guessLegacySectionNameFromWikiText( $text ) {
6169 # Strip out wikitext links(they break the anchor)
6170 $text = $this->stripSectionName( $text );
6171 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6172 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6176 * Strips a text string of wikitext for use in a section anchor
6178 * Accepts a text string and then removes all wikitext from the
6179 * string and leaves only the resultant text (i.e. the result of
6180 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6181 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6182 * to create valid section anchors by mimicing the output of the
6183 * parser when headings are parsed.
6185 * @param string $text Text string to be stripped of wikitext
6186 * for use in a Section anchor
6187 * @return string Filtered text string
6189 public function stripSectionName( $text ) {
6190 # Strip internal link markup
6191 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6192 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6194 # Strip external link markup
6195 # @todo FIXME: Not tolerant to blank link text
6196 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6197 # on how many empty links there are on the page - need to figure that out.
6198 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6200 # Parse wikitext quotes (italics & bold)
6201 $text = $this->doQuotes( $text );
6204 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6209 * strip/replaceVariables/unstrip for preprocessor regression testing
6211 * @param string $text
6212 * @param Title $title
6213 * @param ParserOptions $options
6214 * @param int $outputType
6218 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6219 $magicScopeVariable = $this->lock();
6220 $this->startParse( $title, $options, $outputType, true );
6222 $text = $this->replaceVariables( $text );
6223 $text = $this->mStripState
->unstripBoth( $text );
6224 $text = Sanitizer
::removeHTMLtags( $text );
6229 * @param string $text
6230 * @param Title $title
6231 * @param ParserOptions $options
6234 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6235 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6239 * @param string $text
6240 * @param Title $title
6241 * @param ParserOptions $options
6244 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6245 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6249 * Call a callback function on all regions of the given text that are not
6250 * inside strip markers, and replace those regions with the return value
6251 * of the callback. For example, with input:
6255 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6256 * two strings will be replaced with the value returned by the callback in
6260 * @param callable $callback
6264 public function markerSkipCallback( $s, $callback ) {
6267 while ( $i < strlen( $s ) ) {
6268 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6269 if ( $markerStart === false ) {
6270 $out .= call_user_func( $callback, substr( $s, $i ) );
6273 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6274 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6275 if ( $markerEnd === false ) {
6276 $out .= substr( $s, $markerStart );
6279 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6280 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6289 * Remove any strip markers found in the given text.
6291 * @param string $text Input string
6294 public function killMarkers( $text ) {
6295 return $this->mStripState
->killMarkers( $text );
6299 * Save the parser state required to convert the given half-parsed text to
6300 * HTML. "Half-parsed" in this context means the output of
6301 * recursiveTagParse() or internalParse(). This output has strip markers
6302 * from replaceVariables (extensionSubstitution() etc.), and link
6303 * placeholders from replaceLinkHolders().
6305 * Returns an array which can be serialized and stored persistently. This
6306 * array can later be loaded into another parser instance with
6307 * unserializeHalfParsedText(). The text can then be safely incorporated into
6308 * the return value of a parser hook.
6310 * @param string $text
6314 public function serializeHalfParsedText( $text ) {
6317 'version' => self
::HALF_PARSED_VERSION
,
6318 'stripState' => $this->mStripState
->getSubState( $text ),
6319 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6325 * Load the parser state given in the $data array, which is assumed to
6326 * have been generated by serializeHalfParsedText(). The text contents is
6327 * extracted from the array, and its markers are transformed into markers
6328 * appropriate for the current Parser instance. This transformed text is
6329 * returned, and can be safely included in the return value of a parser
6332 * If the $data array has been stored persistently, the caller should first
6333 * check whether it is still valid, by calling isValidHalfParsedText().
6335 * @param array $data Serialized data
6336 * @throws MWException
6339 public function unserializeHalfParsedText( $data ) {
6340 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6341 throw new MWException( __METHOD__
. ': invalid version' );
6344 # First, extract the strip state.
6345 $texts = array( $data['text'] );
6346 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6348 # Now renumber links
6349 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6351 # Should be good to go.
6356 * Returns true if the given array, presumed to be generated by
6357 * serializeHalfParsedText(), is compatible with the current version of the
6360 * @param array $data
6364 public function isValidHalfParsedText( $data ) {
6365 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6369 * Parsed a width param of imagelink like 300px or 200x300px
6371 * @param string $value
6376 public function parseWidthParam( $value ) {
6377 $parsedWidthParam = array();
6378 if ( $value === '' ) {
6379 return $parsedWidthParam;
6382 # (bug 13500) In both cases (width/height and width only),
6383 # permit trailing "px" for backward compatibility.
6384 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6385 $width = intval( $m[1] );
6386 $height = intval( $m[2] );
6387 $parsedWidthParam['width'] = $width;
6388 $parsedWidthParam['height'] = $height;
6389 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6390 $width = intval( $value );
6391 $parsedWidthParam['width'] = $width;
6393 return $parsedWidthParam;
6397 * Lock the current instance of the parser.
6399 * This is meant to stop someone from calling the parser
6400 * recursively and messing up all the strip state.
6402 * @throws MWException If parser is in a parse
6403 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6405 protected function lock() {
6406 if ( $this->mInParse
) {
6407 throw new MWException( "Parser state cleared while parsing. "
6408 . "Did you call Parser::parse recursively?" );
6410 $this->mInParse
= true;
6413 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6414 $that->mInParse
= false;
6417 return $recursiveCheck;
6421 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6423 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6424 * or if there is more than one <p/> tag in the input HTML.
6426 * @param string $html
6430 public static function stripOuterParagraph( $html ) {
6432 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6433 if ( strpos( $m[1], '</p>' ) === false ) {
6442 * Return this parser if it is not doing anything, otherwise
6443 * get a fresh parser. You can use this method by doing
6444 * $myParser = $wgParser->getFreshParser(), or more simply
6445 * $wgParser->getFreshParser()->parse( ... );
6446 * if you're unsure if $wgParser is safe to use.
6449 * @return Parser A parser object that is not parsing anything
6451 public function getFreshParser() {
6452 global $wgParserConf;
6453 if ( $this->mInParse
) {
6454 return new $wgParserConf['class']( $wgParserConf );
6461 * Set's up the PHP implementation of OOUI for use in this request
6462 * and instructs OutputPage to enable OOUI for itself.
6466 public function enableOOUI() {
6467 OutputPage
::setupOOUI();
6468 $this->mOutput
->setEnableOOUI( true );