3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform()
39 * produces altered wiki markup
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
89 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
90 # Simplified expression to match an IPv4 or IPv6 address, or
91 # at least one character of a host name (embeds EXT_LINK_URL_CLASS)
92 const EXT_LINK_ADDR
= '(?:[0-9.]+|\\[(?i:[0-9a-f:.]+)\\]|[^][<>"\\x00-\\x20\\x7F\p{Zs}])';
93 # RegExp to make image URLs (embeds IPv6 part of EXT_LINK_ADDR)
94 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)((?:\\[(?i:[0-9a-f:.]+)\\])?[^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
95 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
97 # Regular expression for a non-newline space
98 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
100 # State constants for the definition list colon extraction
101 const COLON_STATE_TEXT
= 0;
102 const COLON_STATE_TAG
= 1;
103 const COLON_STATE_TAGSTART
= 2;
104 const COLON_STATE_CLOSETAG
= 3;
105 const COLON_STATE_TAGSLASH
= 4;
106 const COLON_STATE_COMMENT
= 5;
107 const COLON_STATE_COMMENTDASH
= 6;
108 const COLON_STATE_COMMENTDASHDASH
= 7;
110 # Flags for preprocessToDom
111 const PTD_FOR_INCLUSION
= 1;
113 # Allowed values for $this->mOutputType
114 # Parameter to startExternalParse().
115 const OT_HTML
= 1; # like parse()
116 const OT_WIKI
= 2; # like preSaveTransform()
117 const OT_PREPROCESS
= 3; # like preprocess()
119 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
122 * @var string Prefix and suffix for temporary replacement strings
123 * for the multipass parser.
125 * \x7f should never appear in input as it's disallowed in XML.
126 * Using it at the front also gives us a little extra robustness
127 * since it shouldn't match when butted up against identifier-like
130 * Must not consist of all title characters, or else it will change
131 * the behavior of <nowiki> in a link.
133 const MARKER_SUFFIX
= "-QINU\x7f";
134 const MARKER_PREFIX
= "\x7fUNIQ-";
136 # Markers used for wrapping the table of contents
137 const TOC_START
= '<mw:toc>';
138 const TOC_END
= '</mw:toc>';
141 public $mTagHooks = array();
142 public $mTransparentTagHooks = array();
143 public $mFunctionHooks = array();
144 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
145 public $mFunctionTagHooks = array();
146 public $mStripList = array();
147 public $mDefaultStripList = array();
148 public $mVarCache = array();
149 public $mImageParams = array();
150 public $mImageParamsMagicArray = array();
151 public $mMarkerIndex = 0;
152 public $mFirstCall = true;
154 # Initialised by initialiseVariables()
157 * @var MagicWordArray
162 * @var MagicWordArray
165 # Initialised in constructor
166 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
168 # Initialized in getPreprocessor()
169 /** @var Preprocessor */
170 public $mPreprocessor;
172 # Cleared with clearState():
177 public $mAutonumber, $mDTopen;
184 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
186 * @var LinkHolderArray
188 public $mLinkHolders;
191 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
192 public $mDefaultSort;
193 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
194 public $mExpensiveFunctionCount; # number of expensive parser function calls
195 public $mShowToc, $mForceTocPosition;
200 public $mUser; # User object; only used when doing pre-save transform
203 # These are variables reset at least once per parse regardless of $clearState
213 public $mTitle; # Title context, used for self-link rendering and similar things
214 public $mOutputType; # Output type, one of the OT_xxx constants
215 public $ot; # Shortcut alias, see setOutputType()
216 public $mRevisionObject; # The revision object of the specified revision ID
217 public $mRevisionId; # ID to display in {{REVISIONID}} tags
218 public $mRevisionTimestamp; # The timestamp of the specified revision ID
219 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
220 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
221 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
222 public $mInputSize = false; # For {{PAGESIZE}} on current page.
225 * @var string Deprecated accessor for the strip marker prefix.
226 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
228 public $mUniqPrefix = Parser
::MARKER_PREFIX
;
231 * @var array Array with the language name of each language link (i.e. the
232 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
233 * duplicate language links to the ParserOutput.
235 public $mLangLinkLanguages;
238 * @var MapCacheLRU|null
241 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
243 public $currentRevisionCache;
246 * @var bool Recursive call protection.
247 * This variable should be treated as if it were private.
249 public $mInParse = false;
251 /** @var SectionProfiler */
252 protected $mProfiler;
257 public function __construct( $conf = array() ) {
258 $this->mConf
= $conf;
259 $this->mUrlProtocols
= wfUrlProtocols();
260 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
261 self
::EXT_LINK_ADDR
.
262 self
::EXT_LINK_URL_CLASS
. '*)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
263 if ( isset( $conf['preprocessorClass'] ) ) {
264 $this->mPreprocessorClass
= $conf['preprocessorClass'];
265 } elseif ( defined( 'HPHP_VERSION' ) ) {
266 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
267 $this->mPreprocessorClass
= 'Preprocessor_Hash';
268 } elseif ( extension_loaded( 'domxml' ) ) {
269 # PECL extension that conflicts with the core DOM extension (bug 13770)
270 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
271 $this->mPreprocessorClass
= 'Preprocessor_Hash';
272 } elseif ( extension_loaded( 'dom' ) ) {
273 $this->mPreprocessorClass
= 'Preprocessor_DOM';
275 $this->mPreprocessorClass
= 'Preprocessor_Hash';
277 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
281 * Reduce memory usage to reduce the impact of circular references
283 public function __destruct() {
284 if ( isset( $this->mLinkHolders
) ) {
285 unset( $this->mLinkHolders
);
287 foreach ( $this as $name => $value ) {
288 unset( $this->$name );
293 * Allow extensions to clean up when the parser is cloned
295 public function __clone() {
296 $this->mInParse
= false;
298 // Bug 56226: When you create a reference "to" an object field, that
299 // makes the object field itself be a reference too (until the other
300 // reference goes out of scope). When cloning, any field that's a
301 // reference is copied as a reference in the new object. Both of these
302 // are defined PHP5 behaviors, as inconvenient as it is for us when old
303 // hooks from PHP4 days are passing fields by reference.
304 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
305 // Make a non-reference copy of the field, then rebind the field to
306 // reference the new copy.
312 Hooks
::run( 'ParserCloned', array( $this ) );
316 * Do various kinds of initialisation on the first call of the parser
318 public function firstCallInit() {
319 if ( !$this->mFirstCall
) {
322 $this->mFirstCall
= false;
324 CoreParserFunctions
::register( $this );
325 CoreTagHooks
::register( $this );
326 $this->initialiseVariables();
328 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
336 public function clearState() {
337 if ( $this->mFirstCall
) {
338 $this->firstCallInit();
340 $this->mOutput
= new ParserOutput
;
341 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
342 $this->mAutonumber
= 0;
343 $this->mLastSection
= '';
344 $this->mDTopen
= false;
345 $this->mIncludeCount
= array();
346 $this->mArgStack
= false;
347 $this->mInPre
= false;
348 $this->mLinkHolders
= new LinkHolderArray( $this );
350 $this->mRevisionObject
= $this->mRevisionTimestamp
=
351 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
352 $this->mVarCache
= array();
354 $this->mLangLinkLanguages
= array();
355 $this->currentRevisionCache
= null;
357 $this->mStripState
= new StripState
;
359 # Clear these on every parse, bug 4549
360 $this->mTplRedirCache
= $this->mTplDomCache
= array();
362 $this->mShowToc
= true;
363 $this->mForceTocPosition
= false;
364 $this->mIncludeSizes
= array(
368 $this->mPPNodeCount
= 0;
369 $this->mGeneratedPPNodeCount
= 0;
370 $this->mHighestExpansionDepth
= 0;
371 $this->mDefaultSort
= false;
372 $this->mHeadings
= array();
373 $this->mDoubleUnderscores
= array();
374 $this->mExpensiveFunctionCount
= 0;
377 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
378 $this->mPreprocessor
= null;
381 $this->mProfiler
= new SectionProfiler();
383 Hooks
::run( 'ParserClearState', array( &$this ) );
387 * Convert wikitext to HTML
388 * Do not call this function recursively.
390 * @param string $text Text we want to parse
391 * @param Title $title
392 * @param ParserOptions $options
393 * @param bool $linestart
394 * @param bool $clearState
395 * @param int $revid Number to pass in {{REVISIONID}}
396 * @return ParserOutput A ParserOutput
398 public function parse( $text, Title
$title, ParserOptions
$options,
399 $linestart = true, $clearState = true, $revid = null
402 * First pass--just handle <nowiki> sections, pass the rest off
403 * to internalParse() which does all the real work.
406 global $wgShowHostnames;
409 // We use U+007F DELETE to construct strip markers, so we have to make
410 // sure that this character does not occur in the input text.
411 $text = strtr( $text, "\x7f", "?" );
412 $magicScopeVariable = $this->lock();
415 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
417 $this->currentRevisionCache
= null;
418 $this->mInputSize
= strlen( $text );
419 if ( $this->mOptions
->getEnableLimitReport() ) {
420 $this->mOutput
->resetParseStartTime();
423 $oldRevisionId = $this->mRevisionId
;
424 $oldRevisionObject = $this->mRevisionObject
;
425 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
426 $oldRevisionUser = $this->mRevisionUser
;
427 $oldRevisionSize = $this->mRevisionSize
;
428 if ( $revid !== null ) {
429 $this->mRevisionId
= $revid;
430 $this->mRevisionObject
= null;
431 $this->mRevisionTimestamp
= null;
432 $this->mRevisionUser
= null;
433 $this->mRevisionSize
= null;
436 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
438 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
439 $text = $this->internalParse( $text );
440 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
442 $text = $this->internalParseHalfParsed( $text, true, $linestart );
445 * A converted title will be provided in the output object if title and
446 * content conversion are enabled, the article text does not contain
447 * a conversion-suppressing double-underscore tag, and no
448 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
449 * automatic link conversion.
451 if ( !( $options->getDisableTitleConversion()
452 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
453 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
454 ||
$this->mOutput
->getDisplayTitle() !== false )
456 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
457 if ( $convruletitle ) {
458 $this->mOutput
->setTitleText( $convruletitle );
460 $titleText = $this->getConverterLanguage()->convertTitle( $title );
461 $this->mOutput
->setTitleText( $titleText );
465 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
466 $this->limitationWarn( 'expensive-parserfunction',
467 $this->mExpensiveFunctionCount
,
468 $this->mOptions
->getExpensiveParserFunctionLimit()
472 # Information on include size limits, for the benefit of users who try to skirt them
473 if ( $this->mOptions
->getEnableLimitReport() ) {
474 $max = $this->mOptions
->getMaxIncludeSize();
476 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
477 if ( $cpuTime !== null ) {
478 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
479 sprintf( "%.3f", $cpuTime )
483 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
484 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
485 sprintf( "%.3f", $wallTime )
488 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
489 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
491 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
492 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
494 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
495 array( $this->mIncludeSizes
['post-expand'], $max )
497 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
498 array( $this->mIncludeSizes
['arg'], $max )
500 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
501 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
503 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
504 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
506 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
508 $limitReport = "NewPP limit report\n";
509 if ( $wgShowHostnames ) {
510 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
512 $limitReport .= 'Cached time: ' . $this->mOutput
->getCacheTime() . "\n";
513 $limitReport .= 'Cache expiry: ' . $this->mOutput
->getCacheExpiry() . "\n";
514 $limitReport .= 'Dynamic content: ' . ( $this->mOutput
->hasDynamicContent() ?
'true' : 'false' ) . "\n";
515 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
516 if ( Hooks
::run( 'ParserLimitReportFormat',
517 array( $key, &$value, &$limitReport, false, false )
519 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
520 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
521 ->inLanguage( 'en' )->useDatabase( false );
522 if ( !$valueMsg->exists() ) {
523 $valueMsg = new RawMessage( '$1' );
525 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
526 $valueMsg->params( $value );
527 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
531 // Since we're not really outputting HTML, decode the entities and
532 // then re-encode the things that need hiding inside HTML comments.
533 $limitReport = htmlspecialchars_decode( $limitReport );
534 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
536 // Sanitize for comment. Note '‐' in the replacement is U+2010,
537 // which looks much like the problematic '-'.
538 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
539 $text .= "\n<!-- \n$limitReport-->\n";
541 // Add on template profiling data
542 $dataByFunc = $this->mProfiler
->getFunctionStats();
543 uasort( $dataByFunc, function ( $a, $b ) {
544 return $a['real'] < $b['real']; // descending order
546 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
547 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
548 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
549 $item['%real'], $item['real'], $item['calls'],
550 htmlspecialchars( $item['name'] ) );
552 $text .= "\n<!-- \n$profileReport-->\n";
554 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
555 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
556 $this->mTitle
->getPrefixedDBkey() );
559 $this->mOutput
->setText( $text );
561 $this->mRevisionId
= $oldRevisionId;
562 $this->mRevisionObject
= $oldRevisionObject;
563 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
564 $this->mRevisionUser
= $oldRevisionUser;
565 $this->mRevisionSize
= $oldRevisionSize;
566 $this->mInputSize
= false;
567 $this->currentRevisionCache
= null;
569 return $this->mOutput
;
573 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
574 * can be called from an extension tag hook.
576 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
577 * instead, which means that lists and links have not been fully parsed yet,
578 * and strip markers are still present.
580 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
582 * Use this function if you're a parser tag hook and you want to parse
583 * wikitext before or after applying additional transformations, and you
584 * intend to *return the result as hook output*, which will cause it to go
585 * through the rest of parsing process automatically.
587 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
588 * $text are not expanded
590 * @param string $text Text extension wants to have parsed
591 * @param bool|PPFrame $frame The frame to use for expanding any template variables
592 * @return string UNSAFE half-parsed HTML
594 public function recursiveTagParse( $text, $frame = false ) {
595 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
596 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
597 $text = $this->internalParse( $text, false, $frame );
602 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
603 * point can be called from an extension tag hook.
605 * The output of this function is fully-parsed HTML that is safe for output.
606 * If you're a parser tag hook, you might want to use recursiveTagParse()
609 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
610 * $text are not expanded
614 * @param string $text Text extension wants to have parsed
615 * @param bool|PPFrame $frame The frame to use for expanding any template variables
616 * @return string Fully parsed HTML
618 public function recursiveTagParseFully( $text, $frame = false ) {
619 $text = $this->recursiveTagParse( $text, $frame );
620 $text = $this->internalParseHalfParsed( $text, false );
625 * Expand templates and variables in the text, producing valid, static wikitext.
626 * Also removes comments.
627 * Do not call this function recursively.
628 * @param string $text
629 * @param Title $title
630 * @param ParserOptions $options
631 * @param int|null $revid
632 * @param bool|PPFrame $frame
633 * @return mixed|string
635 public function preprocess( $text, Title
$title = null,
636 ParserOptions
$options, $revid = null, $frame = false
638 $magicScopeVariable = $this->lock();
639 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
640 if ( $revid !== null ) {
641 $this->mRevisionId
= $revid;
643 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
644 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
645 $text = $this->replaceVariables( $text, $frame );
646 $text = $this->mStripState
->unstripBoth( $text );
651 * Recursive parser entry point that can be called from an extension tag
654 * @param string $text Text to be expanded
655 * @param bool|PPFrame $frame The frame to use for expanding any template variables
659 public function recursivePreprocess( $text, $frame = false ) {
660 $text = $this->replaceVariables( $text, $frame );
661 $text = $this->mStripState
->unstripBoth( $text );
666 * Process the wikitext for the "?preload=" feature. (bug 5210)
668 * "<noinclude>", "<includeonly>" etc. are parsed as for template
669 * transclusion, comments, templates, arguments, tags hooks and parser
670 * functions are untouched.
672 * @param string $text
673 * @param Title $title
674 * @param ParserOptions $options
675 * @param array $params
678 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
679 $msg = new RawMessage( $text );
680 $text = $msg->params( $params )->plain();
682 # Parser (re)initialisation
683 $magicScopeVariable = $this->lock();
684 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
686 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
687 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
688 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
689 $text = $this->mStripState
->unstripBoth( $text );
694 * Get a random string
697 * @deprecated since 1.26; use wfRandomString() instead.
699 public static function getRandomString() {
700 wfDeprecated( __METHOD__
, '1.26' );
701 return wfRandomString( 16 );
705 * Set the current user.
706 * Should only be used when doing pre-save transform.
708 * @param User|null $user User object or null (to reset)
710 public function setUser( $user ) {
711 $this->mUser
= $user;
715 * Accessor for mUniqPrefix.
718 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
720 public function uniqPrefix() {
721 wfDeprecated( __METHOD__
, '1.26' );
722 return self
::MARKER_PREFIX
;
726 * Set the context title
730 public function setTitle( $t ) {
732 $t = Title
::newFromText( 'NO TITLE' );
735 if ( $t->hasFragment() ) {
736 # Strip the fragment to avoid various odd effects
737 $this->mTitle
= clone $t;
738 $this->mTitle
->setFragment( '' );
745 * Accessor for the Title object
749 public function getTitle() {
750 return $this->mTitle
;
754 * Accessor/mutator for the Title object
756 * @param Title $x Title object or null to just get the current one
759 public function Title( $x = null ) {
760 return wfSetVar( $this->mTitle
, $x );
764 * Set the output type
766 * @param int $ot New value
768 public function setOutputType( $ot ) {
769 $this->mOutputType
= $ot;
772 'html' => $ot == self
::OT_HTML
,
773 'wiki' => $ot == self
::OT_WIKI
,
774 'pre' => $ot == self
::OT_PREPROCESS
,
775 'plain' => $ot == self
::OT_PLAIN
,
780 * Accessor/mutator for the output type
782 * @param int|null $x New value or null to just get the current one
785 public function OutputType( $x = null ) {
786 return wfSetVar( $this->mOutputType
, $x );
790 * Get the ParserOutput object
792 * @return ParserOutput
794 public function getOutput() {
795 return $this->mOutput
;
799 * Get the ParserOptions object
801 * @return ParserOptions
803 public function getOptions() {
804 return $this->mOptions
;
808 * Accessor/mutator for the ParserOptions object
810 * @param ParserOptions $x New value or null to just get the current one
811 * @return ParserOptions Current ParserOptions object
813 public function Options( $x = null ) {
814 return wfSetVar( $this->mOptions
, $x );
820 public function nextLinkID() {
821 return $this->mLinkID++
;
827 public function setLinkID( $id ) {
828 $this->mLinkID
= $id;
832 * Get a language object for use in parser functions such as {{FORMATNUM:}}
835 public function getFunctionLang() {
836 return $this->getTargetLanguage();
840 * Get the target language for the content being parsed. This is usually the
841 * language that the content is in.
845 * @throws MWException
848 public function getTargetLanguage() {
849 $target = $this->mOptions
->getTargetLanguage();
851 if ( $target !== null ) {
853 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
854 return $this->mOptions
->getUserLangObj();
855 } elseif ( is_null( $this->mTitle
) ) {
856 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
859 return $this->mTitle
->getPageLanguage();
863 * Get the language object for language conversion
864 * @return Language|null
866 public function getConverterLanguage() {
867 return $this->getTargetLanguage();
871 * Get a User object either from $this->mUser, if set, or from the
872 * ParserOptions object otherwise
876 public function getUser() {
877 if ( !is_null( $this->mUser
) ) {
880 return $this->mOptions
->getUser();
884 * Get a preprocessor object
886 * @return Preprocessor
888 public function getPreprocessor() {
889 if ( !isset( $this->mPreprocessor
) ) {
890 $class = $this->mPreprocessorClass
;
891 $this->mPreprocessor
= new $class( $this );
893 return $this->mPreprocessor
;
897 * Replaces all occurrences of HTML-style comments and the given tags
898 * in the text with a random marker and returns the next text. The output
899 * parameter $matches will be an associative array filled with data in
903 * 'UNIQ-xxxxx' => array(
906 * array( 'param' => 'x' ),
907 * '<element param="x">tag content</element>' ) )
910 * @param array $elements List of element names. Comments are always extracted.
911 * @param string $text Source text string.
912 * @param array $matches Out parameter, Array: extracted tags
913 * @param string|null $uniq_prefix
914 * @return string Stripped text
915 * @since 1.26 The uniq_prefix argument is deprecated.
917 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
918 if ( $uniq_prefix !== null ) {
919 wfDeprecated( __METHOD__
. ' called with $prefix argument', '1.26' );
925 $taglist = implode( '|', $elements );
926 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
928 while ( $text != '' ) {
929 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
931 if ( count( $p ) < 5 ) {
934 if ( count( $p ) > 5 ) {
948 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
949 $stripped .= $marker;
951 if ( $close === '/>' ) {
952 # Empty element tag, <tag />
957 if ( $element === '!--' ) {
960 $end = "/(<\\/$element\\s*>)/i";
962 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
964 if ( count( $q ) < 3 ) {
965 # No end tag -- let it run out to the end of the text.
974 $matches[$marker] = array( $element,
976 Sanitizer
::decodeTagAttributes( $attributes ),
977 "<$element$attributes$close$content$tail" );
983 * Get a list of strippable XML-like elements
987 public function getStripList() {
988 return $this->mStripList
;
992 * Add an item to the strip state
993 * Returns the unique tag which must be inserted into the stripped text
994 * The tag will be replaced with the original text in unstrip()
996 * @param string $text
1000 public function insertStripItem( $text ) {
1001 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1002 $this->mMarkerIndex++
;
1003 $this->mStripState
->addGeneral( $marker, $text );
1008 * parse the wiki syntax used to render tables
1011 * @param string $text
1014 public function doTableStuff( $text ) {
1016 $lines = StringUtils
::explode( "\n", $text );
1018 $td_history = array(); # Is currently a td tag open?
1019 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1020 $tr_history = array(); # Is currently a tr tag open?
1021 $tr_attributes = array(); # history of tr attributes
1022 $has_opened_tr = array(); # Did this table open a <tr> element?
1023 $indent_level = 0; # indent level of the table
1025 foreach ( $lines as $outLine ) {
1026 $line = trim( $outLine );
1028 if ( $line === '' ) { # empty line, go to next line
1029 $out .= $outLine . "\n";
1033 $first_character = $line[0];
1034 $first_two = substr( $line, 0, 2 );
1037 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1038 # First check if we are starting a new table
1039 $indent_level = strlen( $matches[1] );
1041 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1042 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1044 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1045 array_push( $td_history, false );
1046 array_push( $last_tag_history, '' );
1047 array_push( $tr_history, false );
1048 array_push( $tr_attributes, '' );
1049 array_push( $has_opened_tr, false );
1050 } elseif ( count( $td_history ) == 0 ) {
1051 # Don't do any of the following
1052 $out .= $outLine . "\n";
1054 } elseif ( $first_two === '|}' ) {
1055 # We are ending a table
1056 $line = '</table>' . substr( $line, 2 );
1057 $last_tag = array_pop( $last_tag_history );
1059 if ( !array_pop( $has_opened_tr ) ) {
1060 $line = "<tr><td></td></tr>{$line}";
1063 if ( array_pop( $tr_history ) ) {
1064 $line = "</tr>{$line}";
1067 if ( array_pop( $td_history ) ) {
1068 $line = "</{$last_tag}>{$line}";
1070 array_pop( $tr_attributes );
1071 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1072 } elseif ( $first_two === '|-' ) {
1073 # Now we have a table row
1074 $line = preg_replace( '#^\|-+#', '', $line );
1076 # Whats after the tag is now only attributes
1077 $attributes = $this->mStripState
->unstripBoth( $line );
1078 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1079 array_pop( $tr_attributes );
1080 array_push( $tr_attributes, $attributes );
1083 $last_tag = array_pop( $last_tag_history );
1084 array_pop( $has_opened_tr );
1085 array_push( $has_opened_tr, true );
1087 if ( array_pop( $tr_history ) ) {
1091 if ( array_pop( $td_history ) ) {
1092 $line = "</{$last_tag}>{$line}";
1096 array_push( $tr_history, false );
1097 array_push( $td_history, false );
1098 array_push( $last_tag_history, '' );
1099 } elseif ( $first_character === '|'
1100 ||
$first_character === '!'
1101 ||
$first_two === '|+'
1103 # This might be cell elements, td, th or captions
1104 if ( $first_two === '|+' ) {
1105 $first_character = '+';
1106 $line = substr( $line, 2 );
1108 $line = substr( $line, 1 );
1111 if ( $first_character === '!' ) {
1112 $line = str_replace( '!!', '||', $line );
1115 # Split up multiple cells on the same line.
1116 # FIXME : This can result in improper nesting of tags processed
1117 # by earlier parser steps, but should avoid splitting up eg
1118 # attribute values containing literal "||".
1119 $cells = StringUtils
::explodeMarkup( '||', $line );
1123 # Loop through each table cell
1124 foreach ( $cells as $cell ) {
1126 if ( $first_character !== '+' ) {
1127 $tr_after = array_pop( $tr_attributes );
1128 if ( !array_pop( $tr_history ) ) {
1129 $previous = "<tr{$tr_after}>\n";
1131 array_push( $tr_history, true );
1132 array_push( $tr_attributes, '' );
1133 array_pop( $has_opened_tr );
1134 array_push( $has_opened_tr, true );
1137 $last_tag = array_pop( $last_tag_history );
1139 if ( array_pop( $td_history ) ) {
1140 $previous = "</{$last_tag}>\n{$previous}";
1143 if ( $first_character === '|' ) {
1145 } elseif ( $first_character === '!' ) {
1147 } elseif ( $first_character === '+' ) {
1148 $last_tag = 'caption';
1153 array_push( $last_tag_history, $last_tag );
1155 # A cell could contain both parameters and data
1156 $cell_data = explode( '|', $cell, 2 );
1158 # Bug 553: Note that a '|' inside an invalid link should not
1159 # be mistaken as delimiting cell parameters
1160 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1161 $cell = "{$previous}<{$last_tag}>{$cell}";
1162 } elseif ( count( $cell_data ) == 1 ) {
1163 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1165 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1166 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1167 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1171 array_push( $td_history, true );
1174 $out .= $outLine . "\n";
1177 # Closing open td, tr && table
1178 while ( count( $td_history ) > 0 ) {
1179 if ( array_pop( $td_history ) ) {
1182 if ( array_pop( $tr_history ) ) {
1185 if ( !array_pop( $has_opened_tr ) ) {
1186 $out .= "<tr><td></td></tr>\n";
1189 $out .= "</table>\n";
1192 # Remove trailing line-ending (b/c)
1193 if ( substr( $out, -1 ) === "\n" ) {
1194 $out = substr( $out, 0, -1 );
1197 # special case: don't return empty table
1198 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1206 * Helper function for parse() that transforms wiki markup into half-parsed
1207 * HTML. Only called for $mOutputType == self::OT_HTML.
1211 * @param string $text
1212 * @param bool $isMain
1213 * @param PPFrame|bool $frame
1217 public function internalParse( $text, $isMain = true, $frame = false ) {
1221 # Hook to suspend the parser in this state
1222 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1226 # if $frame is provided, then use $frame for replacing any variables
1228 # use frame depth to infer how include/noinclude tags should be handled
1229 # depth=0 means this is the top-level document; otherwise it's an included document
1230 if ( !$frame->depth
) {
1233 $flag = Parser
::PTD_FOR_INCLUSION
;
1235 $dom = $this->preprocessToDom( $text, $flag );
1236 $text = $frame->expand( $dom );
1238 # if $frame is not provided, then use old-style replaceVariables
1239 $text = $this->replaceVariables( $text );
1242 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1243 $text = Sanitizer
::removeHTMLtags(
1245 array( &$this, 'attributeStripCallback' ),
1247 array_keys( $this->mTransparentTagHooks
)
1249 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1251 # Tables need to come after variable replacement for things to work
1252 # properly; putting them before other transformations should keep
1253 # exciting things like link expansions from showing up in surprising
1255 $text = $this->doTableStuff( $text );
1257 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1259 $text = $this->doDoubleUnderscore( $text );
1261 $text = $this->doHeadings( $text );
1262 $text = $this->replaceInternalLinks( $text );
1263 $text = $this->doAllQuotes( $text );
1264 $text = $this->replaceExternalLinks( $text );
1266 # replaceInternalLinks may sometimes leave behind
1267 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1268 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1270 $text = $this->doMagicLinks( $text );
1271 $text = $this->formatHeadings( $text, $origText, $isMain );
1277 * Helper function for parse() that transforms half-parsed HTML into fully
1280 * @param string $text
1281 * @param bool $isMain
1282 * @param bool $linestart
1285 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1286 $text = $this->mStripState
->unstripGeneral( $text );
1289 Hooks
::run( 'ParserAfterUnstrip', array( &$this, &$text ) );
1292 # Clean up special characters, only run once, next-to-last before doBlockLevels
1294 # french spaces, last one Guillemet-left
1295 # only if there is something before the space
1296 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1297 # french spaces, Guillemet-right
1298 '/(\\302\\253) /' => '\\1 ',
1299 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1301 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1303 $text = $this->doBlockLevels( $text, $linestart );
1305 $this->replaceLinkHolders( $text );
1308 * The input doesn't get language converted if
1310 * b) Content isn't converted
1311 * c) It's a conversion table
1312 * d) it is an interface message (which is in the user language)
1314 if ( !( $this->mOptions
->getDisableContentConversion()
1315 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1317 if ( !$this->mOptions
->getInterfaceMessage() ) {
1318 # The position of the convert() call should not be changed. it
1319 # assumes that the links are all replaced and the only thing left
1320 # is the <nowiki> mark.
1321 $text = $this->getConverterLanguage()->convert( $text );
1325 $text = $this->mStripState
->unstripNoWiki( $text );
1328 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1331 $text = $this->replaceTransparentTags( $text );
1332 $text = $this->mStripState
->unstripGeneral( $text );
1334 $text = Sanitizer
::normalizeCharReferences( $text );
1336 if ( MWTidy
::isEnabled() && $this->mOptions
->getTidy() ) {
1337 $text = MWTidy
::tidy( $text );
1339 # attempt to sanitize at least some nesting problems
1340 # (bug #2702 and quite a few others)
1342 # ''Something [http://www.cool.com cool''] -->
1343 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1344 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1345 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1346 # fix up an anchor inside another anchor, only
1347 # at least for a single single nested link (bug 3695)
1348 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1349 '\\1\\2</a>\\3</a>\\1\\4</a>',
1350 # fix div inside inline elements- doBlockLevels won't wrap a line which
1351 # contains a div, so fix it up here; replace
1352 # div with escaped text
1353 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1354 '\\1\\3<div\\5>\\6</div>\\8\\9',
1355 # remove empty italic or bold tag pairs, some
1356 # introduced by rules above
1357 '/<([bi])><\/\\1>/' => '',
1360 $text = preg_replace(
1361 array_keys( $tidyregs ),
1362 array_values( $tidyregs ),
1367 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1374 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1375 * magic external links.
1380 * @param string $text
1384 public function doMagicLinks( $text ) {
1385 $prots = wfUrlProtocolsWithoutProtRel();
1386 $urlChar = self
::EXT_LINK_URL_CLASS
;
1387 $addr = self
::EXT_LINK_ADDR
;
1388 $space = self
::SPACE_NOT_NL
; # non-newline space
1389 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1390 $spaces = "$space++"; # possessive match of 1 or more spaces
1391 $text = preg_replace_callback(
1393 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1394 (<.*?>) | # m[2]: Skip stuff inside
1395 # HTML elements' . "
1396 (\b(?i:$prots)($addr$urlChar*)) | # m[3]: Free external links
1397 # m[4]: Post-protocol path
1398 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1400 \bISBN $spaces ( # m[6]: ISBN, capture number
1401 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1402 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1403 [0-9Xx] # check digit
1405 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1410 * @throws MWException
1412 * @return HTML|string
1414 public function magicLinkCallback( $m ) {
1415 if ( isset( $m[1] ) && $m[1] !== '' ) {
1418 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1421 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1422 # Free external link
1423 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1424 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1426 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1429 $cssClass = 'mw-magiclink-rfc';
1431 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1433 $urlmsg = 'pubmedurl';
1434 $cssClass = 'mw-magiclink-pmid';
1437 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1438 substr( $m[0], 0, 20 ) . '"' );
1440 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1441 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1442 } elseif ( isset( $m[6] ) && $m[6] !== '' ) {
1445 $space = self
::SPACE_NOT_NL
; # non-newline space
1446 $isbn = preg_replace( "/$space/", ' ', $isbn );
1447 $num = strtr( $isbn, array(
1452 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1453 return '<a href="' .
1454 htmlspecialchars( $titleObj->getLocalURL() ) .
1455 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1462 * Make a free external link, given a user-supplied URL
1464 * @param string $url
1465 * @param int $numPostProto
1466 * The number of characters after the protocol.
1467 * @return string HTML
1470 public function makeFreeExternalLink( $url, $numPostProto ) {
1474 # The characters '<' and '>' (which were escaped by
1475 # removeHTMLtags()) should not be included in
1476 # URLs, per RFC 2396.
1477 # Make terminate a URL as well (bug T84937)
1479 if ( preg_match( '/&(lt|gt|nbsp|#x0*(3[CcEe]|[Aa]0)|#0*(60|62|160));/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1480 $trail = substr( $url, $m2[0][1] ) . $trail;
1481 $url = substr( $url, 0, $m2[0][1] );
1484 # Move trailing punctuation to $trail
1486 # If there is no left bracket, then consider right brackets fair game too
1487 if ( strpos( $url, '(' ) === false ) {
1491 $urlRev = strrev( $url );
1492 $numSepChars = strspn( $urlRev, $sep );
1493 # Don't break a trailing HTML entity by moving the ; into $trail
1494 # This is in hot code, so use substr_compare to avoid having to
1495 # create a new string object for the comparison
1496 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1497 # more optimization: instead of running preg_match with a $
1498 # anchor, which can be slow, do the match on the reversed
1499 # string starting at the desired offset.
1500 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1501 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1505 if ( $numSepChars ) {
1506 $trail = substr( $url, -$numSepChars ) . $trail;
1507 $url = substr( $url, 0, -$numSepChars );
1510 # Verify that we still have a real URL after trail removal, and
1511 # not just lone protocol
1512 if ( strlen( $trail ) >= $numPostProto ) {
1513 return $url . $trail;
1516 $url = Sanitizer
::cleanUrl( $url );
1518 # Is this an external image?
1519 $text = $this->maybeMakeExternalImage( $url );
1520 if ( $text === false ) {
1521 # Not an image, make a link
1522 $text = Linker
::makeExternalLink( $url,
1523 $this->getConverterLanguage()->markNoConversion( $url, true ),
1525 $this->getExternalLinkAttribs( $url ) );
1526 # Register it in the output object...
1527 # Replace unnecessary URL escape codes with their equivalent characters
1528 $pasteurized = self
::normalizeLinkUrl( $url );
1529 $this->mOutput
->addExternalLink( $pasteurized );
1531 return $text . $trail;
1535 * Parse headers and return html
1539 * @param string $text
1543 public function doHeadings( $text ) {
1544 for ( $i = 6; $i >= 1; --$i ) {
1545 $h = str_repeat( '=', $i );
1546 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1552 * Replace single quotes with HTML markup
1555 * @param string $text
1557 * @return string The altered text
1559 public function doAllQuotes( $text ) {
1561 $lines = StringUtils
::explode( "\n", $text );
1562 foreach ( $lines as $line ) {
1563 $outtext .= $this->doQuotes( $line ) . "\n";
1565 $outtext = substr( $outtext, 0, -1 );
1570 * Helper function for doAllQuotes()
1572 * @param string $text
1576 public function doQuotes( $text ) {
1577 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1578 $countarr = count( $arr );
1579 if ( $countarr == 1 ) {
1583 // First, do some preliminary work. This may shift some apostrophes from
1584 // being mark-up to being text. It also counts the number of occurrences
1585 // of bold and italics mark-ups.
1588 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1589 $thislen = strlen( $arr[$i] );
1590 // If there are ever four apostrophes, assume the first is supposed to
1591 // be text, and the remaining three constitute mark-up for bold text.
1592 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1593 if ( $thislen == 4 ) {
1594 $arr[$i - 1] .= "'";
1597 } elseif ( $thislen > 5 ) {
1598 // If there are more than 5 apostrophes in a row, assume they're all
1599 // text except for the last 5.
1600 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1601 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1605 // Count the number of occurrences of bold and italics mark-ups.
1606 if ( $thislen == 2 ) {
1608 } elseif ( $thislen == 3 ) {
1610 } elseif ( $thislen == 5 ) {
1616 // If there is an odd number of both bold and italics, it is likely
1617 // that one of the bold ones was meant to be an apostrophe followed
1618 // by italics. Which one we cannot know for certain, but it is more
1619 // likely to be one that has a single-letter word before it.
1620 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1621 $firstsingleletterword = -1;
1622 $firstmultiletterword = -1;
1624 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1625 if ( strlen( $arr[$i] ) == 3 ) {
1626 $x1 = substr( $arr[$i - 1], -1 );
1627 $x2 = substr( $arr[$i - 1], -2, 1 );
1628 if ( $x1 === ' ' ) {
1629 if ( $firstspace == -1 ) {
1632 } elseif ( $x2 === ' ' ) {
1633 $firstsingleletterword = $i;
1634 // if $firstsingleletterword is set, we don't
1635 // look at the other options, so we can bail early.
1638 if ( $firstmultiletterword == -1 ) {
1639 $firstmultiletterword = $i;
1645 // If there is a single-letter word, use it!
1646 if ( $firstsingleletterword > -1 ) {
1647 $arr[$firstsingleletterword] = "''";
1648 $arr[$firstsingleletterword - 1] .= "'";
1649 } elseif ( $firstmultiletterword > -1 ) {
1650 // If not, but there's a multi-letter word, use that one.
1651 $arr[$firstmultiletterword] = "''";
1652 $arr[$firstmultiletterword - 1] .= "'";
1653 } elseif ( $firstspace > -1 ) {
1654 // ... otherwise use the first one that has neither.
1655 // (notice that it is possible for all three to be -1 if, for example,
1656 // there is only one pentuple-apostrophe in the line)
1657 $arr[$firstspace] = "''";
1658 $arr[$firstspace - 1] .= "'";
1662 // Now let's actually convert our apostrophic mush to HTML!
1667 foreach ( $arr as $r ) {
1668 if ( ( $i %
2 ) == 0 ) {
1669 if ( $state === 'both' ) {
1675 $thislen = strlen( $r );
1676 if ( $thislen == 2 ) {
1677 if ( $state === 'i' ) {
1680 } elseif ( $state === 'bi' ) {
1683 } elseif ( $state === 'ib' ) {
1684 $output .= '</b></i><b>';
1686 } elseif ( $state === 'both' ) {
1687 $output .= '<b><i>' . $buffer . '</i>';
1689 } else { // $state can be 'b' or ''
1693 } elseif ( $thislen == 3 ) {
1694 if ( $state === 'b' ) {
1697 } elseif ( $state === 'bi' ) {
1698 $output .= '</i></b><i>';
1700 } elseif ( $state === 'ib' ) {
1703 } elseif ( $state === 'both' ) {
1704 $output .= '<i><b>' . $buffer . '</b>';
1706 } else { // $state can be 'i' or ''
1710 } elseif ( $thislen == 5 ) {
1711 if ( $state === 'b' ) {
1712 $output .= '</b><i>';
1714 } elseif ( $state === 'i' ) {
1715 $output .= '</i><b>';
1717 } elseif ( $state === 'bi' ) {
1718 $output .= '</i></b>';
1720 } elseif ( $state === 'ib' ) {
1721 $output .= '</b></i>';
1723 } elseif ( $state === 'both' ) {
1724 $output .= '<i><b>' . $buffer . '</b></i>';
1726 } else { // ($state == '')
1734 // Now close all remaining tags. Notice that the order is important.
1735 if ( $state === 'b' ||
$state === 'ib' ) {
1738 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1741 if ( $state === 'bi' ) {
1744 // There might be lonely ''''', so make sure we have a buffer
1745 if ( $state === 'both' && $buffer ) {
1746 $output .= '<b><i>' . $buffer . '</i></b>';
1752 * Replace external links (REL)
1754 * Note: this is all very hackish and the order of execution matters a lot.
1755 * Make sure to run tests/parserTests.php if you change this code.
1759 * @param string $text
1761 * @throws MWException
1764 public function replaceExternalLinks( $text ) {
1766 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1767 if ( $bits === false ) {
1768 throw new MWException( "PCRE needs to be compiled with "
1769 . "--enable-unicode-properties in order for MediaWiki to function" );
1771 $s = array_shift( $bits );
1774 while ( $i < count( $bits ) ) {
1777 $text = $bits[$i++
];
1778 $trail = $bits[$i++
];
1780 # The characters '<' and '>' (which were escaped by
1781 # removeHTMLtags()) should not be included in
1782 # URLs, per RFC 2396.
1784 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1785 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1786 $url = substr( $url, 0, $m2[0][1] );
1789 # If the link text is an image URL, replace it with an <img> tag
1790 # This happened by accident in the original parser, but some people used it extensively
1791 $img = $this->maybeMakeExternalImage( $text );
1792 if ( $img !== false ) {
1798 # Set linktype for CSS - if URL==text, link is essentially free
1799 $linktype = ( $text === $url ) ?
'free' : 'text';
1801 # No link text, e.g. [http://domain.tld/some.link]
1802 if ( $text == '' ) {
1804 $langObj = $this->getTargetLanguage();
1805 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1806 $linktype = 'autonumber';
1808 # Have link text, e.g. [http://domain.tld/some.link text]s
1810 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1813 $text = $this->getConverterLanguage()->markNoConversion( $text );
1815 $url = Sanitizer
::cleanUrl( $url );
1817 # Use the encoded URL
1818 # This means that users can paste URLs directly into the text
1819 # Funny characters like ö aren't valid in URLs anyway
1820 # This was changed in August 2004
1821 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1822 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1824 # Register link in the output object.
1825 # Replace unnecessary URL escape codes with the referenced character
1826 # This prevents spammers from hiding links from the filters
1827 $pasteurized = self
::normalizeLinkUrl( $url );
1828 $this->mOutput
->addExternalLink( $pasteurized );
1835 * Get the rel attribute for a particular external link.
1838 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1839 * nofollow if appropriate
1840 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1841 * @return string|null Rel attribute for $url
1843 public static function getExternalLinkRel( $url = false, $title = null ) {
1844 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1845 $ns = $title ?
$title->getNamespace() : false;
1846 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1847 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1855 * Get an associative array of additional HTML attributes appropriate for a
1856 * particular external link. This currently may include rel => nofollow
1857 * (depending on configuration, namespace, and the URL's domain) and/or a
1858 * target attribute (depending on configuration).
1860 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1861 * nofollow if appropriate
1862 * @return array Associative array of HTML attributes
1864 public function getExternalLinkAttribs( $url = false ) {
1866 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1868 if ( $this->mOptions
->getExternalLinkTarget() ) {
1869 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1875 * Replace unusual escape codes in a URL with their equivalent characters
1877 * @deprecated since 1.24, use normalizeLinkUrl
1878 * @param string $url
1881 public static function replaceUnusualEscapes( $url ) {
1882 wfDeprecated( __METHOD__
, '1.24' );
1883 return self
::normalizeLinkUrl( $url );
1887 * Replace unusual escape codes in a URL with their equivalent characters
1889 * This generally follows the syntax defined in RFC 3986, with special
1890 * consideration for HTTP query strings.
1892 * @param string $url
1895 public static function normalizeLinkUrl( $url ) {
1896 # First, make sure unsafe characters are encoded
1897 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1899 return rawurlencode( $m[0] );
1905 $end = strlen( $url );
1907 # Fragment part - 'fragment'
1908 $start = strpos( $url, '#' );
1909 if ( $start !== false && $start < $end ) {
1910 $ret = self
::normalizeUrlComponent(
1911 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1915 # Query part - 'query' minus &=+;
1916 $start = strpos( $url, '?' );
1917 if ( $start !== false && $start < $end ) {
1918 $ret = self
::normalizeUrlComponent(
1919 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1923 # Scheme and path part - 'pchar'
1924 # (we assume no userinfo or encoded colons in the host)
1925 $ret = self
::normalizeUrlComponent(
1926 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1931 private static function normalizeUrlComponent( $component, $unsafe ) {
1932 $callback = function ( $matches ) use ( $unsafe ) {
1933 $char = urldecode( $matches[0] );
1934 $ord = ord( $char );
1935 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1939 # Leave it escaped, but use uppercase for a-f
1940 return strtoupper( $matches[0] );
1943 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1947 * make an image if it's allowed, either through the global
1948 * option, through the exception, or through the on-wiki whitelist
1950 * @param string $url
1954 private function maybeMakeExternalImage( $url ) {
1955 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1956 $imagesexception = !empty( $imagesfrom );
1958 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1959 if ( $imagesexception && is_array( $imagesfrom ) ) {
1960 $imagematch = false;
1961 foreach ( $imagesfrom as $match ) {
1962 if ( strpos( $url, $match ) === 0 ) {
1967 } elseif ( $imagesexception ) {
1968 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1970 $imagematch = false;
1973 if ( $this->mOptions
->getAllowExternalImages()
1974 ||
( $imagesexception && $imagematch )
1976 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1978 $text = Linker
::makeExternalImage( $url );
1981 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1982 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1984 $whitelist = explode(
1986 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1989 foreach ( $whitelist as $entry ) {
1990 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1991 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1994 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1995 # Image matches a whitelist entry
1996 $text = Linker
::makeExternalImage( $url );
2005 * Process [[ ]] wikilinks
2009 * @return string Processed text
2013 public function replaceInternalLinks( $s ) {
2014 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2019 * Process [[ ]] wikilinks (RIL)
2021 * @throws MWException
2022 * @return LinkHolderArray
2026 public function replaceInternalLinks2( &$s ) {
2027 global $wgExtraInterlanguageLinkPrefixes;
2029 static $tc = false, $e1, $e1_img;
2030 # the % is needed to support urlencoded titles as well
2032 $tc = Title
::legalChars() . '#%';
2033 # Match a link having the form [[namespace:link|alternate]]trail
2034 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2035 # Match cases where there is no "]]", which might still be images
2036 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2039 $holders = new LinkHolderArray( $this );
2041 # split the entire text string on occurrences of [[
2042 $a = StringUtils
::explode( '[[', ' ' . $s );
2043 # get the first element (all text up to first [[), and remove the space we added
2046 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2047 $s = substr( $s, 1 );
2049 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2051 if ( $useLinkPrefixExtension ) {
2052 # Match the end of a line for a word that's not followed by whitespace,
2053 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2055 $charset = $wgContLang->linkPrefixCharset();
2056 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2059 if ( is_null( $this->mTitle
) ) {
2060 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2062 $nottalk = !$this->mTitle
->isTalkPage();
2064 if ( $useLinkPrefixExtension ) {
2066 if ( preg_match( $e2, $s, $m ) ) {
2067 $first_prefix = $m[2];
2069 $first_prefix = false;
2075 $useSubpages = $this->areSubpagesAllowed();
2077 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2078 # Loop for each link
2079 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2080 // @codingStandardsIgnoreStart
2082 # Check for excessive memory usage
2083 if ( $holders->isBig() ) {
2085 # Do the existence check, replace the link holders and clear the array
2086 $holders->replace( $s );
2090 if ( $useLinkPrefixExtension ) {
2091 if ( preg_match( $e2, $s, $m ) ) {
2098 if ( $first_prefix ) {
2099 $prefix = $first_prefix;
2100 $first_prefix = false;
2104 $might_be_img = false;
2106 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2108 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2109 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2110 # the real problem is with the $e1 regex
2113 # Still some problems for cases where the ] is meant to be outside punctuation,
2114 # and no image is in sight. See bug 2095.
2117 && substr( $m[3], 0, 1 ) === ']'
2118 && strpos( $text, '[' ) !== false
2120 $text .= ']'; # so that replaceExternalLinks($text) works later
2121 $m[3] = substr( $m[3], 1 );
2123 # fix up urlencoded title texts
2124 if ( strpos( $m[1], '%' ) !== false ) {
2125 # Should anchors '#' also be rejected?
2126 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2129 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2130 # Invalid, but might be an image with a link in its caption
2131 $might_be_img = true;
2133 if ( strpos( $m[1], '%' ) !== false ) {
2134 $m[1] = rawurldecode( $m[1] );
2137 } else { # Invalid form; output directly
2138 $s .= $prefix . '[[' . $line;
2144 # Don't allow internal links to pages containing
2145 # PROTO: where PROTO is a valid URL protocol; these
2146 # should be external links.
2147 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2148 $s .= $prefix . '[[' . $line;
2152 # Make subpage if necessary
2153 if ( $useSubpages ) {
2154 $link = $this->maybeDoSubpageLink( $origLink, $text );
2159 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2161 # Strip off leading ':'
2162 $link = substr( $link, 1 );
2165 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2166 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2167 if ( $nt === null ) {
2168 $s .= $prefix . '[[' . $line;
2172 $ns = $nt->getNamespace();
2173 $iw = $nt->getInterwiki();
2175 if ( $might_be_img ) { # if this is actually an invalid link
2176 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2179 # look at the next 'line' to see if we can close it there
2181 $next_line = $a->current();
2182 if ( $next_line === false ||
$next_line === null ) {
2185 $m = explode( ']]', $next_line, 3 );
2186 if ( count( $m ) == 3 ) {
2187 # the first ]] closes the inner link, the second the image
2189 $text .= "[[{$m[0]}]]{$m[1]}";
2192 } elseif ( count( $m ) == 2 ) {
2193 # if there's exactly one ]] that's fine, we'll keep looking
2194 $text .= "[[{$m[0]}]]{$m[1]}";
2196 # if $next_line is invalid too, we need look no further
2197 $text .= '[[' . $next_line;
2202 # we couldn't find the end of this imageLink, so output it raw
2203 # but don't ignore what might be perfectly normal links in the text we've examined
2204 $holders->merge( $this->replaceInternalLinks2( $text ) );
2205 $s .= "{$prefix}[[$link|$text";
2206 # note: no $trail, because without an end, there *is* no trail
2209 } else { # it's not an image, so output it raw
2210 $s .= "{$prefix}[[$link|$text";
2211 # note: no $trail, because without an end, there *is* no trail
2216 $wasblank = ( $text == '' );
2220 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2221 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2222 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2223 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2224 $text = $this->doQuotes( $text );
2227 # Link not escaped by : , create the various objects
2228 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2231 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2232 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2233 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2236 # Bug 24502: filter duplicates
2237 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2238 $this->mLangLinkLanguages
[$iw] = true;
2239 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2242 $s = rtrim( $s . $prefix );
2243 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2247 if ( $ns == NS_FILE
) {
2248 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2250 # if no parameters were passed, $text
2251 # becomes something like "File:Foo.png",
2252 # which we don't want to pass on to the
2256 # recursively parse links inside the image caption
2257 # actually, this will parse them in any other parameters, too,
2258 # but it might be hard to fix that, and it doesn't matter ATM
2259 $text = $this->replaceExternalLinks( $text );
2260 $holders->merge( $this->replaceInternalLinks2( $text ) );
2262 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2263 $s .= $prefix . $this->armorLinks(
2264 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2266 $s .= $prefix . $trail;
2271 if ( $ns == NS_CATEGORY
) {
2272 $s = rtrim( $s . "\n" ); # bug 87
2275 $sortkey = $this->getDefaultSort();
2279 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2280 $sortkey = str_replace( "\n", '', $sortkey );
2281 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2282 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2285 * Strip the whitespace Category links produce, see bug 87
2287 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2293 # Self-link checking. For some languages, variants of the title are checked in
2294 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2295 # for linking to a different variant.
2296 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2297 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2301 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2302 # @todo FIXME: Should do batch file existence checks, see comment below
2303 if ( $ns == NS_MEDIA
) {
2304 # Give extensions a chance to select the file revision for us
2307 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2308 array( $this, $nt, &$options, &$descQuery ) );
2309 # Fetch and register the file (file title may be different via hooks)
2310 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2311 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2312 $s .= $prefix . $this->armorLinks(
2313 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2317 # Some titles, such as valid special pages or files in foreign repos, should
2318 # be shown as bluelinks even though they're not included in the page table
2320 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2321 # batch file existence checks for NS_FILE and NS_MEDIA
2322 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2323 $this->mOutput
->addLink( $nt );
2324 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2326 # Links will be added to the output link list after checking
2327 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2334 * Render a forced-blue link inline; protect against double expansion of
2335 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2336 * Since this little disaster has to split off the trail text to avoid
2337 * breaking URLs in the following text without breaking trails on the
2338 * wiki links, it's been made into a horrible function.
2341 * @param string $text
2342 * @param array|string $query
2343 * @param string $trail
2344 * @param string $prefix
2345 * @return string HTML-wikitext mix oh yuck
2347 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2348 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2350 if ( is_string( $query ) ) {
2351 $query = wfCgiToArray( $query );
2353 if ( $text == '' ) {
2354 $text = htmlspecialchars( $nt->getPrefixedText() );
2357 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2359 return $this->armorLinks( $link ) . $trail;
2363 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2364 * going to go through further parsing steps before inline URL expansion.
2366 * Not needed quite as much as it used to be since free links are a bit
2367 * more sensible these days. But bracketed links are still an issue.
2369 * @param string $text More-or-less HTML
2370 * @return string Less-or-more HTML with NOPARSE bits
2372 public function armorLinks( $text ) {
2373 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2374 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2378 * Return true if subpage links should be expanded on this page.
2381 public function areSubpagesAllowed() {
2382 # Some namespaces don't allow subpages
2383 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2387 * Handle link to subpage if necessary
2389 * @param string $target The source of the link
2390 * @param string &$text The link text, modified as necessary
2391 * @return string The full name of the link
2394 public function maybeDoSubpageLink( $target, &$text ) {
2395 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2399 * Used by doBlockLevels()
2404 public function closeParagraph() {
2406 if ( $this->mLastSection
!= '' ) {
2407 $result = '</' . $this->mLastSection
. ">\n";
2409 $this->mInPre
= false;
2410 $this->mLastSection
= '';
2415 * getCommon() returns the length of the longest common substring
2416 * of both arguments, starting at the beginning of both.
2419 * @param string $st1
2420 * @param string $st2
2424 public function getCommon( $st1, $st2 ) {
2425 $fl = strlen( $st1 );
2426 $shorter = strlen( $st2 );
2427 if ( $fl < $shorter ) {
2431 for ( $i = 0; $i < $shorter; ++
$i ) {
2432 if ( $st1[$i] != $st2[$i] ) {
2440 * These next three functions open, continue, and close the list
2441 * element appropriate to the prefix character passed into them.
2444 * @param string $char
2448 public function openList( $char ) {
2449 $result = $this->closeParagraph();
2451 if ( '*' === $char ) {
2452 $result .= "<ul><li>";
2453 } elseif ( '#' === $char ) {
2454 $result .= "<ol><li>";
2455 } elseif ( ':' === $char ) {
2456 $result .= "<dl><dd>";
2457 } elseif ( ';' === $char ) {
2458 $result .= "<dl><dt>";
2459 $this->mDTopen
= true;
2461 $result = '<!-- ERR 1 -->';
2469 * @param string $char
2474 public function nextItem( $char ) {
2475 if ( '*' === $char ||
'#' === $char ) {
2476 return "</li>\n<li>";
2477 } elseif ( ':' === $char ||
';' === $char ) {
2479 if ( $this->mDTopen
) {
2482 if ( ';' === $char ) {
2483 $this->mDTopen
= true;
2484 return $close . '<dt>';
2486 $this->mDTopen
= false;
2487 return $close . '<dd>';
2490 return '<!-- ERR 2 -->';
2495 * @param string $char
2500 public function closeList( $char ) {
2501 if ( '*' === $char ) {
2502 $text = "</li></ul>";
2503 } elseif ( '#' === $char ) {
2504 $text = "</li></ol>";
2505 } elseif ( ':' === $char ) {
2506 if ( $this->mDTopen
) {
2507 $this->mDTopen
= false;
2508 $text = "</dt></dl>";
2510 $text = "</dd></dl>";
2513 return '<!-- ERR 3 -->';
2520 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2522 * @param string $text
2523 * @param bool $linestart Whether or not this is at the start of a line.
2525 * @return string The lists rendered as HTML
2527 public function doBlockLevels( $text, $linestart ) {
2529 # Parsing through the text line by line. The main thing
2530 # happening here is handling of block-level elements p, pre,
2531 # and making lists from lines starting with * # : etc.
2533 $textLines = StringUtils
::explode( "\n", $text );
2535 $lastPrefix = $output = '';
2536 $this->mDTopen
= $inBlockElem = false;
2538 $paragraphStack = false;
2539 $inBlockquote = false;
2541 foreach ( $textLines as $oLine ) {
2543 if ( !$linestart ) {
2553 $lastPrefixLength = strlen( $lastPrefix );
2554 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2555 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2556 # If not in a <pre> element, scan for and figure out what prefixes are there.
2557 if ( !$this->mInPre
) {
2558 # Multiple prefixes may abut each other for nested lists.
2559 $prefixLength = strspn( $oLine, '*#:;' );
2560 $prefix = substr( $oLine, 0, $prefixLength );
2563 # ; and : are both from definition-lists, so they're equivalent
2564 # for the purposes of determining whether or not we need to open/close
2566 $prefix2 = str_replace( ';', ':', $prefix );
2567 $t = substr( $oLine, $prefixLength );
2568 $this->mInPre
= (bool)$preOpenMatch;
2570 # Don't interpret any other prefixes in preformatted text
2572 $prefix = $prefix2 = '';
2577 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2578 # Same as the last item, so no need to deal with nesting or opening stuff
2579 $output .= $this->nextItem( substr( $prefix, -1 ) );
2580 $paragraphStack = false;
2582 if ( substr( $prefix, -1 ) === ';' ) {
2583 # The one nasty exception: definition lists work like this:
2584 # ; title : definition text
2585 # So we check for : in the remainder text to split up the
2586 # title and definition, without b0rking links.
2588 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2590 $output .= $term . $this->nextItem( ':' );
2593 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2594 # We need to open or close prefixes, or both.
2596 # Either open or close a level...
2597 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2598 $paragraphStack = false;
2600 # Close all the prefixes which aren't shared.
2601 while ( $commonPrefixLength < $lastPrefixLength ) {
2602 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2603 --$lastPrefixLength;
2606 # Continue the current prefix if appropriate.
2607 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2608 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2611 # Open prefixes where appropriate.
2612 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2615 while ( $prefixLength > $commonPrefixLength ) {
2616 $char = substr( $prefix, $commonPrefixLength, 1 );
2617 $output .= $this->openList( $char );
2619 if ( ';' === $char ) {
2620 # @todo FIXME: This is dupe of code above
2621 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2623 $output .= $term . $this->nextItem( ':' );
2626 ++
$commonPrefixLength;
2628 if ( !$prefixLength && $lastPrefix ) {
2631 $lastPrefix = $prefix2;
2634 # If we have no prefixes, go to paragraph mode.
2635 if ( 0 == $prefixLength ) {
2636 # No prefix (not in list)--go to paragraph mode
2637 # XXX: use a stack for nestable elements like span, table and div
2638 $openmatch = preg_match(
2639 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2640 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2643 $closematch = preg_match(
2644 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2645 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2646 . self
::MARKER_PREFIX
2647 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2651 if ( $openmatch ||
$closematch ) {
2652 $paragraphStack = false;
2653 # @todo bug 5718: paragraph closed
2654 $output .= $this->closeParagraph();
2655 if ( $preOpenMatch && !$preCloseMatch ) {
2656 $this->mInPre
= true;
2659 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2660 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2661 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2663 $inBlockElem = !$closematch;
2664 } elseif ( !$inBlockElem && !$this->mInPre
) {
2665 if ( ' ' == substr( $t, 0, 1 )
2666 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2670 if ( $this->mLastSection
!== 'pre' ) {
2671 $paragraphStack = false;
2672 $output .= $this->closeParagraph() . '<pre>';
2673 $this->mLastSection
= 'pre';
2675 $t = substr( $t, 1 );
2678 if ( trim( $t ) === '' ) {
2679 if ( $paragraphStack ) {
2680 $output .= $paragraphStack . '<br />';
2681 $paragraphStack = false;
2682 $this->mLastSection
= 'p';
2684 if ( $this->mLastSection
!== 'p' ) {
2685 $output .= $this->closeParagraph();
2686 $this->mLastSection
= '';
2687 $paragraphStack = '<p>';
2689 $paragraphStack = '</p><p>';
2693 if ( $paragraphStack ) {
2694 $output .= $paragraphStack;
2695 $paragraphStack = false;
2696 $this->mLastSection
= 'p';
2697 } elseif ( $this->mLastSection
!== 'p' ) {
2698 $output .= $this->closeParagraph() . '<p>';
2699 $this->mLastSection
= 'p';
2705 # somewhere above we forget to get out of pre block (bug 785)
2706 if ( $preCloseMatch && $this->mInPre
) {
2707 $this->mInPre
= false;
2709 if ( $paragraphStack === false ) {
2711 if ( $prefixLength === 0 ) {
2716 while ( $prefixLength ) {
2717 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2719 if ( !$prefixLength ) {
2723 if ( $this->mLastSection
!= '' ) {
2724 $output .= '</' . $this->mLastSection
. '>';
2725 $this->mLastSection
= '';
2732 * Split up a string on ':', ignoring any occurrences inside tags
2733 * to prevent illegal overlapping.
2735 * @param string $str The string to split
2736 * @param string &$before Set to everything before the ':'
2737 * @param string &$after Set to everything after the ':'
2738 * @throws MWException
2739 * @return string The position of the ':', or false if none found
2741 public function findColonNoLinks( $str, &$before, &$after ) {
2743 $pos = strpos( $str, ':' );
2744 if ( $pos === false ) {
2749 $lt = strpos( $str, '<' );
2750 if ( $lt === false ||
$lt > $pos ) {
2751 # Easy; no tag nesting to worry about
2752 $before = substr( $str, 0, $pos );
2753 $after = substr( $str, $pos +
1 );
2757 # Ugly state machine to walk through avoiding tags.
2758 $state = self
::COLON_STATE_TEXT
;
2760 $len = strlen( $str );
2761 for ( $i = 0; $i < $len; $i++
) {
2765 # (Using the number is a performance hack for common cases)
2766 case 0: # self::COLON_STATE_TEXT:
2769 # Could be either a <start> tag or an </end> tag
2770 $state = self
::COLON_STATE_TAGSTART
;
2773 if ( $stack == 0 ) {
2775 $before = substr( $str, 0, $i );
2776 $after = substr( $str, $i +
1 );
2779 # Embedded in a tag; don't break it.
2782 # Skip ahead looking for something interesting
2783 $colon = strpos( $str, ':', $i );
2784 if ( $colon === false ) {
2785 # Nothing else interesting
2788 $lt = strpos( $str, '<', $i );
2789 if ( $stack === 0 ) {
2790 if ( $lt === false ||
$colon < $lt ) {
2792 $before = substr( $str, 0, $colon );
2793 $after = substr( $str, $colon +
1 );
2797 if ( $lt === false ) {
2798 # Nothing else interesting to find; abort!
2799 # We're nested, but there's no close tags left. Abort!
2802 # Skip ahead to next tag start
2804 $state = self
::COLON_STATE_TAGSTART
;
2807 case 1: # self::COLON_STATE_TAG:
2812 $state = self
::COLON_STATE_TEXT
;
2815 # Slash may be followed by >?
2816 $state = self
::COLON_STATE_TAGSLASH
;
2822 case 2: # self::COLON_STATE_TAGSTART:
2825 $state = self
::COLON_STATE_CLOSETAG
;
2828 $state = self
::COLON_STATE_COMMENT
;
2831 # Illegal early close? This shouldn't happen D:
2832 $state = self
::COLON_STATE_TEXT
;
2835 $state = self
::COLON_STATE_TAG
;
2838 case 3: # self::COLON_STATE_CLOSETAG:
2843 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2846 $state = self
::COLON_STATE_TEXT
;
2849 case self
::COLON_STATE_TAGSLASH
:
2851 # Yes, a self-closed tag <blah/>
2852 $state = self
::COLON_STATE_TEXT
;
2854 # Probably we're jumping the gun, and this is an attribute
2855 $state = self
::COLON_STATE_TAG
;
2858 case 5: # self::COLON_STATE_COMMENT:
2860 $state = self
::COLON_STATE_COMMENTDASH
;
2863 case self
::COLON_STATE_COMMENTDASH
:
2865 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2867 $state = self
::COLON_STATE_COMMENT
;
2870 case self
::COLON_STATE_COMMENTDASHDASH
:
2872 $state = self
::COLON_STATE_TEXT
;
2874 $state = self
::COLON_STATE_COMMENT
;
2878 throw new MWException( "State machine error in " . __METHOD__
);
2882 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2889 * Return value of a magic variable (like PAGENAME)
2894 * @param bool|PPFrame $frame
2896 * @throws MWException
2899 public function getVariableValue( $index, $frame = false ) {
2900 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2901 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2903 if ( is_null( $this->mTitle
) ) {
2904 // If no title set, bad things are going to happen
2905 // later. Title should always be set since this
2906 // should only be called in the middle of a parse
2907 // operation (but the unit-tests do funky stuff)
2908 throw new MWException( __METHOD__
. ' Should only be '
2909 . ' called while parsing (no title set)' );
2913 * Some of these require message or data lookups and can be
2914 * expensive to check many times.
2916 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2917 if ( isset( $this->mVarCache
[$index] ) ) {
2918 return $this->mVarCache
[$index];
2922 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2923 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2925 $pageLang = $this->getFunctionLang();
2931 case 'currentmonth':
2932 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2934 case 'currentmonth1':
2935 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2937 case 'currentmonthname':
2938 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2940 case 'currentmonthnamegen':
2941 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2943 case 'currentmonthabbrev':
2944 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2947 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2950 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2953 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2956 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2958 case 'localmonthname':
2959 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2961 case 'localmonthnamegen':
2962 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2964 case 'localmonthabbrev':
2965 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2968 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2971 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2974 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2977 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2979 case 'fullpagename':
2980 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2982 case 'fullpagenamee':
2983 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2986 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2988 case 'subpagenamee':
2989 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2991 case 'rootpagename':
2992 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2994 case 'rootpagenamee':
2995 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2998 $this->mTitle
->getRootText()
3001 case 'basepagename':
3002 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3004 case 'basepagenamee':
3005 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3008 $this->mTitle
->getBaseText()
3011 case 'talkpagename':
3012 if ( $this->mTitle
->canTalk() ) {
3013 $talkPage = $this->mTitle
->getTalkPage();
3014 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3019 case 'talkpagenamee':
3020 if ( $this->mTitle
->canTalk() ) {
3021 $talkPage = $this->mTitle
->getTalkPage();
3022 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3027 case 'subjectpagename':
3028 $subjPage = $this->mTitle
->getSubjectPage();
3029 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3031 case 'subjectpagenamee':
3032 $subjPage = $this->mTitle
->getSubjectPage();
3033 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3035 case 'pageid': // requested in bug 23427
3036 $pageid = $this->getTitle()->getArticleID();
3037 if ( $pageid == 0 ) {
3038 # 0 means the page doesn't exist in the database,
3039 # which means the user is previewing a new page.
3040 # The vary-revision flag must be set, because the magic word
3041 # will have a different value once the page is saved.
3042 $this->mOutput
->setFlag( 'vary-revision' );
3043 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3045 $value = $pageid ?
$pageid : null;
3048 # Let the edit saving system know we should parse the page
3049 # *after* a revision ID has been assigned.
3050 $this->mOutput
->setFlag( 'vary-revision' );
3051 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3052 $value = $this->mRevisionId
;
3055 # Let the edit saving system know we should parse the page
3056 # *after* a revision ID has been assigned. This is for null edits.
3057 $this->mOutput
->setFlag( 'vary-revision' );
3058 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3059 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3061 case 'revisionday2':
3062 # Let the edit saving system know we should parse the page
3063 # *after* a revision ID has been assigned. This is for null edits.
3064 $this->mOutput
->setFlag( 'vary-revision' );
3065 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3066 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3068 case 'revisionmonth':
3069 # Let the edit saving system know we should parse the page
3070 # *after* a revision ID has been assigned. This is for null edits.
3071 $this->mOutput
->setFlag( 'vary-revision' );
3072 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3073 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3075 case 'revisionmonth1':
3076 # Let the edit saving system know we should parse the page
3077 # *after* a revision ID has been assigned. This is for null edits.
3078 $this->mOutput
->setFlag( 'vary-revision' );
3079 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3080 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3082 case 'revisionyear':
3083 # Let the edit saving system know we should parse the page
3084 # *after* a revision ID has been assigned. This is for null edits.
3085 $this->mOutput
->setFlag( 'vary-revision' );
3086 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3087 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3089 case 'revisiontimestamp':
3090 # Let the edit saving system know we should parse the page
3091 # *after* a revision ID has been assigned. This is for null edits.
3092 $this->mOutput
->setFlag( 'vary-revision' );
3093 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3094 $value = $this->getRevisionTimestamp();
3096 case 'revisionuser':
3097 # Let the edit saving system know we should parse the page
3098 # *after* a revision ID has been assigned. This is for null edits.
3099 $this->mOutput
->setFlag( 'vary-revision' );
3100 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3101 $value = $this->getRevisionUser();
3103 case 'revisionsize':
3104 # Let the edit saving system know we should parse the page
3105 # *after* a revision ID has been assigned. This is for null edits.
3106 $this->mOutput
->setFlag( 'vary-revision' );
3107 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3108 $value = $this->getRevisionSize();
3111 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3114 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3116 case 'namespacenumber':
3117 $value = $this->mTitle
->getNamespace();
3120 $value = $this->mTitle
->canTalk()
3121 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3125 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3127 case 'subjectspace':
3128 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3130 case 'subjectspacee':
3131 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3133 case 'currentdayname':
3134 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3137 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3140 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3143 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3146 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3147 # int to remove the padding
3148 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3151 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3153 case 'localdayname':
3154 $value = $pageLang->getWeekdayName(
3155 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3159 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3162 $value = $pageLang->time(
3163 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3169 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3172 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3173 # int to remove the padding
3174 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3177 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3179 case 'numberofarticles':
3180 $value = $pageLang->formatNum( SiteStats
::articles() );
3182 case 'numberoffiles':
3183 $value = $pageLang->formatNum( SiteStats
::images() );
3185 case 'numberofusers':
3186 $value = $pageLang->formatNum( SiteStats
::users() );
3188 case 'numberofactiveusers':
3189 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3191 case 'numberofpages':
3192 $value = $pageLang->formatNum( SiteStats
::pages() );
3194 case 'numberofadmins':
3195 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3197 case 'numberofedits':
3198 $value = $pageLang->formatNum( SiteStats
::edits() );
3200 case 'currenttimestamp':
3201 $value = wfTimestamp( TS_MW
, $ts );
3203 case 'localtimestamp':
3204 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3206 case 'currentversion':
3207 $value = SpecialVersion
::getVersion();
3210 return $wgArticlePath;
3216 return $wgServerName;
3218 return $wgScriptPath;
3220 return $wgStylePath;
3221 case 'directionmark':
3222 return $pageLang->getDirMark();
3223 case 'contentlanguage':
3224 global $wgLanguageCode;
3225 return $wgLanguageCode;
3226 case 'cascadingsources':
3227 $value = CoreParserFunctions
::cascadingsources( $this );
3232 'ParserGetVariableValueSwitch',
3233 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3240 $this->mVarCache
[$index] = $value;
3247 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3251 public function initialiseVariables() {
3252 $variableIDs = MagicWord
::getVariableIDs();
3253 $substIDs = MagicWord
::getSubstIDs();
3255 $this->mVariables
= new MagicWordArray( $variableIDs );
3256 $this->mSubstWords
= new MagicWordArray( $substIDs );
3260 * Preprocess some wikitext and return the document tree.
3261 * This is the ghost of replace_variables().
3263 * @param string $text The text to parse
3264 * @param int $flags Bitwise combination of:
3265 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3266 * included. Default is to assume a direct page view.
3268 * The generated DOM tree must depend only on the input text and the flags.
3269 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3271 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3272 * change in the DOM tree for a given text, must be passed through the section identifier
3273 * in the section edit link and thus back to extractSections().
3275 * The output of this function is currently only cached in process memory, but a persistent
3276 * cache may be implemented at a later date which takes further advantage of these strict
3277 * dependency requirements.
3281 public function preprocessToDom( $text, $flags = 0 ) {
3282 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3287 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3293 public static function splitWhitespace( $s ) {
3294 $ltrimmed = ltrim( $s );
3295 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3296 $trimmed = rtrim( $ltrimmed );
3297 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3299 $w2 = substr( $ltrimmed, -$diff );
3303 return array( $w1, $trimmed, $w2 );
3307 * Replace magic variables, templates, and template arguments
3308 * with the appropriate text. Templates are substituted recursively,
3309 * taking care to avoid infinite loops.
3311 * Note that the substitution depends on value of $mOutputType:
3312 * self::OT_WIKI: only {{subst:}} templates
3313 * self::OT_PREPROCESS: templates but not extension tags
3314 * self::OT_HTML: all templates and extension tags
3316 * @param string $text The text to transform
3317 * @param bool|PPFrame $frame Object describing the arguments passed to the
3318 * template. Arguments may also be provided as an associative array, as
3319 * was the usual case before MW1.12. Providing arguments this way may be
3320 * useful for extensions wishing to perform variable replacement
3322 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3323 * double-brace expansion.
3326 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3327 # Is there any text? Also, Prevent too big inclusions!
3328 $textSize = strlen( $text );
3329 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3333 if ( $frame === false ) {
3334 $frame = $this->getPreprocessor()->newFrame();
3335 } elseif ( !( $frame instanceof PPFrame
) ) {
3336 wfDebug( __METHOD__
. " called using plain parameters instead of "
3337 . "a PPFrame instance. Creating custom frame.\n" );
3338 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3341 $dom = $this->preprocessToDom( $text );
3342 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3343 $text = $frame->expand( $dom, $flags );
3349 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3351 * @param array $args
3355 public static function createAssocArgs( $args ) {
3356 $assocArgs = array();
3358 foreach ( $args as $arg ) {
3359 $eqpos = strpos( $arg, '=' );
3360 if ( $eqpos === false ) {
3361 $assocArgs[$index++
] = $arg;
3363 $name = trim( substr( $arg, 0, $eqpos ) );
3364 $value = trim( substr( $arg, $eqpos +
1 ) );
3365 if ( $value === false ) {
3368 if ( $name !== false ) {
3369 $assocArgs[$name] = $value;
3378 * Warn the user when a parser limitation is reached
3379 * Will warn at most once the user per limitation type
3381 * @param string $limitationType Should be one of:
3382 * 'expensive-parserfunction' (corresponding messages:
3383 * 'expensive-parserfunction-warning',
3384 * 'expensive-parserfunction-category')
3385 * 'post-expand-template-argument' (corresponding messages:
3386 * 'post-expand-template-argument-warning',
3387 * 'post-expand-template-argument-category')
3388 * 'post-expand-template-inclusion' (corresponding messages:
3389 * 'post-expand-template-inclusion-warning',
3390 * 'post-expand-template-inclusion-category')
3391 * 'node-count-exceeded' (corresponding messages:
3392 * 'node-count-exceeded-warning',
3393 * 'node-count-exceeded-category')
3394 * 'expansion-depth-exceeded' (corresponding messages:
3395 * 'expansion-depth-exceeded-warning',
3396 * 'expansion-depth-exceeded-category')
3397 * @param string|int|null $current Current value
3398 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3399 * exceeded, provide the values (optional)
3401 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3402 # does no harm if $current and $max are present but are unnecessary for the message
3403 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3404 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3405 $this->mOutput
->addWarning( $warning );
3406 $this->addTrackingCategory( "$limitationType-category" );
3410 * Return the text of a template, after recursively
3411 * replacing any variables or templates within the template.
3413 * @param array $piece The parts of the template
3414 * $piece['title']: the title, i.e. the part before the |
3415 * $piece['parts']: the parameter array
3416 * $piece['lineStart']: whether the brace was at the start of a line
3417 * @param PPFrame $frame The current frame, contains template arguments
3419 * @return string The text of the template
3421 public function braceSubstitution( $piece, $frame ) {
3425 // $text has been filled
3427 // wiki markup in $text should be escaped
3429 // $text is HTML, armour it against wikitext transformation
3431 // Force interwiki transclusion to be done in raw mode not rendered
3432 $forceRawInterwiki = false;
3433 // $text is a DOM node needing expansion in a child frame
3434 $isChildObj = false;
3435 // $text is a DOM node needing expansion in the current frame
3436 $isLocalObj = false;
3438 # Title object, where $text came from
3441 # $part1 is the bit before the first |, and must contain only title characters.
3442 # Various prefixes will be stripped from it later.
3443 $titleWithSpaces = $frame->expand( $piece['title'] );
3444 $part1 = trim( $titleWithSpaces );
3447 # Original title text preserved for various purposes
3448 $originalTitle = $part1;
3450 # $args is a list of argument nodes, starting from index 0, not including $part1
3451 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3452 # below won't work b/c this $args isn't an object
3453 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3455 $profileSection = null; // profile templates
3459 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3461 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3462 # Decide whether to expand template or keep wikitext as-is.
3463 if ( $this->ot
['wiki'] ) {
3464 if ( $substMatch === false ) {
3465 $literal = true; # literal when in PST with no prefix
3467 $literal = false; # expand when in PST with subst: or safesubst:
3470 if ( $substMatch == 'subst' ) {
3471 $literal = true; # literal when not in PST with plain subst:
3473 $literal = false; # expand when not in PST with safesubst: or no prefix
3477 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3484 if ( !$found && $args->getLength() == 0 ) {
3485 $id = $this->mVariables
->matchStartToEnd( $part1 );
3486 if ( $id !== false ) {
3487 $text = $this->getVariableValue( $id, $frame );
3488 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3489 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3495 # MSG, MSGNW and RAW
3498 $mwMsgnw = MagicWord
::get( 'msgnw' );
3499 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3502 # Remove obsolete MSG:
3503 $mwMsg = MagicWord
::get( 'msg' );
3504 $mwMsg->matchStartAndRemove( $part1 );
3508 $mwRaw = MagicWord
::get( 'raw' );
3509 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3510 $forceRawInterwiki = true;
3516 $colonPos = strpos( $part1, ':' );
3517 if ( $colonPos !== false ) {
3518 $func = substr( $part1, 0, $colonPos );
3519 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3520 for ( $i = 0; $i < $args->getLength(); $i++
) {
3521 $funcArgs[] = $args->item( $i );
3524 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3525 } catch ( Exception
$ex ) {
3529 # The interface for parser functions allows for extracting
3530 # flags into the local scope. Extract any forwarded flags
3536 # Finish mangling title and then check for loops.
3537 # Set $title to a Title object and $titleText to the PDBK
3540 # Split the title into page and subpage
3542 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3543 if ( $part1 !== $relative ) {
3545 $ns = $this->mTitle
->getNamespace();
3547 $title = Title
::newFromText( $part1, $ns );
3549 $titleText = $title->getPrefixedText();
3550 # Check for language variants if the template is not found
3551 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3552 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3554 # Do recursion depth check
3555 $limit = $this->mOptions
->getMaxTemplateDepth();
3556 if ( $frame->depth
>= $limit ) {
3558 $text = '<span class="error">'
3559 . wfMessage( 'parser-template-recursion-depth-warning' )
3560 ->numParams( $limit )->inContentLanguage()->text()
3566 # Load from database
3567 if ( !$found && $title ) {
3568 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3569 if ( !$title->isExternal() ) {
3570 if ( $title->isSpecialPage()
3571 && $this->mOptions
->getAllowSpecialInclusion()
3572 && $this->ot
['html']
3574 // Pass the template arguments as URL parameters.
3575 // "uselang" will have no effect since the Language object
3576 // is forced to the one defined in ParserOptions.
3577 $pageArgs = array();
3578 $argsLength = $args->getLength();
3579 for ( $i = 0; $i < $argsLength; $i++
) {
3580 $bits = $args->item( $i )->splitArg();
3581 if ( strval( $bits['index'] ) === '' ) {
3582 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3583 $value = trim( $frame->expand( $bits['value'] ) );
3584 $pageArgs[$name] = $value;
3588 // Create a new context to execute the special page
3589 $context = new RequestContext
;
3590 $context->setTitle( $title );
3591 $context->setRequest( new FauxRequest( $pageArgs ) );
3592 $context->setUser( $this->getUser() );
3593 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3594 $ret = SpecialPageFactory
::capturePath( $title, $context );
3596 $text = $context->getOutput()->getHTML();
3597 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3600 $this->disableCache();
3602 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3603 $found = false; # access denied
3604 wfDebug( __METHOD__
. ": template inclusion denied for " .
3605 $title->getPrefixedDBkey() . "\n" );
3607 list( $text, $title ) = $this->getTemplateDom( $title );
3608 if ( $text !== false ) {
3614 # If the title is valid but undisplayable, make a link to it
3615 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3616 $text = "[[:$titleText]]";
3619 } elseif ( $title->isTrans() ) {
3620 # Interwiki transclusion
3621 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3622 $text = $this->interwikiTransclude( $title, 'render' );
3625 $text = $this->interwikiTransclude( $title, 'raw' );
3626 # Preprocess it like a template
3627 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3633 # Do infinite loop check
3634 # This has to be done after redirect resolution to avoid infinite loops via redirects
3635 if ( !$frame->loopCheck( $title ) ) {
3637 $text = '<span class="error">'
3638 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3640 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3644 # If we haven't found text to substitute by now, we're done
3645 # Recover the source wikitext and return it
3647 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3648 if ( $profileSection ) {
3649 $this->mProfiler
->scopedProfileOut( $profileSection );
3651 return array( 'object' => $text );
3654 # Expand DOM-style return values in a child frame
3655 if ( $isChildObj ) {
3656 # Clean up argument array
3657 $newFrame = $frame->newChild( $args, $title );
3660 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3661 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3662 # Expansion is eligible for the empty-frame cache
3663 $text = $newFrame->cachedExpand( $titleText, $text );
3665 # Uncached expansion
3666 $text = $newFrame->expand( $text );
3669 if ( $isLocalObj && $nowiki ) {
3670 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3671 $isLocalObj = false;
3674 if ( $profileSection ) {
3675 $this->mProfiler
->scopedProfileOut( $profileSection );
3678 # Replace raw HTML by a placeholder
3680 $text = $this->insertStripItem( $text );
3681 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3682 # Escape nowiki-style return values
3683 $text = wfEscapeWikiText( $text );
3684 } elseif ( is_string( $text )
3685 && !$piece['lineStart']
3686 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3688 # Bug 529: if the template begins with a table or block-level
3689 # element, it should be treated as beginning a new line.
3690 # This behavior is somewhat controversial.
3691 $text = "\n" . $text;
3694 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3695 # Error, oversize inclusion
3696 if ( $titleText !== false ) {
3697 # Make a working, properly escaped link if possible (bug 23588)
3698 $text = "[[:$titleText]]";
3700 # This will probably not be a working link, but at least it may
3701 # provide some hint of where the problem is
3702 preg_replace( '/^:/', '', $originalTitle );
3703 $text = "[[:$originalTitle]]";
3705 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3706 . 'post-expand include size too large -->' );
3707 $this->limitationWarn( 'post-expand-template-inclusion' );
3710 if ( $isLocalObj ) {
3711 $ret = array( 'object' => $text );
3713 $ret = array( 'text' => $text );
3720 * Call a parser function and return an array with text and flags.
3722 * The returned array will always contain a boolean 'found', indicating
3723 * whether the parser function was found or not. It may also contain the
3725 * text: string|object, resulting wikitext or PP DOM object
3726 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3727 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3728 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3729 * nowiki: bool, wiki markup in $text should be escaped
3732 * @param PPFrame $frame The current frame, contains template arguments
3733 * @param string $function Function name
3734 * @param array $args Arguments to the function
3735 * @throws MWException
3738 public function callParserFunction( $frame, $function, array $args = array() ) {
3742 # Case sensitive functions
3743 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3744 $function = $this->mFunctionSynonyms
[1][$function];
3746 # Case insensitive functions
3747 $function = $wgContLang->lc( $function );
3748 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3749 $function = $this->mFunctionSynonyms
[0][$function];
3751 return array( 'found' => false );
3755 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3757 # Workaround for PHP bug 35229 and similar
3758 if ( !is_callable( $callback ) ) {
3759 throw new MWException( "Tag hook for $function is not callable\n" );
3762 $allArgs = array( &$this );
3763 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3764 # Convert arguments to PPNodes and collect for appending to $allArgs
3765 $funcArgs = array();
3766 foreach ( $args as $k => $v ) {
3767 if ( $v instanceof PPNode ||
$k === 0 ) {
3770 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3774 # Add a frame parameter, and pass the arguments as an array
3775 $allArgs[] = $frame;
3776 $allArgs[] = $funcArgs;
3778 # Convert arguments to plain text and append to $allArgs
3779 foreach ( $args as $k => $v ) {
3780 if ( $v instanceof PPNode
) {
3781 $allArgs[] = trim( $frame->expand( $v ) );
3782 } elseif ( is_int( $k ) && $k >= 0 ) {
3783 $allArgs[] = trim( $v );
3785 $allArgs[] = trim( "$k=$v" );
3790 $result = call_user_func_array( $callback, $allArgs );
3792 # The interface for function hooks allows them to return a wikitext
3793 # string or an array containing the string and any flags. This mungs
3794 # things around to match what this method should return.
3795 if ( !is_array( $result ) ) {
3801 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3802 $result['text'] = $result[0];
3804 unset( $result[0] );
3811 $preprocessFlags = 0;
3812 if ( isset( $result['noparse'] ) ) {
3813 $noparse = $result['noparse'];
3815 if ( isset( $result['preprocessFlags'] ) ) {
3816 $preprocessFlags = $result['preprocessFlags'];
3820 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3821 $result['isChildObj'] = true;
3828 * Get the semi-parsed DOM representation of a template with a given title,
3829 * and its redirect destination title. Cached.
3831 * @param Title $title
3835 public function getTemplateDom( $title ) {
3836 $cacheTitle = $title;
3837 $titleText = $title->getPrefixedDBkey();
3839 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3840 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3841 $title = Title
::makeTitle( $ns, $dbk );
3842 $titleText = $title->getPrefixedDBkey();
3844 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3845 return array( $this->mTplDomCache
[$titleText], $title );
3848 # Cache miss, go to the database
3849 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3851 if ( $text === false ) {
3852 $this->mTplDomCache
[$titleText] = false;
3853 return array( false, $title );
3856 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3857 $this->mTplDomCache
[$titleText] = $dom;
3859 if ( !$title->equals( $cacheTitle ) ) {
3860 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3861 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3864 return array( $dom, $title );
3868 * Fetch the current revision of a given title. Note that the revision
3869 * (and even the title) may not exist in the database, so everything
3870 * contributing to the output of the parser should use this method
3871 * where possible, rather than getting the revisions themselves. This
3872 * method also caches its results, so using it benefits performance.
3875 * @param Title $title
3878 public function fetchCurrentRevisionOfTitle( $title ) {
3879 $cacheKey = $title->getPrefixedDBkey();
3880 if ( !$this->currentRevisionCache
) {
3881 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3883 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3884 $this->currentRevisionCache
->set( $cacheKey,
3885 // Defaults to Parser::statelessFetchRevision()
3886 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3889 return $this->currentRevisionCache
->get( $cacheKey );
3893 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3894 * without passing them on to it.
3897 * @param Title $title
3898 * @param Parser|bool $parser
3901 public static function statelessFetchRevision( $title, $parser = false ) {
3902 return Revision
::newFromTitle( $title );
3906 * Fetch the unparsed text of a template and register a reference to it.
3907 * @param Title $title
3908 * @return array ( string or false, Title )
3910 public function fetchTemplateAndTitle( $title ) {
3911 // Defaults to Parser::statelessFetchTemplate()
3912 $templateCb = $this->mOptions
->getTemplateCallback();
3913 $stuff = call_user_func( $templateCb, $title, $this );
3914 // We use U+007F DELETE to distinguish strip markers from regular text.
3915 $text = $stuff['text'];
3916 if ( is_string( $stuff['text'] ) ) {
3917 $text = strtr( $text, "\x7f", "?" );
3919 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3920 if ( isset( $stuff['deps'] ) ) {
3921 foreach ( $stuff['deps'] as $dep ) {
3922 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3923 if ( $dep['title']->equals( $this->getTitle() ) ) {
3924 // If we transclude ourselves, the final result
3925 // will change based on the new version of the page
3926 $this->mOutput
->setFlag( 'vary-revision' );
3930 return array( $text, $finalTitle );
3934 * Fetch the unparsed text of a template and register a reference to it.
3935 * @param Title $title
3936 * @return string|bool
3938 public function fetchTemplate( $title ) {
3939 $rv = $this->fetchTemplateAndTitle( $title );
3944 * Static function to get a template
3945 * Can be overridden via ParserOptions::setTemplateCallback().
3947 * @param Title $title
3948 * @param bool|Parser $parser
3952 public static function statelessFetchTemplate( $title, $parser = false ) {
3953 $text = $skip = false;
3954 $finalTitle = $title;
3957 # Loop to fetch the article, with up to 1 redirect
3958 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3959 # Give extensions a chance to select the revision instead
3960 $id = false; # Assume current
3961 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3962 array( $parser, $title, &$skip, &$id ) );
3968 'page_id' => $title->getArticleID(),
3975 $rev = Revision
::newFromId( $id );
3976 } elseif ( $parser ) {
3977 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3979 $rev = Revision
::newFromTitle( $title );
3981 $rev_id = $rev ?
$rev->getId() : 0;
3982 # If there is no current revision, there is no page
3983 if ( $id === false && !$rev ) {
3984 $linkCache = LinkCache
::singleton();
3985 $linkCache->addBadLinkObj( $title );
3990 'page_id' => $title->getArticleID(),
3991 'rev_id' => $rev_id );
3992 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3993 # We fetched a rev from a different title; register it too...
3995 'title' => $rev->getTitle(),
3996 'page_id' => $rev->getPage(),
3997 'rev_id' => $rev_id );
4001 $content = $rev->getContent();
4002 $text = $content ?
$content->getWikitextForTransclusion() : null;
4004 if ( $text === false ||
$text === null ) {
4008 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4010 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4011 if ( !$message->exists() ) {
4015 $content = $message->content();
4016 $text = $message->plain();
4024 $finalTitle = $title;
4025 $title = $content->getRedirectTarget();
4029 'finalTitle' => $finalTitle,
4034 * Fetch a file and its title and register a reference to it.
4035 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4036 * @param Title $title
4037 * @param array $options Array of options to RepoGroup::findFile
4040 public function fetchFile( $title, $options = array() ) {
4041 $res = $this->fetchFileAndTitle( $title, $options );
4046 * Fetch a file and its title and register a reference to it.
4047 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4048 * @param Title $title
4049 * @param array $options Array of options to RepoGroup::findFile
4050 * @return array ( File or false, Title of file )
4052 public function fetchFileAndTitle( $title, $options = array() ) {
4053 $file = $this->fetchFileNoRegister( $title, $options );
4055 $time = $file ?
$file->getTimestamp() : false;
4056 $sha1 = $file ?
$file->getSha1() : false;
4057 # Register the file as a dependency...
4058 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4059 if ( $file && !$title->equals( $file->getTitle() ) ) {
4060 # Update fetched file title
4061 $title = $file->getTitle();
4062 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4064 return array( $file, $title );
4068 * Helper function for fetchFileAndTitle.
4070 * Also useful if you need to fetch a file but not use it yet,
4071 * for example to get the file's handler.
4073 * @param Title $title
4074 * @param array $options Array of options to RepoGroup::findFile
4077 protected function fetchFileNoRegister( $title, $options = array() ) {
4078 if ( isset( $options['broken'] ) ) {
4079 $file = false; // broken thumbnail forced by hook
4080 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4081 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4082 } else { // get by (name,timestamp)
4083 $file = wfFindFile( $title, $options );
4089 * Transclude an interwiki link.
4091 * @param Title $title
4092 * @param string $action
4096 public function interwikiTransclude( $title, $action ) {
4097 global $wgEnableScaryTranscluding;
4099 if ( !$wgEnableScaryTranscluding ) {
4100 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4103 $url = $title->getFullURL( array( 'action' => $action ) );
4105 if ( strlen( $url ) > 255 ) {
4106 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4108 return $this->fetchScaryTemplateMaybeFromCache( $url );
4112 * @param string $url
4113 * @return mixed|string
4115 public function fetchScaryTemplateMaybeFromCache( $url ) {
4116 global $wgTranscludeCacheExpiry;
4117 $dbr = wfGetDB( DB_SLAVE
);
4118 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4119 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4120 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4122 return $obj->tc_contents
;
4125 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4126 $status = $req->execute(); // Status object
4127 if ( $status->isOK() ) {
4128 $text = $req->getContent();
4129 } elseif ( $req->getStatus() != 200 ) {
4130 // Though we failed to fetch the content, this status is useless.
4131 return wfMessage( 'scarytranscludefailed-httpstatus' )
4132 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4134 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4137 $dbw = wfGetDB( DB_MASTER
);
4138 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4140 'tc_time' => $dbw->timestamp( time() ),
4141 'tc_contents' => $text
4147 * Triple brace replacement -- used for template arguments
4150 * @param array $piece
4151 * @param PPFrame $frame
4155 public function argSubstitution( $piece, $frame ) {
4158 $parts = $piece['parts'];
4159 $nameWithSpaces = $frame->expand( $piece['title'] );
4160 $argName = trim( $nameWithSpaces );
4162 $text = $frame->getArgument( $argName );
4163 if ( $text === false && $parts->getLength() > 0
4164 && ( $this->ot
['html']
4166 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4169 # No match in frame, use the supplied default
4170 $object = $parts->item( 0 )->getChildren();
4172 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4173 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4174 $this->limitationWarn( 'post-expand-template-argument' );
4177 if ( $text === false && $object === false ) {
4179 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4181 if ( $error !== false ) {
4184 if ( $object !== false ) {
4185 $ret = array( 'object' => $object );
4187 $ret = array( 'text' => $text );
4194 * Return the text to be used for a given extension tag.
4195 * This is the ghost of strip().
4197 * @param array $params Associative array of parameters:
4198 * name PPNode for the tag name
4199 * attr PPNode for unparsed text where tag attributes are thought to be
4200 * attributes Optional associative array of parsed attributes
4201 * inner Contents of extension element
4202 * noClose Original text did not have a close tag
4203 * @param PPFrame $frame
4205 * @throws MWException
4208 public function extensionSubstitution( $params, $frame ) {
4209 $name = $frame->expand( $params['name'] );
4210 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4211 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4212 $marker = self
::MARKER_PREFIX
. "-$name-"
4213 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4215 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4216 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4217 if ( $isFunctionTag ) {
4218 $markerType = 'none';
4220 $markerType = 'general';
4222 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4223 $name = strtolower( $name );
4224 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4225 if ( isset( $params['attributes'] ) ) {
4226 $attributes = $attributes +
$params['attributes'];
4229 if ( isset( $this->mTagHooks
[$name] ) ) {
4230 # Workaround for PHP bug 35229 and similar
4231 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4232 throw new MWException( "Tag hook for $name is not callable\n" );
4234 $output = call_user_func_array( $this->mTagHooks
[$name],
4235 array( $content, $attributes, $this, $frame ) );
4236 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4237 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4238 if ( !is_callable( $callback ) ) {
4239 throw new MWException( "Tag hook for $name is not callable\n" );
4242 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4244 $output = '<span class="error">Invalid tag extension name: ' .
4245 htmlspecialchars( $name ) . '</span>';
4248 if ( is_array( $output ) ) {
4249 # Extract flags to local scope (to override $markerType)
4251 $output = $flags[0];
4256 if ( is_null( $attrText ) ) {
4259 if ( isset( $params['attributes'] ) ) {
4260 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4261 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4262 htmlspecialchars( $attrValue ) . '"';
4265 if ( $content === null ) {
4266 $output = "<$name$attrText/>";
4268 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4269 $output = "<$name$attrText>$content$close";
4273 if ( $markerType === 'none' ) {
4275 } elseif ( $markerType === 'nowiki' ) {
4276 $this->mStripState
->addNoWiki( $marker, $output );
4277 } elseif ( $markerType === 'general' ) {
4278 $this->mStripState
->addGeneral( $marker, $output );
4280 throw new MWException( __METHOD__
. ': invalid marker type' );
4286 * Increment an include size counter
4288 * @param string $type The type of expansion
4289 * @param int $size The size of the text
4290 * @return bool False if this inclusion would take it over the maximum, true otherwise
4292 public function incrementIncludeSize( $type, $size ) {
4293 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4296 $this->mIncludeSizes
[$type] +
= $size;
4302 * Increment the expensive function count
4304 * @return bool False if the limit has been exceeded
4306 public function incrementExpensiveFunctionCount() {
4307 $this->mExpensiveFunctionCount++
;
4308 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4312 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4313 * Fills $this->mDoubleUnderscores, returns the modified text
4315 * @param string $text
4319 public function doDoubleUnderscore( $text ) {
4321 # The position of __TOC__ needs to be recorded
4322 $mw = MagicWord
::get( 'toc' );
4323 if ( $mw->match( $text ) ) {
4324 $this->mShowToc
= true;
4325 $this->mForceTocPosition
= true;
4327 # Set a placeholder. At the end we'll fill it in with the TOC.
4328 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4330 # Only keep the first one.
4331 $text = $mw->replace( '', $text );
4334 # Now match and remove the rest of them
4335 $mwa = MagicWord
::getDoubleUnderscoreArray();
4336 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4338 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4339 $this->mOutput
->mNoGallery
= true;
4341 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4342 $this->mShowToc
= false;
4344 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4345 && $this->mTitle
->getNamespace() == NS_CATEGORY
4347 $this->addTrackingCategory( 'hidden-category-category' );
4349 # (bug 8068) Allow control over whether robots index a page.
4351 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4352 # is not desirable, the last one on the page should win.
4353 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4354 $this->mOutput
->setIndexPolicy( 'noindex' );
4355 $this->addTrackingCategory( 'noindex-category' );
4357 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4358 $this->mOutput
->setIndexPolicy( 'index' );
4359 $this->addTrackingCategory( 'index-category' );
4362 # Cache all double underscores in the database
4363 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4364 $this->mOutput
->setProperty( $key, '' );
4371 * @see ParserOutput::addTrackingCategory()
4372 * @param string $msg Message key
4373 * @return bool Whether the addition was successful
4375 public function addTrackingCategory( $msg ) {
4376 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4380 * This function accomplishes several tasks:
4381 * 1) Auto-number headings if that option is enabled
4382 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4383 * 3) Add a Table of contents on the top for users who have enabled the option
4384 * 4) Auto-anchor headings
4386 * It loops through all headlines, collects the necessary data, then splits up the
4387 * string and re-inserts the newly formatted headlines.
4389 * @param string $text
4390 * @param string $origText Original, untouched wikitext
4391 * @param bool $isMain
4392 * @return mixed|string
4395 public function formatHeadings( $text, $origText, $isMain = true ) {
4396 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4398 # Inhibit editsection links if requested in the page
4399 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4400 $maybeShowEditLink = $showEditLink = false;
4402 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4403 $showEditLink = $this->mOptions
->getEditSection();
4405 if ( $showEditLink ) {
4406 $this->mOutput
->setEditSectionTokens( true );
4409 # Get all headlines for numbering them and adding funky stuff like [edit]
4410 # links - this is for later, but we need the number of headlines right now
4412 $numMatches = preg_match_all(
4413 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4418 # if there are fewer than 4 headlines in the article, do not show TOC
4419 # unless it's been explicitly enabled.
4420 $enoughToc = $this->mShowToc
&&
4421 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4423 # Allow user to stipulate that a page should have a "new section"
4424 # link added via __NEWSECTIONLINK__
4425 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4426 $this->mOutput
->setNewSection( true );
4429 # Allow user to remove the "new section"
4430 # link via __NONEWSECTIONLINK__
4431 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4432 $this->mOutput
->hideNewSection( true );
4435 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4436 # override above conditions and always show TOC above first header
4437 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4438 $this->mShowToc
= true;
4446 # Ugh .. the TOC should have neat indentation levels which can be
4447 # passed to the skin functions. These are determined here
4451 $sublevelCount = array();
4452 $levelCount = array();
4457 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4458 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4459 $oldType = $this->mOutputType
;
4460 $this->setOutputType( self
::OT_WIKI
);
4461 $frame = $this->getPreprocessor()->newFrame();
4462 $root = $this->preprocessToDom( $origText );
4463 $node = $root->getFirstChild();
4468 $headlines = $numMatches !== false ?
$matches[3] : array();
4470 foreach ( $headlines as $headline ) {
4471 $isTemplate = false;
4473 $sectionIndex = false;
4475 $markerMatches = array();
4476 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4477 $serial = $markerMatches[1];
4478 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4479 $isTemplate = ( $titleText != $baseTitleText );
4480 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4484 $prevlevel = $level;
4486 $level = $matches[1][$headlineCount];
4488 if ( $level > $prevlevel ) {
4489 # Increase TOC level
4491 $sublevelCount[$toclevel] = 0;
4492 if ( $toclevel < $wgMaxTocLevel ) {
4493 $prevtoclevel = $toclevel;
4494 $toc .= Linker
::tocIndent();
4497 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4498 # Decrease TOC level, find level to jump to
4500 for ( $i = $toclevel; $i > 0; $i-- ) {
4501 if ( $levelCount[$i] == $level ) {
4502 # Found last matching level
4505 } elseif ( $levelCount[$i] < $level ) {
4506 # Found first matching level below current level
4514 if ( $toclevel < $wgMaxTocLevel ) {
4515 if ( $prevtoclevel < $wgMaxTocLevel ) {
4516 # Unindent only if the previous toc level was shown :p
4517 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4518 $prevtoclevel = $toclevel;
4520 $toc .= Linker
::tocLineEnd();
4524 # No change in level, end TOC line
4525 if ( $toclevel < $wgMaxTocLevel ) {
4526 $toc .= Linker
::tocLineEnd();
4530 $levelCount[$toclevel] = $level;
4532 # count number of headlines for each level
4533 $sublevelCount[$toclevel]++
;
4535 for ( $i = 1; $i <= $toclevel; $i++
) {
4536 if ( !empty( $sublevelCount[$i] ) ) {
4540 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4545 # The safe header is a version of the header text safe to use for links
4547 # Remove link placeholders by the link text.
4548 # <!--LINK number-->
4550 # link text with suffix
4551 # Do this before unstrip since link text can contain strip markers
4552 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4554 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4555 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4557 # Strip out HTML (first regex removes any tag not allowed)
4559 # * <sup> and <sub> (bug 8393)
4562 # * <bdi> (bug 72884)
4563 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4565 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4566 # to allow setting directionality in toc items.
4567 $tocline = preg_replace(
4569 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4570 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4572 array( '', '<$1>' ),
4576 # Strip '<span></span>', which is the result from the above if
4577 # <span id="foo"></span> is used to produce an additional anchor
4579 $tocline = str_replace( '<span></span>', '', $tocline );
4581 $tocline = trim( $tocline );
4583 # For the anchor, strip out HTML-y stuff period
4584 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4585 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4587 # Save headline for section edit hint before it's escaped
4588 $headlineHint = $safeHeadline;
4590 if ( $wgExperimentalHtmlIds ) {
4591 # For reverse compatibility, provide an id that's
4592 # HTML4-compatible, like we used to.
4594 # It may be worth noting, academically, that it's possible for
4595 # the legacy anchor to conflict with a non-legacy headline
4596 # anchor on the page. In this case likely the "correct" thing
4597 # would be to either drop the legacy anchors or make sure
4598 # they're numbered first. However, this would require people
4599 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4600 # manually, so let's not bother worrying about it.
4601 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4602 array( 'noninitial', 'legacy' ) );
4603 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4605 if ( $legacyHeadline == $safeHeadline ) {
4606 # No reason to have both (in fact, we can't)
4607 $legacyHeadline = false;
4610 $legacyHeadline = false;
4611 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4615 # HTML names must be case-insensitively unique (bug 10721).
4616 # This does not apply to Unicode characters per
4617 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4618 # @todo FIXME: We may be changing them depending on the current locale.
4619 $arrayKey = strtolower( $safeHeadline );
4620 if ( $legacyHeadline === false ) {
4621 $legacyArrayKey = false;
4623 $legacyArrayKey = strtolower( $legacyHeadline );
4626 # Create the anchor for linking from the TOC to the section
4627 $anchor = $safeHeadline;
4628 $legacyAnchor = $legacyHeadline;
4629 if ( isset( $refers[$arrayKey] ) ) {
4630 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4632 $refers["${arrayKey}_$i"] = true;
4634 $refers[$arrayKey] = true;
4636 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4637 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4638 $legacyAnchor .= "_$i";
4639 $refers["${legacyArrayKey}_$i"] = true;
4641 $refers[$legacyArrayKey] = true;
4644 # Don't number the heading if it is the only one (looks silly)
4645 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4646 # the two are different if the line contains a link
4647 $headline = Html
::element(
4649 array( 'class' => 'mw-headline-number' ),
4651 ) . ' ' . $headline;
4654 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4655 $toc .= Linker
::tocLine( $anchor, $tocline,
4656 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4659 # Add the section to the section tree
4660 # Find the DOM node for this header
4661 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4662 while ( $node && !$noOffset ) {
4663 if ( $node->getName() === 'h' ) {
4664 $bits = $node->splitHeading();
4665 if ( $bits['i'] == $sectionIndex ) {
4669 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4670 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4671 $node = $node->getNextSibling();
4674 'toclevel' => $toclevel,
4677 'number' => $numbering,
4678 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4679 'fromtitle' => $titleText,
4680 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4681 'anchor' => $anchor,
4684 # give headline the correct <h#> tag
4685 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4686 // Output edit section links as markers with styles that can be customized by skins
4687 if ( $isTemplate ) {
4688 # Put a T flag in the section identifier, to indicate to extractSections()
4689 # that sections inside <includeonly> should be counted.
4690 $editsectionPage = $titleText;
4691 $editsectionSection = "T-$sectionIndex";
4692 $editsectionContent = null;
4694 $editsectionPage = $this->mTitle
->getPrefixedText();
4695 $editsectionSection = $sectionIndex;
4696 $editsectionContent = $headlineHint;
4698 // We use a bit of pesudo-xml for editsection markers. The
4699 // language converter is run later on. Using a UNIQ style marker
4700 // leads to the converter screwing up the tokens when it
4701 // converts stuff. And trying to insert strip tags fails too. At
4702 // this point all real inputted tags have already been escaped,
4703 // so we don't have to worry about a user trying to input one of
4704 // these markers directly. We use a page and section attribute
4705 // to stop the language converter from converting these
4706 // important bits of data, but put the headline hint inside a
4707 // content block because the language converter is supposed to
4708 // be able to convert that piece of data.
4709 // Gets replaced with html in ParserOutput::getText
4710 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4711 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4712 if ( $editsectionContent !== null ) {
4713 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4720 $head[$headlineCount] = Linker
::makeHeadline( $level,
4721 $matches['attrib'][$headlineCount], $anchor, $headline,
4722 $editlink, $legacyAnchor );
4727 $this->setOutputType( $oldType );
4729 # Never ever show TOC if no headers
4730 if ( $numVisible < 1 ) {
4735 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4736 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4738 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4739 $this->mOutput
->setTOCHTML( $toc );
4740 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4741 $this->mOutput
->addModules( 'mediawiki.toc' );
4745 $this->mOutput
->setSections( $tocraw );
4748 # split up and insert constructed headlines
4749 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4752 // build an array of document sections
4753 $sections = array();
4754 foreach ( $blocks as $block ) {
4755 // $head is zero-based, sections aren't.
4756 if ( empty( $head[$i - 1] ) ) {
4757 $sections[$i] = $block;
4759 $sections[$i] = $head[$i - 1] . $block;
4763 * Send a hook, one per section.
4764 * The idea here is to be able to make section-level DIVs, but to do so in a
4765 * lower-impact, more correct way than r50769
4768 * $section : the section number
4769 * &$sectionContent : ref to the content of the section
4770 * $showEditLinks : boolean describing whether this section has an edit link
4772 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4777 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4778 // append the TOC at the beginning
4779 // Top anchor now in skin
4780 $sections[0] = $sections[0] . $toc . "\n";
4783 $full .= join( '', $sections );
4785 if ( $this->mForceTocPosition
) {
4786 return str_replace( '<!--MWTOC-->', $toc, $full );
4793 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4794 * conversion, substituting signatures, {{subst:}} templates, etc.
4796 * @param string $text The text to transform
4797 * @param Title $title The Title object for the current article
4798 * @param User $user The User object describing the current user
4799 * @param ParserOptions $options Parsing options
4800 * @param bool $clearState Whether to clear the parser state first
4801 * @return string The altered wiki markup
4803 public function preSaveTransform( $text, Title
$title, User
$user,
4804 ParserOptions
$options, $clearState = true
4806 if ( $clearState ) {
4807 $magicScopeVariable = $this->lock();
4809 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4810 $this->setUser( $user );
4816 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4817 if ( $options->getPreSaveTransform() ) {
4818 $text = $this->pstPass2( $text, $user );
4820 $text = $this->mStripState
->unstripBoth( $text );
4822 $this->setUser( null ); #Reset
4828 * Pre-save transform helper function
4830 * @param string $text
4835 private function pstPass2( $text, $user ) {
4838 # Note: This is the timestamp saved as hardcoded wikitext to
4839 # the database, we use $wgContLang here in order to give
4840 # everyone the same signature and use the default one rather
4841 # than the one selected in each user's preferences.
4842 # (see also bug 12815)
4843 $ts = $this->mOptions
->getTimestamp();
4844 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4845 $ts = $timestamp->format( 'YmdHis' );
4846 $tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
4848 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4850 # Variable replacement
4851 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4852 $text = $this->replaceVariables( $text );
4854 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4855 # which may corrupt this parser instance via its wfMessage()->text() call-
4858 $sigText = $this->getUserSig( $user );
4859 $text = strtr( $text, array(
4861 '~~~~' => "$sigText $d",
4865 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4866 $tc = '[' . Title
::legalChars() . ']';
4867 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4869 // [[ns:page (context)|]]
4870 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4871 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4872 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4873 // [[ns:page (context), context|]] (using either single or double-width comma)
4874 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4875 // [[|page]] (reverse pipe trick: add context from page title)
4876 $p2 = "/\[\[\\|($tc+)]]/";
4878 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4879 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4880 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4881 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4883 $t = $this->mTitle
->getText();
4885 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4886 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4887 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4888 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4890 # if there's no context, don't bother duplicating the title
4891 $text = preg_replace( $p2, '[[\\1]]', $text );
4894 # Trim trailing whitespace
4895 $text = rtrim( $text );
4901 * Fetch the user's signature text, if any, and normalize to
4902 * validated, ready-to-insert wikitext.
4903 * If you have pre-fetched the nickname or the fancySig option, you can
4904 * specify them here to save a database query.
4905 * Do not reuse this parser instance after calling getUserSig(),
4906 * as it may have changed if it's the $wgParser.
4909 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4910 * @param bool|null $fancySig whether the nicknname is the complete signature
4911 * or null to use default value
4914 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4915 global $wgMaxSigChars;
4917 $username = $user->getName();
4919 # If not given, retrieve from the user object.
4920 if ( $nickname === false ) {
4921 $nickname = $user->getOption( 'nickname' );
4924 if ( is_null( $fancySig ) ) {
4925 $fancySig = $user->getBoolOption( 'fancysig' );
4928 $nickname = $nickname == null ?
$username : $nickname;
4930 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4931 $nickname = $username;
4932 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4933 } elseif ( $fancySig !== false ) {
4934 # Sig. might contain markup; validate this
4935 if ( $this->validateSig( $nickname ) !== false ) {
4936 # Validated; clean up (if needed) and return it
4937 return $this->cleanSig( $nickname, true );
4939 # Failed to validate; fall back to the default
4940 $nickname = $username;
4941 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4945 # Make sure nickname doesnt get a sig in a sig
4946 $nickname = self
::cleanSigInSig( $nickname );
4948 # If we're still here, make it a link to the user page
4949 $userText = wfEscapeWikiText( $username );
4950 $nickText = wfEscapeWikiText( $nickname );
4951 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4953 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4954 ->title( $this->getTitle() )->text();
4958 * Check that the user's signature contains no bad XML
4960 * @param string $text
4961 * @return string|bool An expanded string, or false if invalid.
4963 public function validateSig( $text ) {
4964 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4968 * Clean up signature text
4970 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4971 * 2) Substitute all transclusions
4973 * @param string $text
4974 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4975 * @return string Signature text
4977 public function cleanSig( $text, $parsing = false ) {
4980 $magicScopeVariable = $this->lock();
4981 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4984 # Option to disable this feature
4985 if ( !$this->mOptions
->getCleanSignatures() ) {
4989 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4990 # => Move this logic to braceSubstitution()
4991 $substWord = MagicWord
::get( 'subst' );
4992 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4993 $substText = '{{' . $substWord->getSynonym( 0 );
4995 $text = preg_replace( $substRegex, $substText, $text );
4996 $text = self
::cleanSigInSig( $text );
4997 $dom = $this->preprocessToDom( $text );
4998 $frame = $this->getPreprocessor()->newFrame();
4999 $text = $frame->expand( $dom );
5002 $text = $this->mStripState
->unstripBoth( $text );
5009 * Strip 3, 4 or 5 tildes out of signatures.
5011 * @param string $text
5012 * @return string Signature text with /~{3,5}/ removed
5014 public static function cleanSigInSig( $text ) {
5015 $text = preg_replace( '/~{3,5}/', '', $text );
5020 * Set up some variables which are usually set up in parse()
5021 * so that an external function can call some class members with confidence
5023 * @param Title|null $title
5024 * @param ParserOptions $options
5025 * @param int $outputType
5026 * @param bool $clearState
5028 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5029 $outputType, $clearState = true
5031 $this->startParse( $title, $options, $outputType, $clearState );
5035 * @param Title|null $title
5036 * @param ParserOptions $options
5037 * @param int $outputType
5038 * @param bool $clearState
5040 private function startParse( Title
$title = null, ParserOptions
$options,
5041 $outputType, $clearState = true
5043 $this->setTitle( $title );
5044 $this->mOptions
= $options;
5045 $this->setOutputType( $outputType );
5046 if ( $clearState ) {
5047 $this->clearState();
5052 * Wrapper for preprocess()
5054 * @param string $text The text to preprocess
5055 * @param ParserOptions $options Options
5056 * @param Title|null $title Title object or null to use $wgTitle
5059 public function transformMsg( $text, $options, $title = null ) {
5060 static $executing = false;
5062 # Guard against infinite recursion
5073 $text = $this->preprocess( $text, $title, $options );
5080 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5081 * The callback should have the following form:
5082 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5084 * Transform and return $text. Use $parser for any required context, e.g. use
5085 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5087 * Hooks may return extended information by returning an array, of which the
5088 * first numbered element (index 0) must be the return string, and all other
5089 * entries are extracted into local variables within an internal function
5090 * in the Parser class.
5092 * This interface (introduced r61913) appears to be undocumented, but
5093 * 'markerType' is used by some core tag hooks to override which strip
5094 * array their results are placed in. **Use great caution if attempting
5095 * this interface, as it is not documented and injudicious use could smash
5096 * private variables.**
5098 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5099 * @param callable $callback The callback function (and object) to use for the tag
5100 * @throws MWException
5101 * @return callable|null The old value of the mTagHooks array associated with the hook
5103 public function setHook( $tag, $callback ) {
5104 $tag = strtolower( $tag );
5105 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5106 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5108 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5109 $this->mTagHooks
[$tag] = $callback;
5110 if ( !in_array( $tag, $this->mStripList
) ) {
5111 $this->mStripList
[] = $tag;
5118 * As setHook(), but letting the contents be parsed.
5120 * Transparent tag hooks are like regular XML-style tag hooks, except they
5121 * operate late in the transformation sequence, on HTML instead of wikitext.
5123 * This is probably obsoleted by things dealing with parser frames?
5124 * The only extension currently using it is geoserver.
5127 * @todo better document or deprecate this
5129 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5130 * @param callable $callback The callback function (and object) to use for the tag
5131 * @throws MWException
5132 * @return callable|null The old value of the mTagHooks array associated with the hook
5134 public function setTransparentTagHook( $tag, $callback ) {
5135 $tag = strtolower( $tag );
5136 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5137 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5139 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5140 $this->mTransparentTagHooks
[$tag] = $callback;
5146 * Remove all tag hooks
5148 public function clearTagHooks() {
5149 $this->mTagHooks
= array();
5150 $this->mFunctionTagHooks
= array();
5151 $this->mStripList
= $this->mDefaultStripList
;
5155 * Create a function, e.g. {{sum:1|2|3}}
5156 * The callback function should have the form:
5157 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5159 * Or with Parser::SFH_OBJECT_ARGS:
5160 * function myParserFunction( $parser, $frame, $args ) { ... }
5162 * The callback may either return the text result of the function, or an array with the text
5163 * in element 0, and a number of flags in the other elements. The names of the flags are
5164 * specified in the keys. Valid flags are:
5165 * found The text returned is valid, stop processing the template. This
5167 * nowiki Wiki markup in the return value should be escaped
5168 * isHTML The returned text is HTML, armour it against wikitext transformation
5170 * @param string $id The magic word ID
5171 * @param callable $callback The callback function (and object) to use
5172 * @param int $flags A combination of the following flags:
5173 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5175 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5176 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5177 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5178 * the arguments, and to control the way they are expanded.
5180 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5181 * arguments, for instance:
5182 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5184 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5185 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5186 * working if/when this is changed.
5188 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5191 * Please read the documentation in includes/parser/Preprocessor.php for more information
5192 * about the methods available in PPFrame and PPNode.
5194 * @throws MWException
5195 * @return string|callable The old callback function for this name, if any
5197 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5200 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5201 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5203 # Add to function cache
5204 $mw = MagicWord
::get( $id );
5206 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5209 $synonyms = $mw->getSynonyms();
5210 $sensitive = intval( $mw->isCaseSensitive() );
5212 foreach ( $synonyms as $syn ) {
5214 if ( !$sensitive ) {
5215 $syn = $wgContLang->lc( $syn );
5218 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5221 # Remove trailing colon
5222 if ( substr( $syn, -1, 1 ) === ':' ) {
5223 $syn = substr( $syn, 0, -1 );
5225 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5231 * Get all registered function hook identifiers
5235 public function getFunctionHooks() {
5236 return array_keys( $this->mFunctionHooks
);
5240 * Create a tag function, e.g. "<test>some stuff</test>".
5241 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5242 * Unlike parser functions, their content is not preprocessed.
5243 * @param string $tag
5244 * @param callable $callback
5246 * @throws MWException
5249 public function setFunctionTagHook( $tag, $callback, $flags ) {
5250 $tag = strtolower( $tag );
5251 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5252 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5254 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5255 $this->mFunctionTagHooks
[$tag] : null;
5256 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5258 if ( !in_array( $tag, $this->mStripList
) ) {
5259 $this->mStripList
[] = $tag;
5266 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5267 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5268 * Placeholders created in Skin::makeLinkObj()
5270 * @param string $text
5271 * @param int $options
5273 public function replaceLinkHolders( &$text, $options = 0 ) {
5274 $this->mLinkHolders
->replace( $text );
5278 * Replace "<!--LINK-->" link placeholders with plain text of links
5279 * (not HTML-formatted).
5281 * @param string $text
5284 public function replaceLinkHoldersText( $text ) {
5285 return $this->mLinkHolders
->replaceText( $text );
5289 * Renders an image gallery from a text with one line per image.
5290 * text labels may be given by using |-style alternative text. E.g.
5291 * Image:one.jpg|The number "1"
5292 * Image:tree.jpg|A tree
5293 * given as text will return the HTML of a gallery with two images,
5294 * labeled 'The number "1"' and
5297 * @param string $text
5298 * @param array $params
5299 * @return string HTML
5301 public function renderImageGallery( $text, $params ) {
5304 if ( isset( $params['mode'] ) ) {
5305 $mode = $params['mode'];
5309 $ig = ImageGalleryBase
::factory( $mode );
5310 } catch ( Exception
$e ) {
5311 // If invalid type set, fallback to default.
5312 $ig = ImageGalleryBase
::factory( false );
5315 $ig->setContextTitle( $this->mTitle
);
5316 $ig->setShowBytes( false );
5317 $ig->setShowFilename( false );
5318 $ig->setParser( $this );
5319 $ig->setHideBadImages();
5320 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5322 if ( isset( $params['showfilename'] ) ) {
5323 $ig->setShowFilename( true );
5325 $ig->setShowFilename( false );
5327 if ( isset( $params['caption'] ) ) {
5328 $caption = $params['caption'];
5329 $caption = htmlspecialchars( $caption );
5330 $caption = $this->replaceInternalLinks( $caption );
5331 $ig->setCaptionHtml( $caption );
5333 if ( isset( $params['perrow'] ) ) {
5334 $ig->setPerRow( $params['perrow'] );
5336 if ( isset( $params['widths'] ) ) {
5337 $ig->setWidths( $params['widths'] );
5339 if ( isset( $params['heights'] ) ) {
5340 $ig->setHeights( $params['heights'] );
5342 $ig->setAdditionalOptions( $params );
5344 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5346 $lines = StringUtils
::explode( "\n", $text );
5347 foreach ( $lines as $line ) {
5348 # match lines like these:
5349 # Image:someimage.jpg|This is some image
5351 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5353 if ( count( $matches ) == 0 ) {
5357 if ( strpos( $matches[0], '%' ) !== false ) {
5358 $matches[1] = rawurldecode( $matches[1] );
5360 $title = Title
::newFromText( $matches[1], NS_FILE
);
5361 if ( is_null( $title ) ) {
5362 # Bogus title. Ignore these so we don't bomb out later.
5366 # We need to get what handler the file uses, to figure out parameters.
5367 # Note, a hook can overide the file name, and chose an entirely different
5368 # file (which potentially could be of a different type and have different handler).
5371 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5372 array( $this, $title, &$options, &$descQuery ) );
5373 # Don't register it now, as ImageGallery does that later.
5374 $file = $this->fetchFileNoRegister( $title, $options );
5375 $handler = $file ?
$file->getHandler() : false;
5378 'img_alt' => 'gallery-internal-alt',
5379 'img_link' => 'gallery-internal-link',
5382 $paramMap = $paramMap +
$handler->getParamMap();
5383 // We don't want people to specify per-image widths.
5384 // Additionally the width parameter would need special casing anyhow.
5385 unset( $paramMap['img_width'] );
5388 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5393 $handlerOptions = array();
5394 if ( isset( $matches[3] ) ) {
5395 // look for an |alt= definition while trying not to break existing
5396 // captions with multiple pipes (|) in it, until a more sensible grammar
5397 // is defined for images in galleries
5399 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5400 // splitting on '|' is a bit odd, and different from makeImage.
5401 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5402 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5404 foreach ( $parameterMatches as $parameterMatch ) {
5405 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5407 $paramName = $paramMap[$magicName];
5409 switch ( $paramName ) {
5410 case 'gallery-internal-alt':
5411 $alt = $this->stripAltText( $match, false );
5413 case 'gallery-internal-link':
5414 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5415 $chars = self
::EXT_LINK_URL_CLASS
;
5416 $addr = self
::EXT_LINK_ADDR
;
5417 $prots = $this->mUrlProtocols
;
5418 //check to see if link matches an absolute url, if not then it must be a wiki link.
5419 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5422 $localLinkTitle = Title
::newFromText( $linkValue );
5423 if ( $localLinkTitle !== null ) {
5424 $link = $localLinkTitle->getLinkURL();
5429 // Must be a handler specific parameter.
5430 if ( $handler->validateParam( $paramName, $match ) ) {
5431 $handlerOptions[$paramName] = $match;
5433 // Guess not. Append it to the caption.
5434 wfDebug( "$parameterMatch failed parameter validation\n" );
5435 $label .= '|' . $parameterMatch;
5440 // concatenate all other pipes
5441 $label .= '|' . $parameterMatch;
5444 // remove the first pipe
5445 $label = substr( $label, 1 );
5448 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5450 $html = $ig->toHTML();
5451 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5456 * @param MediaHandler $handler
5459 public function getImageParams( $handler ) {
5461 $handlerClass = get_class( $handler );
5465 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5466 # Initialise static lists
5467 static $internalParamNames = array(
5468 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5469 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5470 'bottom', 'text-bottom' ),
5471 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5472 'upright', 'border', 'link', 'alt', 'class' ),
5474 static $internalParamMap;
5475 if ( !$internalParamMap ) {
5476 $internalParamMap = array();
5477 foreach ( $internalParamNames as $type => $names ) {
5478 foreach ( $names as $name ) {
5479 $magicName = str_replace( '-', '_', "img_$name" );
5480 $internalParamMap[$magicName] = array( $type, $name );
5485 # Add handler params
5486 $paramMap = $internalParamMap;
5488 $handlerParamMap = $handler->getParamMap();
5489 foreach ( $handlerParamMap as $magic => $paramName ) {
5490 $paramMap[$magic] = array( 'handler', $paramName );
5493 $this->mImageParams
[$handlerClass] = $paramMap;
5494 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5496 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5500 * Parse image options text and use it to make an image
5502 * @param Title $title
5503 * @param string $options
5504 * @param LinkHolderArray|bool $holders
5505 * @return string HTML
5507 public function makeImage( $title, $options, $holders = false ) {
5508 # Check if the options text is of the form "options|alt text"
5510 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5511 # * left no resizing, just left align. label is used for alt= only
5512 # * right same, but right aligned
5513 # * none same, but not aligned
5514 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5515 # * center center the image
5516 # * frame Keep original image size, no magnify-button.
5517 # * framed Same as "frame"
5518 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5519 # * upright reduce width for upright images, rounded to full __0 px
5520 # * border draw a 1px border around the image
5521 # * alt Text for HTML alt attribute (defaults to empty)
5522 # * class Set a class for img node
5523 # * link Set the target of the image link. Can be external, interwiki, or local
5524 # vertical-align values (no % or length right now):
5534 $parts = StringUtils
::explode( "|", $options );
5536 # Give extensions a chance to select the file revision for us
5539 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5540 array( $this, $title, &$options, &$descQuery ) );
5541 # Fetch and register the file (file title may be different via hooks)
5542 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5545 $handler = $file ?
$file->getHandler() : false;
5547 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5550 $this->addTrackingCategory( 'broken-file-category' );
5553 # Process the input parameters
5555 $params = array( 'frame' => array(), 'handler' => array(),
5556 'horizAlign' => array(), 'vertAlign' => array() );
5557 $seenformat = false;
5558 foreach ( $parts as $part ) {
5559 $part = trim( $part );
5560 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5562 if ( isset( $paramMap[$magicName] ) ) {
5563 list( $type, $paramName ) = $paramMap[$magicName];
5565 # Special case; width and height come in one variable together
5566 if ( $type === 'handler' && $paramName === 'width' ) {
5567 $parsedWidthParam = $this->parseWidthParam( $value );
5568 if ( isset( $parsedWidthParam['width'] ) ) {
5569 $width = $parsedWidthParam['width'];
5570 if ( $handler->validateParam( 'width', $width ) ) {
5571 $params[$type]['width'] = $width;
5575 if ( isset( $parsedWidthParam['height'] ) ) {
5576 $height = $parsedWidthParam['height'];
5577 if ( $handler->validateParam( 'height', $height ) ) {
5578 $params[$type]['height'] = $height;
5582 # else no validation -- bug 13436
5584 if ( $type === 'handler' ) {
5585 # Validate handler parameter
5586 $validated = $handler->validateParam( $paramName, $value );
5588 # Validate internal parameters
5589 switch ( $paramName ) {
5593 # @todo FIXME: Possibly check validity here for
5594 # manualthumb? downstream behavior seems odd with
5595 # missing manual thumbs.
5597 $value = $this->stripAltText( $value, $holders );
5600 $chars = self
::EXT_LINK_URL_CLASS
;
5601 $addr = self
::EXT_LINK_ADDR
;
5602 $prots = $this->mUrlProtocols
;
5603 if ( $value === '' ) {
5604 $paramName = 'no-link';
5607 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5608 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5609 $paramName = 'link-url';
5610 $this->mOutput
->addExternalLink( $value );
5611 if ( $this->mOptions
->getExternalLinkTarget() ) {
5612 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5617 $linkTitle = Title
::newFromText( $value );
5619 $paramName = 'link-title';
5620 $value = $linkTitle;
5621 $this->mOutput
->addLink( $linkTitle );
5629 // use first appearing option, discard others.
5630 $validated = ! $seenformat;
5634 # Most other things appear to be empty or numeric...
5635 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5640 $params[$type][$paramName] = $value;
5644 if ( !$validated ) {
5649 # Process alignment parameters
5650 if ( $params['horizAlign'] ) {
5651 $params['frame']['align'] = key( $params['horizAlign'] );
5653 if ( $params['vertAlign'] ) {
5654 $params['frame']['valign'] = key( $params['vertAlign'] );
5657 $params['frame']['caption'] = $caption;
5659 # Will the image be presented in a frame, with the caption below?
5660 $imageIsFramed = isset( $params['frame']['frame'] )
5661 ||
isset( $params['frame']['framed'] )
5662 ||
isset( $params['frame']['thumbnail'] )
5663 ||
isset( $params['frame']['manualthumb'] );
5665 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5666 # came to also set the caption, ordinary text after the image -- which
5667 # makes no sense, because that just repeats the text multiple times in
5668 # screen readers. It *also* came to set the title attribute.
5670 # Now that we have an alt attribute, we should not set the alt text to
5671 # equal the caption: that's worse than useless, it just repeats the
5672 # text. This is the framed/thumbnail case. If there's no caption, we
5673 # use the unnamed parameter for alt text as well, just for the time be-
5674 # ing, if the unnamed param is set and the alt param is not.
5676 # For the future, we need to figure out if we want to tweak this more,
5677 # e.g., introducing a title= parameter for the title; ignoring the un-
5678 # named parameter entirely for images without a caption; adding an ex-
5679 # plicit caption= parameter and preserving the old magic unnamed para-
5681 if ( $imageIsFramed ) { # Framed image
5682 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5683 # No caption or alt text, add the filename as the alt text so
5684 # that screen readers at least get some description of the image
5685 $params['frame']['alt'] = $title->getText();
5687 # Do not set $params['frame']['title'] because tooltips don't make sense
5689 } else { # Inline image
5690 if ( !isset( $params['frame']['alt'] ) ) {
5691 # No alt text, use the "caption" for the alt text
5692 if ( $caption !== '' ) {
5693 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5695 # No caption, fall back to using the filename for the
5697 $params['frame']['alt'] = $title->getText();
5700 # Use the "caption" for the tooltip text
5701 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5704 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5706 # Linker does the rest
5707 $time = isset( $options['time'] ) ?
$options['time'] : false;
5708 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5709 $time, $descQuery, $this->mOptions
->getThumbSize() );
5711 # Give the handler a chance to modify the parser object
5713 $handler->parserTransformHook( $this, $file );
5720 * @param string $caption
5721 * @param LinkHolderArray|bool $holders
5722 * @return mixed|string
5724 protected function stripAltText( $caption, $holders ) {
5725 # Strip bad stuff out of the title (tooltip). We can't just use
5726 # replaceLinkHoldersText() here, because if this function is called
5727 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5729 $tooltip = $holders->replaceText( $caption );
5731 $tooltip = $this->replaceLinkHoldersText( $caption );
5734 # make sure there are no placeholders in thumbnail attributes
5735 # that are later expanded to html- so expand them now and
5737 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5738 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5744 * Set a flag in the output object indicating that the content is dynamic and
5745 * shouldn't be cached.
5747 public function disableCache() {
5748 wfDebug( "Parser output marked as uncacheable.\n" );
5749 if ( !$this->mOutput
) {
5750 throw new MWException( __METHOD__
.
5751 " can only be called when actually parsing something" );
5753 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5754 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5758 * Callback from the Sanitizer for expanding items found in HTML attribute
5759 * values, so they can be safely tested and escaped.
5761 * @param string $text
5762 * @param bool|PPFrame $frame
5765 public function attributeStripCallback( &$text, $frame = false ) {
5766 $text = $this->replaceVariables( $text, $frame );
5767 $text = $this->mStripState
->unstripBoth( $text );
5776 public function getTags() {
5778 array_keys( $this->mTransparentTagHooks
),
5779 array_keys( $this->mTagHooks
),
5780 array_keys( $this->mFunctionTagHooks
)
5785 * Replace transparent tags in $text with the values given by the callbacks.
5787 * Transparent tag hooks are like regular XML-style tag hooks, except they
5788 * operate late in the transformation sequence, on HTML instead of wikitext.
5790 * @param string $text
5794 public function replaceTransparentTags( $text ) {
5796 $elements = array_keys( $this->mTransparentTagHooks
);
5797 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5798 $replacements = array();
5800 foreach ( $matches as $marker => $data ) {
5801 list( $element, $content, $params, $tag ) = $data;
5802 $tagName = strtolower( $element );
5803 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5804 $output = call_user_func_array(
5805 $this->mTransparentTagHooks
[$tagName],
5806 array( $content, $params, $this )
5811 $replacements[$marker] = $output;
5813 return strtr( $text, $replacements );
5817 * Break wikitext input into sections, and either pull or replace
5818 * some particular section's text.
5820 * External callers should use the getSection and replaceSection methods.
5822 * @param string $text Page wikitext
5823 * @param string|number $sectionId A section identifier string of the form:
5824 * "<flag1> - <flag2> - ... - <section number>"
5826 * Currently the only recognised flag is "T", which means the target section number
5827 * was derived during a template inclusion parse, in other words this is a template
5828 * section edit link. If no flags are given, it was an ordinary section edit link.
5829 * This flag is required to avoid a section numbering mismatch when a section is
5830 * enclosed by "<includeonly>" (bug 6563).
5832 * The section number 0 pulls the text before the first heading; other numbers will
5833 * pull the given section along with its lower-level subsections. If the section is
5834 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5836 * Section 0 is always considered to exist, even if it only contains the empty
5837 * string. If $text is the empty string and section 0 is replaced, $newText is
5840 * @param string $mode One of "get" or "replace"
5841 * @param string $newText Replacement text for section data.
5842 * @return string For "get", the extracted section text.
5843 * for "replace", the whole page with the section replaced.
5845 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5846 global $wgTitle; # not generally used but removes an ugly failure mode
5848 $magicScopeVariable = $this->lock();
5849 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5851 $frame = $this->getPreprocessor()->newFrame();
5853 # Process section extraction flags
5855 $sectionParts = explode( '-', $sectionId );
5856 $sectionIndex = array_pop( $sectionParts );
5857 foreach ( $sectionParts as $part ) {
5858 if ( $part === 'T' ) {
5859 $flags |
= self
::PTD_FOR_INCLUSION
;
5863 # Check for empty input
5864 if ( strval( $text ) === '' ) {
5865 # Only sections 0 and T-0 exist in an empty document
5866 if ( $sectionIndex == 0 ) {
5867 if ( $mode === 'get' ) {
5873 if ( $mode === 'get' ) {
5881 # Preprocess the text
5882 $root = $this->preprocessToDom( $text, $flags );
5884 # <h> nodes indicate section breaks
5885 # They can only occur at the top level, so we can find them by iterating the root's children
5886 $node = $root->getFirstChild();
5888 # Find the target section
5889 if ( $sectionIndex == 0 ) {
5890 # Section zero doesn't nest, level=big
5891 $targetLevel = 1000;
5894 if ( $node->getName() === 'h' ) {
5895 $bits = $node->splitHeading();
5896 if ( $bits['i'] == $sectionIndex ) {
5897 $targetLevel = $bits['level'];
5901 if ( $mode === 'replace' ) {
5902 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5904 $node = $node->getNextSibling();
5910 if ( $mode === 'get' ) {
5917 # Find the end of the section, including nested sections
5919 if ( $node->getName() === 'h' ) {
5920 $bits = $node->splitHeading();
5921 $curLevel = $bits['level'];
5922 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5926 if ( $mode === 'get' ) {
5927 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5929 $node = $node->getNextSibling();
5932 # Write out the remainder (in replace mode only)
5933 if ( $mode === 'replace' ) {
5934 # Output the replacement text
5935 # Add two newlines on -- trailing whitespace in $newText is conventionally
5936 # stripped by the editor, so we need both newlines to restore the paragraph gap
5937 # Only add trailing whitespace if there is newText
5938 if ( $newText != "" ) {
5939 $outText .= $newText . "\n\n";
5943 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5944 $node = $node->getNextSibling();
5948 if ( is_string( $outText ) ) {
5949 # Re-insert stripped tags
5950 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5957 * This function returns the text of a section, specified by a number ($section).
5958 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5959 * the first section before any such heading (section 0).
5961 * If a section contains subsections, these are also returned.
5963 * @param string $text Text to look in
5964 * @param string|number $sectionId Section identifier as a number or string
5965 * (e.g. 0, 1 or 'T-1').
5966 * @param string $defaultText Default to return if section is not found
5968 * @return string Text of the requested section
5970 public function getSection( $text, $sectionId, $defaultText = '' ) {
5971 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5975 * This function returns $oldtext after the content of the section
5976 * specified by $section has been replaced with $text. If the target
5977 * section does not exist, $oldtext is returned unchanged.
5979 * @param string $oldText Former text of the article
5980 * @param string|number $sectionId Section identifier as a number or string
5981 * (e.g. 0, 1 or 'T-1').
5982 * @param string $newText Replacing text
5984 * @return string Modified text
5986 public function replaceSection( $oldText, $sectionId, $newText ) {
5987 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5991 * Get the ID of the revision we are parsing
5995 public function getRevisionId() {
5996 return $this->mRevisionId
;
6000 * Get the revision object for $this->mRevisionId
6002 * @return Revision|null Either a Revision object or null
6003 * @since 1.23 (public since 1.23)
6005 public function getRevisionObject() {
6006 if ( !is_null( $this->mRevisionObject
) ) {
6007 return $this->mRevisionObject
;
6009 if ( is_null( $this->mRevisionId
) ) {
6013 $rev = call_user_func(
6014 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
6017 # If the parse is for a new revision, then the callback should have
6018 # already been set to force the object and should match mRevisionId.
6019 # If not, try to fetch by mRevisionId for sanity.
6020 if ( $rev && $rev->getId() != $this->mRevisionId
) {
6021 $rev = Revision
::newFromId( $this->mRevisionId
);
6024 $this->mRevisionObject
= $rev;
6026 return $this->mRevisionObject
;
6030 * Get the timestamp associated with the current revision, adjusted for
6031 * the default server-local timestamp
6034 public function getRevisionTimestamp() {
6035 if ( is_null( $this->mRevisionTimestamp
) ) {
6038 $revObject = $this->getRevisionObject();
6039 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6041 # The cryptic '' timezone parameter tells to use the site-default
6042 # timezone offset instead of the user settings.
6044 # Since this value will be saved into the parser cache, served
6045 # to other users, and potentially even used inside links and such,
6046 # it needs to be consistent for all visitors.
6047 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6050 return $this->mRevisionTimestamp
;
6054 * Get the name of the user that edited the last revision
6056 * @return string User name
6058 public function getRevisionUser() {
6059 if ( is_null( $this->mRevisionUser
) ) {
6060 $revObject = $this->getRevisionObject();
6062 # if this template is subst: the revision id will be blank,
6063 # so just use the current user's name
6065 $this->mRevisionUser
= $revObject->getUserText();
6066 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6067 $this->mRevisionUser
= $this->getUser()->getName();
6070 return $this->mRevisionUser
;
6074 * Get the size of the revision
6076 * @return int|null Revision size
6078 public function getRevisionSize() {
6079 if ( is_null( $this->mRevisionSize
) ) {
6080 $revObject = $this->getRevisionObject();
6082 # if this variable is subst: the revision id will be blank,
6083 # so just use the parser input size, because the own substituation
6084 # will change the size.
6086 $this->mRevisionSize
= $revObject->getSize();
6087 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6088 $this->mRevisionSize
= $this->mInputSize
;
6091 return $this->mRevisionSize
;
6095 * Mutator for $mDefaultSort
6097 * @param string $sort New value
6099 public function setDefaultSort( $sort ) {
6100 $this->mDefaultSort
= $sort;
6101 $this->mOutput
->setProperty( 'defaultsort', $sort );
6105 * Accessor for $mDefaultSort
6106 * Will use the empty string if none is set.
6108 * This value is treated as a prefix, so the
6109 * empty string is equivalent to sorting by
6114 public function getDefaultSort() {
6115 if ( $this->mDefaultSort
!== false ) {
6116 return $this->mDefaultSort
;
6123 * Accessor for $mDefaultSort
6124 * Unlike getDefaultSort(), will return false if none is set
6126 * @return string|bool
6128 public function getCustomDefaultSort() {
6129 return $this->mDefaultSort
;
6133 * Try to guess the section anchor name based on a wikitext fragment
6134 * presumably extracted from a heading, for example "Header" from
6137 * @param string $text
6141 public function guessSectionNameFromWikiText( $text ) {
6142 # Strip out wikitext links(they break the anchor)
6143 $text = $this->stripSectionName( $text );
6144 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6145 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6149 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6150 * instead. For use in redirects, since IE6 interprets Redirect: headers
6151 * as something other than UTF-8 (apparently?), resulting in breakage.
6153 * @param string $text The section name
6154 * @return string An anchor
6156 public function guessLegacySectionNameFromWikiText( $text ) {
6157 # Strip out wikitext links(they break the anchor)
6158 $text = $this->stripSectionName( $text );
6159 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6160 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6164 * Strips a text string of wikitext for use in a section anchor
6166 * Accepts a text string and then removes all wikitext from the
6167 * string and leaves only the resultant text (i.e. the result of
6168 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6169 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6170 * to create valid section anchors by mimicing the output of the
6171 * parser when headings are parsed.
6173 * @param string $text Text string to be stripped of wikitext
6174 * for use in a Section anchor
6175 * @return string Filtered text string
6177 public function stripSectionName( $text ) {
6178 # Strip internal link markup
6179 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6180 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6182 # Strip external link markup
6183 # @todo FIXME: Not tolerant to blank link text
6184 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6185 # on how many empty links there are on the page - need to figure that out.
6186 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6188 # Parse wikitext quotes (italics & bold)
6189 $text = $this->doQuotes( $text );
6192 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6197 * strip/replaceVariables/unstrip for preprocessor regression testing
6199 * @param string $text
6200 * @param Title $title
6201 * @param ParserOptions $options
6202 * @param int $outputType
6206 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6207 $magicScopeVariable = $this->lock();
6208 $this->startParse( $title, $options, $outputType, true );
6210 $text = $this->replaceVariables( $text );
6211 $text = $this->mStripState
->unstripBoth( $text );
6212 $text = Sanitizer
::removeHTMLtags( $text );
6217 * @param string $text
6218 * @param Title $title
6219 * @param ParserOptions $options
6222 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6223 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6227 * @param string $text
6228 * @param Title $title
6229 * @param ParserOptions $options
6232 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6233 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6237 * Call a callback function on all regions of the given text that are not
6238 * inside strip markers, and replace those regions with the return value
6239 * of the callback. For example, with input:
6243 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6244 * two strings will be replaced with the value returned by the callback in
6248 * @param callable $callback
6252 public function markerSkipCallback( $s, $callback ) {
6255 while ( $i < strlen( $s ) ) {
6256 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6257 if ( $markerStart === false ) {
6258 $out .= call_user_func( $callback, substr( $s, $i ) );
6261 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6262 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6263 if ( $markerEnd === false ) {
6264 $out .= substr( $s, $markerStart );
6267 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6268 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6277 * Remove any strip markers found in the given text.
6279 * @param string $text Input string
6282 public function killMarkers( $text ) {
6283 return $this->mStripState
->killMarkers( $text );
6287 * Save the parser state required to convert the given half-parsed text to
6288 * HTML. "Half-parsed" in this context means the output of
6289 * recursiveTagParse() or internalParse(). This output has strip markers
6290 * from replaceVariables (extensionSubstitution() etc.), and link
6291 * placeholders from replaceLinkHolders().
6293 * Returns an array which can be serialized and stored persistently. This
6294 * array can later be loaded into another parser instance with
6295 * unserializeHalfParsedText(). The text can then be safely incorporated into
6296 * the return value of a parser hook.
6298 * @param string $text
6302 public function serializeHalfParsedText( $text ) {
6305 'version' => self
::HALF_PARSED_VERSION
,
6306 'stripState' => $this->mStripState
->getSubState( $text ),
6307 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6313 * Load the parser state given in the $data array, which is assumed to
6314 * have been generated by serializeHalfParsedText(). The text contents is
6315 * extracted from the array, and its markers are transformed into markers
6316 * appropriate for the current Parser instance. This transformed text is
6317 * returned, and can be safely included in the return value of a parser
6320 * If the $data array has been stored persistently, the caller should first
6321 * check whether it is still valid, by calling isValidHalfParsedText().
6323 * @param array $data Serialized data
6324 * @throws MWException
6327 public function unserializeHalfParsedText( $data ) {
6328 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6329 throw new MWException( __METHOD__
. ': invalid version' );
6332 # First, extract the strip state.
6333 $texts = array( $data['text'] );
6334 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6336 # Now renumber links
6337 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6339 # Should be good to go.
6344 * Returns true if the given array, presumed to be generated by
6345 * serializeHalfParsedText(), is compatible with the current version of the
6348 * @param array $data
6352 public function isValidHalfParsedText( $data ) {
6353 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6357 * Parsed a width param of imagelink like 300px or 200x300px
6359 * @param string $value
6364 public function parseWidthParam( $value ) {
6365 $parsedWidthParam = array();
6366 if ( $value === '' ) {
6367 return $parsedWidthParam;
6370 # (bug 13500) In both cases (width/height and width only),
6371 # permit trailing "px" for backward compatibility.
6372 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6373 $width = intval( $m[1] );
6374 $height = intval( $m[2] );
6375 $parsedWidthParam['width'] = $width;
6376 $parsedWidthParam['height'] = $height;
6377 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6378 $width = intval( $value );
6379 $parsedWidthParam['width'] = $width;
6381 return $parsedWidthParam;
6385 * Lock the current instance of the parser.
6387 * This is meant to stop someone from calling the parser
6388 * recursively and messing up all the strip state.
6390 * @throws MWException If parser is in a parse
6391 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6393 protected function lock() {
6394 if ( $this->mInParse
) {
6395 throw new MWException( "Parser state cleared while parsing. "
6396 . "Did you call Parser::parse recursively?" );
6398 $this->mInParse
= true;
6401 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6402 $that->mInParse
= false;
6405 return $recursiveCheck;
6409 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6411 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6412 * or if there is more than one <p/> tag in the input HTML.
6414 * @param string $html
6418 public static function stripOuterParagraph( $html ) {
6420 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6421 if ( strpos( $m[1], '</p>' ) === false ) {
6430 * Return this parser if it is not doing anything, otherwise
6431 * get a fresh parser. You can use this method by doing
6432 * $myParser = $wgParser->getFreshParser(), or more simply
6433 * $wgParser->getFreshParser()->parse( ... );
6434 * if you're unsure if $wgParser is safe to use.
6437 * @return Parser A parser object that is not parsing anything
6439 public function getFreshParser() {
6440 global $wgParserConf;
6441 if ( $this->mInParse
) {
6442 return new $wgParserConf['class']( $wgParserConf );
6449 * Set's up the PHP implementation of OOUI for use in this request
6450 * and instructs OutputPage to enable OOUI for itself.
6454 public function enableOOUI() {
6455 OutputPage
::setupOOUI();
6456 $this->mOutput
->setEnableOOUI( true );